views:

82

answers:

2

I have a string "[u'foo']" (Yes, it includes the square brackets and the u''). I have to convert that to a list which looks like [u'foo'].

list("[u'foo']") won't work.

Any suggestions?

+1  A: 
eval("[u'foo']", {'__builtins__':[]}, {})
leoluk
You know that passing empty dicts for `locals` and `globals` isn't enough to 'secure' `eval`, yes? This still gives an attacker basically full access to your system.
Aaron Gallagher
POC: `eval('__import__("os").getcwd()', {}, {})`, I edited my answer
leoluk
@leoluk, that doesn't 'prove' anything. `eval("[x for x in type(type(1)).__bases__[0].__subclasses__() if x.__name__ == 'file'][0]('/etc/passwd').readline()", {}, {})` gives me the first line of `/etc/passwd` on my system.
Aaron Gallagher
@Aaron, cool... By the way, if I can't use literal_eval(), what would you suggest as a 'secure' eval?
Albert
@Albert, I would suggest modifying your desires so that you don't have to.
Aaron Gallagher
@Aaron: `eval('__import__("os").getcwd()', {}, {})` is no proof, it works fine. I just wanted to give an example that the first revision was insecure, and I fixed it.
leoluk
+8  A: 
>>> import ast
>>> s = "[u'foo']"
>>> ast.literal_eval(s)
[u'foo']

documentation

Adam Bernier
+1 for the safe `literal_eval` instead of `eval`.
Greg Hewgill