How Safe Is Expression Evaluation Using Eval?
Solution 1:
It's completely unsafe to use eval
, even with built-ins emptied and blocked -- the attacker can start with a literal, get its __class__
, etc, etc, up to object
, its __subclasses__
, and so forth... basically, Python introspection is just too strong to stand up to a skilled, determined attacker.
ast.literal_eval
is safe, if you can live by its limitations...
Solution 2:
Certainly it's possible to consume all available memory or create an infinite loop even without the builtins. There are many ways to do it such as 'a'*999999*999999 or to make an infinite loop:
>>>printeval('[[x.append(a) for a in x] for x in [[0]]]',... {'__builtins__':{}}, {'first_name':'Anurag', 'today':today})
As for 1) and 2), I'm not sure but it looks risky. Here is one thing that I tried that I thought would work, but it seems that someone else already considered that line of attack and blocked it:
>>>import datetime>>>deftoday():>>>return datetime.datetime.now()>>>>>>printeval('today.func_globals', {'__builtins__':{}}, {'first_name':'Anurag', 'today':today})
RuntimeError: restricted attribute
I was half expecting to get this instead:
{'__builtins__': <module'__builtin__' (built-in)>, ...
So I think it's probably a bad idea. You only need one tiny hole and you give access to your entire system. Have you considered other methods that don't use eval? What is wrong with them?
Solution 3:
It is possible to get create and invoke any class defined in the program, which includes ones that can exit the Python interpreter. In addition, you can create and execute arbitrary strings of bytecode, which can segfault the interpreter. See Eval really is dangerous for all the details.
Post a Comment for "How Safe Is Expression Evaluation Using Eval?"