On Sat, Dec 8, 2018 at 7:57 PM <jf...@ms4.hinet.net> wrote: > > Grant Edwards於 2018年12月9日星期日 UTC+8上午12時52分04秒寫道: > > Just to be clear: you do _not_ want to use eval on the string. > > > > If you're not the one who created the string, it might wipe your hard > > drive or empty your bank account. If you _are_ the one who created > > the string, then generate the desired result instead. > > > > -- > > Grant > > I didn't evaluate the input string directly. It's the translated "digit" > string been evaluated, so shouldn't have any danger on using eval().
Replacing the first five letters of the alphabet is not sufficient to sanitize untrusted input for eval. Here's a simple example that avoids using any of those letters: py> eval(re.sub(r'[a-e]', '0', "__import__('su\\x62pro\\x63\\x65ss').run('\\x65\\x63ho rm -rf /', **{'sh\\x65ll': 1})")) rm -rf / CompletedProcess(args='echo rm -rf /', returncode=0) Now, if you remove *all* the characters that could possibly start identifiers (https://docs.python.org/3/reference/lexical_analysis.html#identifiers) then you might be safe. Possibly just removing all the ones in ASCII (A-Z + a-z + _) would suffice. I make no guarantees either way. I wish I could say you should just use ast.literal_eval instead. Unfortunately it doesn't seem to support ==: py> ast.literal_eval('10 + 20 == 30') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.5/ast.py", line 84, in literal_eval return _convert(node_or_string) File "/usr/lib/python3.5/ast.py", line 83, in _convert raise ValueError('malformed node or string: ' + repr(node)) ValueError: malformed node or string: <_ast.Compare object at 0x78172bee5358> -- https://mail.python.org/mailman/listinfo/python-list