Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 1 | # -*- 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 | |
| 12 | :copyright: Copyright 2008 by Armin Ronacher. |
| 13 | :license: BSD. |
| 14 | """ |
Armin Ronacher | b5f522c | 2008-05-04 18:25:02 +0200 | [diff] [blame] | 15 | from types import FunctionType, MethodType, TracebackType, CodeType, \ |
| 16 | FrameType, GeneratorType |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 17 | from jinja2.runtime import Undefined |
| 18 | from jinja2.environment import Environment |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame^] | 19 | from jinja2.exceptions import SecurityError |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 20 | |
| 21 | |
| 22 | #: maximum number of items a range may produce |
| 23 | MAX_RANGE = 100000 |
| 24 | |
Armin Ronacher | 76c280b | 2008-05-04 12:31:48 +0200 | [diff] [blame] | 25 | #: attributes of function objects that are considered unsafe. |
| 26 | UNSAFE_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 |
| 30 | UNSAFE_METHOD_ATTRIBUTES = set(['im_class', 'im_func', 'im_self']) |
| 31 | |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 32 | |
| 33 | def safe_range(*args): |
| 34 | """A range that can't generate ranges with a length of more than |
Armin Ronacher | 7ceced5 | 2008-05-03 10:15:31 +0200 | [diff] [blame] | 35 | MAX_RANGE items. |
| 36 | """ |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 37 | rng = xrange(*args) |
| 38 | if len(rng) > MAX_RANGE: |
Armin Ronacher | 76c280b | 2008-05-04 12:31:48 +0200 | [diff] [blame] | 39 | raise OverflowError('range too big, maximum size for range is %d' % |
| 40 | MAX_RANGE) |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 41 | return rng |
| 42 | |
| 43 | |
| 44 | def unsafe(f): |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame^] | 45 | """ |
| 46 | Mark a function or method as unsafe:: |
| 47 | |
| 48 | @unsafe |
| 49 | def delete(self): |
| 50 | pass |
| 51 | """ |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 52 | f.unsafe_callable = True |
| 53 | return f |
| 54 | |
| 55 | |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame^] | 56 | def is_internal_attribute(obj, attr): |
| 57 | """Test if the attribute given is an internal python attribute. For |
| 58 | example this function returns `True` for the `func_code` attribute of |
| 59 | python objects. This is useful if the environment method |
| 60 | :meth:`~SandboxedEnvironment.is_safe_attribute` is overriden. |
| 61 | |
| 62 | >>> from jinja2.sandbox import is_internal_attribute |
| 63 | >>> is_internal_attribute(lambda: None, "func_code") |
| 64 | True |
| 65 | >>> is_internal_attribute((lambda x:x).func_code, 'co_code') |
| 66 | True |
| 67 | >>> is_internal_attribute(str, "upper") |
| 68 | False |
| 69 | """ |
| 70 | if isinstance(obj, FunctionType): |
| 71 | return attr in UNSAFE_FUNCTION_ATTRIBUTES |
| 72 | if isinstance(obj, MethodType): |
| 73 | return attr in UNSAFE_FUNCTION_ATTRIBUTES or \ |
| 74 | attr in UNSAFE_METHOD_ATTRIBUTES |
| 75 | if isinstance(obj, type): |
| 76 | return attr == 'mro' |
| 77 | if isinstance(obj, (CodeType, TracebackType, FrameType)): |
| 78 | return True |
| 79 | if isinstance(obj, GeneratorType): |
| 80 | return attr == 'gi_frame' |
| 81 | return attr.startswith('__') |
| 82 | |
| 83 | |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 84 | class SandboxedEnvironment(Environment): |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame^] | 85 | """The sandboxed environment. It works like the regular environment but |
| 86 | tells the compiler to generate sandboxed code. Additionally subclasses of |
| 87 | this environment may override the methods that tell the runtime what |
| 88 | attributes or functions are safe to access. |
| 89 | |
| 90 | If the template tries to access insecure code a :exc:`SecurityError` is |
| 91 | raised. However also other exceptions may occour during the rendering so |
| 92 | the caller has to ensure that all exceptions are catched. |
| 93 | """ |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 94 | sandboxed = True |
| 95 | |
| 96 | def __init__(self, *args, **kwargs): |
| 97 | Environment.__init__(self, *args, **kwargs) |
| 98 | self.globals['range'] = safe_range |
| 99 | |
Armin Ronacher | 9a82205 | 2008-04-17 18:44:07 +0200 | [diff] [blame] | 100 | def is_safe_attribute(self, obj, attr, value): |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 101 | """The sandboxed environment will call this method to check if the |
| 102 | attribute of an object is safe to access. Per default all attributes |
| 103 | starting with an underscore are considered private as well as the |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame^] | 104 | special attributes of internal python objects as returned by the |
| 105 | :func:`is_internal_attribute` function. |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 106 | """ |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame^] | 107 | return not (attr.startswith('_') or is_internal_attribute(obj, attr)) |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 108 | |
| 109 | def is_safe_callable(self, obj): |
| 110 | """Check if an object is safely callable. Per default a function is |
| 111 | considered safe unless the `unsafe_callable` attribute exists and is |
Armin Ronacher | 7ceced5 | 2008-05-03 10:15:31 +0200 | [diff] [blame] | 112 | True. Override this method to alter the behavior, but this won't |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 113 | affect the `unsafe` decorator from this module. |
| 114 | """ |
Armin Ronacher | 7ceced5 | 2008-05-03 10:15:31 +0200 | [diff] [blame] | 115 | return not (getattr(obj, 'unsafe_callable', False) or \ |
| 116 | getattr(obj, 'alters_data', False)) |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 117 | |
Armin Ronacher | 9a82205 | 2008-04-17 18:44:07 +0200 | [diff] [blame] | 118 | def subscribe(self, obj, argument): |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 119 | """Subscribe an object from sandboxed code.""" |
Armin Ronacher | 9a82205 | 2008-04-17 18:44:07 +0200 | [diff] [blame] | 120 | is_unsafe = False |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 121 | try: |
Armin Ronacher | 9a82205 | 2008-04-17 18:44:07 +0200 | [diff] [blame] | 122 | value = getattr(obj, str(argument)) |
| 123 | except (AttributeError, UnicodeError): |
| 124 | pass |
| 125 | else: |
| 126 | if self.is_safe_attribute(obj, argument, value): |
| 127 | return value |
| 128 | is_unsafe = True |
| 129 | try: |
| 130 | return obj[argument] |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 131 | except (TypeError, LookupError): |
Armin Ronacher | 9a82205 | 2008-04-17 18:44:07 +0200 | [diff] [blame] | 132 | if is_unsafe: |
| 133 | return self.undefined('access to attribute %r of %r object is' |
| 134 | ' unsafe.' % ( |
| 135 | argument, |
| 136 | obj.__class__.__name__ |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame^] | 137 | ), name=argument, exc=SecurityError) |
Armin Ronacher | 9a82205 | 2008-04-17 18:44:07 +0200 | [diff] [blame] | 138 | return self.undefined(obj=obj, name=argument) |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 139 | |
| 140 | def call(__self, __obj, *args, **kwargs): |
| 141 | """Call an object from sandboxed code.""" |
| 142 | # the double prefixes are to avoid double keyword argument |
| 143 | # errors when proxying the call. |
| 144 | if not __self.is_safe_callable(__obj): |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame^] | 145 | raise SecurityError('%r is not safely callable' % (__obj,)) |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 146 | return __obj(*args, **kwargs) |