Skip to content
Myr

rewrite sandbox docs, add more security discussion

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parent 186aa82 · Browse files · 1 file+71 added−54 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+71 added−54 removed

  • other:+71 added−54 removed

1 file+71 added−54 removed

modified:docs/sandbox.rst+71 added-54 removed
1Sandbox2=======34The Jinja sandbox can be used to evaluate untrusted code. Access to unsafe5attributes and methods is prohibited.4The Jinja sandbox can be used to render untrusted templates. Access to5attributes, method calls, operators, mutating data structures, and6string formatting can be intercepted and prohibited.77Assuming `env` is a :class:`SandboxedEnvironment` in the default configuration8the following piece of code shows how it works:8.. code-block:: pycon910 >>> from jinja2.sandbox import SandboxedEnvironment11 >>> env = SandboxedEnvironment()12 >>> func = lambda: "Hello, Sandbox!"10>>> env.from_string("{{ func.func_code }}").render(func=lambda:None)11u''12>>> env.from_string("{{ func.func_code.do_something }}").render(func=lambda:None)13Traceback (most recent call last):14 ...15SecurityError: access to attribute 'func_code' of 'function' object is unsafe.13 >>> env.from_string("{{ func() }}").render(func=func)14 'Hello, Sandbox!'15 >>> env.from_string("{{ func.__code__.co_code }}").render(func=func)16 Traceback (most recent call last):17 ...18 SecurityError: access to attribute '__code__' of 'function' object is unsafe.1920A sandboxed environment can be useful, for example, to allow users of an21internal reporting system to create custom emails. You would document22what data is available in the templates, then the user would write a23template using that information. Your code would generate the report24data and pass it to the user's sandboxed template to render.252627Security Considerations28-----------------------2930The sandbox alone is not a solution for perfect security. Keep these31things in mind when using the sandbox.3233Templates can still raise errors when compiled or rendered. Your code34should attempt to catch errors instead of crashing.3536It is possible to construct a relatively small template that renders to37a very large amount of output, which could correspond to a high use of38CPU or memory. You should run your application with limits on resources39such as CPU and memory to mitigate this.4041Jinja only renders text, it does not understand, for example, JavaScript42code. Depending on how the rendered template will be used, you may need43to do other postprocessing to restrict the output.4445Pass only the data that is relevant to the template. Avoid passing46global data, or objects with methods that have side effects. By default47the sandbox prevents private and internal attribute access. You can48override :meth:`~SandboxedEnvironment.is_safe_attribute` to further49restrict attributes access. Decorate methods with :func:`unsafe` to50prevent calling them from templates when passing objects as data. Use51:class:`ImmutableSandboxedEnvironment` to prevent modifying lists and52dictionaries.535455API56---5758.. module:: jinja2.sandbox
12 unmodified lines
71.. autofunction:: is_internal_attribute7273.. autofunction:: modifies_known_mutable7437.. admonition:: Note7539 The Jinja sandbox alone is no solution for perfect security. Especially40 for web applications you have to keep in mind that users may create41 templates with arbitrary HTML in so it's crucial to ensure that (if you42 are running multiple users on the same server) they can't harm each other43 via JavaScript insertions and much more.4445 Also the sandbox is only as good as the configuration. We strongly46 recommend only passing non-shared resources to the template and use47 some sort of whitelisting for attributes.4849 Also keep in mind that templates may raise runtime or compile time errors,50 so make sure to catch them.5176Operator Intercepting77---------------------7855.. versionadded:: 2.679For performance, Jinja outputs operators directly when compiling. This80means it's not possible to intercept operator behavior by overriding81:meth:`SandboxEnvironment.call <Environment.call>` by default, because82operator special methods are handled by the Python interpreter, and83might not correspond with exactly one method depending on the operator's84use.8557For maximum performance Jinja will let operators call directly the type58specific callback methods. This means that it's not possible to have this59intercepted by overriding :meth:`Environment.call`. Furthermore a60conversion from operator to special method is not always directly possible61due to how operators work. For instance for divisions more than one62special method exist.86The sandbox can instruct the compiler to output a function to intercept87certain operators instead. Override88:attr:`SandboxedEnvironment.intercepted_binops` and89:attr:`SandboxedEnvironment.intercepted_unops` with the operator symbols90you want to intercept. The compiler will replace the symbols with calls91to :meth:`SandboxedEnvironment.call_binop` and92:meth:`SandboxedEnvironment.call_unop` instead. The default93implementation of those methods will use94:attr:`SandboxedEnvironment.binop_table` and95:attr:`SandboxedEnvironment.unop_table` to translate operator symbols96into :mod:`operator` functions.9764With Jinja 2.6 there is now support for explicit operator intercepting.65This can be used to customize specific operators as necessary. In order66to intercept an operator one has to override the67:attr:`SandboxedEnvironment.intercepted_binops` attribute. Once the68operator that needs to be intercepted is added to that set Jinja will69generate bytecode that calls the :meth:`SandboxedEnvironment.call_binop`70function. For unary operators the `unary` attributes and methods have to71be used instead.98For example, the power (``**``) operator can be disabled:9973The default implementation of :attr:`SandboxedEnvironment.call_binop`74will use the :attr:`SandboxedEnvironment.binop_table` to translate75operator symbols into callbacks performing the default operator behavior.100.. code-block:: python10177This example shows how the power (``**``) operator can be disabled in78Jinja::79102 from jinja2.sandbox import SandboxedEnvironment10382104 class MyEnvironment(SandboxedEnvironment):84 intercepted_binops = frozenset(['**'])105 intercepted_binops = frozenset(["**"])106107 def call_binop(self, context, operator, left, right):87 if operator == '**':88 return self.undefined('the power operator is unavailable')89 return SandboxedEnvironment.call_binop(self, context,90 operator, left, right)108 if operator == "**":109 return self.undefined("The power (**) operator is unavailable.")11092Make sure to always call into the super method, even if you are not93intercepting the call. Jinja might internally call the method to94evaluate expressions.111 return super().call_binop(self, context, operator, left, right)