damon
damon

Reputation: 8477

preventing xss hole in django

In the Django docs it says:

Django templates escape specific characters which are particularly dangerous to HTML. While this protects users from most malicious input, it is not entirely foolproof. For example, it will not protect the following:

 <style class={{ var }}>...</style>

If var is set to 'class1 onmouseover=javascript:func()', this can result in unauthorized JavaScript execution, depending on how the browser renders imperfect HTML.

How can I prevent this?

Upvotes: 1

Views: 1050

Answers (2)

Kevin Reid
Kevin Reid

Reputation: 43842

I'm not especially familiar with Django, but it looks to me like the error they intended to point out is that there are no quotes around the attribute value, meaning that the space in the example value causes the rest of the string (onmouseover=...) to be interpreted as a separate attribute. Instead, you should put quotes like so:

<style class="{{ var }}">...</style>

If I understand correctly, this would be safe since all the characters that could interfere with the quoting are escaped. You might want to verify that interpretation; for example, write <span title="{{ var }}">foo</span>, run the template with foo set to <>"'&, and then make sure that they're properly escaped in the HTML and that the title appears in the browser with the original characters.

Upvotes: 1

Ngenator
Ngenator

Reputation: 11269

One thing you can do is not allow variable classes. You can use something like

<style class={% if class_foo %}foo{% elif class_bar %}bar{% else %}baz{% endif %}>...</style>

There are also filters available to prevent xss elsewhere: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#std:templatefilter-escape

Upvotes: 1

Related Questions