Implemented operator intercepting
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent b6b3c99 · Browse files · 5 files·+161 added−13 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+161 added−13 removed
- other:+161 added−13 removed
Provenance
- Commit
a919538- Tree
ecaca9b- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
b6b3c99
5 files changed+161 added−13 removed
modified:jinja2/testsuite/security.py+36 added-1 removed
14 unmodified lines15 from jinja2 import Environment16 from jinja2.sandbox import SandboxedEnvironment, \17 ImmutableSandboxedEnvironment, unsafe18 from jinja2 import Markup, escape19-from jinja2.exceptions import SecurityError, TemplateSyntaxError19+from jinja2.exceptions import SecurityError, TemplateSyntaxError, \20+ TemplateRuntimeError21 22 23 class PrivateStuff(object):24 98 unmodified lines123 env = SandboxedEnvironment()124 tmpl = env.from_string('{{ cls|attr("__subclasses__")() }}')125 self.assert_raises(SecurityError, tmpl.render, cls=int)126 127+ def test_binary_operator_intercepting(self):128+ def disable_op(left, right):129+ raise TemplateRuntimeError('that operator so does not work')130+ for expr, ctx, rv in ('1 + 2', {}, '3'), ('a + 2', {'a': 2}, '4'):131+ env = SandboxedEnvironment()132+ env.binop_table['+'] = disable_op133+ t = env.from_string('{{ %s }}' % expr)134+ assert t.render(ctx) == rv135+ env.intercepted_binops = frozenset(['+'])136+ t = env.from_string('{{ %s }}' % expr)137+ try:138+ t.render(ctx)139+ except TemplateRuntimeError, e:140+ pass141+ else:142+ self.fail('expected runtime error')143 144+ def test_unary_operator_intercepting(self):145+ def disable_op(arg):146+ raise TemplateRuntimeError('that operator so does not work')147+ for expr, ctx, rv in ('-1', {}, '-1'), ('-a', {'a': 2}, '-2'):148+ env = SandboxedEnvironment()149+ env.unop_table['-'] = disable_op150+ t = env.from_string('{{ %s }}' % expr)151+ assert t.render(ctx) == rv152+ env.intercepted_unops = frozenset(['-'])153+ t = env.from_string('{{ %s }}' % expr)154+ try:155+ t.render(ctx)156+ except TemplateRuntimeError, e:157+ pass158+ else:159+ self.fail('expected runtime error')160+161+162 def suite():163 suite = unittest.TestSuite()164 suite.addTest(unittest.makeSuite(SandboxTestCase))165 return suitemodified:jinja2/compiler.py+23 added-11 removed
1419 unmodified lines1420 self.write(': ')1421 self.visit(item.value, frame)1422 self.write('}')1423 1424- def binop(operator):1424+ def binop(operator, interceptable=True):1425 def visitor(self, node, frame):1426+ if self.environment.sandboxed and \1427+ operator in self.environment.intercepted_binops:1428+ self.write('environment.call_binop(context, %r, ' % operator)1429+ self.visit(node.left, frame)1430+ self.write(', ')1431+ self.visit(node.right, frame)1432+ else:1426- self.write('(')1427- self.visit(node.left, frame)1428- self.write(' %s ' % operator)1429- self.visit(node.right, frame)1433+ self.write('(')1434+ self.visit(node.left, frame)1435+ self.write(' %s ' % operator)1436+ self.visit(node.right, frame)1437 self.write(')')1438 return visitor1439 1433- def uaop(operator):1440+ def uaop(operator, interceptable=True):1441 def visitor(self, node, frame):1442+ if self.environment.sandboxed and \1443+ operator in self.environment.intercepted_unops:1444+ self.write('environment.call_unop(context, %r, ' % operator)1445+ self.visit(node.node, frame)1446+ else:1435- self.write('(' + operator)1436- self.visit(node.node, frame)1447+ self.write('(' + operator)1448+ self.visit(node.node, frame)1449 self.write(')')1450 return visitor1451 1452 visit_Add = binop('+')2 unmodified lines1455 visit_Div = binop('/')1456 visit_FloorDiv = binop('//')1457 visit_Pow = binop('**')1458 visit_Mod = binop('%')1447- visit_And = binop('and')1448- visit_Or = binop('or')1459+ visit_And = binop('and', interceptable=False)1460+ visit_Or = binop('or', interceptable=False)1461 visit_Pos = uaop('+')1462 visit_Neg = uaop('-')1451- visit_Not = uaop('not ')1463+ visit_Not = uaop('not ', interceptable=False)1464 del binop, uaop1465 1466 def visit_Concat(self, node, frame):1467 if frame.eval_ctx.volatile:185 unmodified linesmodified:jinja2/nodes.py+8 added
370 unmodified lines371 abstract = True372 373 def as_const(self, eval_ctx=None):374 eval_ctx = get_eval_context(self, eval_ctx)375+ # intercepted operators cannot be folded at compile time376+ if self.environment.sandboxed and \377+ self.operator in self.environment.intercepted_binops:378+ raise Impossible()379 f = _binop_to_func[self.operator]380 try:381 return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))382 except Exception:7 unmodified lines390 abstract = True391 392 def as_const(self, eval_ctx=None):393 eval_ctx = get_eval_context(self, eval_ctx)394+ # intercepted operators cannot be folded at compile time395+ if self.environment.sandboxed and \396+ self.operator in self.environment.intercepted_unops:397+ raise Impossible()398 f = _uaop_to_func[self.operator]399 try:400 return f(self.node.as_const(eval_ctx))401 except Exception:508 unmodified linesmodified:jinja2/sandbox.py+90 added-1 removed
11 unmodified lines12 :copyright: (c) 2010 by the Jinja Team.13 :license: BSD.14 """15 import operator16-from jinja2.runtime import Undefined16 from jinja2.environment import Environment17 from jinja2.exceptions import SecurityError18 from jinja2.utils import FunctionType, MethodType, TracebackType, CodeType, \19 FrameType, GeneratorType160 unmodified lines180 the caller has to ensure that all exceptions are catched.181 """182 sandboxed = True183 184+ #: default callback table for the binary operators. A copy of this is185+ #: available on each instance of a sandboxed environment as186+ #: :attr:`binop_table`187+ default_binop_table = {188+ '+': operator.add,189+ '-': operator.sub,190+ '*': operator.mul,191+ '/': operator.truediv,192+ '//': operator.floordiv,193+ '**': operator.pow,194+ '%': operator.mod195+ }196+197+ #: default callback table for the unary operators. A copy of this is198+ #: available on each instance of a sandboxed environment as199+ #: :attr:`unop_table`200+ default_unop_table = {201+ '+': operator.pos,202+ '-': operator.neg203+ }204+205+ #: a set of binary operators that should be intercepted. Each operator206+ #: that is added to this set (empty by default) is delegated to the207+ #: :meth:`call_binop` method that will perform the operator. The default208+ #: operator callback is specified by :attr:`binop_table`.209+ #:210+ #: The following binary operators are interceptable:211+ #: ``//``, ``%``, ``+``, ``*``, ``-``, ``/``, and ``**``212+ #:213+ #: The default operation form the operator table corresponds to the214+ #: builtin function. Intercepted calls are always slower than the native215+ #: operator call, so make sure only to intercept the ones you are216+ #: interested in.217+ #:218+ #: .. versionadded:: 2.6219+ intercepted_binops = frozenset()220+221+ #: a set of unary operators that should be intercepted. Each operator222+ #: that is added to this set (empty by default) is delegated to the223+ #: :meth:`call_unop` method that will perform the operator. The default224+ #: operator callback is specified by :attr:`unop_table`.225+ #:226+ #: The following unary operators are interceptable: ``+``, ``-``227+ #:228+ #: The default operation form the operator table corresponds to the229+ #: builtin function. Intercepted calls are always slower than the native230+ #: operator call, so make sure only to intercept the ones you are231+ #: interested in.232+ #:233+ #: .. versionadded:: 2.6234+ intercepted_unops = frozenset()235+236+ def intercept_unop(self, operator):237+ """Called during template compilation with the name of a unary238+ operator to check if it should be intercepted at runtime. If this239+ method returns `True`, :meth:`call_unop` is excuted for this unary240+ operator. The default implementation of :meth:`call_unop` will use241+ the :attr:`unop_table` dictionary to perform the operator with the242+ same logic as the builtin one.243+244+ The following unary operators are interceptable: ``+`` and ``-``245+246+ Intercepted calls are always slower than the native operator call,247+ so make sure only to intercept the ones you are interested in.248+249+ .. versionadded:: 2.6250+ """251+ return False252+253+254 def __init__(self, *args, **kwargs):255 Environment.__init__(self, *args, **kwargs)256 self.globals['range'] = safe_range257+ self.binop_table = self.default_binop_table.copy()258+ self.unop_table = self.default_unop_table.copy()259 260 def is_safe_attribute(self, obj, attr, value):261 """The sandboxed environment will call this method to check if the262 attribute of an object is safe to access. Per default all attributes11 unmodified lines274 """275 return not (getattr(obj, 'unsafe_callable', False) or276 getattr(obj, 'alters_data', False))277 278+ def call_binop(self, context, operator, left, right):279+ """For intercepted binary operator calls (:meth:`intercepted_binops`)280+ this function is executed instead of the builtin operator. This can281+ be used to fine tune the behavior of certain operators.282+283+ .. versionadded:: 2.6284+ """285+ return self.binop_table[operator](left, right)286+287+ def call_unop(self, context, operator, arg):288+ """For intercepted unary operator calls (:meth:`intercepted_unops`)289+ this function is executed instead of the builtin operator. This can290+ be used to fine tune the behavior of certain operators.291+292+ .. versionadded:: 2.6293+ """294+ return self.unop_table[operator](arg)295+296 def getitem(self, obj, argument):297 """Subscribe an object from sandboxed code."""298 try:299 return obj[argument]61 unmodified linesmodified:CHANGES+4 added
7 unmodified lines8 - internal attributes now raise an internal attribute error now instead9 of returning an undefined. This fixes problems when passing undefined10 objects to Python semantics expecting APIs.11 - traceback support now works properly for PyPy. (Tested with 1.4)12+- implemented operator intercepting for sandboxed environments. This13+ allows application developers to disable builtin operators for better14+ security. (For instance limit the mathematical operators to actual15+ integers instead of longs)16 17 Version 2.5.518 -------------19 (re-release of 2.5.4 with built documentation removed for filesize.229 unmodified lines