1 # -*- coding: utf-8 -*-
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.
10 The behavior can be changed by subclassing the environment.
12 :copyright: Copyright 2008 by Armin Ronacher.
16 from jinja2.runtime import Undefined
17 from jinja2.environment import Environment
18 from jinja2.exceptions import SecurityError
19 from jinja2.utils import FunctionType, MethodType, TracebackType, CodeType, \
20 FrameType, GeneratorType
23 #: maximum number of items a range may produce
26 #: attributes of function objects that are considered unsafe.
27 UNSAFE_FUNCTION_ATTRIBUTES = set(['func_closure', 'func_code', 'func_dict',
28 'func_defaults', 'func_globals'])
30 #: unsafe method attributes. function attributes are unsafe for methods too
31 UNSAFE_METHOD_ATTRIBUTES = set(['im_class', 'im_func', 'im_self'])
34 from collections import deque
35 from sets import Set, ImmutableSet
36 from UserDict import UserDict, DictMixin
37 from UserList import UserList
38 _mutable_set_types = (ImmutableSet, Set, set)
39 _mutable_mapping_types = (UserDict, DictMixin, dict)
40 _mutable_sequence_types = (UserList, list)
42 #: register Python 2.6 abstract base classes
44 from collections import MutableSet, MutableMapping, MutableSequence
45 _mutable_set_types += (MutableSet,)
46 _mutable_mapping_types += (MutableMapping,)
47 _mutable_sequence_types += (MutableSequence,)
52 (_mutable_set_types, frozenset([
53 'add', 'clear', 'difference_update', 'discard', 'pop', 'remove',
54 'symmetric_difference_update', 'update'
56 (_mutable_mapping_types, frozenset([
57 'clear', 'pop', 'popitem', 'setdefault', 'update'
59 (_mutable_sequence_types, frozenset([
60 'append', 'reverse', 'insert', 'sort', 'extend', 'remove'
63 'append', 'appendleft', 'clear', 'extend', 'extendleft', 'pop',
64 'popleft', 'remove', 'rotate'
69 def safe_range(*args):
70 """A range that can't generate ranges with a length of more than
74 if len(rng) > MAX_RANGE:
75 raise OverflowError('range too big, maximum size for range is %d' %
82 Mark a function or method as unsafe::
88 f.unsafe_callable = True
92 def is_internal_attribute(obj, attr):
93 """Test if the attribute given is an internal python attribute. For
94 example this function returns `True` for the `func_code` attribute of
95 python objects. This is useful if the environment method
96 :meth:`~SandboxedEnvironment.is_safe_attribute` is overriden.
98 >>> from jinja2.sandbox import is_internal_attribute
99 >>> is_internal_attribute(lambda: None, "func_code")
101 >>> is_internal_attribute((lambda x:x).func_code, 'co_code')
103 >>> is_internal_attribute(str, "upper")
106 if isinstance(obj, FunctionType):
107 if attr in UNSAFE_FUNCTION_ATTRIBUTES:
109 elif isinstance(obj, MethodType):
110 if attr in UNSAFE_FUNCTION_ATTRIBUTES or \
111 attr in UNSAFE_METHOD_ATTRIBUTES:
113 elif isinstance(obj, type):
116 elif isinstance(obj, (CodeType, TracebackType, FrameType)):
118 elif isinstance(obj, GeneratorType):
119 if attr == 'gi_frame':
121 return attr.startswith('__')
124 def modifies_known_mutable(obj, attr):
125 """This function checks if an attribute on a builtin mutable object
126 (list, dict, set or deque) would modify it if called. It also supports
127 the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and
128 with Python 2.6 onwards the abstract base classes `MutableSet`,
129 `MutableMapping`, and `MutableSequence`.
131 >>> modifies_known_mutable({}, "clear")
133 >>> modifies_known_mutable({}, "keys")
135 >>> modifies_known_mutable([], "append")
137 >>> modifies_known_mutable([], "index")
140 If called with an unsupported object (such as unicode) `False` is
143 >>> modifies_known_mutable("foo", "upper")
146 for typespec, unsafe in _mutable_spec:
147 if isinstance(obj, typespec):
148 return attr in unsafe
152 class SandboxedEnvironment(Environment):
153 """The sandboxed environment. It works like the regular environment but
154 tells the compiler to generate sandboxed code. Additionally subclasses of
155 this environment may override the methods that tell the runtime what
156 attributes or functions are safe to access.
158 If the template tries to access insecure code a :exc:`SecurityError` is
159 raised. However also other exceptions may occour during the rendering so
160 the caller has to ensure that all exceptions are catched.
164 def __init__(self, *args, **kwargs):
165 Environment.__init__(self, *args, **kwargs)
166 self.globals['range'] = safe_range
168 def is_safe_attribute(self, obj, attr, value):
169 """The sandboxed environment will call this method to check if the
170 attribute of an object is safe to access. Per default all attributes
171 starting with an underscore are considered private as well as the
172 special attributes of internal python objects as returned by the
173 :func:`is_internal_attribute` function.
175 return not (attr.startswith('_') or is_internal_attribute(obj, attr))
177 def is_safe_callable(self, obj):
178 """Check if an object is safely callable. Per default a function is
179 considered safe unless the `unsafe_callable` attribute exists and is
180 True. Override this method to alter the behavior, but this won't
181 affect the `unsafe` decorator from this module.
183 return not (getattr(obj, 'unsafe_callable', False) or \
184 getattr(obj, 'alters_data', False))
186 def getitem(self, obj, argument):
187 """Subscribe an object from sandboxed code."""
190 except (TypeError, LookupError):
191 if isinstance(argument, basestring):
198 value = getattr(obj, attr)
199 except AttributeError:
202 if self.is_safe_attribute(obj, argument, value):
204 return self.unsafe_undefined(obj, argument)
205 return self.undefined(obj=obj, name=argument)
207 def getattr(self, obj, attribute):
208 """Subscribe an object from sandboxed code and prefer the
209 attribute. The attribute passed *must* be a bytestring.
212 value = getattr(obj, attribute)
213 except AttributeError:
215 return obj[attribute]
216 except (TypeError, LookupError):
219 if self.is_safe_attribute(obj, attribute, value):
221 return self.unsafe_undefined(obj, attribute)
222 return self.undefined(obj=obj, name=attribute)
224 def unsafe_undefined(self, obj, attribute):
225 """Return an undefined object for unsafe attributes."""
226 return self.undefined('access to attribute %r of %r '
227 'object is unsafe.' % (
229 obj.__class__.__name__
230 ), name=attribute, obj=obj, exc=SecurityError)
232 def call(__self, __context, __obj, *args, **kwargs):
233 """Call an object from sandboxed code."""
234 # the double prefixes are to avoid double keyword argument
235 # errors when proxying the call.
236 if not __self.is_safe_callable(__obj):
237 raise SecurityError('%r is not safely callable' % (__obj,))
238 return __context.call(__obj, *args, **kwargs)
241 class ImmutableSandboxedEnvironment(SandboxedEnvironment):
242 """Works exactly like the regular `SandboxedEnvironment` but does not
243 permit modifications on the builtin mutable objects `list`, `set`, and
244 `dict` by using the :func:`modifies_known_mutable` function.
247 def is_safe_attribute(self, obj, attr, value):
248 if not SandboxedEnvironment.is_safe_attribute(self, obj, attr, value):
250 return not modifies_known_mutable(obj, attr)