Merge pull request #1616 from pallets/docs-sandbox
Before adoption: this commit came in with the history the project adopted, so no landing records it.
rewrite sandbox docs, add more security discussion
authored by David Lord · committed by GitHub · parents 186aa82, 165e972 · 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
Provenance
- Commit
350bc53- Tree
33773fa- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
186aa82- Parent 2
165e972
1 file changed+71 added−54 removed
modified:docs/sandbox.rst+71 added-54 removed
1 Sandbox2 =======3 4-The Jinja sandbox can be used to evaluate untrusted code. Access to unsafe5-attributes and methods is prohibited.4+The Jinja sandbox can be used to render untrusted templates. Access to5+attributes, method calls, operators, mutating data structures, and6+string formatting can be intercepted and prohibited.7 7-Assuming `env` is a :class:`SandboxedEnvironment` in the default configuration8-the following piece of code shows how it works:8+.. code-block:: pycon9 10+ >>> from jinja2.sandbox import SandboxedEnvironment11+ >>> env = SandboxedEnvironment()12+ >>> func = lambda: "Hello, Sandbox!"10->>> env.from_string("{{ func.func_code }}").render(func=lambda:None)11-u''12->>> env.from_string("{{ func.func_code.do_something }}").render(func=lambda:None)13-Traceback (most recent call last):14- ...15-SecurityError: 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.19 20+A sandboxed environment can be useful, for example, to allow users of an21+internal reporting system to create custom emails. You would document22+what data is available in the templates, then the user would write a23+template using that information. Your code would generate the report24+data and pass it to the user's sandboxed template to render.25+26+27+Security Considerations28+-----------------------29+30+The sandbox alone is not a solution for perfect security. Keep these31+things in mind when using the sandbox.32+33+Templates can still raise errors when compiled or rendered. Your code34+should attempt to catch errors instead of crashing.35+36+It is possible to construct a relatively small template that renders to37+a very large amount of output, which could correspond to a high use of38+CPU or memory. You should run your application with limits on resources39+such as CPU and memory to mitigate this.40+41+Jinja only renders text, it does not understand, for example, JavaScript42+code. Depending on how the rendered template will be used, you may need43+to do other postprocessing to restrict the output.44+45+Pass only the data that is relevant to the template. Avoid passing46+global data, or objects with methods that have side effects. By default47+the sandbox prevents private and internal attribute access. You can48+override :meth:`~SandboxedEnvironment.is_safe_attribute` to further49+restrict attributes access. Decorate methods with :func:`unsafe` to50+prevent calling them from templates when passing objects as data. Use51+:class:`ImmutableSandboxedEnvironment` to prevent modifying lists and52+dictionaries.53+54+55 API56 ---57 58 .. module:: jinja2.sandbox12 unmodified lines71 .. autofunction:: is_internal_attribute72 73 .. autofunction:: modifies_known_mutable74 37-.. admonition:: Note75 39- 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.44-45- 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.48-49- Also keep in mind that templates may raise runtime or compile time errors,50- so make sure to catch them.51-76 Operator Intercepting77 ---------------------78 55-.. versionadded:: 2.679+For performance, Jinja outputs operators directly when compiling. This80+means it's not possible to intercept operator behavior by overriding81+:meth:`SandboxEnvironment.call <Environment.call>` by default, because82+operator special methods are handled by the Python interpreter, and83+might not correspond with exactly one method depending on the operator's84+use.85 57-For maximum performance Jinja will let operators call directly the type58-specific callback methods. This means that it's not possible to have this59-intercepted by overriding :meth:`Environment.call`. Furthermore a60-conversion from operator to special method is not always directly possible61-due to how operators work. For instance for divisions more than one62-special method exist.86+The sandbox can instruct the compiler to output a function to intercept87+certain operators instead. Override88+:attr:`SandboxedEnvironment.intercepted_binops` and89+:attr:`SandboxedEnvironment.intercepted_unops` with the operator symbols90+you want to intercept. The compiler will replace the symbols with calls91+to :meth:`SandboxedEnvironment.call_binop` and92+:meth:`SandboxedEnvironment.call_unop` instead. The default93+implementation of those methods will use94+:attr:`SandboxedEnvironment.binop_table` and95+:attr:`SandboxedEnvironment.unop_table` to translate operator symbols96+into :mod:`operator` functions.97 64-With Jinja 2.6 there is now support for explicit operator intercepting.65-This can be used to customize specific operators as necessary. In order66-to intercept an operator one has to override the67-:attr:`SandboxedEnvironment.intercepted_binops` attribute. Once the68-operator that needs to be intercepted is added to that set Jinja will69-generate bytecode that calls the :meth:`SandboxedEnvironment.call_binop`70-function. For unary operators the `unary` attributes and methods have to71-be used instead.98+For example, the power (``**``) operator can be disabled:99 73-The default implementation of :attr:`SandboxedEnvironment.call_binop`74-will use the :attr:`SandboxedEnvironment.binop_table` to translate75-operator symbols into callbacks performing the default operator behavior.100+.. code-block:: python101 77-This example shows how the power (``**``) operator can be disabled in78-Jinja::79-102 from jinja2.sandbox import SandboxedEnvironment103 82-104 class MyEnvironment(SandboxedEnvironment):84- intercepted_binops = frozenset(['**'])105+ intercepted_binops = frozenset(["**"])106 107 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.")110 92-Make sure to always call into the super method, even if you are not93-intercepting the call. Jinja might internally call the method to94-evaluate expressions.111+ return super().call_binop(self, context, operator, left, right)