Sandbox

The Jinja2 sandbox can be used to evaluate untrusted code. Access to unsafeattributes and methods is prohibited.

Assuming env is a SandboxedEnvironment in the default configurationthe following piece of code shows how it works:

  1. >>> env.from_string("{{ func.func_code }}").render(func=lambda:None)
  2. u''
  3. >>> env.from_string("{{ func.func_code.do_something }}").render(func=lambda:None)
  4. Traceback (most recent call last):
  5. ...
  6. SecurityError: access to attribute 'func_code' of 'function' object is unsafe.

API

  • class jinja2.sandbox.SandboxedEnvironment([options])
  • The sandboxed environment. It works like the regular environment buttells the compiler to generate sandboxed code. Additionally subclasses ofthis environment may override the methods that tell the runtime whatattributes or functions are safe to access.

If the template tries to access insecure code a SecurityError israised. However also other exceptions may occur during the rendering sothe caller has to ensure that all exceptions are caught.

  • callbinop(_context, operator, left, right)
  • For intercepted binary operator calls (intercepted_binops())this function is executed instead of the builtin operator. This canbe used to fine tune the behavior of certain operators.

Changelog

New in version 2.6.

  • callunop(_context, operator, arg)
  • For intercepted unary operator calls (intercepted_unops())this function is executed instead of the builtin operator. This canbe used to fine tune the behavior of certain operators.

Changelog

New in version 2.6.

  • defaultbinop_table = {'%': , '': , '*': , '+': , '-': , '/': , '//': }_
  • default callback table for the binary operators. A copy of this isavailable on each instance of a sandboxed environment asbinop_table

  • defaultunop_table = {'+': , '-': }_

  • default callback table for the unary operators. A copy of this isavailable on each instance of a sandboxed environment asunop_table

  • interceptedbinops = frozenset({})_

  • a set of binary operators that should be intercepted. Each operatorthat is added to this set (empty by default) is delegated to thecall_binop() method that will perform the operator. The defaultoperator callback is specified by binop_table.

The following binary operators are interceptable://, %, +, , -, /, and *

The default operation form the operator table corresponds to thebuiltin function. Intercepted calls are always slower than the nativeoperator call, so make sure only to intercept the ones you areinterested in.

Changelog

New in version 2.6.

  • interceptedunops = frozenset({})_
  • a set of unary operators that should be intercepted. Each operatorthat is added to this set (empty by default) is delegated to thecall_unop() method that will perform the operator. The defaultoperator callback is specified by unop_table.

The following unary operators are interceptable: +, -

The default operation form the operator table corresponds to thebuiltin function. Intercepted calls are always slower than the nativeoperator call, so make sure only to intercept the ones you areinterested in.

Changelog

New in version 2.6.

  • issafe_attribute(_obj, attr, value)
  • The sandboxed environment will call this method to check if theattribute of an object is safe to access. Per default all attributesstarting with an underscore are considered private as well as thespecial attributes of internal python objects as returned by theis_internal_attribute() function.

  • issafe_callable(_obj)

  • Check if an object is safely callable. Per default a function isconsidered safe unless the unsafe_callable attribute exists and isTrue. Override this method to alter the behavior, but this won’taffect the unsafe decorator from this module.

  • class jinja2.sandbox.ImmutableSandboxedEnvironment([options])
  • Works exactly like the regular SandboxedEnvironment but does notpermit modifications on the builtin mutable objects list, set, anddict by using the modifies_known_mutable() function.
  • exception jinja2.sandbox.SecurityError(message=None)
  • Raised if a template tries to do something insecure if thesandbox is enabled.
  • jinja2.sandbox.unsafe(f)
  • Marks a function or method as unsafe.
  1. @unsafe
  2. def delete(self):
  3. pass
  • jinja2.sandbox.isinternal_attribute(_obj, attr)
  • Test if the attribute given is an internal python attribute. Forexample this function returns True for the func_code attribute ofpython objects. This is useful if the environment methodis_safe_attribute() is overridden.
  1. >>> from jinja2.sandbox import is_internal_attribute
  2. >>> is_internal_attribute(str, "mro")
  3. True
  4. >>> is_internal_attribute(str, "upper")
  5. False
  • jinja2.sandbox.modifiesknown_mutable(_obj, attr)
  • This function checks if an attribute on a builtin mutable object(list, dict, set or deque) would modify it if called. It also supportsthe “user”-versions of the objects (sets.Set, UserDict.* etc.) andwith Python 2.6 onwards the abstract base classes MutableSet,MutableMapping, and MutableSequence.
  1. >>> modifies_known_mutable({}, "clear")
  2. True
  3. >>> modifies_known_mutable({}, "keys")
  4. False
  5. >>> modifies_known_mutable([], "append")
  6. True
  7. >>> modifies_known_mutable([], "index")
  8. False

If called with an unsupported object (such as unicode) False isreturned.

  1. >>> modifies_known_mutable("foo", "upper")
  2. False

Note

The Jinja2 sandbox alone is no solution for perfect security. Especiallyfor web applications you have to keep in mind that users may createtemplates with arbitrary HTML in so it’s crucial to ensure that (if youare running multiple users on the same server) they can’t harm each othervia JavaScript insertions and much more.

Also the sandbox is only as good as the configuration. We stronglyrecommend only passing non-shared resources to the template and usesome sort of whitelisting for attributes.

Also keep in mind that templates may raise runtime or compile time errors,so make sure to catch them.

Operator Intercepting

Changelog

New in version 2.6.

For maximum performance Jinja2 will let operators call directly the typespecific callback methods. This means that it’s not possible to have thisintercepted by overriding Environment.call(). Furthermore aconversion from operator to special method is not always directly possibledue to how operators work. For instance for divisions more than onespecial method exist.

With Jinja 2.6 there is now support for explicit operator intercepting.This can be used to customize specific operators as necessary. In orderto intercept an operator one has to override theSandboxedEnvironment.intercepted_binops attribute. Once theoperator that needs to be intercepted is added to that set Jinja2 willgenerate bytecode that calls the SandboxedEnvironment.call_binop()function. For unary operators the unary attributes and methods have tobe used instead.

The default implementation of SandboxedEnvironment.call_binopwill use the SandboxedEnvironment.binop_table to translateoperator symbols into callbacks performing the default operator behavior.

This example shows how the power (**) operator can be disabled inJinja2:

  1. from jinja2.sandbox import SandboxedEnvironment
  2. class MyEnvironment(SandboxedEnvironment):
  3. intercepted_binops = frozenset(['**'])
  4. def call_binop(self, context, operator, left, right):
  5. if operator == '**':
  6. return self.undefined('the power operator is unavailable')
  7. return SandboxedEnvironment.call_binop(self, context,
  8. operator, left, right)

Make sure to always call into the super method, even if you are notintercepting the call. Jinja2 might internally call the method toevaluate expressions.