1
0

sandbox.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. # -*- coding: utf-8 -*-
  2. """A sandbox layer that ensures unsafe operations cannot be performed.
  3. Useful when the template itself comes from an untrusted source.
  4. """
  5. import operator
  6. import types
  7. import warnings
  8. from collections import deque
  9. from string import Formatter
  10. from markupsafe import EscapeFormatter
  11. from markupsafe import Markup
  12. from ._compat import abc
  13. from ._compat import PY2
  14. from ._compat import range_type
  15. from ._compat import string_types
  16. from .environment import Environment
  17. from .exceptions import SecurityError
  18. #: maximum number of items a range may produce
  19. MAX_RANGE = 100000
  20. #: attributes of function objects that are considered unsafe.
  21. if PY2:
  22. UNSAFE_FUNCTION_ATTRIBUTES = {
  23. "func_closure",
  24. "func_code",
  25. "func_dict",
  26. "func_defaults",
  27. "func_globals",
  28. }
  29. else:
  30. # On versions > python 2 the special attributes on functions are gone,
  31. # but they remain on methods and generators for whatever reason.
  32. UNSAFE_FUNCTION_ATTRIBUTES = set()
  33. #: unsafe method attributes. function attributes are unsafe for methods too
  34. UNSAFE_METHOD_ATTRIBUTES = {"im_class", "im_func", "im_self"}
  35. #: unsafe generator attributes.
  36. UNSAFE_GENERATOR_ATTRIBUTES = {"gi_frame", "gi_code"}
  37. #: unsafe attributes on coroutines
  38. UNSAFE_COROUTINE_ATTRIBUTES = {"cr_frame", "cr_code"}
  39. #: unsafe attributes on async generators
  40. UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}
  41. # make sure we don't warn in python 2.6 about stuff we don't care about
  42. warnings.filterwarnings(
  43. "ignore", "the sets module", DeprecationWarning, module=__name__
  44. )
  45. _mutable_set_types = (set,)
  46. _mutable_mapping_types = (dict,)
  47. _mutable_sequence_types = (list,)
  48. # on python 2.x we can register the user collection types
  49. try:
  50. from UserDict import UserDict, DictMixin
  51. from UserList import UserList
  52. _mutable_mapping_types += (UserDict, DictMixin)
  53. _mutable_set_types += (UserList,)
  54. except ImportError:
  55. pass
  56. # if sets is still available, register the mutable set from there as well
  57. try:
  58. from sets import Set
  59. _mutable_set_types += (Set,)
  60. except ImportError:
  61. pass
  62. #: register Python 2.6 abstract base classes
  63. _mutable_set_types += (abc.MutableSet,)
  64. _mutable_mapping_types += (abc.MutableMapping,)
  65. _mutable_sequence_types += (abc.MutableSequence,)
  66. _mutable_spec = (
  67. (
  68. _mutable_set_types,
  69. frozenset(
  70. [
  71. "add",
  72. "clear",
  73. "difference_update",
  74. "discard",
  75. "pop",
  76. "remove",
  77. "symmetric_difference_update",
  78. "update",
  79. ]
  80. ),
  81. ),
  82. (
  83. _mutable_mapping_types,
  84. frozenset(["clear", "pop", "popitem", "setdefault", "update"]),
  85. ),
  86. (
  87. _mutable_sequence_types,
  88. frozenset(["append", "reverse", "insert", "sort", "extend", "remove"]),
  89. ),
  90. (
  91. deque,
  92. frozenset(
  93. [
  94. "append",
  95. "appendleft",
  96. "clear",
  97. "extend",
  98. "extendleft",
  99. "pop",
  100. "popleft",
  101. "remove",
  102. "rotate",
  103. ]
  104. ),
  105. ),
  106. )
  107. class _MagicFormatMapping(abc.Mapping):
  108. """This class implements a dummy wrapper to fix a bug in the Python
  109. standard library for string formatting.
  110. See https://bugs.python.org/issue13598 for information about why
  111. this is necessary.
  112. """
  113. def __init__(self, args, kwargs):
  114. self._args = args
  115. self._kwargs = kwargs
  116. self._last_index = 0
  117. def __getitem__(self, key):
  118. if key == "":
  119. idx = self._last_index
  120. self._last_index += 1
  121. try:
  122. return self._args[idx]
  123. except LookupError:
  124. pass
  125. key = str(idx)
  126. return self._kwargs[key]
  127. def __iter__(self):
  128. return iter(self._kwargs)
  129. def __len__(self):
  130. return len(self._kwargs)
  131. def inspect_format_method(callable):
  132. if not isinstance(
  133. callable, (types.MethodType, types.BuiltinMethodType)
  134. ) or callable.__name__ not in ("format", "format_map"):
  135. return None
  136. obj = callable.__self__
  137. if isinstance(obj, string_types):
  138. return obj
  139. def safe_range(*args):
  140. """A range that can't generate ranges with a length of more than
  141. MAX_RANGE items.
  142. """
  143. rng = range_type(*args)
  144. if len(rng) > MAX_RANGE:
  145. raise OverflowError(
  146. "Range too big. The sandbox blocks ranges larger than"
  147. " MAX_RANGE (%d)." % MAX_RANGE
  148. )
  149. return rng
  150. def unsafe(f):
  151. """Marks a function or method as unsafe.
  152. ::
  153. @unsafe
  154. def delete(self):
  155. pass
  156. """
  157. f.unsafe_callable = True
  158. return f
  159. def is_internal_attribute(obj, attr):
  160. """Test if the attribute given is an internal python attribute. For
  161. example this function returns `True` for the `func_code` attribute of
  162. python objects. This is useful if the environment method
  163. :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.
  164. >>> from jinja2.sandbox import is_internal_attribute
  165. >>> is_internal_attribute(str, "mro")
  166. True
  167. >>> is_internal_attribute(str, "upper")
  168. False
  169. """
  170. if isinstance(obj, types.FunctionType):
  171. if attr in UNSAFE_FUNCTION_ATTRIBUTES:
  172. return True
  173. elif isinstance(obj, types.MethodType):
  174. if attr in UNSAFE_FUNCTION_ATTRIBUTES or attr in UNSAFE_METHOD_ATTRIBUTES:
  175. return True
  176. elif isinstance(obj, type):
  177. if attr == "mro":
  178. return True
  179. elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):
  180. return True
  181. elif isinstance(obj, types.GeneratorType):
  182. if attr in UNSAFE_GENERATOR_ATTRIBUTES:
  183. return True
  184. elif hasattr(types, "CoroutineType") and isinstance(obj, types.CoroutineType):
  185. if attr in UNSAFE_COROUTINE_ATTRIBUTES:
  186. return True
  187. elif hasattr(types, "AsyncGeneratorType") and isinstance(
  188. obj, types.AsyncGeneratorType
  189. ):
  190. if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:
  191. return True
  192. return attr.startswith("__")
  193. def modifies_known_mutable(obj, attr):
  194. """This function checks if an attribute on a builtin mutable object
  195. (list, dict, set or deque) would modify it if called. It also supports
  196. the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and
  197. with Python 2.6 onwards the abstract base classes `MutableSet`,
  198. `MutableMapping`, and `MutableSequence`.
  199. >>> modifies_known_mutable({}, "clear")
  200. True
  201. >>> modifies_known_mutable({}, "keys")
  202. False
  203. >>> modifies_known_mutable([], "append")
  204. True
  205. >>> modifies_known_mutable([], "index")
  206. False
  207. If called with an unsupported object (such as unicode) `False` is
  208. returned.
  209. >>> modifies_known_mutable("foo", "upper")
  210. False
  211. """
  212. for typespec, unsafe in _mutable_spec:
  213. if isinstance(obj, typespec):
  214. return attr in unsafe
  215. return False
  216. class SandboxedEnvironment(Environment):
  217. """The sandboxed environment. It works like the regular environment but
  218. tells the compiler to generate sandboxed code. Additionally subclasses of
  219. this environment may override the methods that tell the runtime what
  220. attributes or functions are safe to access.
  221. If the template tries to access insecure code a :exc:`SecurityError` is
  222. raised. However also other exceptions may occur during the rendering so
  223. the caller has to ensure that all exceptions are caught.
  224. """
  225. sandboxed = True
  226. #: default callback table for the binary operators. A copy of this is
  227. #: available on each instance of a sandboxed environment as
  228. #: :attr:`binop_table`
  229. default_binop_table = {
  230. "+": operator.add,
  231. "-": operator.sub,
  232. "*": operator.mul,
  233. "/": operator.truediv,
  234. "//": operator.floordiv,
  235. "**": operator.pow,
  236. "%": operator.mod,
  237. }
  238. #: default callback table for the unary operators. A copy of this is
  239. #: available on each instance of a sandboxed environment as
  240. #: :attr:`unop_table`
  241. default_unop_table = {"+": operator.pos, "-": operator.neg}
  242. #: a set of binary operators that should be intercepted. Each operator
  243. #: that is added to this set (empty by default) is delegated to the
  244. #: :meth:`call_binop` method that will perform the operator. The default
  245. #: operator callback is specified by :attr:`binop_table`.
  246. #:
  247. #: The following binary operators are interceptable:
  248. #: ``//``, ``%``, ``+``, ``*``, ``-``, ``/``, and ``**``
  249. #:
  250. #: The default operation form the operator table corresponds to the
  251. #: builtin function. Intercepted calls are always slower than the native
  252. #: operator call, so make sure only to intercept the ones you are
  253. #: interested in.
  254. #:
  255. #: .. versionadded:: 2.6
  256. intercepted_binops = frozenset()
  257. #: a set of unary operators that should be intercepted. Each operator
  258. #: that is added to this set (empty by default) is delegated to the
  259. #: :meth:`call_unop` method that will perform the operator. The default
  260. #: operator callback is specified by :attr:`unop_table`.
  261. #:
  262. #: The following unary operators are interceptable: ``+``, ``-``
  263. #:
  264. #: The default operation form the operator table corresponds to the
  265. #: builtin function. Intercepted calls are always slower than the native
  266. #: operator call, so make sure only to intercept the ones you are
  267. #: interested in.
  268. #:
  269. #: .. versionadded:: 2.6
  270. intercepted_unops = frozenset()
  271. def intercept_unop(self, operator):
  272. """Called during template compilation with the name of a unary
  273. operator to check if it should be intercepted at runtime. If this
  274. method returns `True`, :meth:`call_unop` is executed for this unary
  275. operator. The default implementation of :meth:`call_unop` will use
  276. the :attr:`unop_table` dictionary to perform the operator with the
  277. same logic as the builtin one.
  278. The following unary operators are interceptable: ``+`` and ``-``
  279. Intercepted calls are always slower than the native operator call,
  280. so make sure only to intercept the ones you are interested in.
  281. .. versionadded:: 2.6
  282. """
  283. return False
  284. def __init__(self, *args, **kwargs):
  285. Environment.__init__(self, *args, **kwargs)
  286. self.globals["range"] = safe_range
  287. self.binop_table = self.default_binop_table.copy()
  288. self.unop_table = self.default_unop_table.copy()
  289. def is_safe_attribute(self, obj, attr, value):
  290. """The sandboxed environment will call this method to check if the
  291. attribute of an object is safe to access. Per default all attributes
  292. starting with an underscore are considered private as well as the
  293. special attributes of internal python objects as returned by the
  294. :func:`is_internal_attribute` function.
  295. """
  296. return not (attr.startswith("_") or is_internal_attribute(obj, attr))
  297. def is_safe_callable(self, obj):
  298. """Check if an object is safely callable. Per default a function is
  299. considered safe unless the `unsafe_callable` attribute exists and is
  300. True. Override this method to alter the behavior, but this won't
  301. affect the `unsafe` decorator from this module.
  302. """
  303. return not (
  304. getattr(obj, "unsafe_callable", False) or getattr(obj, "alters_data", False)
  305. )
  306. def call_binop(self, context, operator, left, right):
  307. """For intercepted binary operator calls (:meth:`intercepted_binops`)
  308. this function is executed instead of the builtin operator. This can
  309. be used to fine tune the behavior of certain operators.
  310. .. versionadded:: 2.6
  311. """
  312. return self.binop_table[operator](left, right)
  313. def call_unop(self, context, operator, arg):
  314. """For intercepted unary operator calls (:meth:`intercepted_unops`)
  315. this function is executed instead of the builtin operator. This can
  316. be used to fine tune the behavior of certain operators.
  317. .. versionadded:: 2.6
  318. """
  319. return self.unop_table[operator](arg)
  320. def getitem(self, obj, argument):
  321. """Subscribe an object from sandboxed code."""
  322. try:
  323. return obj[argument]
  324. except (TypeError, LookupError):
  325. if isinstance(argument, string_types):
  326. try:
  327. attr = str(argument)
  328. except Exception:
  329. pass
  330. else:
  331. try:
  332. value = getattr(obj, attr)
  333. except AttributeError:
  334. pass
  335. else:
  336. if self.is_safe_attribute(obj, argument, value):
  337. return value
  338. return self.unsafe_undefined(obj, argument)
  339. return self.undefined(obj=obj, name=argument)
  340. def getattr(self, obj, attribute):
  341. """Subscribe an object from sandboxed code and prefer the
  342. attribute. The attribute passed *must* be a bytestring.
  343. """
  344. try:
  345. value = getattr(obj, attribute)
  346. except AttributeError:
  347. try:
  348. return obj[attribute]
  349. except (TypeError, LookupError):
  350. pass
  351. else:
  352. if self.is_safe_attribute(obj, attribute, value):
  353. return value
  354. return self.unsafe_undefined(obj, attribute)
  355. return self.undefined(obj=obj, name=attribute)
  356. def unsafe_undefined(self, obj, attribute):
  357. """Return an undefined object for unsafe attributes."""
  358. return self.undefined(
  359. "access to attribute %r of %r "
  360. "object is unsafe." % (attribute, obj.__class__.__name__),
  361. name=attribute,
  362. obj=obj,
  363. exc=SecurityError,
  364. )
  365. def format_string(self, s, args, kwargs, format_func=None):
  366. """If a format call is detected, then this is routed through this
  367. method so that our safety sandbox can be used for it.
  368. """
  369. if isinstance(s, Markup):
  370. formatter = SandboxedEscapeFormatter(self, s.escape)
  371. else:
  372. formatter = SandboxedFormatter(self)
  373. if format_func is not None and format_func.__name__ == "format_map":
  374. if len(args) != 1 or kwargs:
  375. raise TypeError(
  376. "format_map() takes exactly one argument %d given"
  377. % (len(args) + (kwargs is not None))
  378. )
  379. kwargs = args[0]
  380. args = None
  381. kwargs = _MagicFormatMapping(args, kwargs)
  382. rv = formatter.vformat(s, args, kwargs)
  383. return type(s)(rv)
  384. def call(__self, __context, __obj, *args, **kwargs): # noqa: B902
  385. """Call an object from sandboxed code."""
  386. fmt = inspect_format_method(__obj)
  387. if fmt is not None:
  388. return __self.format_string(fmt, args, kwargs, __obj)
  389. # the double prefixes are to avoid double keyword argument
  390. # errors when proxying the call.
  391. if not __self.is_safe_callable(__obj):
  392. raise SecurityError("%r is not safely callable" % (__obj,))
  393. return __context.call(__obj, *args, **kwargs)
  394. class ImmutableSandboxedEnvironment(SandboxedEnvironment):
  395. """Works exactly like the regular `SandboxedEnvironment` but does not
  396. permit modifications on the builtin mutable objects `list`, `set`, and
  397. `dict` by using the :func:`modifies_known_mutable` function.
  398. """
  399. def is_safe_attribute(self, obj, attr, value):
  400. if not SandboxedEnvironment.is_safe_attribute(self, obj, attr, value):
  401. return False
  402. return not modifies_known_mutable(obj, attr)
  403. # This really is not a public API apparently.
  404. try:
  405. from _string import formatter_field_name_split
  406. except ImportError:
  407. def formatter_field_name_split(field_name):
  408. return field_name._formatter_field_name_split()
  409. class SandboxedFormatterMixin(object):
  410. def __init__(self, env):
  411. self._env = env
  412. def get_field(self, field_name, args, kwargs):
  413. first, rest = formatter_field_name_split(field_name)
  414. obj = self.get_value(first, args, kwargs)
  415. for is_attr, i in rest:
  416. if is_attr:
  417. obj = self._env.getattr(obj, i)
  418. else:
  419. obj = self._env.getitem(obj, i)
  420. return obj, first
  421. class SandboxedFormatter(SandboxedFormatterMixin, Formatter):
  422. def __init__(self, env):
  423. SandboxedFormatterMixin.__init__(self, env)
  424. Formatter.__init__(self)
  425. class SandboxedEscapeFormatter(SandboxedFormatterMixin, EscapeFormatter):
  426. def __init__(self, env, escape):
  427. SandboxedFormatterMixin.__init__(self, env)
  428. EscapeFormatter.__init__(self, escape)