[Tutor] avoid eval how???

Kent Johnson kent37 at tds.net
Fri Nov 4 04:02:34 CET 2005


Colin J. Williams wrote:
> No, I was thinking of exec.  The given statement can be executed in a 
> specified environment.
> You might say "The rogue code can dodge that with an import statement 
> with an import".
> 
> True, but it seems to me that a user specified __import__ function can 
> protect against this.
> 
> I have not tried this.

This is a pretty frequent topic on comp.lang.python. There are some pretty devious tricks you can use in exec and eval even when builtins are disabled. 

The most promising route seems to be to use the Python parser to generate a syntax tree, then to check the tree for only valid node types before evaluating it. For example see this thread for discussion:
http://groups.google.com/group/comp.lang.python/browse_frm/thread/d5f4d7e2c397c2ca/5d1af7f9c7b1789b?q=safe+exec+parser&rnum=1#5d1af7f9c7b1789b

and this recipe for a _very_limited_ application of the idea:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469

Kent
-- 
http://www.kentsjohnson.com



More information about the Tutor mailing list