SadSalad
SadSalad

Reputation: 89

How to prevent XSS attack in django

I'm trying to prevent XSS attacks in Django. Is it ok to use {{ body|escape }} in my HTML file only? How can I filter data in the backend?

Upvotes: 0

Views: 4839

Answers (1)

codeadict
codeadict

Reputation: 2753

Not every case is the same security-wise, so it's hard to give complete advice without seeing your application and the use cases and the version of Django you use.

If you use the Django's template system and make sure that auto-escaping is enabled (it is enabled by default in recent versions), you're 95% percent safe. Django provides an auto-escaping mechanism for stopping XSS: it'll automatically escape data that is dynamically inserted into the template. You still have to be aware of some issues:

  • Use quotes around all the attributes where dynamic data is inserted. Use <img alt="{{somevar}}"> instead of <img alt={{somevar}} ...>. Django's auto-escaping will not cover your unquoted attribute values.

  • Data inserted into CSS (style tags and attributes) or Javascript (script blocks, event handlers, and onclick attributes): you must manually escape the data using escaping rules that are appropriate for CSS or Javascript (probably using a custom filter on the Python side).

  • Data inserted into a URL attribute (href, img src): you must manually validate the URL to make sure it is safe by checking the protocol against a whitelist of allowed protocols (e.g. https:, mailto:, ... but never javascript:).

  • Avoid setting HTML attributes from user input.

  • If you use mark_safe, make sure you know what you are doing and the data is really "safe".

There is always more but this covers the most known issues. Always make sure to refer to OWASP to understand the different XSS attacks and how they apply to your specific application:

Upvotes: 4

Related Questions