View Single Post
Old 5th April 2009
mwatkins mwatkins is offline
Flying Circus Master
 
Join Date: Mar 2009
Location: Vancouver
Posts: 23
Default

The problem with "eval" is that it is not secure at all. If someone or something else gets to the registry, they can insert code into a key which your code may read and execute, code which may darn well be malicious.

For example the following file "foo" could just as easily be the C:\ntldr:

Code:
eval("open('foo','w').write('p0wned!')")
You might check (Python 2.6 or greater) literal_eval from the ast module:

Code:
literal_eval(node_or_string)
    Safely evaluate an expression node or a string containing a Python
    expression.  The string or node provided may only consist of the following
    Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
    and None.
aka - I take that to mean no function calls or methods. Check it out further - I've not used this myself, but here's the above example:

Code:
>>> import ast
>>> ast.literal_eval("open('foo','w').write('p0wned!')")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.1/ast.py", line 80, in literal_eval
    return _convert(node_or_string)
  File "/usr/local/lib/python3.1/ast.py", line 79, in _convert
    raise ValueError('malformed string')
ValueError: malformed string
If literal_eval doesn't meet your needs, google "python safe eval" for other approaches.

(And yes, I'm using an unreleased version of Python. Not advisable for general use. I'm working on moving all our code to Python 3.x, generally liking it.)

Last edited by mwatkins; 5th April 2009 at 05:39 PM. Reason: Added example
Reply With Quote