sandbox indirect calls to str.format
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Lydxn · committed by David Lord · parent 0871c71 · 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
Provenance
- Commit
91a972f- Tree
6138ef6- Author
Lydxn <hlyndon20@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
0871c71
3 files changed+63 added−38 removed
modified:src/jinja2/sandbox.py+43 added-38 removed
6 unmodified lines7 import typing as t8 from _string import formatter_field_name_split # type: ignore9 from collections import abc10 from collections import deque11+from functools import update_wrapper12 from string import Formatter13 14 from markupsafe import EscapeFormatter15 from markupsafe import Markup67 unmodified lines83 ),84 )85 86 86-def 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 None91-92- obj = callable.__self__93-94- if isinstance(obj, str):95- return obj96-97- return None98-99-87 def 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 lines302 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 lines322 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 lines340 obj=obj,341 exc=SecurityError,342 )343 351- 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 None354+355+ f_self: t.Any = value.__self__356+357+ if not isinstance(f_self, str):358+ return None359+360+ str_type: t.Type[str] = type(f_self)361+ is_format_map = value.__name__ == "format_map"362 formatter: SandboxedFormatter363+362- 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)368 367- 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.vformat370 374- 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")375 377- 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+ )380 381+ kwargs = args[0]382+ args = ()383+384+ return str_type(vformat(f_self, args, kwargs))385+386+ return update_wrapper(wrapper, value)387+388 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)396 397 # the double prefixes are to avoid double keyword argument398 # errors when proxying the call.399 if not __self.is_safe_callable(__obj):37 unmodified linesmodified:tests/test_security.py+17 added
171 unmodified lines172 t = env.from_string(173 '{{ ("a{x.foo}b{y}"|safe).format_map({"x":{"foo": 42}, "y":"<foo>"}) }}'174 )175 assert t.render() == "a42b<foo>"176+177+ def test_indirect_call(self):178+ def run(value, arg):179+ return value.run(arg)180+181+ 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+ )190+191+ with pytest.raises(SecurityError):192+ t.render()modified:CHANGES.rst+3 added
3 unmodified lines4 -------------5 6 Unreleased7 8+- 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