pythondjangosnyk

Unsanitized input from an HTTP parameter flows into django.http.HttpResponse


In my python (django) project, I have following code snippet

  someError = request.GET.get('error', None)

        if someError is not None:
            self.logger.exception(f'Authorization failed with error: {someError}')
            return HttpResponse(f'Authorization failed with error: {someError}')

The code is working fine, howevere when scheduled Snyk scan is run then it complains this

Info: Unsanitized input from an HTTP parameter flows into django.http.HttpResponse, where it is used to render an HTML page returned to the user. This may result in a Cross-Site Scripting attack (XSS).

I did some research and tried to convert someError object as string but it is still complaining about that. Can someone please let me know how to sanitize the error? Thanks in advance


Solution

  • This is a trivial example but it will be a good quick explanation. Imagine you have a user whose Request was hijacked client side by a cross site script. The attacker changes the Request to send their own payload. Since you receive this payload and return it as is to the client, the client becomes vulnerable to the attack when the payload is received by the client’s browser. This is called a Cross-Site Scripting attack.

    You got this vulnerability on your server by doing this:

    someError = request.GET.get('error', None)
        •••Rest of code•••
        return HttpResponse(f'Authorization failed with error: {someError}')

    You send the URL GET method parameter 'error' as is without any validation nor sanitization.

    Snyk has to warn you of this because it can easily be exploited. Don’t trust user input. Don’t even assume anything about user input. Do your validation, sanitization, anything else you can possibly do to have peace of mind.

    The OP is not production code and my example is not a real world example but real world examples are worse and we should keep reminding ourselves that the world is not a bed of roses so stay safe.