3 ms·
> Python's Jinja templating language has the concept of "safe" and "unsafe" strings. By default all strings are unsafe (meaning they will be escaped wherever th
by JimDabell 11y ago
> Python's Jinja templating language has the concept of "safe" and "unsafe" strings. By default all strings are unsafe (meaning they will be escaped wherever they are rendered) and you need to explicitly mark them as safe in order to be able to treat them as HTML.
That's good, but it's not ideal as it confuses HTML/unsafe. An unwary developer could output untrusted text "safely" and still open up an XSS vulnerability – because they could be outputting to JavaScript embedded within HTML. Yes, Jinja will encode it as HTML by default, rendering it "safe" in terms of the HTML parser, but that still doesn't make it actually safe.
Example:
alert("Hello, {{user.name}}!");
By default, Jinja will encode this as HTML, meaning that you can't trick the HTML parser into injecting your HTML. But it is still completely vulnerable to the exact same security vulnerability, except by tricking the JavaScript parser.
We should recognise what's actually the issue at play here. It's not really about whether data is safe or not. It's about correctly encoding data in a manner that's suitable for the context in which it is being output. Sometimes that's HTML, sometimes it's JavaScript, sometimes it's CSS, etc.
- marcosdumay 11y agoYes, Jinja's "safe"/"unsafe" are just "html"/"text" by another name. One could create the more comprehensive "html"/"css"/"javascript"/"text" set in dynamic languages too, but Jinja doesn't.