Safe eval?
Geoff Gerrietts
geoff at gerrietts.net
Tue Apr 16 16:57:06 EDT 2002
Quoting Philipp Lenssen (lenssen at hitnet.rwth-aachen.de):
> I just realized, as opposed to PHP, there's much stricter namespaces in
> Python and maybe not using "import" on anything harmful could be the
> solution?
You can hack on the rexec module to make it do what you want to do;
that's what I do. It may or may not provide ample security for your
purposes; it's certainly better than a raw eval().
The code I use is attached; under 2.something, this breaks unless you
override make_re to pass.
Thanks,
--G.
--
Geoff Gerrietts "There is no fate that cannot be
<geoff at gerrietts net> surmounted by scorn." --Albert Camus
import rexec
class SEval(rexec.RExec):
nok_builtin_names = tuple(__builtins__.keys())
ok_builtin_modules = ()
ok_path = ()
ok_posix_names = ()
ok_sys_names = ()
def __crunch(*args):
raise SystemError, "Untrusted code did bad things."
def make_re(*args):
pass
r_execfile = s_eval = s_exec = r_exec = __crunch
s_execfile = r_open = r_reload = r_import = __crunch
r_unload = s_import = s_reload = s_unload = __crunch
se = SEval()
def secure_eval(string):
try:
res = se.r_eval(string)
return res
except:
log("Untrusted code evaluated to an error: %s" % string)
raise
More information about the Python-list
mailing list