blob: b9b17162bf696d473150d90ec86c07c7f6037e45 [file] [log] [blame]
Armin Ronacherc63243e2008-04-14 22:53:58 +02001# -*- coding: utf-8 -*-
2"""
3 jinja2.sandbox
4 ~~~~~~~~~~~~~~
5
6 Adds a sandbox layer to Jinja as it was the default behavior in the old
7 Jinja 1 releases. This sandbox is slightly different from Jinja 1 as the
8 default behavior is easier to use.
9
10 The behavior can be changed by subclassing the environment.
11
Armin Ronacher55494e42010-01-22 09:41:48 +010012 :copyright: (c) 2010 by the Jinja Team.
Armin Ronacherc63243e2008-04-14 22:53:58 +020013 :license: BSD.
14"""
Armin Ronacher522cad62008-05-17 13:55:37 +020015import operator
Armin Ronacherc63243e2008-04-14 22:53:58 +020016from jinja2.environment import Environment
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +020017from jinja2.exceptions import SecurityError
Armin Ronacher9a0078d2008-08-13 18:24:17 +020018from jinja2.utils import FunctionType, MethodType, TracebackType, CodeType, \
19 FrameType, GeneratorType
Armin Ronacherc63243e2008-04-14 22:53:58 +020020
21
22#: maximum number of items a range may produce
23MAX_RANGE = 100000
24
Armin Ronacher76c280b2008-05-04 12:31:48 +020025#: attributes of function objects that are considered unsafe.
26UNSAFE_FUNCTION_ATTRIBUTES = set(['func_closure', 'func_code', 'func_dict',
27 'func_defaults', 'func_globals'])
28
29#: unsafe method attributes. function attributes are unsafe for methods too
30UNSAFE_METHOD_ATTRIBUTES = set(['im_class', 'im_func', 'im_self'])
31
Armin Ronacher522cad62008-05-17 13:55:37 +020032
Armin Ronacher51097172009-02-19 19:57:01 +010033import warnings
34
35# make sure we don't warn in python 2.6 about stuff we don't care about
36warnings.filterwarnings('ignore', 'the sets module', DeprecationWarning,
37 module='jinja2.sandbox')
38
Armin Ronacherd71fff02008-05-26 23:57:07 +020039from collections import deque
Armin Ronacher790b8a82010-02-10 00:05:46 +010040
Armin Ronacher51097172009-02-19 19:57:01 +010041_mutable_set_types = (set,)
Armin Ronacher790b8a82010-02-10 00:05:46 +010042_mutable_mapping_types = (dict,)
43_mutable_sequence_types = (list,)
44
45
46# on python 2.x we can register the user collection types
47try:
48 from UserDict import UserDict, DictMixin
49 from UserList import UserList
50 _mutable_mapping_types += (UserDict, DictMixin)
51 _mutable_set_types += (UserList,)
52except ImportError:
53 pass
Armin Ronacher522cad62008-05-17 13:55:37 +020054
Armin Ronacher51097172009-02-19 19:57:01 +010055# if sets is still available, register the mutable set from there as well
56try:
57 from sets import Set
58 _mutable_set_types += (Set,)
59except ImportError:
60 pass
61
Armin Ronacherd71fff02008-05-26 23:57:07 +020062#: register Python 2.6 abstract base classes
63try:
64 from collections import MutableSet, MutableMapping, MutableSequence
65 _mutable_set_types += (MutableSet,)
66 _mutable_mapping_types += (MutableMapping,)
67 _mutable_sequence_types += (MutableSequence,)
68except ImportError:
69 pass
70
71_mutable_spec = (
72 (_mutable_set_types, frozenset([
73 'add', 'clear', 'difference_update', 'discard', 'pop', 'remove',
74 'symmetric_difference_update', 'update'
75 ])),
76 (_mutable_mapping_types, frozenset([
77 'clear', 'pop', 'popitem', 'setdefault', 'update'
78 ])),
79 (_mutable_sequence_types, frozenset([
80 'append', 'reverse', 'insert', 'sort', 'extend', 'remove'
81 ])),
82 (deque, frozenset([
83 'append', 'appendleft', 'clear', 'extend', 'extendleft', 'pop',
84 'popleft', 'remove', 'rotate'
85 ]))
86)
Armin Ronacher522cad62008-05-17 13:55:37 +020087
Armin Ronacherc63243e2008-04-14 22:53:58 +020088
89def safe_range(*args):
90 """A range that can't generate ranges with a length of more than
Armin Ronacher7ceced52008-05-03 10:15:31 +020091 MAX_RANGE items.
92 """
Thomas Waldmanne0003552013-05-17 23:52:14 +020093 rng = range(*args)
Armin Ronacherc63243e2008-04-14 22:53:58 +020094 if len(rng) > MAX_RANGE:
Armin Ronacher76c280b2008-05-04 12:31:48 +020095 raise OverflowError('range too big, maximum size for range is %d' %
96 MAX_RANGE)
Armin Ronacherc63243e2008-04-14 22:53:58 +020097 return rng
98
99
100def unsafe(f):
Armin Ronacher53278a32011-01-24 01:16:00 +0100101 """Marks a function or method as unsafe.
102
103 ::
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200104
105 @unsafe
106 def delete(self):
107 pass
108 """
Armin Ronacherc63243e2008-04-14 22:53:58 +0200109 f.unsafe_callable = True
110 return f
111
112
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200113def is_internal_attribute(obj, attr):
114 """Test if the attribute given is an internal python attribute. For
115 example this function returns `True` for the `func_code` attribute of
116 python objects. This is useful if the environment method
117 :meth:`~SandboxedEnvironment.is_safe_attribute` is overriden.
118
119 >>> from jinja2.sandbox import is_internal_attribute
120 >>> is_internal_attribute(lambda: None, "func_code")
121 True
122 >>> is_internal_attribute((lambda x:x).func_code, 'co_code')
123 True
124 >>> is_internal_attribute(str, "upper")
125 False
126 """
127 if isinstance(obj, FunctionType):
Armin Ronacherd71fff02008-05-26 23:57:07 +0200128 if attr in UNSAFE_FUNCTION_ATTRIBUTES:
129 return True
130 elif isinstance(obj, MethodType):
131 if attr in UNSAFE_FUNCTION_ATTRIBUTES or \
132 attr in UNSAFE_METHOD_ATTRIBUTES:
133 return True
134 elif isinstance(obj, type):
135 if attr == 'mro':
136 return True
137 elif isinstance(obj, (CodeType, TracebackType, FrameType)):
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200138 return True
Armin Ronacherd71fff02008-05-26 23:57:07 +0200139 elif isinstance(obj, GeneratorType):
140 if attr == 'gi_frame':
141 return True
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200142 return attr.startswith('__')
143
144
Armin Ronacherd71fff02008-05-26 23:57:07 +0200145def modifies_known_mutable(obj, attr):
Armin Ronacher522cad62008-05-17 13:55:37 +0200146 """This function checks if an attribute on a builtin mutable object
Armin Ronacherd71fff02008-05-26 23:57:07 +0200147 (list, dict, set or deque) would modify it if called. It also supports
148 the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and
149 with Python 2.6 onwards the abstract base classes `MutableSet`,
150 `MutableMapping`, and `MutableSequence`.
Armin Ronacher522cad62008-05-17 13:55:37 +0200151
Armin Ronacherd71fff02008-05-26 23:57:07 +0200152 >>> modifies_known_mutable({}, "clear")
Armin Ronacher522cad62008-05-17 13:55:37 +0200153 True
Armin Ronacherd71fff02008-05-26 23:57:07 +0200154 >>> modifies_known_mutable({}, "keys")
Armin Ronacher522cad62008-05-17 13:55:37 +0200155 False
Armin Ronacherd71fff02008-05-26 23:57:07 +0200156 >>> modifies_known_mutable([], "append")
Armin Ronacher522cad62008-05-17 13:55:37 +0200157 True
Armin Ronacherd71fff02008-05-26 23:57:07 +0200158 >>> modifies_known_mutable([], "index")
Armin Ronacher522cad62008-05-17 13:55:37 +0200159 False
160
161 If called with an unsupported object (such as unicode) `False` is
162 returned.
163
Armin Ronacherd71fff02008-05-26 23:57:07 +0200164 >>> modifies_known_mutable("foo", "upper")
Armin Ronacher522cad62008-05-17 13:55:37 +0200165 False
166 """
Armin Ronacherd71fff02008-05-26 23:57:07 +0200167 for typespec, unsafe in _mutable_spec:
168 if isinstance(obj, typespec):
169 return attr in unsafe
Armin Ronacher522cad62008-05-17 13:55:37 +0200170 return False
171
172
Armin Ronacherc63243e2008-04-14 22:53:58 +0200173class SandboxedEnvironment(Environment):
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200174 """The sandboxed environment. It works like the regular environment but
175 tells the compiler to generate sandboxed code. Additionally subclasses of
176 this environment may override the methods that tell the runtime what
177 attributes or functions are safe to access.
178
179 If the template tries to access insecure code a :exc:`SecurityError` is
180 raised. However also other exceptions may occour during the rendering so
181 the caller has to ensure that all exceptions are catched.
182 """
Armin Ronacherc63243e2008-04-14 22:53:58 +0200183 sandboxed = True
184
Armin Ronachera9195382010-11-29 13:21:57 +0100185 #: default callback table for the binary operators. A copy of this is
186 #: available on each instance of a sandboxed environment as
187 #: :attr:`binop_table`
188 default_binop_table = {
189 '+': operator.add,
190 '-': operator.sub,
191 '*': operator.mul,
192 '/': operator.truediv,
193 '//': operator.floordiv,
194 '**': operator.pow,
195 '%': operator.mod
196 }
197
198 #: default callback table for the unary operators. A copy of this is
199 #: available on each instance of a sandboxed environment as
200 #: :attr:`unop_table`
201 default_unop_table = {
202 '+': operator.pos,
203 '-': operator.neg
204 }
205
206 #: a set of binary operators that should be intercepted. Each operator
207 #: that is added to this set (empty by default) is delegated to the
208 #: :meth:`call_binop` method that will perform the operator. The default
209 #: operator callback is specified by :attr:`binop_table`.
210 #:
211 #: The following binary operators are interceptable:
212 #: ``//``, ``%``, ``+``, ``*``, ``-``, ``/``, and ``**``
213 #:
214 #: The default operation form the operator table corresponds to the
215 #: builtin function. Intercepted calls are always slower than the native
216 #: operator call, so make sure only to intercept the ones you are
217 #: interested in.
218 #:
219 #: .. versionadded:: 2.6
220 intercepted_binops = frozenset()
221
222 #: a set of unary operators that should be intercepted. Each operator
223 #: that is added to this set (empty by default) is delegated to the
224 #: :meth:`call_unop` method that will perform the operator. The default
225 #: operator callback is specified by :attr:`unop_table`.
226 #:
227 #: The following unary operators are interceptable: ``+``, ``-``
228 #:
229 #: The default operation form the operator table corresponds to the
230 #: builtin function. Intercepted calls are always slower than the native
231 #: operator call, so make sure only to intercept the ones you are
232 #: interested in.
233 #:
234 #: .. versionadded:: 2.6
235 intercepted_unops = frozenset()
236
237 def intercept_unop(self, operator):
238 """Called during template compilation with the name of a unary
239 operator to check if it should be intercepted at runtime. If this
240 method returns `True`, :meth:`call_unop` is excuted for this unary
241 operator. The default implementation of :meth:`call_unop` will use
242 the :attr:`unop_table` dictionary to perform the operator with the
243 same logic as the builtin one.
244
245 The following unary operators are interceptable: ``+`` and ``-``
246
247 Intercepted calls are always slower than the native operator call,
248 so make sure only to intercept the ones you are interested in.
249
250 .. versionadded:: 2.6
251 """
252 return False
253
254
Armin Ronacherc63243e2008-04-14 22:53:58 +0200255 def __init__(self, *args, **kwargs):
256 Environment.__init__(self, *args, **kwargs)
257 self.globals['range'] = safe_range
Armin Ronachera9195382010-11-29 13:21:57 +0100258 self.binop_table = self.default_binop_table.copy()
259 self.unop_table = self.default_unop_table.copy()
Armin Ronacherc63243e2008-04-14 22:53:58 +0200260
Armin Ronacher9a822052008-04-17 18:44:07 +0200261 def is_safe_attribute(self, obj, attr, value):
Armin Ronacherc63243e2008-04-14 22:53:58 +0200262 """The sandboxed environment will call this method to check if the
263 attribute of an object is safe to access. Per default all attributes
264 starting with an underscore are considered private as well as the
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200265 special attributes of internal python objects as returned by the
266 :func:`is_internal_attribute` function.
Armin Ronacherc63243e2008-04-14 22:53:58 +0200267 """
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200268 return not (attr.startswith('_') or is_internal_attribute(obj, attr))
Armin Ronacherc63243e2008-04-14 22:53:58 +0200269
270 def is_safe_callable(self, obj):
271 """Check if an object is safely callable. Per default a function is
272 considered safe unless the `unsafe_callable` attribute exists and is
Armin Ronacher7ceced52008-05-03 10:15:31 +0200273 True. Override this method to alter the behavior, but this won't
Armin Ronacherc63243e2008-04-14 22:53:58 +0200274 affect the `unsafe` decorator from this module.
275 """
Armin Ronacherd9455c12010-11-29 12:39:11 +0100276 return not (getattr(obj, 'unsafe_callable', False) or
Armin Ronacher7ceced52008-05-03 10:15:31 +0200277 getattr(obj, 'alters_data', False))
Armin Ronacherc63243e2008-04-14 22:53:58 +0200278
Armin Ronachera9195382010-11-29 13:21:57 +0100279 def call_binop(self, context, operator, left, right):
280 """For intercepted binary operator calls (:meth:`intercepted_binops`)
281 this function is executed instead of the builtin operator. This can
282 be used to fine tune the behavior of certain operators.
283
284 .. versionadded:: 2.6
285 """
286 return self.binop_table[operator](left, right)
287
288 def call_unop(self, context, operator, arg):
289 """For intercepted unary operator calls (:meth:`intercepted_unops`)
290 this function is executed instead of the builtin operator. This can
291 be used to fine tune the behavior of certain operators.
292
293 .. versionadded:: 2.6
294 """
295 return self.unop_table[operator](arg)
296
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200297 def getitem(self, obj, argument):
Armin Ronacherc63243e2008-04-14 22:53:58 +0200298 """Subscribe an object from sandboxed code."""
Armin Ronacher9a822052008-04-17 18:44:07 +0200299 try:
300 return obj[argument]
Armin Ronacherc63243e2008-04-14 22:53:58 +0200301 except (TypeError, LookupError):
Armin Ronacherf15f5f72008-05-26 12:21:45 +0200302 if isinstance(argument, basestring):
303 try:
304 attr = str(argument)
Ian Lewisab014bd2010-10-31 20:29:28 +0900305 except Exception:
Armin Ronacherf15f5f72008-05-26 12:21:45 +0200306 pass
307 else:
308 try:
309 value = getattr(obj, attr)
310 except AttributeError:
311 pass
312 else:
313 if self.is_safe_attribute(obj, argument, value):
314 return value
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200315 return self.unsafe_undefined(obj, argument)
Armin Ronacher9a822052008-04-17 18:44:07 +0200316 return self.undefined(obj=obj, name=argument)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200317
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200318 def getattr(self, obj, attribute):
319 """Subscribe an object from sandboxed code and prefer the
320 attribute. The attribute passed *must* be a bytestring.
321 """
322 try:
323 value = getattr(obj, attribute)
324 except AttributeError:
325 try:
Armin Ronacher9efe0812008-11-02 12:22:00 +0100326 return obj[attribute]
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200327 except (TypeError, LookupError):
328 pass
329 else:
330 if self.is_safe_attribute(obj, attribute, value):
331 return value
332 return self.unsafe_undefined(obj, attribute)
Armin Ronacher9efe0812008-11-02 12:22:00 +0100333 return self.undefined(obj=obj, name=attribute)
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200334
335 def unsafe_undefined(self, obj, attribute):
336 """Return an undefined object for unsafe attributes."""
337 return self.undefined('access to attribute %r of %r '
338 'object is unsafe.' % (
339 attribute,
340 obj.__class__.__name__
341 ), name=attribute, obj=obj, exc=SecurityError)
342
Armin Ronacherfd310492008-05-25 00:16:51 +0200343 def call(__self, __context, __obj, *args, **kwargs):
Armin Ronacherc63243e2008-04-14 22:53:58 +0200344 """Call an object from sandboxed code."""
345 # the double prefixes are to avoid double keyword argument
346 # errors when proxying the call.
347 if not __self.is_safe_callable(__obj):
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200348 raise SecurityError('%r is not safely callable' % (__obj,))
Armin Ronacherfd310492008-05-25 00:16:51 +0200349 return __context.call(__obj, *args, **kwargs)
Armin Ronacher522cad62008-05-17 13:55:37 +0200350
351
352class ImmutableSandboxedEnvironment(SandboxedEnvironment):
353 """Works exactly like the regular `SandboxedEnvironment` but does not
354 permit modifications on the builtin mutable objects `list`, `set`, and
Armin Ronacherd71fff02008-05-26 23:57:07 +0200355 `dict` by using the :func:`modifies_known_mutable` function.
Armin Ronacher522cad62008-05-17 13:55:37 +0200356 """
357
358 def is_safe_attribute(self, obj, attr, value):
359 if not SandboxedEnvironment.is_safe_attribute(self, obj, attr, value):
360 return False
Armin Ronacherd71fff02008-05-26 23:57:07 +0200361 return not modifies_known_mutable(obj, attr)