Pieter
Pieter

Reputation: 32755

Using eval securely to execute functions

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?

Upvotes: 2

Views: 1285

Answers (3)

Ned Batchelder
Ned Batchelder

Reputation: 375484

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.

Upvotes: 0

Michael Williamson
Michael Williamson

Reputation: 11438

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.

Upvotes: 1

Mike Graham
Mike Graham

Reputation: 76663

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.

Upvotes: 1

Related Questions