Hardening enviroment by overloading __import__?

Jp Calderone exarkun at divmod.com
Thu Jun 23 16:24:51 EDT 2005


On Thu, 23 Jun 2005 13:12:12 -0700, Steve Juranich <sjuranic at gmail.com> wrote:
>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?

__builtin__.__import__ is what you need to replace.  Note, of course, that this only makes it trivially more difficult for malicious code to do destructive things: it doesn't even prevent the code from importing any module it likes, it just makes it take a few extra lines of code.

Jp



More information about the Python-list mailing list