Skip to content
Myr

Merge commit from fork

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

fix format string vulnerability

authored by David Lord · committed by GitHub · parents 0871c71, 91a972f · Browse files · 3 files+63 added−38 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+63 added−38 removed

  • tests:+17 added−0 removed
  • other:+46 added−38 removed

3 files+63 added−38 removed

modified:src/jinja2/sandbox.py+43 added-38 removed
6 unmodified lines
7import typing as t8from _string import formatter_field_name_split # type: ignore9from collections import abc10from collections import deque11from functools import update_wrapper12from string import Formatter1314from markupsafe import EscapeFormatter15from markupsafe import Markup
67 unmodified lines
83 ),84)858686def inspect_format_method(callable: t.Callable[..., t.Any]) -> t.Optional[str]:87 if not isinstance(88 callable, (types.MethodType, types.BuiltinMethodType)89 ) or callable.__name__ not in ("format", "format_map"):90 return None9192 obj = callable.__self__9394 if isinstance(obj, str):95 return obj9697 return None989987def safe_range(*args: int) -> range:88 """A range that can't generate ranges with a length of more than89 MAX_RANGE items.90 """
211 unmodified lines
302 value = getattr(obj, attr)303 except AttributeError:304 pass305 else:306 fmt = self.wrap_str_format(value)307 if fmt is not None:308 return fmt309 if self.is_safe_attribute(obj, argument, value):310 return value311 return self.unsafe_undefined(obj, argument)312 return self.undefined(obj=obj, name=argument)
9 unmodified lines
322 return obj[attribute]323 except (TypeError, LookupError):324 pass325 else:326 fmt = self.wrap_str_format(value)327 if fmt is not None:328 return fmt329 if self.is_safe_attribute(obj, attribute, value):330 return value331 return self.unsafe_undefined(obj, attribute)332 return self.undefined(obj=obj, name=attribute)
7 unmodified lines
340 obj=obj,341 exc=SecurityError,342 )343351 def format_string(352 self,353 s: str,354 args: t.Tuple[t.Any, ...],355 kwargs: t.Dict[str, t.Any],356 format_func: t.Optional[t.Callable[..., t.Any]] = None,357 ) -> str:358 """If a format call is detected, then this is routed through this359 method so that our safety sandbox can be used for it.344 def wrap_str_format(self, value: t.Any) -> t.Optional[t.Callable[..., str]]:345 """If the given value is a ``str.format`` or ``str.format_map`` method,346 return a new function than handles sandboxing. This is done at access347 rather than in :meth:`call`, so that calls made without ``call`` are348 also sandboxed.349 """350 if not isinstance(351 value, (types.MethodType, types.BuiltinMethodType)352 ) or value.__name__ not in ("format", "format_map"):353 return None354355 f_self: t.Any = value.__self__356357 if not isinstance(f_self, str):358 return None359360 str_type: t.Type[str] = type(f_self)361 is_format_map = value.__name__ == "format_map"362 formatter: SandboxedFormatter363362 if isinstance(s, Markup):363 formatter = SandboxedEscapeFormatter(self, escape=s.escape)364 if isinstance(f_self, Markup):365 formatter = SandboxedEscapeFormatter(self, escape=f_self.escape)366 else:367 formatter = SandboxedFormatter(self)368367 if format_func is not None and format_func.__name__ == "format_map":368 if len(args) != 1 or kwargs:369 raise TypeError(370 "format_map() takes exactly one argument"371 f" {len(args) + (kwargs is not None)} given"372 )369 vformat = formatter.vformat370374 kwargs = args[0]375 args = ()371 def wrapper(*args: t.Any, **kwargs: t.Any) -> str:372 if is_format_map:373 if kwargs:374 raise TypeError("format_map() takes no keyword arguments")375377 rv = formatter.vformat(s, args, kwargs)378 return type(s)(rv)376 if len(args) != 1:377 raise TypeError(378 f"format_map() takes exactly one argument ({len(args)} given)"379 )380381 kwargs = args[0]382 args = ()383384 return str_type(vformat(f_self, args, kwargs))385386 return update_wrapper(wrapper, value)387388 def call(389 __self, # noqa: B902390 __context: Context,391 __obj: t.Any,392 *args: t.Any,393 **kwargs: t.Any,394 ) -> t.Any:395 """Call an object from sandboxed code."""388 fmt = inspect_format_method(__obj)389 if fmt is not None:390 return __self.format_string(fmt, args, kwargs, __obj)396397 # the double prefixes are to avoid double keyword argument398 # errors when proxying the call.399 if not __self.is_safe_callable(__obj):
37 unmodified lines
modified:tests/test_security.py+17 added
171 unmodified lines
172 t = env.from_string(173 '{{ ("a{x.foo}b{y}"|safe).format_map({"x":{"foo": 42}, "y":"<foo>"}) }}'174 )175 assert t.render() == "a42b&lt;foo&gt;"176177 def test_indirect_call(self):178 def run(value, arg):179 return value.run(arg)180181 env = SandboxedEnvironment()182 env.filters["run"] = run183 t = env.from_string(184 """{% set185 ns = namespace(run="{0.__call__.__builtins__[__import__]}".format)186 %}187 {{ ns | run(not_here) }}188 """189 )190191 with pytest.raises(SecurityError):192 t.render()
modified:CHANGES.rst+3 added
3 unmodified lines
4-------------56Unreleased78- The sandboxed environment handles indirect calls to ``str.format``, such as9 by passing a stored reference to a filter that calls its argument.10 :ghsa:`q2x7-8rv6-6q7h`11- Sandbox does not allow ``clear`` and ``pop`` on known mutable sequence12 types. :issue:`2032`13- Calling sync ``render`` for an async template uses ``asyncio.run``.14 :pr:`1952`
1017 unmodified lines