By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,345 Members | 1,746 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,345 IT Pros & Developers. It's quick & easy.

Hardening enviroment by overloading __import__?

P: n/a
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.
--
Steve Juranich
Tucson, AZ
USA
Jul 19 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Steve Juranich <sj******@gmail.com> writes:
Am I barking up the wrong tree with __import__??
Yes.
Where should I look for this answer?


Don't.
Jul 19 '05 #2

P: n/a
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
Jul 19 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.