On 11/27/13 3:44 PM, Chris Kaynor wrote:
On Wed, Nov 27, 2013 at 12:09 PM, Ned Batchelder <[email protected] <mailto:[email protected]>> wrote:* Is there perhaps a better way to achieve what I'm trying to do? What I'm really after, is to check that python expressions embedded in text files are: - well behaved (no syntax errors etc) - don't accidentally access anything it shouldn't - I serve them with the values they need on execution I hope you aren't trying to prevent malice this way: you cannot examine a piece of Python code to prove that it's safe to execute. For an extreme example, see: Eval Really Is Dangerous: http://nedbatchelder.com/blog/__201206/eval_really_is___dangerous.html <http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html> In your environment it looks like you have a whitelist of identifiers, so you're probably ok. I just tested the crash example from that link in Python 2.7.5 win64 and the co_names from the compiled code is empty. Therefore, a simple whitelist would not catch that problematic code (and likely any other global access done correctly). Even a simple test of making sure that at least one (or any number of) valid identifier exists would be insufficent, as you can merely tack on a ",a" to add "a" to the co_names, and thus for any other variable.
Ah, right you are! I neglected to go back and examine the dangerous code. So eval really is dangerous!
--Ned.
Basically, even with a pure whitelist, there is likely no possible way to make eval/exec safe, unless you also eliminate the ability to make literals. Chris
-- https://mail.python.org/mailman/listinfo/python-list
