Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for Jinja's tojson filter to properly escape JSON values #1483

Open
RealOrangeOne opened this issue Feb 19, 2025 · 0 comments
Open

Comments

@RealOrangeOne
Copy link

In Jinja2, it's possible to pass user-controlled data into a template, safe that the browser won't parse it as a script tag:

For example, with foo = "</script><script>console.log(\'xss\');//"

<script>
  var somedata = {{ foo|tojson }};
</script>

Becomes:

<script>
  var somedata = "\u0060xscript\u0062x\u0060xscript\u0062xconsole.log('xss');//";
</script>

Which remains a plan string, rather than being parsed as HTML.

However, nunjucks has no such protections. If rendering a template with the same context as above:

<script>
  var somedata = {{ foo }};
</script>

Becomes:

<script>
  var somedata = &quot;&lt;/script&gt;&lt;script&gt;console.log(&#39;xss&#39;);//&quot;;
</script>

Which isn't valid because of the escaping (all fine so far), and marking the string as safe is a security issue:

<script>
  var somedata = "</script><script>console.log('xss');//";
</script>

Because, as GitHub helpfully shows, the HTML takes precedence. django-argonauts has a great write-up of the problem. |dump doesn't solve the problem, as it still uses HTML escape codes, rather than JSON.

Is there a way to correctly sanitize this data, without relying on manually chaining |replace calls to strip out the offending characters?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant