Hardening enviroment by overloading __import__?

S

Steve Juranich

If this is a FAQ, please let me know where the answer is.

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. I thought that one way I
could harden the enviroment against malicious code would be to
temporarily disable the import statement by overloading __import__,
but I tried what seemed obvious to me, and it didn't work.

What I want do do is something like this:

def __import__(*args, **kwargs):
raise ImportError, 'Not so fast, bucko!'

eval(potentially_dangerous_string)

del __import__ # To get the builtin behavior back.

Am I barking up the wrong tree with __import__?? Where should I look
for this answer?

Thanks.
 
S

Steven Bethard

Steve said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,062
Latest member
OrderKetozenseACV

Latest Threads

Top