If I am evaluating a Python string using eval(), and have a class like:
class Foo(object):
a = 3
def bar(self, x): return x + a
What are the security risks if I do not trust the string? In particular:
- Is
eval(string, {"f": Foo()}, {})
unsafe? That is, can you reach os or sys or something unsafe from a Foo instance?
- Is
eval(string, {}, {})
unsafe? That is, can I reach os or sys entirely from builtins like len and list?
- Is there a way to make builtins not present at all in the eval context?
There are some unsafe strings like "[0] * 100000000" I don't care about, because at worst they slow/stop the program. I am primarily concerned about protecting user data external to the program.
Obviously, eval(string)
without custom dictionaries is unsafe in most cases.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…