开发者

Using eval securely to execute functions

开发者 https://www.devze.com 2022-12-21 11:52 出处:网络
def myFunc(arg1, arg2): print \"This is a test with \" + arg1 + \" and \" + arg2 while (input != \"quit\"):
def myFunc(arg1, arg2):
    print "This is a test with " + arg1 + " and " + arg2

while (input != "quit"):
    input = raw_input("> ")

    if input != "quit":
        eval(input)

This code gives me a prompt, allowing me to invoke myFunc with parameters I want. I know that eval can be dangerous if a dictionary is not supplied, so I added this:

eval(inp开发者_开发知识库ut, {"__builtins__": {} }

Now I can no longer invoke myFunc. How do I fix this without leaving eval open to exploits?


This will allow you to use myFunc:

eval(input, {"__builtins__": {}, "myFunc": myFunc})

However, as others have pointed out, using eval is inherently insecure, and still vulnerabe to exploits.


Your question, "How do I fix this without leaving eval open to exploits?", isn't the right one—eval is vulnerable to exploits, period. Not introducing __builtins__ into the global namespace of the evaluated code does not make the __builtin__ module impossible to access, and it doesn't close off other points of entry.

If you explained more about the problem you are trying to solve, someone may be able to suggest a secure option to accomplish your goals.


If you need a demonstration of how eval is still dangerous even with the builtins removed, see this: Eval really is dangerous. There are examples there of segfaulting the CPython interpreter, or of exiting it directly.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号