Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent XSS attacks in Django REST API CharFields?

I'm currently working on an app using Django 2.2 with djangorestframework 3.9.2. I am aware that Django itself provides protection against SQL Injection or in in the context of displaying content in django templates (XSS), but I've noticed that while I use Django REST API, all the CharFields in my models are not sanitized automatically.

Note: this question does not apply to django templates.

E.g. having a direct messages model (message/models.py):

class Message(models.Model):
    sender = models.ForeignKey(...)
    receiver = models.ForeignKey(...)
    message = models.CharField(max_length=1200)
    timestamp = models.DateTimeField(...)
    is_read = models.BooleanField(default=False)

Actually does not prevent anyone from sending a message with content <script>alert("Hello there");</script>. It will be saved in database and returned by the REST API as is, allowing to remotely run any JS script (basically a Cross Site Scripting).

Is this an expected behavior? How can this be prevented?

like image 565
Lis Avatar asked Dec 07 '22 10:12

Lis


1 Answers

You can use escape() method inside serializer's validation:

from django.utils.html import escape

class MySerializer:
    def validate_myfield(self, value):
        return escape(value)
like image 146
neverwalkaloner Avatar answered Dec 30 '22 12:12

neverwalkaloner