sandbox.py
This file
Path
src/jinja2/sandbox.py
434 lines · 14.6 KiB · Python
Last changed by
drop end of life python versions (#2096)David Lordbefore adoption49c48a0
History of this fileTake it
1"""A sandbox layer that ensures unsafe operations cannot be performed.2Useful when the template itself comes from an untrusted source.3"""45import operator6import types7import 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 Markup1617from .environment import Environment18from .exceptions import SecurityError19from .runtime import Context20from .runtime import Undefined2122F = t.TypeVar("F", bound=t.Callable[..., t.Any])2324#: maximum number of items a range may produce25MAX_RANGE = 1000002627#: Unsafe function attributes.28UNSAFE_FUNCTION_ATTRIBUTES: set[str] = set()2930#: Unsafe method attributes. Function attributes are unsafe for methods too.31UNSAFE_METHOD_ATTRIBUTES: set[str] = set()3233#: unsafe generator attributes.34UNSAFE_GENERATOR_ATTRIBUTES = {"gi_frame", "gi_code"}3536#: unsafe attributes on coroutines37UNSAFE_COROUTINE_ATTRIBUTES = {"cr_frame", "cr_code"}3839#: unsafe attributes on async generators40UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}4142_mutable_spec: tuple[tuple[type[t.Any], frozenset[str]], ...] = (43 (44 abc.MutableSet,45 frozenset(46 [47 "add",48 "clear",49 "difference_update",50 "discard",51 "pop",52 "remove",53 "symmetric_difference_update",54 "update",55 ]56 ),57 ),58 (59 abc.MutableMapping,60 frozenset(["clear", "pop", "popitem", "setdefault", "update"]),61 ),62 (63 abc.MutableSequence,64 frozenset(65 ["append", "clear", "pop", "reverse", "insert", "sort", "extend", "remove"]66 ),67 ),68 (69 deque,70 frozenset(71 [72 "append",73 "appendleft",74 "clear",75 "extend",76 "extendleft",77 "pop",78 "popleft",79 "remove",80 "rotate",81 ]82 ),83 ),84)858687def safe_range(*args: int) -> range:88 """A range that can't generate ranges with a length of more than89 MAX_RANGE items.90 """91 rng = range(*args)9293 if len(rng) > MAX_RANGE:94 raise OverflowError(95 "Range too big. The sandbox blocks ranges larger than"96 f" MAX_RANGE ({MAX_RANGE})."97 )9899 return rng100101102def unsafe(f: F) -> F:103 """Marks a function or method as unsafe.104105 .. code-block: python106107 @unsafe108 def delete(self):109 pass110 """111 f.unsafe_callable = True # type: ignore112 return f113114115def is_internal_attribute(obj: t.Any, attr: str) -> bool:116 """Test if the attribute given is an internal python attribute. For117 example this function returns `True` for the `func_code` attribute of118 python objects. This is useful if the environment method119 :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.120121 >>> from jinja2.sandbox import is_internal_attribute122 >>> is_internal_attribute(str, "mro")123 True124 >>> is_internal_attribute(str, "upper")125 False126 """127 if isinstance(obj, types.FunctionType):128 if attr in UNSAFE_FUNCTION_ATTRIBUTES:129 return True130 elif isinstance(obj, types.MethodType):131 if attr in UNSAFE_FUNCTION_ATTRIBUTES or attr in UNSAFE_METHOD_ATTRIBUTES:132 return True133 elif isinstance(obj, type):134 if attr == "mro":135 return True136 elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):137 return True138 elif isinstance(obj, types.GeneratorType):139 if attr in UNSAFE_GENERATOR_ATTRIBUTES:140 return True141 elif hasattr(types, "CoroutineType") and isinstance(obj, types.CoroutineType):142 if attr in UNSAFE_COROUTINE_ATTRIBUTES:143 return True144 elif hasattr(types, "AsyncGeneratorType") and isinstance(145 obj, types.AsyncGeneratorType146 ):147 if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:148 return True149 return attr.startswith("__")150151152def modifies_known_mutable(obj: t.Any, attr: str) -> bool:153 """This function checks if an attribute on a builtin mutable object154 (list, dict, set or deque) or the corresponding ABCs would modify it155 if called.156157 >>> modifies_known_mutable({}, "clear")158 True159 >>> modifies_known_mutable({}, "keys")160 False161 >>> modifies_known_mutable([], "append")162 True163 >>> modifies_known_mutable([], "index")164 False165166 If called with an unsupported object, ``False`` is returned.167168 >>> modifies_known_mutable("foo", "upper")169 False170 """171 for typespec, unsafe in _mutable_spec:172 if isinstance(obj, typespec):173 return attr in unsafe174 return False175176177class SandboxedEnvironment(Environment):178 """The sandboxed environment. It works like the regular environment but179 tells the compiler to generate sandboxed code. Additionally subclasses of180 this environment may override the methods that tell the runtime what181 attributes or functions are safe to access.182183 If the template tries to access insecure code a :exc:`SecurityError` is184 raised. However also other exceptions may occur during the rendering so185 the caller has to ensure that all exceptions are caught.186 """187188 sandboxed = True189190 #: default callback table for the binary operators. A copy of this is191 #: available on each instance of a sandboxed environment as192 #: :attr:`binop_table`193 default_binop_table: dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {194 "+": operator.add,195 "-": operator.sub,196 "*": operator.mul,197 "/": operator.truediv,198 "//": operator.floordiv,199 "**": operator.pow,200 "%": operator.mod,201 }202203 #: default callback table for the unary operators. A copy of this is204 #: available on each instance of a sandboxed environment as205 #: :attr:`unop_table`206 default_unop_table: dict[str, t.Callable[[t.Any], t.Any]] = {207 "+": operator.pos,208 "-": operator.neg,209 }210211 #: a set of binary operators that should be intercepted. Each operator212 #: that is added to this set (empty by default) is delegated to the213 #: :meth:`call_binop` method that will perform the operator. The default214 #: operator callback is specified by :attr:`binop_table`.215 #:216 #: The following binary operators are interceptable:217 #: ``//``, ``%``, ``+``, ``*``, ``-``, ``/``, and ``**``218 #:219 #: The default operation form the operator table corresponds to the220 #: builtin function. Intercepted calls are always slower than the native221 #: operator call, so make sure only to intercept the ones you are222 #: interested in.223 #:224 #: .. versionadded:: 2.6225 intercepted_binops: frozenset[str] = frozenset()226227 #: a set of unary operators that should be intercepted. Each operator228 #: that is added to this set (empty by default) is delegated to the229 #: :meth:`call_unop` method that will perform the operator. The default230 #: operator callback is specified by :attr:`unop_table`.231 #:232 #: The following unary operators are interceptable: ``+``, ``-``233 #:234 #: The default operation form the operator table corresponds to the235 #: builtin function. Intercepted calls are always slower than the native236 #: operator call, so make sure only to intercept the ones you are237 #: interested in.238 #:239 #: .. versionadded:: 2.6240 intercepted_unops: frozenset[str] = frozenset()241242 def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:243 super().__init__(*args, **kwargs)244 self.globals["range"] = safe_range245 self.binop_table = self.default_binop_table.copy()246 self.unop_table = self.default_unop_table.copy()247248 def is_safe_attribute(self, obj: t.Any, attr: str, value: t.Any) -> bool:249 """The sandboxed environment will call this method to check if the250 attribute of an object is safe to access. Per default all attributes251 starting with an underscore are considered private as well as the252 special attributes of internal python objects as returned by the253 :func:`is_internal_attribute` function.254 """255 return not (attr.startswith("_") or is_internal_attribute(obj, attr))256257 def is_safe_callable(self, obj: t.Any) -> bool:258 """Check if an object is safely callable. By default callables259 are considered safe unless decorated with :func:`unsafe`.260261 This also recognizes the Django convention of setting262 ``func.alters_data = True``.263 """264 return not (265 getattr(obj, "unsafe_callable", False) or getattr(obj, "alters_data", False)266 )267268 def call_binop(269 self, context: Context, operator: str, left: t.Any, right: t.Any270 ) -> t.Any:271 """For intercepted binary operator calls (:meth:`intercepted_binops`)272 this function is executed instead of the builtin operator. This can273 be used to fine tune the behavior of certain operators.274275 .. versionadded:: 2.6276 """277 return self.binop_table[operator](left, right)278279 def call_unop(self, context: Context, operator: str, arg: t.Any) -> t.Any:280 """For intercepted unary operator calls (:meth:`intercepted_unops`)281 this function is executed instead of the builtin operator. This can282 be used to fine tune the behavior of certain operators.283284 .. versionadded:: 2.6285 """286 return self.unop_table[operator](arg)287288 def getitem(self, obj: t.Any, argument: str | t.Any) -> t.Any | Undefined:289 """Subscribe an object from sandboxed code."""290 try:291 return obj[argument]292 except (TypeError, LookupError):293 if isinstance(argument, str):294 try:295 attr = str(argument)296 except Exception:297 pass298 else:299 try:300 value = getattr(obj, attr)301 except AttributeError:302 pass303 else:304 fmt = self.wrap_str_format(value)305 if fmt is not None:306 return fmt307 if self.is_safe_attribute(obj, argument, value):308 return value309 return self.unsafe_undefined(obj, argument)310 return self.undefined(obj=obj, name=argument)311312 def getattr(self, obj: t.Any, attribute: str) -> t.Any | Undefined:313 """Subscribe an object from sandboxed code and prefer the314 attribute. The attribute passed *must* be a bytestring.315 """316 try:317 value = getattr(obj, attribute)318 except AttributeError:319 try:320 return obj[attribute]321 except (TypeError, LookupError):322 pass323 else:324 fmt = self.wrap_str_format(value)325 if fmt is not None:326 return fmt327 if self.is_safe_attribute(obj, attribute, value):328 return value329 return self.unsafe_undefined(obj, attribute)330 return self.undefined(obj=obj, name=attribute)331332 def unsafe_undefined(self, obj: t.Any, attribute: str) -> Undefined:333 """Return an undefined object for unsafe attributes."""334 return self.undefined(335 f"access to attribute {attribute!r} of"336 f" {type(obj).__name__!r} object is unsafe.",337 name=attribute,338 obj=obj,339 exc=SecurityError,340 )341342 def wrap_str_format(self, value: t.Any) -> t.Callable[..., str] | None:343 """If the given value is a ``str.format`` or ``str.format_map`` method,344 return a new function than handles sandboxing. This is done at access345 rather than in :meth:`call`, so that calls made without ``call`` are346 also sandboxed.347 """348 if not isinstance(349 value, (types.MethodType, types.BuiltinMethodType)350 ) or value.__name__ not in ("format", "format_map"):351 return None352353 f_self: t.Any = value.__self__354355 if not isinstance(f_self, str):356 return None357358 str_type: type[str] = type(f_self)359 is_format_map = value.__name__ == "format_map"360 formatter: SandboxedFormatter361362 if isinstance(f_self, Markup):363 formatter = SandboxedEscapeFormatter(self, escape=f_self.escape)364 else:365 formatter = SandboxedFormatter(self)366367 vformat = formatter.vformat368369 def wrapper(*args: t.Any, **kwargs: t.Any) -> str:370 if is_format_map:371 if kwargs:372 raise TypeError("format_map() takes no keyword arguments")373374 if len(args) != 1:375 raise TypeError(376 f"format_map() takes exactly one argument ({len(args)} given)"377 )378379 kwargs = args[0]380 args = ()381382 return str_type(vformat(f_self, args, kwargs))383384 return update_wrapper(wrapper, value)385386 def call(387 __self, # noqa: B902388 __context: Context,389 __obj: t.Any,390 *args: t.Any,391 **kwargs: t.Any,392 ) -> t.Any:393 """Call an object from sandboxed code."""394395 # the double prefixes are to avoid double keyword argument396 # errors when proxying the call.397 if not __self.is_safe_callable(__obj):398 raise SecurityError(f"{__obj!r} is not safely callable")399 return __context.call(__obj, *args, **kwargs)400401402class ImmutableSandboxedEnvironment(SandboxedEnvironment):403 """Works exactly like the regular `SandboxedEnvironment` but does not404 permit modifications on the builtin mutable objects `list`, `set`, and405 `dict` by using the :func:`modifies_known_mutable` function.406 """407408 def is_safe_attribute(self, obj: t.Any, attr: str, value: t.Any) -> bool:409 if not super().is_safe_attribute(obj, attr, value):410 return False411412 return not modifies_known_mutable(obj, attr)413414415class SandboxedFormatter(Formatter):416 def __init__(self, env: Environment, **kwargs: t.Any) -> None:417 self._env = env418 super().__init__(**kwargs)419420 def get_field(421 self, field_name: str, args: t.Sequence[t.Any], kwargs: t.Mapping[str, t.Any]422 ) -> tuple[t.Any, str]:423 first, rest = formatter_field_name_split(field_name)424 obj = self.get_value(first, args, kwargs)425 for is_attr, i in rest:426 if is_attr:427 obj = self._env.getattr(obj, i)428 else:429 obj = self._env.getitem(obj, i)430 return obj, first431432433class SandboxedEscapeFormatter(SandboxedFormatter, EscapeFormatter):434 pass