[Tutor] eval and exec

Alan Gauld alan.gauld at freenet.co.uk
Mon Dec 6 00:48:29 CET 2004


> And how can __import__ be safer?

Safer because it is limited in what it can do, import a file.
The file must exist in the python path, so its much harder for
the user to do something bad - they have to create a new file
with malicious code in it and insert it into the python path
and then get that filename string into your program. Its much,
much easier when you can type malicious code directly

> And couldn't he import untrusted code?

Yes, but he has to get the code onto your machine first!

> in it?  And what about the apply() function?  Aren't all of these
the
> same open door?

Again apply calls a pre-existing function, the attacker has
to actually create the function and get it into your namespace
before calling it.

All of these are potentially dangerous, you are right, but
they are second order dangers because they
1) have a clearly delimited scope of what can be done
2) the string executed is not directly executed, it must fit a
   specific form and is therefore more easily monitored for
   "sanity" before execution.
3) The code that is executed must already exist.

> I love the exec() call.  I love the idea of code that makes and
execs
> code.  I'll make myself obsolete.  :^)

It is very powerful, and self modifying code is indeed fun to play
with (albeit surprisingly difficult to find a genuine use for!)
But it must be used in full cognisance of the security dangers.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list