Skip to content
Myr

SECURITY: support sandboxing in format expressions

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

authored by Armin Ronacher · committed by Armin Ronacher · parent 8189d21 · Browse files · 3 files+143 added−5 removed
This commit

State

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

Diff stats

3 files+143 added−5 removed

  • tests:+26 added−1 removed
  • other:+117 added−4 removed

3 files+143 added−5 removed

modified:jinja2/nodes.py+1 added-1 removed
602 unmodified lines
603 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')604605 def as_const(self, eval_ctx=None):606 eval_ctx = get_eval_context(self, eval_ctx)607 if eval_ctx.volatile:607 if eval_ctx.volatile or eval_ctx.environment.sandboxed:608 raise Impossible()609 obj = self.node.as_const(eval_ctx)610611 # don't evaluate context functions
308 unmodified lines
modified:jinja2/sandbox.py+116 added-3 removed
12 unmodified lines
13 :license: BSD.14"""15import types16import operator17from collections import Mapping18from jinja2.environment import Environment19from jinja2.exceptions import SecurityError19from jinja2._compat import string_types, PY220from jinja2._compat import string_types, text_type, PY221from jinja2.utils import Markup2223has_format = False24if hasattr(text_type, 'format'):25 from markupsafe import EscapeFormatter26 from string import Formatter27 has_format = True282930#: maximum number of items a range may produce31MAX_RANGE = 1000003233#: attributes of function objects that are considered unsafe.
11 unmodified lines
4546#: unsafe generator attirbutes.47UNSAFE_GENERATOR_ATTRIBUTES = set(['gi_frame', 'gi_code'])4849#: unsafe attributes on coroutines50UNSAFE_COROUTINE_ATTRIBUTES = set(['cr_frame', 'cr_code'])5152#: unsafe attributes on async generators53UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = set(['ag_code', 'ag_frame'])5455import warnings5657# make sure we don't warn in python 2.6 about stuff we don't care about58warnings.filterwarnings('ignore', 'the sets module', DeprecationWarning,
48 unmodified lines
107 ]))108)109110111class _MagicFormatMapping(Mapping):112 """This class implements a dummy wrapper to fix a bug in the Python113 standard library for string formatting.114115 See http://bugs.python.org/issue13598 for information about why116 this is necessary.117 """118119 def __init__(self, args, kwargs):120 self._args = args121 self._kwargs = kwargs122 self._last_index = 0123124 def __getitem__(self, key):125 if key == '':126 idx = self._last_index127 self._last_index += 1128 try:129 return self._args[idx]130 except LookupError:131 pass132 key = str(idx)133 return self._kwargs[key]134135 def __iter__(self):136 return iter(self._kwargs)137138 def __len__(self):139 return len(self._kwargs)140141142def inspect_format_method(callable):143 if not has_format:144 return None145 if not isinstance(callable, (types.MethodType,146 types.BuiltinMethodType)) or \147 callable.__name__ != 'format':148 return None149 obj = callable.__self__150 if isinstance(obj, string_types):151 return obj152153154def safe_range(*args):155 """A range that can't generate ranges with a length of more than156 MAX_RANGE items.157 """
43 unmodified lines
201 return True202 elif isinstance(obj, types.GeneratorType):203 if attr in UNSAFE_GENERATOR_ATTRIBUTES:204 return True205 elif hasattr(types, 'CoroutineType') and isinstance(obj, types.CoroutineType):206 if attr in UNSAFE_COROUTINE_ATTRIBUTES:207 return True208 elif hasattr(types, 'AsyncGeneratorType') and isinstance(obj, types.AsyncGeneratorType):209 if attri in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:210 return True211 return attr.startswith('__')212213214def modifies_known_mutable(obj, attr):
30 unmodified lines
245 this environment may override the methods that tell the runtime what246 attributes or functions are safe to access.247248 If the template tries to access insecure code a :exc:`SecurityError` is186 raised. However also other exceptions may occour during the rendering so187 the caller has to ensure that all exceptions are catched.249 raised. However also other exceptions may occur during the rendering so250 the caller has to ensure that all exceptions are caught.251 """252 sandboxed = True253254 #: default callback table for the binary operators. A copy of this is
153 unmodified lines
408 attribute,409 obj.__class__.__name__410 ), name=attribute, obj=obj, exc=SecurityError)411412 def format_string(self, s, args, kwargs):413 """If a format call is detected, then this is routed through this414 method so that our safety sandbox can be used for it.415 """416 if isinstance(s, Markup):417 formatter = SandboxedEscapeFormatter(self, s.escape)418 else:419 formatter = SandboxedFormatter(self)420 kwargs = _MagicFormatMapping(args, kwargs)421 rv = formatter.vformat(s, args, kwargs)422 return type(s)(rv)423424 def call(__self, __context, __obj, *args, **kwargs):425 """Call an object from sandboxed code."""426 fmt = inspect_format_method(__obj)427 if fmt is not None:428 return __self.format_string(fmt, args, kwargs)429430 # the double prefixes are to avoid double keyword argument431 # errors when proxying the call.432 if not __self.is_safe_callable(__obj):433 raise SecurityError('%r is not safely callable' % (__obj,))
9 unmodified lines
443 def is_safe_attribute(self, obj, attr, value):444 if not SandboxedEnvironment.is_safe_attribute(self, obj, attr, value):445 return False446 return not modifies_known_mutable(obj, attr)447448449if has_format:450 # This really is not a public API apparenlty.451 try:452 from _string import formatter_field_name_split453 except ImportError:454 def formatter_field_name_split(field_name):455 return field_name._formatter_field_name_split()456457 class SandboxedFormatterMixin(object):458459 def __init__(self, env):460 self._env = env461462 def get_field(self, field_name, args, kwargs):463 first, rest = formatter_field_name_split(field_name)464 obj = self.get_value(first, args, kwargs)465 for is_attr, i in rest:466 if is_attr:467 obj = self._env.getattr(obj, i)468 else:469 obj = self._env.getitem(obj, i)470 return obj, first471472 class SandboxedFormatter(SandboxedFormatterMixin, Formatter):473 def __init__(self, env):474 SandboxedFormatterMixin.__init__(self, env)475 Formatter.__init__(self)476477 class SandboxedEscapeFormatter(SandboxedFormatterMixin, EscapeFormatter):478 def __init__(self, env, escape):479 SandboxedFormatterMixin.__init__(self, env)480 EscapeFormatter.__init__(self, escape)
modified:tests/test_security.py+26 added-1 removed
10 unmodified lines
11import pytest1213from jinja2 import Environment14from jinja2.sandbox import SandboxedEnvironment, \15 ImmutableSandboxedEnvironment, unsafe15 ImmutableSandboxedEnvironment, unsafe, has_format16from jinja2 import Markup, escape17from jinja2.exceptions import SecurityError, TemplateSyntaxError, \18 TemplateRuntimeError19from jinja2._compat import text_type
138 unmodified lines
158 except TemplateRuntimeError as e:159 pass160 else:161 assert False, 'expected runtime error'162163164@pytest.mark.sandbox165@pytest.mark.skipif(not has_format, reason='No format support')166class TestStringFormat(object):167168 def test_basic_format_safety(self):169 env = SandboxedEnvironment()170 t = env.from_string('{{ "a{0.__class__}b".format(42) }}')171 assert t.render() == 'ab'172173 def test_basic_format_all_okay(self):174 env = SandboxedEnvironment()175 t = env.from_string('{{ "a{0.foo}b".format({"foo": 42}) }}')176 assert t.render() == 'a42b'177178 def test_basic_format_safety(self):179 env = SandboxedEnvironment()180 t = env.from_string('{{ ("a{0.__class__}b{1}"|safe).format(42, "<foo>") }}')181 assert t.render() == 'ab&lt;foo&gt;'182183 def test_basic_format_all_okay(self):184 env = SandboxedEnvironment()185 t = env.from_string('{{ ("a{0.foo}b{1}"|safe).format({"foo": 42}, "<foo>") }}')186 assert t.render() == 'a42b&lt;foo&gt;'