Toggle navigation

Sandbox

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

Assuming [UNKNOWN NODE title_reference] is a SandboxedEnvironment in the default configuration the following piece of code shows how it works:

[UNKNOWN NODE doctest_block]

API

class jinja2.sandbox.SandboxedEnvironment([options])

The sandboxed environment. It works like the regular environment but tells the compiler to generate sandboxed code. Additionally subclasses of this environment may override the methods that tell the runtime what attributes or functions are safe to access.

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

call_binop(context, operator, left, right)

For intercepted binary operator calls (intercepted_binops()) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators.

New in version 2.6.

call_unop(context, operator, arg)

For intercepted unary operator calls (intercepted_unops()) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators.

New in version 2.6.

default_binop_table = {'%': <built-in function mod>, '*': <built-in function mul>, '**': <built-in function pow>, '+': <built-in function add>, '-': <built-in function sub>, '/': <built-in function truediv>, '//': <built-in function floordiv>}

default callback table for the binary operators. A copy of this is available on each instance of a sandboxed environment as binop_table

default_unop_table = {'+': <built-in function pos>, '-': <built-in function neg>}

default callback table for the unary operators. A copy of this is available on each instance of a sandboxed environment as unop_table

intercepted_binops = frozenset([])

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

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

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

New in version 2.6.

intercepted_unops = frozenset([])

a set of unary operators that should be intercepted. Each operator that is added to this set (empty by default) is delegated to the call_unop() method that will perform the operator. The default operator callback is specified by unop_table.

The following unary operators are interceptable: +, -

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

New in version 2.6.

is_safe_attribute(obj, attr, value)

The sandboxed environment will call this method to check if the attribute of an object is safe to access. Per default all attributes starting with an underscore are considered private as well as the special attributes of internal python objects as returned by the is_internal_attribute() function.

is_safe_callable(obj)

Check if an object is safely callable. Per default a function is considered safe unless the [UNKNOWN NODE title_reference] attribute exists and is True. Override this method to alter the behavior, but this won’t affect the [UNKNOWN NODE title_reference] decorator from this module.

class jinja2.sandbox.ImmutableSandboxedEnvironment([options])

Works exactly like the regular [UNKNOWN NODE title_reference] but does not permit modifications on the builtin mutable objects [UNKNOWN NODE title_reference], [UNKNOWN NODE title_reference], and [UNKNOWN NODE title_reference] by using the modifies_known_mutable() function.

exception jinja2.sandbox.SecurityError(message=None)

Raised if a template tries to do something insecure if the sandbox is enabled.

jinja2.sandbox.unsafe(f)

Marks a function or method as unsafe.

@unsafe
def delete(self):
    pass
jinja2.sandbox.is_internal_attribute(obj, attr)

Test if the attribute given is an internal python attribute. For example this function returns [UNKNOWN NODE title_reference] for the [UNKNOWN NODE title_reference] attribute of python objects. This is useful if the environment method is_safe_attribute() is overridden.

[UNKNOWN NODE doctest_block]
jinja2.sandbox.modifies_known_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 supports the “user”-versions of the objects ([UNKNOWN NODE title_reference], [UNKNOWN NODE title_reference] etc.) and with Python 2.6 onwards the abstract base classes [UNKNOWN NODE title_reference], [UNKNOWN NODE title_reference], and [UNKNOWN NODE title_reference].

[UNKNOWN NODE doctest_block]

If called with an unsupported object (such as unicode) [UNKNOWN NODE title_reference] is returned.

[UNKNOWN NODE doctest_block]

Operator Intercepting

New in version 2.6.

For maximum performance Jinja2 will let operators call directly the type specific callback methods. This means that it’s not possible to have this intercepted by overriding Environment.call(). Furthermore a conversion from operator to special method is not always directly possible due to how operators work. For instance for divisions more than one special 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 order to intercept an operator one has to override the SandboxedEnvironment.intercepted_binops attribute. Once the operator that needs to be intercepted is added to that set Jinja2 will generate bytecode that calls the SandboxedEnvironment.call_binop() function. For unary operators the [UNKNOWN NODE title_reference] attributes and methods have to be used instead.

The default implementation of SandboxedEnvironment.call_binop will use the SandboxedEnvironment.binop_table to translate operator symbols into callbacks performing the default operator behavior.

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

from jinja2.sandbox import SandboxedEnvironment


class MyEnvironment(SandboxedEnvironment):
    intercepted_binops = frozenset(['**'])

    def call_binop(self, context, operator, left, right):
        if operator == '**':
            return self.undefined('the power operator is unavailable')
        return SandboxedEnvironment.call_binop(self, context,
                                               operator, left, right)

Make sure to always call into the super method, even if you are not intercepting the call. Jinja2 might internally call the method to evaluate expressions.