def visitGetattr(self, node, *args): "Disallow any attempts to access a restricted attribute." name = node.attrname lineno = Helpers.get_node_lineno(node) if is_unallowed_attr(name): self.errors.append(SafeEvalAttrError( \ "access to attribute '%s' is denied" % name, lineno))
def visit(self, node, *args): "Recursively validate node and all of its children." fn = getattr(self, 'visit' + Helpers.classname(node)) if Helpers.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 = Helpers.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 trace(self, node): "Debugging utility for tracing the validation of AST nodes." print Helpers.classname(node) for attr in dir(node): if attr[:2] != '__': print ' ' * 4, "%-15.15s" % attr, getattr(node, attr)
def fail(self, node, *args): "Default callback for unallowed AST nodes." lineno = Helpers.get_node_lineno(node) self.errors.append(SafeEvalASTNodeError( \ "execution of '%s' statements is denied" % Helpers.classname(node), lineno))
# '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(Helpers.is_valid_ast_node(ast_name)) for name in unallowed_builtins: assert( (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. #----------------------------------------------------------------------