DS wrote: > I have been writing a web-based application in which users would be able > to input expressions which would be evaluated on the server. I had read > about the dangers of using eval for such things, and so I parse the > expressions myself, and calculate the expressions using my own code. > This wasn't too bad, because that gave me a chance to learn about > parsing expressions, AST, and other aspects of coding that I wasn't > particularly familiar with. If that was all I needed to do, my code > seems adequate for this purpose. > > Now, I've been starting to think about adding multiline expressions, or > really, at this point, programs. I don't think it would be all that bad > to implement some simple structure for doing that, but I can't help but > think that it would make more sense to simply use Python directly. Not > only is it already implemented, but I certainly like to use it, and it > might promote the use of Python just a bit more. > > Is this simply such a bad idea that I should not even consider it? Is > there a way that I can limit usage by filtering all programs for > operating system calls, certain imports, maybe not allowing lambdas? I > would hate to get compromised in some way that I don't understand.
It is very challenging to even come close to safety. If you search comp.lang.python for eval or exec you will find many discussions of this. For example http://groups.google.com/group/comp.lang.python/browse_frm/thread/cf6093c5551a6587/23ddf23a6dfc3e11?q=eval&rnum=1#23ddf23a6dfc3e11 One approach is to use the compiler module to parse the input data and write a custom visitor for the parse tree that only allows 'safe' parse elements to be processed. There is some discussion here: http://groups.google.com/group/comp.lang.python/browse_frm/thread/d5f4d7e2c397c2ca/5d1af7f9c7b1789b?q=python+compiler+safe+eval&rnum=1#5d1af7f9c7b1789b There is also a hack that provides an empty __builtin__ namespace to eval which prevents at least naive attempts at hacking. Bottom line - it's a very hard problem which I don't think anyone has solved to the satisfaction of all observers, though there are limited solutions which some people find acceptable. Kent _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor