Provides a retricted enviroment for dynamically executing a subset of the Python language suitable for configuration scripts, end-user oriented scripting and storing data in a user-friendly way.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | #----------------------------------------------------------------------
# I, Babar K. Zafar, the author or of this code dedicate any and all
# copyright interest in this code to the public domain. I make this
# dedication for the benefit of the public at large and to the
# detriment of our heirs and successors. I intend this dedication to
# be an overt act of relinquishment in perpetuity of all present and
# future rights this code under copyright law.
#
# Version 0.1 / May 27 2006
#----------------------------------------------------------------------
import inspect, compiler.ast
import thread, time
#----------------------------------------------------------------------
# Module globals.
#----------------------------------------------------------------------
# Toggle module level debugging mode.
DEBUG = False
# List of all AST node classes in compiler/ast.py.
all_ast_nodes = \
[name for (name, obj) in inspect.getmembers(compiler.ast)
if inspect.isclass(obj) and issubclass(obj, compiler.ast.Node)]
# List of all builtin functions and types (ignoring exception classes).
all_builtins = \
[name for (name, obj) in inspect.getmembers(__builtins__)
if inspect.isbuiltin(obj) or (inspect.isclass(obj) and \
not issubclass(obj, Exception))]
#----------------------------------------------------------------------
# Utilties.
#----------------------------------------------------------------------
def classname(obj):
return obj.__class__.__name__
def is_valid_ast_node(name):
return name in all_ast_nodes
def is_valid_builtin(name):
return name in all_builtins
def get_node_lineno(node):
return (node.lineno) and node.lineno or 0
#----------------------------------------------------------------------
# Restricted AST nodes & builtins.
#----------------------------------------------------------------------
# Deny evaluation of code if the AST contain any of the following nodes:
unallowed_ast_nodes = [
# 'Add', 'And',
# 'AssAttr', 'AssList', 'AssName', 'AssTuple',
# 'Assert', 'Assign', 'AugAssign',
'Backquote',
# 'Bitand', 'Bitor', 'Bitxor', 'Break',
# 'CallFunc', 'Class', 'Compare', 'Const', 'Continue',
# 'Decorators', 'Dict', 'Discard', 'Div',
# 'Ellipsis', 'EmptyNode',
'Exec',
# 'Expression', 'FloorDiv',
# 'For',
'From',
# 'Function',
# 'GenExpr', 'GenExprFor', 'GenExprIf', 'GenExprInner',
# 'Getattr', 'Global', 'If',
'Import',
# 'Invert',
# 'Keyword', 'Lambda', 'LeftShift',
# 'List', 'ListComp', 'ListCompFor', 'ListCompIf', 'Mod',
# 'Module',
# 'Mul', 'Name', 'Node', 'Not', 'Or', 'Pass', 'Power',
# 'Print', 'Printnl',
'Raise',
# 'Return', 'RightShift', 'Slice', 'Sliceobj',
# 'Stmt', 'Sub', 'Subscript',
'TryExcept', 'TryFinally',
# 'Tuple', 'UnaryAdd', 'UnarySub',
# 'While','Yield'
]
# Deny evaluation of code if it tries to access any of the following builtins:
unallowed_builtins = [
'__import__',
# 'abs', 'apply', 'basestring', 'bool', 'buffer',
# 'callable', 'chr', 'classmethod', 'cmp', 'coerce',
'compile',
# 'complex',
'delattr',
# 'dict',
'dir',
# 'divmod', 'enumerate',
'eval', 'execfile', 'file',
# 'filter', 'float', 'frozenset',
'getattr', 'globals', 'hasattr',
# 'hash', 'hex', 'id',
'input',
# 'int', 'intern', 'isinstance', 'issubclass', 'iter',
# 'len', 'list',
'locals',
# 'long', 'map', 'max', 'min', 'object', 'oct',
'open',
# 'ord', 'pow', 'property', 'range',
'raw_input',
# 'reduce',
'reload',
# 'repr', 'reversed', 'round', 'set',
'setattr',
# 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
# 'tuple', 'type', 'unichr', 'unicode',
'vars',
# 'xrange', 'zip'
]
for ast_name in unallowed_ast_nodes:
assert(is_valid_ast_node(ast_name))
for name in unallowed_builtins:
assert(is_valid_builtin(name))
def is_unallowed_ast_node(kind):
return kind in unallowed_ast_nodes
def is_unallowed_builtin(name):
return name in unallowed_builtins
#----------------------------------------------------------------------
# Restricted attributes.
#----------------------------------------------------------------------
# In addition to these we deny access to all lowlevel attrs (__xxx__).
unallowed_attr = [
'im_class', 'im_func', 'im_self',
'func_code', 'func_defaults', 'func_globals', 'func_name',
'tb_frame', 'tb_next',
'f_back', 'f_builtins', 'f_code', 'f_exc_traceback',
'f_exc_type', 'f_exc_value', 'f_globals', 'f_locals']
def is_unallowed_attr(name):
return (name[:2] == '__' and name[-2:] == '__') or \
(name in unallowed_attr)
#----------------------------------------------------------------------
# SafeEvalVisitor.
#----------------------------------------------------------------------
class SafeEvalError(object):
"""
Base class for all which occur while walking the AST.
Attributes:
errmsg = short decription about the nature of the error
lineno = line offset to where error occured in source code
"""
def __init__(self, errmsg, lineno):
self.errmsg, self.lineno = errmsg, lineno
def __str__(self):
return "line %d : %s" % (self.lineno, self.errmsg)
class SafeEvalASTNodeError(SafeEvalError):
"Expression/statement in AST evaluates to a restricted AST node type."
pass
class SafeEvalBuiltinError(SafeEvalError):
"Expression/statement in tried to access a restricted builtin."
pass
class SafeEvalAttrError(SafeEvalError):
"Expression/statement in tried to access a restricted attribute."
pass
class SafeEvalVisitor(object):
"""
Data-driven visitor which walks the AST for some code and makes
sure it doesn't contain any expression/statements which are
declared as restricted in 'unallowed_ast_nodes'. We'll also make
sure that there aren't any attempts to access/lookup restricted
builtin declared in 'unallowed_builtins'. By default we also won't
allow access to lowlevel stuff which can be used to dynamically
access non-local envrioments.
Interface:
walk(ast) = validate AST and return True if AST is 'safe'
Attributes:
errors = list of SafeEvalError if walk() returned False
Implementation:
The visitor will automatically generate methods for all of the
available AST node types and redirect them to self.ok or self.fail
reflecting the configuration in 'unallowed_ast_nodes'. While
walking the AST we simply forward the validating step to each of
node callbacks which take care of reporting errors.
"""
def __init__(self):
"Initialize visitor by generating callbacks for all AST node types."
self.errors = []
for ast_name in all_ast_nodes:
# Don't reset any overridden callbacks.
if getattr(self, 'visit' + ast_name, None): continue
if is_unallowed_ast_node(ast_name):
setattr(self, 'visit' + ast_name, self.fail)
else:
setattr(self, 'visit' + ast_name, self.ok)
def walk(self, ast):
"Validate each node in AST and return True if AST is 'safe'."
self.visit(ast)
return self.errors == []
def visit(self, node, *args):
"Recursively validate node and all of its children."
fn = getattr(self, 'visit' + classname(node))
if DEBUG: self.trace(node)
fn(node, *args)
for child in node.getChildNodes():
self.visit(child, *args)
def visitName(self, node, *args):
"Disallow any attempts to access a restricted builtin/attr."
name = node.getChildren()[0]
lineno = get_node_lineno(node)
if is_unallowed_builtin(name):
self.errors.append(SafeEvalBuiltinError( \
"access to builtin '%s' is denied" % name, lineno))
elif is_unallowed_attr(name):
self.errors.append(SafeEvalAttrError( \
"access to attribute '%s' is denied" % name, lineno))
def visitGetattr(self, node, *args):
"Disallow any attempts to access a restricted attribute."
name = node.attrname
lineno = get_node_lineno(node)
if is_unallowed_attr(name):
self.errors.append(SafeEvalAttrError( \
"access to attribute '%s' is denied" % name, lineno))
def ok(self, node, *args):
"Default callback for 'harmless' AST nodes."
pass
def fail(self, node, *args):
"Default callback for unallowed AST nodes."
lineno = get_node_lineno(node)
self.errors.append(SafeEvalASTNodeError( \
"execution of '%s' statements is denied" % classname(node),
lineno))
def trace(self, node):
"Debugging utility for tracing the validation of AST nodes."
print classname(node)
for attr in dir(node):
if attr[:2] != '__':
print ' ' * 4, "%-15.15s" % attr, getattr(node, attr)
#----------------------------------------------------------------------
# Safe 'eval' replacement.
#----------------------------------------------------------------------
class SafeEvalException(Exception):
"Base class for all safe-eval related errors."
pass
class SafeEvalCodeException(SafeEvalException):
"""
Exception class for reporting all errors which occured while
validating AST for source code in safe_eval().
Attributes:
code = raw source code which failed to validate
errors = list of SafeEvalError
"""
def __init__(self, code, errors):
self.code, self.errors = code, errors
def __str__(self):
return '\n'.join([str(err) for err in self.errors])
class SafeEvalContextException(SafeEvalException):
"""
Exception class for reporting unallowed objects found in the dict
intended to be used as the local enviroment in safe_eval().
Attributes:
keys = list of keys of the unallowed objects
errors = list of strings describing the nature of the error
for each key in 'keys'
"""
def __init__(self, keys, errors):
self.keys, self.errors = keys, errors
def __str__(self):
return '\n'.join([str(err) for err in self.errors])
class SafeEvalTimeoutException(SafeEvalException):
"""
Exception class for reporting that code evaluation execeeded
the given timelimit.
Attributes:
timeout = time limit in seconds
"""
def __init__(self, timeout):
self.timeout = timeout
def __str__(self):
return "Timeout limit execeeded (%s secs) during exec" % self.timeout
def exec_timed(code, context, timeout_secs):
"""
Dynamically execute 'code' using 'context' as the global enviroment.
SafeEvalTimeoutException is raised if execution does not finish within
the given timelimit.
"""
assert(timeout_secs > 0)
signal_finished = False
def alarm(secs):
def wait(secs):
for n in xrange(timeout_secs):
time.sleep(1)
if signal_finished: break
else:
thread.interrupt_main()
thread.start_new_thread(wait, (secs,))
try:
alarm(timeout_secs)
exec code in context
signal_finished = True
except KeyboardInterrupt:
raise SafeEvalTimeoutException(timeout_secs)
def safe_eval(code, context = {}, timeout_secs = 5):
"""
Validate source code and make sure it contains no unauthorized
expression/statements as configured via 'unallowed_ast_nodes' and
'unallowed_builtins'. By default this means that code is not
allowed import modules or access dangerous builtins like 'open' or
'eval'. If code is considered 'safe' it will be executed via
'exec' using 'context' as the global environment. More details on
how code is executed can be found in the Python Reference Manual
section 6.14 (ignore the remark on '__builtins__'). The 'context'
enviroment is also validated and is not allowed to contain modules
or builtins. The following exception will be raised on errors:
if 'context' contains unallowed objects =
SafeEvalContextException
if code is didn't validate and is considered 'unsafe' =
SafeEvalCodeException
if code did not execute within the given timelimit =
SafeEvalTimeoutException
"""
ctx_errkeys, ctx_errors = [], []
for (key, obj) in context.items():
if inspect.isbuiltin(obj):
ctx_errkeys.append(key)
ctx_errors.append("key '%s' : unallowed builtin %s" % (key, obj))
if inspect.ismodule(obj):
ctx_errkeys.append(key)
ctx_errors.append("key '%s' : unallowed module %s" % (key, obj))
if ctx_errors:
raise SafeEvalContextException(ctx_errkeys, ctx_errors)
ast = compiler.parse(code)
checker = SafeEvalVisitor()
if checker.walk(ast):
exec_timed(code, context, timeout_secs)
else:
raise SafeEvalCodeException(code, checker.errors)
#----------------------------------------------------------------------
# Basic tests.
#----------------------------------------------------------------------
import unittest
class TestSafeEval(unittest.TestCase):
def test_builtin(self):
# attempt to access a unsafe builtin
self.assertRaises(SafeEvalException,
safe_eval, "open('test.txt', 'w')")
def test_getattr(self):
# attempt to get arround direct attr access
self.assertRaises(SafeEvalException, \
safe_eval, "getattr(int, '__abs__')")
def test_func_globals(self):
# attempt to access global enviroment where fun was defined
self.assertRaises(SafeEvalException, \
safe_eval, "def x(): pass; print x.func_globals")
def test_lowlevel(self):
# lowlevel tricks to access 'object'
self.assertRaises(SafeEvalException, \
safe_eval, "().__class__.mro()[1].__subclasses__()")
def test_timeout_ok(self):
# attempt to exectute 'slow' code which finishes within timelimit
def test(): time.sleep(2)
env = {'test':test}
safe_eval("test()", env, timeout_secs = 5)
def test_timeout_exceed(self):
# attempt to exectute code which never teminates
self.assertRaises(SafeEvalException, \
safe_eval, "while 1: pass")
def test_invalid_context(self):
# can't pass an enviroment with modules or builtins
env = {'f' : __builtins__.open, 'g' : time}
self.assertRaises(SafeEvalException, \
safe_eval, "print 1", env)
def test_callback(self):
# modify local variable via callback
self.value = 0
def test(): self.value = 1
env = {'test':test}
safe_eval("test()", env)
self.assertEqual(self.value, 1)
if __name__ == "__main__":
unittest.main()
#----------------------------------------------------------------------
# The End.
#----------------------------------------------------------------------
|
Introducing "eval" into the picture is not for the faint of heart and is unusable as a frontend for end-user targeted scripting due to __builtins__. This module implements a restricted enviroment which makes "eval" somewhat secure albeit for a subset for the Python language, which is perfectly fine for configuration scripts etc.
By default the following restrictions are imposed:
- importing modules is disabled
- unsafe builtins are disabled
- timeout limit ('while 1:pass' can't block forever)
- getattr, setattr, delattr are disabled
- lowlevel attributes like __subclasses__ are disabled
- enviroment passed to 'eval' can't contain modules or builtins
- no exception handling is allowed
None of these restrictions should have any effect on the kind of code you need for storing data or doing basic scripting.
The implementation is quite simple, we inspect the abstract syntax tree (AST) and make sure that the code doesn't try to access dangerous builtins/attributes or execute unsage statements like importing modules.
thread.join? I can't comment on the safety mechanism, but your exec_timed might be more responsive for short evaluations if you use thread.join(timeout) instead of a sleep-loop with a one-second interval. One second can be a looong wait sometimes. :-) You would still need to check "signal_finished" or something like it, since the timeout will not throw an exception (you can't differentiate between a normal thread-death and a timeout).
The timeout mechanism has no effect if eval finishes within the timelimit and I think the 1 second granularity for the timout is pretty reasonable. By checking the "signal_finished" flag every second I make sure that the "alarm" thread doesn't stick around long efter were done with "eval".
right. Sorry, I read your code backwards; now I see what you're doing here.
Assert error. If you try to import this as a module (using 2.4) an assertion error is raised:
File "safeeval.py", line 121, in ? assert(is_valid_builtin(name)) AssertionError
It works fine when run alone with the unit tests. Why this happens is beyond me, even after a few minutes looking at the code.
Assert error. The current recipe use __builtins__, whose value is different when the module is imported. This is an old warth in Python. To get consistent behaviour, the recipe should use "__builtin__" instead, with an "import __builtin__" at the beginning.
Possible DOS: large multiplication. There is still some possible DOS even with this versione of safe_eval. For instance, try:
You will still need a manual CTRL+C to break. I think this is related to the fact that the Python interpreter does not release the GIL during large multiplications, so the alarm thread does not get its chance to break in. Not sure about possible solutions...
why restrict raise?, etc. It's not clear to me why you ban raise statements.
Also, I assume you restrict try/except and try/finally to prevent the code from catching the KeyboardInterrupt raised by the monitor thread. If I don't care about the timeout functionality is there any danger in allowing try/except/finally blocks? For example, looks like you block access to traceback attributes -- are there other dangerous things you can access through the exception object?
Would a solution be to also filter out large numbers? I guess you only need to worry about multiplication, exponentiation, and maybe division.
You could at least remove obvious large arguments to these operators. I'm not sure how you would protect against 2222222*2....
No - what about the Ackermann function?
imports? Any ideas on how to safely allow at least some imports such as random, and re?