[Tutor] a string of nested-list to a list?

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu Mar 27 12:31:02 2003


On Thu, 27 Mar 2003, lonetwin wrote:

> > >>>  a = "[['a','b'],[['c','d'],'e']]"
> > >>>  b = eval(a)
> > >>>  b
> >
> > [['a', 'b'], [['c', 'd'], 'e']]
> >
> > >>>  b[1]
> >
> > [['c', 'd'], 'e']
>
> Re: The above code led me to open up my python prompt and try this:
> >>> import os
> >>> a = '[ "a", "b", ["c", "d"], [ os.system(x) for x in ["/bin/bash",
> "/bin/ls"] ]]'
> >>> b = eval(a)
>
>    Scary, ain't it ?? Also , it needn't be 'os.system()' it could be any
> malicious bit of code. I'd stay away from converting strings repr()s of
> lists if I were pan, unless of course I knew for sure where the repr of
> my list is coming from.

Hello!

eval() can be dangerous, but there's some things that we can do to
restrict what things can be evaluated, to make it partially safer.  For
example:

###
>>> def restricted_eval(s):
...     """Calls eval, but sets the __builtins__ dictionary to be
...        empty when we do the evalutation."""
...     empty_builtin_dict = {'__builtins__': {}}
...     return eval(s, empty_builtin_dict)
...
>>> import os
>>> a = '[ "a", "b", ["c", "d"], os.popen("ls").read()]'
>>> c = restricted_eval(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 5, in restricted_eval
  File "<string>", line 0, in ?
NameError: name 'os' is not defined
###


The idea is to empty out the environment where the evaluation runs, so
that it only knows how to do simple stuff like string and list evaluation:

###
>>> l = '[ "a", "b", ["c", "d"]]'
>>> restricted_eval(l)
['a', 'b', ['c', 'd']]
###



Hope this helps!