Skip to content
CSRF Write-up Beginner

The CSRF Token Nobody Checked

Messenger.com's backend did not verify the anti-forgery token on state-changing requests, so requests with the token removed still succeeded. An attacker could make a logged-in user's browser perform actions such as changing settings, sending messages, removing participants from threads, or deleting threads.

Muhammad Asim Shahzad Follow

Published on masimshahzad.medium.com

Bug Bounty

Muhammad Asim Shahzad, on masimshahzad.medium.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 4 min read.

Context

Messenger.com launched in April 2015 as a web version of Facebook's messaging product. Its clients sent an anti-forgery token with state-changing requests, the usual defence against cross-site request forgery. Whitton tested whether the new domain's backend rejected requests without the token.

This article is an analytical case study of that public disclosure. The facts come from Whitton's post and from related research by Mazin Ahmed; the remediation suggestions below are analysis, not part of the original finding.

AI-generated illustration From the original on masimshahzad.medium.com

Setup

No special tooling is described. The test is a comparison: send a normal state-changing request, then send the same request with the anti-forgery parameter removed or altered, and observe whether the server still treats it as a success.

Finding it

Whitton compared normal requests with variants that tampered with the token. On Messenger.com, removing the token still produced a normal success response for a settings change and for removing a participant from a group thread. After testing a few endpoints he concluded that the check was missing on every request, not just on the two he had exercised.

What made this look wrong is the asymmetry: the client-side code still carried the token plumbing, so the requests looked protected, but the server did not reject the requests that lacked it. A token that is sent but never compared provides no protection at all.

Exploitation

Step 1: capture a legitimate state-changing request

Log in to Messenger.com, perform a normal action such as changing a setting or removing a participant from a group thread, and capture the request. The request carries the session cookie and the anti-forgery parameter.

Step 2: remove the anti-forgery parameter

Replay the same request with the token parameter removed entirely. The server responds with a normal success response, the same as for the legitimate request. The session cookie alone is enough to authorise the action.

Step 3: repeat across endpoints

Run the same removal test against a few more state-changing endpoints. The result is consistent: the check is absent on every request tested, so the missing validation is site-wide rather than confined to one handler.

Step 4: deliver from an attacker page

Because browsers attach session cookies to a request regardless of which site triggered it, any page a logged-in user visits can submit these requests. The attacker does not need to read the response; the state change happens on the server as soon as the request arrives.

Root cause

A new product on a separate origin inherited the client-side token plumbing but not the server-side enforcement. The clients kept sending the token, so the surface looked defended, while the backend accepted requests without it. The existing defence, the token itself, did not stop the attack because nothing on the server compared the supplied value with server-held state.

Impact

Any page a logged-in user visited could trigger actions in that user's Messenger account. Beyond settings, the disclosures describe removing people from threads, sending messages, and deleting threads on the victim's behalf. For a messaging product, silent message spoofing is a trust failure rather than a cosmetic bug.

Fix

Facebook shipped what Whitton called a simple and quick fix: tokens are now verified everywhere. The defensive measures below are analysis rather than part of the disclosure.

  1. Enforce in one place, default-deny. Verify the token in shared middleware that runs before any handler. Endpoints should opt out explicitly, never opt in.
  2. Compare tokens in constant time against server-held state. A missing, empty, or wrong-length value fails the same way as a wrong one.
  3. Refuse state changes over safe methods. GET and HEAD must never mutate data, or a method switch quietly bypasses the check.
  4. Layer SameSite cookies and Origin checks. SameSite=Lax or Strict blocks most cross-site cookie sends; an Origin or Fetch-Metadata check rejects cross-site writes even if a token check regresses.
Python
SAFE_METHODS = {"GET", "HEAD", "OPTIONS"}
Python
def csrf_gate(request, route):
    if request.method in SAFE_METHODS:
        if route.mutates_state:
            raise Rejected("state change over safe method")
        return
    if route.csrf_exempt_reason:          # explicit, reviewed opt-out only
        return
    site = request.headers.get("Sec-Fetch-Site")
    if site not in (None, "same-origin", "same-site"):
        raise Rejected("cross-site write")
    expected = request.session.get("csrf_token")
    supplied = request.form.get("csrf_token") or request.headers.get("X-CSRF-Token")
    if not expected or not supplied:
        raise Rejected("missing token")   # absent == invalid
    if not constant_time_equal(expected, supplied):
        raise Rejected("bad token")
  1. Regression-test the negative cases in CI. For every mutating route, assert rejection with the token removed, emptied, altered, and with the method switched. Diff the route list against the test list so new endpoints cannot ship untested.

Variants to test

  • Token removed: replay a state-changing request without the anti-forgery parameter. A positive result is a normal success response, as seen here.
  • Token emptied or altered: send an empty value or a modified one. A positive result is that the server accepts it instead of rejecting it.
  • Method switch: send a state-changing action over GET or HEAD. A positive result is that the change takes effect, which bypasses a check that only guards POST.
  • New origins and launches: apply the same tests to a recently launched domain or product that shares code with an older one.
  • Negative-path coverage: for each mutating route, confirm that rejection actually happens with the token removed, emptied, altered, and with the method switched. A suite that only checks the success path proves nothing.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 13 min read.

What happened, in plain words

In April 2015, Facebook launched Messenger.com, a website version of its Messenger chat product. The site's pages sent a special secret value, called a CSRF token, along with every action that changes something on the account, such as saving a setting or removing someone from a group chat. That token is the standard defence against a class of attack called cross-site request forgery, or CSRF.

A security researcher, Jack Whitton, asked a simple question: does the server on this new site actually check that token, or does it just expect one to be there? The answer was that the server never compared it to anything. Requests with the token removed entirely still succeeded. After testing a few different actions he concluded the check was missing everywhere, not just on the two actions he had tried. Facebook shipped what he described as a simple and quick fix: tokens are now verified everywhere.

This article is a study of that public disclosure. The facts come from Whitton's post and from related research by Mazin Ahmed; the fix suggestions further down are analysis, not part of the original finding.

AI-generated illustration From the original on masimshahzad.medium.com

The ideas you need first

Before the steps make sense, here are the few concepts involved, explained from zero.

  • A cookie is a small piece of data a website asks your browser to store and send back on every request to that site. The most important one here is the session cookie: after you log in, the server gives your browser a cookie that identifies you, so you do not have to type your password on every page. Your browser attaches it automatically, without asking you.
  • A token in this context is a second, unguessable value that the site's pages include with actions that change data. The idea is that only the real site can know it, so a request coming from somewhere else cannot include the right one. The server is supposed to compare the token it receives with the one it stored for your session, and refuse the request if they do not match.
  • CSRF (cross-site request forgery) is an attack that abuses the fact that your browser sends your cookies to a site no matter which page triggered the request. If you are logged in to a site and then visit a malicious page, that page can quietly make your browser send a request to the logged-in site. Your cookie goes along with it, so the site thinks the request came from you.
  • An endpoint is one specific address on a server that does one specific job, for example "save my settings" or "remove this person from this group". A website is made of many endpoints.
  • An API is the set of endpoints a site's own pages talk to behind the scenes. When you click a button, the page does not reload everything; it sends a request to an API endpoint, and the server does the work and replies.
  • A state-changing request is any request that alters data on the server: saving a setting, sending a message, deleting a thread. The opposite is a request that only reads data, such as loading a page.
  • An origin is the combination of protocol, hostname and port that a browser treats as one site, for example https://messenger.com. Browsers use origins to decide what counts as "the same site" and what counts as "somewhere else".
  • A success response is the server's normal reply saying the action worked. If a request that should have been rejected gets a success response instead, the protection is not working.

Setting up the test

The write-up describes no special tools. The test itself is a comparison: send a normal state-changing request, then send the same request with the anti-forgery parameter removed or changed, and watch whether the server still treats it as a success.

Why compare rather than just look? Because a request that carries a token looks protected. The only way to know whether the server checks it is to take the token away and see what happens.

Finding it

Whitton compared normal requests with variants where the token had been tampered with. On Messenger.com, removing the token still produced a normal success response for a settings change and for removing a participant from a group thread. After testing a few endpoints he concluded the check was missing on every request, not just on the two he had exercised.

What made this look wrong is the mismatch between the two sides. The pages you see in the browser still carried all the machinery for sending the token, so the requests looked protected. But the server did not reject the requests that lacked it. A token that is sent but never compared gives no protection at all: it is decoration.

Exploitation, step by step

Step 1: capture a legitimate state-changing request

Log in to Messenger.com, perform a normal action such as changing a setting or removing a participant from a group thread, and capture the request. The request carries the session cookie and the anti-forgery parameter.

Capturing means recording the exact request your browser sent, so you can send it again yourself. You do this because you need a known-good example to compare against. The captured request contains two things that matter: the session cookie, which identifies you, and the anti-forgery parameter, which is supposed to prove the request came from the real site.

Step 2: remove the anti-forgery parameter

Replay the same request with the token parameter removed entirely. The server responds with a normal success response, the same as for the legitimate request. The session cookie alone is enough to authorise the action.

Replaying means sending the captured request again, unchanged except for the one thing you are testing. Removing the token is the whole experiment: if the server still says the action succeeded, then the token was never being checked. The session cookie alone was enough to prove who you were and to authorise the change.

Step 3: repeat across endpoints

Run the same removal test against a few more state-changing endpoints. The result is consistent: the check is absent on every request tested, so the missing validation is site-wide rather than confined to one handler.

One endpoint failing could be a single forgotten piece of code. Several failing the same way points to something shared: the check is simply not there anywhere on this new site.

Step 4: deliver from an attacker page

Because browsers attach session cookies to a request regardless of which site triggered it, any page a logged-in user visits can submit these requests. The attacker does not need to read the response; the state change happens on the server as soon as the request arrives.

This is the part that turns a missing check into an attack. An attacker does not need to break into anything. They only need you, while logged in to Messenger.com, to load a page they control. That page quietly sends the request, your browser adds your cookie, and the server performs the action. The attacker never needs to see the reply, because the damage is already done on the server.

Why it happened

A new product on a separate origin inherited the client-side token plumbing but not the server-side enforcement. The pages kept sending the token, so the surface looked defended, while the backend accepted requests without it. The existing defence, the token itself, did not stop the attack because nothing on the server compared the supplied value with server-held state.

In plain terms: the new site copied the part of the code that sends the token, but not the part that checks it. Everything looked right from the outside, and nothing was right on the inside.

What an attacker could do

Any page a logged-in user visited could trigger actions in that user's Messenger account. Beyond settings, the disclosures describe removing people from threads, sending messages, and deleting threads on the victim's behalf. For a messaging product, silent message spoofing is a trust failure rather than a cosmetic bug.

Think about what it means when messages can be sent in your name without you knowing. In a chat product, the whole point is that a message from you really came from you. Losing that breaks trust in the product itself, which is why this is more serious than a cosmetic flaw.

The fix

Facebook shipped what Whitton called a simple and quick fix: tokens are now verified everywhere. The defensive measures below are analysis rather than part of the disclosure.

  1. Enforce in one place, default-deny. Verify the token in shared middleware that runs before any handler. Endpoints should opt out explicitly, never opt in.

    Middleware is code that runs in front of every request, before the code that handles the specific action. If the check lives there, a new endpoint is protected automatically. "Default-deny" means the safe behaviour is the default, and an endpoint has to be deliberately, visibly exempted to skip the check. The opposite, where each endpoint has to remember to add the check, is how this bug happens.

  2. Compare tokens in constant time against server-held state. A missing, empty, or wrong-length value fails the same way as a wrong one.

    Constant time means the comparison takes the same amount of time no matter how much of the value matches. A naive comparison can stop at the first wrong character, and the tiny difference in timing can leak information to an attacker. The second sentence is about consistency: a missing token, an empty one, or one of the wrong length should all be rejected exactly like a wrong one, with no special cases.

  3. Refuse state changes over safe methods. GET and HEAD must never mutate data, or a method switch quietly bypasses the check.

    Every request has a method, a word that says what kind of request it is. GET and HEAD are meant for reading only. If an action that changes data can be triggered with GET, then an attacker can skip the token check entirely by using that method instead of the usual one.

  4. Layer SameSite cookies and Origin checks. SameSite=Lax or Strict blocks most cross-site cookie sends; an Origin or Fetch-Metadata check rejects cross-site writes even if a token check regresses.

    SameSite is a setting on a cookie that tells the browser when to send it. With Lax or Strict, the browser withholds the cookie on most requests coming from other sites, which removes the fuel this attack needs. An Origin check looks at which site a request claims to come from and rejects writes from elsewhere. Fetch-Metadata is a set of headers the browser adds describing the request, including Sec-Fetch-Site, which says whether the request is same-origin, same-site or cross-site. These are extra layers, so that if the token check ever breaks again, the attack still fails.

Python
SAFE_METHODS = {"GET", "HEAD", "OPTIONS"}

This line defines a set, a collection of values, holding the request methods that are only supposed to read data: GET, HEAD and OPTIONS. The code below uses it to spot requests that claim to be read-only but actually change something.

Python
def csrf_gate(request, route):
    if request.method in SAFE_METHODS:
        if route.mutates_state:
            raise Rejected("state change over safe method")
        return
    if route.csrf_exempt_reason:          # explicit, reviewed opt-out only
        return
    site = request.headers.get("Sec-Fetch-Site")
    if site not in (None, "same-origin", "same-site"):
        raise Rejected("cross-site write")
    expected = request.session.get("csrf_token")
    supplied = request.form.get("csrf_token") or request.headers.get("X-CSRF-Token")
    if not expected or not supplied:
        raise Rejected("missing token")   # absent == invalid
    if not constant_time_equal(expected, supplied):
        raise Rejected("bad token")

Line by line, in plain words:

  • def csrf_gate(request, route): defines one function, a reusable block of code, that every request passes through before it reaches the code that does the actual work. It receives the request and the description of the endpoint being called.
  • if request.method in SAFE_METHODS: checks whether this request claims to be read-only.
  • if route.mutates_state: then checks whether this particular endpoint actually changes data. If it does, the request is lying about itself, so raise Rejected("state change over safe method") refuses it.
  • return lets a genuinely read-only request through without further checks.
  • if route.csrf_exempt_reason: allows an endpoint to skip the check, but only if it carries a written, reviewed reason. This is the explicit opt-out: nothing is exempt by accident.
  • site = request.headers.get("Sec-Fetch-Site") reads the header the browser adds saying where the request came from.
  • if site not in (None, "same-origin", "same-site"): rejects anything that is not from the same site. None is allowed because older browsers may not send the header at all.
  • expected = request.session.get("csrf_token") fetches the token the server stored for this user's session.
  • supplied = request.form.get("csrf_token") or request.headers.get("X-CSRF-Token") fetches the token the request actually sent, from the form body or from a header.
  • if not expected or not supplied: rejects the request if either side is missing. The comment # absent == invalid is the key idea: no token is treated exactly like a wrong token.
  • if not constant_time_equal(expected, supplied): compares the two values in constant time, and raise Rejected("bad token") refuses the request if they differ.
  1. Regression-test the negative cases in CI. For every mutating route, assert rejection with the token removed, emptied, altered, and with the method switched. Diff the route list against the test list so new endpoints cannot ship untested.

    CI is the automated system that runs tests every time code changes. A regression test checks that something which used to work still works, or in this case that something which should be blocked still is. The important part is testing the failure path: not "does a valid request succeed" but "is an invalid request refused". Comparing the list of endpoints against the list of tests means a newly added endpoint cannot go live without a test proving it rejects bad requests.

Other versions of the test

  • Token removed: replay a state-changing request without the anti-forgery parameter. A positive result is a normal success response, as seen here.
  • Token emptied or altered: send an empty value or a modified one. A positive result is that the server accepts it instead of rejecting it.
  • Method switch: send a state-changing action over GET or HEAD. A positive result is that the change takes effect, which bypasses a check that only guards POST.
  • New origins and launches: apply the same tests to a recently launched domain or product that shares code with an older one.
  • Negative-path coverage: for each mutating route, confirm that rejection actually happens with the token removed, emptied, altered, and with the method switched. A suite that only checks the success path proves nothing.

What to take away

  • Sending a token is not the defence; rejecting requests without a valid one is.
  • New domains and product launches deserve a fresh look at shared security controls.
  • Test the failure path: a CSRF suite that only checks success proves nothing.

Glossary

  • API: the set of endpoints a website's pages talk to behind the scenes to read and change data.
  • CI (continuous integration): an automated system that runs tests whenever code changes.
  • Cookie: a small piece of data a site stores in your browser and your browser sends back on every request to that site.
  • Cross-site request forgery (CSRF): an attack where a page on another site makes your browser send a request to a site you are logged in to, so your cookie goes along and the site treats it as your action.
  • CSRF token: an unguessable value sent with state-changing requests that the server is supposed to compare with its stored copy and reject on mismatch.
  • Constant-time comparison: comparing two values in a way that takes the same time regardless of where they differ, so timing reveals nothing.
  • Endpoint: one specific address on a server that performs one specific job.
  • Fetch-Metadata: headers the browser adds describing a request, including Sec-Fetch-Site, which says whether it is same-origin, same-site or cross-site.
  • GET / HEAD / OPTIONS: request methods meant for reading data, never for changing it.
  • Middleware: code that runs in front of every request, before the code handling the specific action.
  • Origin: the combination of protocol, hostname and port that a browser treats as one site.
  • Regression test: a test that checks something which worked before still works, or that something which should be blocked still is.
  • Replay: sending a captured request again, usually with one thing changed to test a hypothesis.
  • SameSite: a cookie setting (Lax or Strict) that tells the browser to withhold the cookie on most requests coming from other sites.
  • Session cookie: the cookie that identifies you after you log in, so you do not have to sign in on every page.
  • State-changing request: any request that alters data on the server, such as saving a setting or sending a message.
  • Success response: the server's normal reply saying an action worked.
  • Token: a secret value used to prove a request came from the real site rather than somewhere else.

More by Muhammad Asim Shahzad

View all

21 more disclosed reports, best first.

Similar reports

View all

Same bug class and techniques, clearest first.

Cross-site request forgery (CSRF)

The lesson behind this report.

Another site makes a signed-in user's browser perform an action they did not intend.