[Tutor] Beware eval()

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 28 Sep 2001 16:04:59 -0700 (PDT)


On Fri, 28 Sep 2001, David L. Lerner wrote:

> <snip>
> 
> >I haven't written this program yet, but it sounds like it might be really
>  >useful for people who want to avoid the dangers of eval().
> 
> What dangers?


###
>>> 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.

I have to admit that I feel very uncomfortable talking about this --- this
is not the sort of thing I want to think about.  But we have to know that
the possibility of abuse does exist.

If we're taking strings from the "outside", we need to be careful when
eval()ing those strings. eval() gives the outside world as much Python
power as the original programmer.  This is a great thing if the use is
casual for one's private libraries... but akin to the touch of death in a
CGI script.