[Tutor] Beware eval()

Michael P. Reilly arcege@speakeasy.net
Fri, 28 Sep 2001 19:55:19 -0400


On Fri, Sep 28, 2001 at 04:04:59PM -0700, Danny Yoo wrote:
> ###
> >>> some_input = """[1, 2,
> ...     __import__(\"os\").system("echo 'If they knew what I knew...'"),
> ...      3, 4]"""
> >>> eval(some_input)
> If they knew what I knew...
> [1, 2, 0, 3, 4]
> ###
>                 
> Notice that we just called the underlying os.system() here.  The "echo"
> command is very innoculous here... but if we put ourselves in a dark mood,
> we can imagine Really Bad Things happening.

That is why you can just pass empty namespaces:

>>> eval(some_input, {'__builtins__': {}}, {})
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "<string>", line 0, in ?
NameError: __import__
>>>

And since it is an eval, you cannot call statements; only expressions
are allowed.  That leaves anything that is not an unqualified name (value,
function, class, instance, module, etc.).  That's fairly safe, I'd say.

  -Arcege

Incidently, Python has a "parser" module to parse Python code, including
expressions given to eval().

-- 
+----------------------------------+-----------------------------------+
| Michael P. Reilly                | arcege@speakeasy.net              |
| Ailment info: http://www.speakeasy.org/~arcege/michaelwatch.html     |