tags:

views:

165

answers:

2
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(input, {"__builtins__": {} }

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

+1  A: 

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.

Michael Williamson
This does give access to `myFunc` but doesn't accomplish the overall goal of executing the function securely. `eval` cannot be used for that, especially not this easily.
Mike Graham
+1  A: 

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.

Mike Graham
I know there are more secure options, but I have a school assignment that says I have to use `eval` in this particular script (even though I can still have it process `'*' * 10000000` so that Python goes nuts).
Pieter
Okay, just keep in mind that since you are stuck using `eval`, your script is going to be vulnerable to exploits including impossibly-long calculations as well as access to `__builtins__` against your wishes, even with the code above. If one wishes to execute arbitrary Python code securely, you would sandbox the interpreter at an OS level and run it under a supervisor, like they do at http://codepad.org/, but I doubt you really care to go through that trouble for your assignment.
Mike Graham