Securing the Pyton Interpreter?

Jeff Epler jepler at unpythonic.net
Wed Jul 16 14:10:40 EDT 2003


I've never tried to set up a "secure" unix system, in the sense that
users will only be allowed to execute certain commands.  However there
are any number of secure/restricted shells.

I suspect that if you use one of these, you can get what you want.  For
instance, you would have /usr/bin forbidden, and /usr/safebin permitted.
In /usr/safebin/pyscript you'd lead off with "#!/usr/bin/python -E".
"-E" prevents Python from obeying environment variables like
PYTHONPATH, PYTHONHOME, and PYTHONINSPECT, all of which can let the user
"sneak" code in to be executed.

Of course, you have to be sure that the individual python scripts are
"secure" also.  For instance, the following one *isn't*:
	#!/usr/bin/python -E
	# Print prime factors of a number (like /usr/bin/factor)
	import sys, math
	for arg in sys.argv[1:]:
		num = eval(arg)

		print "%d:" % num,
		i=2
		while num != 1:
			while num % i == 0:
				print i,
				num = num / i
			i=i+1
		print
using eval() is the reason, in case you didn't catch it, but there are
more subtle ways to write Python programs that let the user do arbitrary
things.  For instance, if a program uses pickle and lets the user alter
the pickle's contents, the user can execute arbitrary code.  If there's
a bug in the C program that implements the Python interpreter or any
extension module, the user might be able to arrange to "smash the stack"
and do the same thing.  Whether these things really matter depend on
how secure your multi-user system needs to be. (this last type of attack
could be true of any program, though, not just Python)

Jeff





More information about the Python-list mailing list