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
Provenance
- Commit
9b53045- Tree
92a71c0- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
8189d21
3 files changed+143 added−5 removed
modified:jinja2/nodes.py+1 added-1 removed
602 unmodified lines603 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')604 605 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)610 611 # don't evaluate context functions308 unmodified linesmodified:jinja2/sandbox.py+116 added-3 removed
12 unmodified lines13 :license: BSD.14 """15 import types16 import operator17+from collections import Mapping18 from jinja2.environment import Environment19 from jinja2.exceptions import SecurityError19-from jinja2._compat import string_types, PY220+from jinja2._compat import string_types, text_type, PY221+from jinja2.utils import Markup22 23+has_format = False24+if hasattr(text_type, 'format'):25+ from markupsafe import EscapeFormatter26+ from string import Formatter27+ has_format = True28 29+30 #: maximum number of items a range may produce31 MAX_RANGE = 10000032 33 #: attributes of function objects that are considered unsafe.11 unmodified lines45 46 #: unsafe generator attirbutes.47 UNSAFE_GENERATOR_ATTRIBUTES = set(['gi_frame', 'gi_code'])48 49+#: unsafe attributes on coroutines50+UNSAFE_COROUTINE_ATTRIBUTES = set(['cr_frame', 'cr_code'])51+52+#: unsafe attributes on async generators53+UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = set(['ag_code', 'ag_frame'])54+55 import warnings56 57 # make sure we don't warn in python 2.6 about stuff we don't care about58 warnings.filterwarnings('ignore', 'the sets module', DeprecationWarning,48 unmodified lines107 ]))108 )109 110 111+class _MagicFormatMapping(Mapping):112+ """This class implements a dummy wrapper to fix a bug in the Python113+ standard library for string formatting.114+115+ See http://bugs.python.org/issue13598 for information about why116+ this is necessary.117+ """118+119+ def __init__(self, args, kwargs):120+ self._args = args121+ self._kwargs = kwargs122+ self._last_index = 0123+124+ 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]134+135+ def __iter__(self):136+ return iter(self._kwargs)137+138+ def __len__(self):139+ return len(self._kwargs)140+141+142+def 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 obj152+153+154 def safe_range(*args):155 """A range that can't generate ranges with a length of more than156 MAX_RANGE items.157 """43 unmodified lines201 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('__')212 213 214 def modifies_known_mutable(obj, attr):30 unmodified lines245 this environment may override the methods that tell the runtime what246 attributes or functions are safe to access.247 248 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 = True253 254 #: default callback table for the binary operators. A copy of this is153 unmodified lines408 attribute,409 obj.__class__.__name__410 ), name=attribute, obj=obj, exc=SecurityError)411 412+ 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)423+424 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)429+430 # 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 lines443 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)447+448+449+if 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()456+457+ class SandboxedFormatterMixin(object):458+459+ def __init__(self, env):460+ self._env = env461+462+ 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, first471+472+ class SandboxedFormatter(SandboxedFormatterMixin, Formatter):473+ def __init__(self, env):474+ SandboxedFormatterMixin.__init__(self, env)475+ Formatter.__init__(self)476+477+ 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 lines11 import pytest12 13 from jinja2 import Environment14 from jinja2.sandbox import SandboxedEnvironment, \15- ImmutableSandboxedEnvironment, unsafe15+ ImmutableSandboxedEnvironment, unsafe, has_format16 from jinja2 import Markup, escape17 from jinja2.exceptions import SecurityError, TemplateSyntaxError, \18 TemplateRuntimeError19 from jinja2._compat import text_type138 unmodified lines158 except TemplateRuntimeError as e:159 pass160 else:161 assert False, 'expected runtime error'162+163+164+@pytest.mark.sandbox165+@pytest.mark.skipif(not has_format, reason='No format support')166+class TestStringFormat(object):167+168+ 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'172+173+ 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'177+178+ 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<foo>'182+183+ 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<foo>'