Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame] | 1 | Sandbox |
| 2 | ======= |
| 3 | |
| 4 | The Jinja2 sandbox can be used to evaluate untrusted code. Access to unsafe |
| 5 | attributes and methods is prohibited. |
| 6 | |
| 7 | Assuming `env` is a :class:`SandboxedEnvironment` in the default configuration |
| 8 | the following piece of code shows how it works: |
| 9 | |
| 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. |
| 16 | |
| 17 | |
| 18 | .. module:: jinja2.sandbox |
| 19 | |
| 20 | .. autoclass:: SandboxedEnvironment([options]) |
| 21 | :members: is_safe_attribute, is_safe_callable |
| 22 | |
Armin Ronacher | 522cad6 | 2008-05-17 13:55:37 +0200 | [diff] [blame] | 23 | .. autoclass:: ImmutableSandboxedEnvironment([options]) |
| 24 | |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame] | 25 | .. autoexception:: SecurityError |
| 26 | |
| 27 | .. autofunction:: unsafe |
| 28 | |
| 29 | .. autofunction:: is_internal_attribute |
Armin Ronacher | 522cad6 | 2008-05-17 13:55:37 +0200 | [diff] [blame] | 30 | |
Armin Ronacher | d71fff0 | 2008-05-26 23:57:07 +0200 | [diff] [blame] | 31 | .. autofunction:: modifies_known_mutable |
Armin Ronacher | 9bb7e47 | 2008-05-28 11:26:59 +0200 | [diff] [blame] | 32 | |
| 33 | .. admonition:: Note |
| 34 | |
| 35 | The Jinja2 sandbox alone is no solution for perfect security. Especially |
| 36 | for web applications you have to keep in mind that users may create |
| 37 | templates with arbitrary HTML in so it's crucial to ensure that (if you |
| 38 | are running multiple users on the same server) they can't harm each other |
| 39 | via JavaScript insertions and much more. |
| 40 | |
| 41 | Also the sandbox is only as good as the configuration. We stronly |
| 42 | recommend only passing non-shared resources to the template and use |
| 43 | some sort of whitelisting for attributes. |
| 44 | |
| 45 | Also keep in mind that templates may raise runtime or compile time errors, |
| 46 | so make sure to catch them. |