Hardening enviroment by overloading __import__?
Steven Bethard
steven.bethard at gmail.com
Thu Jun 23 17:41:43 EDT 2005
Steve Juranich wrote:
> I have in some code an 'eval', which I hate, but it's the shortest
> path to where I need to get at this point.
What's this code trying to do? If you care about malicious code at all,
you'll avoid 'eval' completely. A couple reasons why:
With only a little trouble, I can get to the file object and write stuff
to your machine:
py> eval("().__class__.mro()[1].__subclasses__()[16]")
<type 'file'>
Sure, you can avoid this by supplying your own __builtins__ to disable
the file constructor:
py> eval("().__class__.mro()[1].__subclasses__()[16]('temp.txt')",
dict(__builtins__={}))
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "<string>", line 0, in ?
IOError: file() constructor not accessible in restricted mode
But even without the file constructor, I can still access pretty much
any attribute of any class object by looking at object.__subclasses__():
py> class C(object):
... def __init__(self):
... self.f = file('temp.txt', 'w')
...
py> eval("().__class__.mro()[1].__subclasses__()[-1]().f.write('junk')",
dict(__builtins__={}))
py> file('temp.txt').read()
'junk'
Moral of the story: don't use eval if you care about security!
STeVe
More information about the Python-list
mailing list