executing arbitrary statements

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Oct 2 10:11:04 EDT 2011


Jonathan Hartley wrote:

> I (and many others) entirely avoid using 'eval' in all my code for many
> years, based on the security concerns that Chris rightly highlights. It's
> worth noting though, that RaymondH's talks last year on some valid uses of
> 'eval' and 'exec' have opened my eyes to it somewhat. In summary, while
> it's dangerous to execute user-submitted code, there are no security risks
> associated with executing code generated by your own program.

That's not strictly true. If you look at the code for namedtuple, you will
see that Raymond actually spends significant effort to sanitise the input
to namedtuple. Right at the top of the class is this comment:

# Parse and validate the field names.  Validation serves two purposes,
# generating informative error messages and preventing template injection
attacks.

So even something like namedtuple needs to take care of security risks.

In a more general sense, "security" does not necessarily mean security
against outsiders. Sometimes the threat you're defending from is an
insider, or even yourself: for example, there are various utility programs
designed to prevent you from emailing while drunk (I know people who should
use them!), *many* security protocols designed to prevent a single rogue
member of an organisation from doing harm (e.g. it takes at least two
people to launch nuclear warheads), etc. This is why (for example) on
Linux, the rm command defaults to interactive use when given as root. If
you've ever typed rm -r * in the wrong directory (especially the root
directory) you'll understand that sometimes the worst threat is yourself.



-- 
Steven




More information about the Python-list mailing list