1

I am using Jinja2 as my templating engine for an admin dashboard, that displays some user feedback. I worry that an attacker could type some python code as their feedback and the Jinja2 template could execute that.

I.e.

An attacker might put the following as their feedback:

__import__('subprocess').getoutput('tree')

When the templater renders this, i.e.

feedback = "__import__('subprocess').getoutput('tree')"
Template("{{ feedback }}").render(feedback=feedback)

The tree command is run in the terminal.

How can I sanitise my strings so that they do not include any python code which might allow them access to my server via the command line?

7
  • 1
    Escape (or remove) { characters in the user-supplied string. Maybe jinja2 has some escape function to do it better.
    – pts
    Commented Oct 3, 2022 at 18:51
  • I did not mean that the things between the {{}} brackets. Please read new edit. Commented Oct 3, 2022 at 18:53
  • I mean that the string contains the code, and is stored as a string variable. This is interpolated, and executed by the Jinja2 templater. Commented Oct 3, 2022 at 18:55
  • 2
    The template {{ feedback }} in your code is already safe and correct: Python commands within the feedback string variable won't be executed.
    – pts
    Commented Oct 3, 2022 at 19:00
  • 1
    Unless you do {{ feedback | safe }}, your ... well, safe: jinja.palletsprojects.com/en/3.1.x/templates/… Commented Oct 3, 2022 at 19:05

1 Answer 1

0

The solution is that the templater only executes it if you put it directly in the template.

So...

Template("{{ __import__('subprocess').getoutput('tree') }}").render()

executes the code.

Whereas...

x = "__import__('subprocess').getoutput('tree')"
Template("{{ x }}").render(x=x)

Will not. So treat them as strings and vulnerabilities are mitigated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.