Eight Doors, One Key: Chaining Misconfigurations into Full Account Takeover
A legacy endpoint that changes the account recovery email accepted requests without a valid CSRF token, with cross-site cookies, and with a text/plain content type that was parsed as JSON, allowing an attacker to change a victim's email and then reset the password to take over the account. The chain bypassed CSRF tokens, SameSite cookies, CORS, and a WAF.
Published on medium.com
Bug Bounty
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
The target exposed two separate frontends against the same backend. The first was a modern Next.js BFF (Backend-for-Frontend), tightly configured: SameSite=Lax cookies, strict CORS, and CSRF tokens validated on every mutating request. The second was a legacy AngularJS application, still live for backward compatibility and proxied under /legacy/.
Both frontends shared the same backend, the same session cookies and the same user data. The legacy surface therefore carried exactly the same blast radius as the flagship product, while receiving less review attention.
The feature at the centre of the chain is the profile update endpoint, which lets a user change fields including their email address. On this target the email change was applied instantly: no confirmation link was sent to the new address, no notification went to the old address, no password re-entry or second factor was required, and eMailAddressVerified silently flipped to False but gated nothing downstream. The password reset flow trusted the field, so whoever controlled the email on the account controlled password reset, and therefore the account.
Setup
The researcher worked against two frontends sharing one backend. The legacy frontend sent an X-CSRF-Token header derived from a stok cookie, a classic double-submit cookie pattern in which a token is mirrored in both a cookie and a header or body field, and the server is supposed to confirm they match. Session cookies carried Secure and HttpOnly. CORS reflected only same-origin requests. A WAF sat in front of the whole stack.
The report does not name the program or the versions in use.
Finding it
Every defence looked correct in isolation. If asked whether CSRF was exploitable here, the researcher would have said no. The starting point was the legacy endpoint itself:
PUT /legacy/rest/v2/user HTTP/1.1Host: target.exampleContent-Type: application/jsonX-CSRF-Token: <stok value>Cookie: JSESSIONID=...; deh=...
{"eMailAddress":"[redacted]","firstName":"John","lastName":"Doe"
This endpoint updates profile fields, including email. Because the email change is applied instantly and the password reset flow trusts the field, it is a crown-jewel mutation: anything that changes the recovery or contact email, adds an SSH key, adds an API token, or changes MFA settings deserves disproportionate attention before lower-impact functionality.
The researcher then tested whether the CSRF token was actually validated server-side, rather than merely present in traffic.
Exploitation
Step 1: Remove the CSRF token
The header was dropped entirely:
PUT /legacy/rest/v2/user HTTP/1.1Cookie: JSESSIONID=...; deh=...
{"eMailAddress":"[redacted]"}
The server returned 200 OK. Garbage sent in place of the token was also accepted. The token generation existed; the validation did not.
A plausible root cause on Spring-based backends is a URL-pattern exclusion in the security configuration:
@Configurationpublic class SecurityConfig {
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf(csrf -> csrf .ignoringRequestMatchers("/legacy/**") ); return http.build(); }}
That single .ignoringRequestMatchers("/legacy/**") line disables CSRF enforcement for the entire legacy path prefix, including an endpoint that changes the account recovery email. Such exclusions are often added once as a temporary unblock during a migration and never revisited.
The corresponding fix is to keep CSRF enforcement and use a cookie-based token repository:
http.csrf(csrf -> csrf .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()));
Step 2: Cookies that travel cross-origin
Even with CSRF validation broken, the attack still needs the browser to attach session cookies to a cross-origin request. Since 2020, Chrome and most major browsers default cookies to SameSite=Lax, which blocks cookies on cross-site requests that are not top-level navigations with safe methods. That default alone kills most classic CSRF.
This application explicitly overrode it:
Set-Cookie: JSESSIONID=...; Path=/legacy; Secure; HttpOnly; SameSite=NoneSet-Cookie: deh=...; Path=/legacy; HttpOnly; Secure; SameSite=Non
SameSite=None tells the browser to send the cookie on every request, cross-origin or not, as long as it is HTTPS. Platforms set this deliberately when the app must function inside third-party iframes (embedded widgets, SSO flows, partner integrations), because SameSite=Lax or Strict cookies do not survive the iframe context. A typical server-side implementation of that decision:
Cookie session = new Cookie("JSESSIONID", sessionId);session.setHttpOnly(true);session.setSecure(true);session.setPath("/legacy");response.addHeader("Set-Cookie", String.format("%s=%s; Path=%s; HttpOnly; Secure; SameSite=None", session.getName(), session.getValue(), session.getPath()));
The problem is that the decision is applied at the cookie level, not the endpoint level. The browser has no concept of sending the cookie cross-origin only for the embed flow and not for some other mutating endpoint. Once SameSite=None is set, every endpoint reachable with that cookie inherits the cross-origin exposure.
Both cookies also carried Path=/legacy, a weak, incidental scoping control that limits where the cookie is sent at all. It did not matter here, because the vulnerable endpoint lives under /legacy itself.
Step 3: No Origin or Referer validation
Every forged request in the chain carried an Origin header pointing straight at the attacker's domain:
Origin: https://evil.comReferer: https://evil.com/poc.html
The OWASP CSRF Prevention Cheat Sheet recommends server-side Origin or Referer validation explicitly as a defence-in-depth layer, precisely to catch the scenario where token-based CSRF protection fails or is missing on a given endpoint. A minimal filter would have caught the entire chain regardless of what happened with tokens, cookies or content types:
public class OriginCheckFilter extends OncePerRequestFilter {
private static final Set<String> ALLOWED_ORIGINS = Set.of( "https://app.target.example", "https://target.example" ); @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { if (isStateChanging(request.getMethod())) { String origin = request.getHeader("Origin"); String referer = request.getHeader("Referer"); boolean trusted = (origin != null && ALLOWED_ORIGINS.contains(origin)) || (origin == null && referer != null && ALLOWED_ORIGINS.stream().anyMatch(referer::startsWith)); if (!trusted) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Origin not allowed"); return; } } chain.doFilter(request, response); } private boolean isStateChanging(String method) { return Set.of("POST", "PUT", "PATCH", "DELETE").contains(method); }}
Such a check is cheap and does not depend on any cookie attribute or body-parsing behaviour, which makes it resilient to the content-type and method-override tricks used later. The server here never looked at either header. Had it rejected requests whose Origin did not match target.example, misconfigurations 1, 2, 4 and 5 would have been irrelevant, because the request would have been rejected before any of them mattered.
A quick way to probe this with curl:
curl -i -X PUT https://target.example/legacy/rest/v2/user \ -H "Origin: https://evil.com" \ -H "Content-Type: application/json" \ -b "JSESSIONID=<session>; deh=<session>" \ -d '{"eMailAddress":"[redacted]"}'
If the response is identical regardless of what Origin says, that confirms a second, independent gap rather than a restatement of the token issue.
The CORS wall
At this point the chain had broken CSRF validation, cookies that travel cross-origin, and no Origin check as a backstop. CORS was still technically in the way: sending Content-Type: application/json cross-origin triggers a CORS preflight (OPTIONS), and the server only reflected Access-Control-Allow-Origin for same-origin requests. The preflight fails and the browser never sends the real request.
This is where knowing the spec pays off. CORS preflighting is only triggered by non-simple requests. The Fetch Standard defines a small set of CORS-safelisted content types that are exempt:
application/x-www-form-urlencodedmultipart/form-datatext/plain
If an endpoint will process a body sent under one of these, the browser classifies it as a simple request: no preflight, sent directly, cookies and all. CORS was never designed to stop this. The mechanism exists to protect against unauthorised reading of cross-origin responses, not unauthorised submission of cross-origin requests with side effects. CORS is a response-confidentiality control, not a request-integrity control. Plain <form> POSTs have always been able to hit any endpoint cross-origin; CORS just stops JavaScript from reading back what happened. If the endpoint mutates state as a side effect of being hit, and does not separately validate CSRF or Origin, CORS buys nothing.
Step 4: text/plain parsed as JSON
PUT /legacy/rest/v2/user HTTP/1.1Content-Type: text/plain
{"eMailAddress":"[redacted]"}
The server returned 200 OK and the email changed. It did not care that the declared content type was text/plain; it looked at the body, recognised JSON and parsed it. This is a well-known behaviour in Java/Spring stacks using permissive HttpMessageConverter chains, often caused by a converter registered to accept a broader media type range than it should:
@Beanpublic [redacted] jacksonConverter() { [redacted] converter = new [redacted]();
converter.setSupportedMediaTypes(List.of( MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN )); return converter;}
Just as commonly, it is a hand-rolled fallback parser sitting ahead of the framework's content negotiation:
@PutMapping("/legacy/rest/v2/user")public ResponseEntity<?> updateUser(@RequestBody String rawBody) { UserUpdateRequest req = objectMapper.readValue(rawBody, UserUpdateRequest.class); userService.update(req); return ResponseEntity.ok(req);}
The underlying cause is almost always the same: a developer wanted the API to be forgiving of clients that forget to set Content-Type correctly, and implemented "if it looks like JSON, parse it as JSON" instead of strictly enforcing the declared type. The fix is to bind the endpoint to a converter that enforces consumes:
@PutMapping(value = "/legacy/rest/v2/user", consumes = MediaType.APPLICATION_JSON_VALUE)public ResponseEntity<?> updateUser(@RequestBody UserUpdateRequest req) { userService.update(req); return ResponseEntity.ok(req);}
With consumes set strictly to application/json, a request sent as text/plain gets rejected with 415 Unsupported Media Type before it reaches application logic.
That leniency is the vulnerability. The Content-Type header becomes purely cosmetic from the browser's perspective: you can tell the browser "this is a CORS-safe simple request" while telling the server "but parse it as structured JSON anyway." The two parties disagree about what the request is, and that disagreement is exactly the gap CORS falls into.
A cheap retest for every JSON-consuming endpoint:
curl -i -X PUT https://target.example/legacy/rest/v2/user \ -H "Content-Type: text/plain" \ -b "JSESSIONID=<session>; deh=<session>" \ -d '{"eMailAddress":"[redacted]"}'
Step 5: HTTP method override
One obstacle remained: HTML forms can only emit GET or POST, and the endpoint is PUT. Even with everything else broken, a plain form submission sends POST /legacy/rest/v2/user, which either 404s, 405s, or hits an unrelated handler.
POST /legacy/rest/v2/user?_method=PUT HTTP/1.1Content-Type: text/plain
{"eMailAddress":"[redacted]"}
The server returned 200 OK: it read _method=PUT and internally re-routed the POST as a PUT. In Spring this is typically enabled with a single filter bean:
@Beanpublic HiddenHttpMethodFilter hiddenHttpMethodFilter() { return new HiddenHttpMethodFilter();}
Method override (_method query parameter, X-HTTP-Method-Override header) dates back to an era when not all HTTP clients, proxies and browsers reliably supported PUT, DELETE or PATCH. Rails (_method), Spring (HiddenHttpMethodFilter) and many other frameworks ship it as an opt-in convenience, and it is frequently left enabled long after the compatibility reason has disappeared. It is rarely flagged in review because it looks like harmless REST tooling, not an access control mechanism. Functionally, it collapses the HTTP verb space: any endpoint behind any verb becomes reachable via a plain POST, the one verb a raw HTML form can forge cross-origin.
The server also accepted X-HTTP-Method-Override as a header, but headers other than a small CORS-safelisted set trigger preflight, so the query-string variant is the one that matters for exploitation here. Not every bypass vector is equally useful for CSRF; only the ones compatible with simple requests are.
A probe for the override:
curl -i -X POST "https://target.example/legacy/rest/v2/user?_method=PUT" \ -H "Content-Type: text/plain" \ -b "JSESSIONID=<session>; deh=<session>" \ -d '{"eMailAddress":"[redacted]"}'
If this is honoured, the CSRF attack surface expands from GET/POST endpoints to every endpoint in the API.
Step 6: No step-up authentication
Per NIST SP 800-63B section 4.3 and RFC 9470 (OAuth 2.0 Step-Up Authentication Challenge Protocol), security-critical operations such as changing a recovery email, resetting MFA or adding a payment method should require re-proof of presence: a fresh password, a TOTP code, a WebAuthn touch. This endpoint required none of it. A live session cookie was sufficient to change the single most security-relevant field on the account. A reasonable version of what is missing:
@PutMapping(value = "/legacy/rest/v2/user", consumes = MediaType.APPLICATION_JSON_VALUE)public ResponseEntity<?> updateUser(@RequestBody UserUpdateRequest req, @RequestHeader("X-Reauth-Token") String reauthToken, HttpSession session) {
if (req.getEMailAddress() != null) { // Changing the recovery email is sensitive: require a fresh // re-authentication token, issued within the last few minutes, // not just a valid long-lived session cookie. if (!reauthService.isRecentlyVerified(session, reauthToken)) { return ResponseEntity.status(401).body("Re-authentication required"); } } userService.update(req); return ResponseEntity.ok(req);}
Step-up auth is the control that should have independently stopped the chain even if CSRF, Origin validation, CORS and content-type handling were all airtight. It exists to limit blast radius when something upstream fails.
Step 7: No email verification loop
The new email took effect immediately. eMailAddressVerified flipped to False, but that flag is cosmetic if nothing reads it. The password reset flow sent its link to whatever address currently sat in that field, verified or not. No confirmation email went to the old address either, which is the control that would have given the real user a chance to notice and react.
The OWASP Account Takeover Prevention Cheat Sheet is explicit about this pattern. A safer flow:
public void requestEmailChange(User user, String newEmail) { String token = tokenService.generate(); pendingEmailChanges.save(user.getId(), newEmail, token, Instant.now().plus(Duration.ofHours(1)));
mailer.send(newEmail, "Confirm your new email", confirmLink(token)); mailer.send(user.getCurrentEmail(), "Your email change was requested", "If this wasn't you, secure your account now.");}public void confirmEmailChange(String token) { PendingChange change = pendingEmailChanges.consume(token) .orElseThrow(() -> new InvalidTokenException()); userService.setEmail(change.getUserId(), change.getNewEmail());}
Email changes should require the new address to confirm via a link before it becomes authoritative, and notify the old address regardless, specifically to catch this kind of attack in progress.
Step 8: No session invalidation after a sensitive change
After the email changed, the victim's existing session stayed fully alive. Nothing forced re-authentication, and no other active sessions were invalidated.
This matters for attacker timing. Without session invalidation, the attacker does not need to race the victim or act within a narrow window; they can let the victim keep using the app undisturbed, with no visible sign anything happened, while separately triggering a password reset to the now-hijacked address at their leisure. A minimal mitigation:
public void onEmailChanged(Long userId) { userService.markEmailChanged(userId); sessionRegistry.invalidateAllExcept(userId, currentSessionId()); mailer.send(user.getPreviousEmail(), "Your account email just changed");}
Forcing re-authentication, or at minimum invalidating other active sessions, whenever a recovery-critical field changes is a standard control, touched on in NIST 800-63B's guidance on session management following credential or authenticator changes. Its absence here turns a narrow exploitation window into an indefinite one.
Why the WAF did not help
WAFs work primarily by pattern-matching request content against signatures for known attack classes: SQL injection syntax, XSS payloads, path traversal sequences, known exploit strings for CVEs. What they are generally not built to reason about is business logic: whether this request, from this origin, to this endpoint, with a session cookie belonging to this user, represents a legitimate action.
The final exploit request is, from a pure pattern-matching standpoint, almost perfectly unremarkable:
POST /legacy/rest/v2/user?_method=PUT HTTP/1.1Content-Type: text/plainCookie: JSESSIONID=<valid session>; deh=<valid session>
{"eMailAddress":"[redacted]","x":"="}
There is no SQL syntax, no script tags, no traversal sequences, no known malicious signature. The body is syntactically valid, boring JSON. The session cookie is completely legitimate, it is the victim's own. The only thing wrong with the request is context: it originated from evil.com, and no control downstream of the WAF ever checked that context. A WAF in front of this traffic has nothing to flag. WAFs catch malicious payloads; they do not catch malicious contexts, and CSRF is fundamentally a context problem.
The chain, end to end
| # | Misconfiguration | What it defeats |
|---|---|---|
| 1 | CSRF token sent, not validated server-side | Primary CSRF defence |
| 2 | SameSite=None on session cookies |
Browser's built-in CSRF mitigation |
| 3 | No Origin/Referer validation | Defence-in-depth CSRF backstop |
| 4 | text/plain parsed as JSON |
CORS preflight requirement |
| 5 | _method=PUT override |
HTML form's GET/POST-only limitation |
| 6 | No step-up authentication | Defence-in-depth for sensitive actions |
| 7 | No email verification / no old-email notice | Blast-radius containment, victim awareness |
| 8 | No session invalidation after sensitive change | Attacker's exploitation time window |
Break any single link and the exploit either stops working or shrinks dramatically in impact. No individual finding here would score above "Medium" on its own in most bug bounty triage; the severity lives entirely in the composition.
Proof of concept
<!DOCTYPE html><html><head><title>Loading...</title></head><body> <h1>Please wait...</h1> <form id="csrf" action="https://target.example/legacy/rest/v2/user?_method=PUT" method="POST" enctype="text/plain"> <input type="hidden" name='{"eMailAddress":"[redacted]","x":"' value='"}'> </form> <script>document.getElementById('csrf').submit();</script></body></html>
The text/plain form-encoding trick
When a browser serialises a <form enctype="text/plain">, it does not JSON-encode anything; it writes name=value pairs, one per line, literally. Normally that produces garbage from a JSON parser's perspective. But if you choose the field name and value carefully, the browser's plain name=value concatenation lands exactly on valid JSON syntax:
name: {"eMailAddress":"[redacted]","x":"value: "}
You can verify this encoding behaviour in a browser console without touching the target:
const form = document.createElement('form');form.enctype = 'text/plain';
const input = document.createElement('input');input.name = '{"eMailAddress":"[redacted]","x":"';input.value = '"}';form.appendChild(input);// This mirrors what the browser sends as the body:console.log(`${input.name}=${input.value}`);// {"eMailAddress":"[redacted]","x":"="}
Concatenated by the browser as name=value:
{"eMailAddress":"[redacted]","x":"="}
The = character the browser inserts between name and value does not break anything: it lands inside the string value of the "x" property, which the server-side JSON parser treats as an arbitrary ignored field. The attacker-controlled eMailAddress value sits cleanly inside its own properly-quoted string, untouched by the encoding mechanics. This technique for smuggling attacker-controlled JSON through a form's text/plain encoding only works because of misconfiguration 4. If the server enforced Content-Type: application/json, the construction would be rejected outright regardless of how clever the encoding is.
What the server actually receives
POST /legacy/rest/v2/user?_method=PUT HTTP/1.1Host: target.exampleContent-Type: text/plainOrigin: https://evil.comReferer: https://evil.com/poc.htmlCookie: JSESSIONID=<victim-session>; deh=<victim-session>
{"eMailAddress":"[redacted]","x":"="}
{ "eMailAddress": "[redacted]", "eMailAddressVerified": "False"}
The Origin: https://evil.com header is right there in the request, completely unvalidated (misconfiguration 3). CORS governs whether JavaScript on evil.com is allowed to read the response; it says nothing about whether the browser is allowed to send the request. Simple requests are sent unconditionally, and the Access-Control-Allow-Origin response header only determines whether the attacker's script can see what came back. Since this attack does not need to read the response, it is a pure state-changing side effect, and CORS was never in a position to stop it, no matter how strictly it was configured.
CSRF tokens, SameSite cookies and Origin validation are the actual anti-CSRF controls. CORS is not one of them, despite how often it is treated as if it were.
Root cause
The chain rests on eight individually unremarkable misconfigurations, each of which shows up in automated scanner output as informational or gets closed in triage as not exploitable given other controls:
- The double-submit CSRF token was generated client-side and sent by the Angular interceptor, but no backend filter rejected requests missing or mismatching it. The likely root cause is a URL-pattern exclusion such as
.ignoringRequestMatchers("/legacy/**")in the security configuration. - Session cookies were set with
SameSite=None, a deliberate decision for iframe embedding applied at the cookie level rather than the endpoint level, so every endpoint under/legacyinherited cross-origin exposure. - The server never validated
OriginorReferer, so the defence-in-depth layer that would have caught the token failure was absent. - The server parsed JSON bodies sent as
text/plain, likely through a permissiveHttpMessageConverterregistration or a hand-rolled fallback parser, so the browser could classify the request as a CORS-simple request while the server still parsed structured JSON. HiddenHttpMethodFilter(or equivalent) was enabled, so a plainPOSTwith?_method=PUTwas re-routed as aPUT, making the endpoint reachable from an HTML form.- No step-up authentication was required for a change to the recovery email.
- No verification loop gated the new email, and no notice went to the old address.
- No session invalidation followed the sensitive change.
The WAF did not stop it because the final request contains no malicious payload syntax, only a legitimate-looking body from an illegitimate origin, and signature-based WAFs have nothing to key on.
Impact
An attacker who can lure a logged-in victim to a single HTML page can change the victim's account email with zero interaction beyond loading the page. Because the password reset flow trusts the email field, the attacker then controls password reset and therefore the account: full account takeover. The victim's session stays alive and nothing visible happens, so the attacker can trigger the reset at their own leisure rather than racing the victim.
The report does not describe any preconditions beyond the victim's browser loading the page.
Fix
Each link has a direct fix:
- Validate CSRF tokens server-side on every mutating endpoint, including legacy or deprecated ones. Do not assume token generation implies token validation.
- Scope
SameSite=Nonecookies as narrowly as possible. If it is needed for iframe embedding, consider splitting session concerns: a narrowly-scoped embed token versus the primary session cookie, so the high-privilege cookie does not inherit cross-origin exposure it does not need. - Add server-side Origin/Referer allowlisting as defence-in-depth on all state-changing endpoints, independent of token validation.
- Enforce the declared
Content-Typestrictly. Reject bodies that do not match the declared type instead of auto-detecting and parsing anyway. - Disable or tightly restrict HTTP method override in production, or require it to come with the same CSRF and auth checks as the real verb would.
- Require step-up authentication (password re-entry, TOTP, WebAuthn) before any change to recovery email, phone, MFA settings or credentials.
- Gate email changes behind a verification loop: the new address must confirm via link before becoming authoritative, and the old address always receives a notice regardless.
- Invalidate other active sessions (or force re-authentication) whenever a recovery-critical field changes, to cap the attacker's exploitation window.
Variants to test
- CSRF token present but not validated. Omit the token entirely, send an empty string, send another valid user's token, send a stale or expired token. A
200response to any of these means generation exists but validation does not. - Cookie attributes across every subdomain and path prefix. Check
Set-Cookieon legacy paths, embedded-widget subdomains and partner-facing subdomains, not just the main login response. A positive result is a looserSameSiteor missingSecureon the same session identifier used elsewhere. - Origin/Referer validation independently of tokens. Alter or strip
OriginandRefererand compare responses. Identical behaviour regardless ofOriginconfirms a second, independent gap. - JSON endpoints retested with
text/plainandmultipart/form-data. A positive result is the body still parsing and the state change still applying under a safelisted content type. - Method override support. Try
_method,X-HTTP-Method-OverrideandX-Method-Overrideon frameworks known to support them (Rails, Spring, Laravel, legacy Express middlewares). A positive result is aPOSTbeing handled as the overridden verb, which turns the CSRF surface from GET/POST only into every verb. - Recovery-critical endpoints. Prioritise anything that touches email, phone, MFA, SSH/API keys or password. A positive result is any of these mutating without step-up authentication.
- WAF assumptions. If the exploit request contains no malicious payload syntax, only a legitimate-looking body from an illegitimate origin, expect a signature-based WAF to have nothing to key on.
- Chaining before triage. Ask what stops the exploit end to end before accepting partial mitigations as sufficient. A program might reasonably close "CSRF token not validated" as low severity if they believe
SameSitecookies are the backstop, and close "SameSite=Nonepresent" as accepted risk if they believe CORS blocks exploitation. Each individual triage can be locally reasonable and still collectively wrong.
What happened, in plain words
A security researcher found a way to take over someone else's account on a website, using nothing more than a single web page that the victim had to open. The victim did not have to type anything, click anything or approve anything. Just loading the page was enough.
The surprising part is that the website looked well protected. It had all the usual locks in place. But each lock had a small gap, and the researcher found eight gaps and used them one after another, like a chain of eight doors where each door's key opens the next one. None of the eight gaps was serious on its own. Together they let the attacker change the victim's email address, and from there reset the password and take the whole account.
This article walks through the same story in the same order as the technical write-up, but explains every idea from scratch. If you can use a browser, you can follow it.
Some background you need first
Before the story makes sense, here are a few everyday ideas. Each one comes back later.
A website and its API. When you use a website, your browser shows you pages: buttons, forms, text. Behind those pages sits a second program, the API (Application Programming Interface), which does the actual work: saving your name, changing your email, checking your password. Think of a restaurant. The dining room with tables and menus is the website you see. The kitchen is the API. The waiter carries your order from the dining room to the kitchen and brings the food back. Your browser is the waiter.
Requests and methods. Every time your browser asks the kitchen to do something, it sends a request. Each request has a method, a word that says what kind of action it is. GET means "give me something" (like reading a page). POST means "here is some data, please accept it" (like submitting a form). PUT means "replace this record with new data" (like updating your profile). DELETE means "remove this". These words are part of a standard called HTTP, the language browsers and servers speak.
Cookies. A cookie is a small piece of text that a website asks your browser to store and to send back with every later request to that site. It is how a website remembers that you are logged in. Think of it as a wristband at a festival: you show your ticket once, get the wristband, and after that the staff let you in and out without asking for the ticket again. The most important cookie here is called JSESSIONID, which is a session identifier: a random string that ties your requests to your logged-in session on the server.
Session. A session is the server's memory of "this person is logged in as user X". The cookie is the ticket; the session is the server-side record it points to.
CSRF (Cross-Site Request Forgery). This is the vulnerability class at the heart of the story. The name sounds scary; the idea is simple. Your browser automatically attaches your cookies to requests, including requests that a different website made your browser send. So if you are logged in to bank.example and you then visit evil.example, a page on evil.example can contain a hidden form that makes your browser send a request to bank.example. Your browser helpfully attaches your bank cookie. The bank sees a request with a valid session and does what it says. You never intended it. That is CSRF: someone else's site forging a request in your name, using your own logged-in browser as the tool.
CSRF token. To stop CSRF, sites use a token: a random value that the site gives your browser and expects back with every state-changing request. A page on evil.example cannot read your token (browsers forbid one site from reading another site's data), so it cannot include the right token, and the server rejects the request. It is like a cloakroom that gives you a numbered ticket and only returns your coat if you show the matching number. A stranger cannot guess your number.
Double-submit cookie. One common way to implement a CSRF token: the server puts the token in a cookie and the page's JavaScript copies the same value into a request header. The server then checks that the two match. The idea is that an attacker can make your browser send the cookie, but cannot read the cookie to copy it into the header. So a matching pair proves the request came from the real site.
Header. Extra information attached to a request, separate from the body. Think of the envelope of a letter: the body is the letter, the headers are the address, the stamp and the "fragile" sticker. Headers like Origin, Referer, Content-Type and Cookie appear throughout this story.
Origin and Referer. Two headers that browsers add automatically. Origin says which website the request came from (for example https://evil.com). Referer says which page linked to or triggered the request. A server can check these and refuse requests coming from unexpected sites. That check is a second, independent lock against CSRF.
SameSite. A cookie setting that tells the browser when to send the cookie. SameSite=Lax (the modern default) means: only send this cookie on requests that come from the same site, with narrow exceptions. SameSite=Strict is even tighter. SameSite=None means: send it everywhere, including from other sites. SameSite=None is what makes classic CSRF possible again.
Secure and HttpOnly. Two more cookie settings. Secure means the cookie is only sent over encrypted HTTPS connections. HttpOnly means JavaScript on the page cannot read the cookie. Both are good, and both were present here.
CORS (Cross-Origin Resource Sharing). A browser rule about reading responses. When JavaScript on evil.example sends a request to target.example, the browser first asks the target (in a separate request called a preflight) whether evil.example is allowed to read the answer. If the target does not say yes, the browser blocks the JavaScript from seeing the response. Crucially, CORS controls whether the attacker can read the reply, not whether the request is sent. This distinction is the single most important idea in the whole article, and we will come back to it.
Simple request. Browsers only do the CORS preflight for requests that are not "simple". A request is simple if it uses one of a small set of content types (the format of the body): application/x-www-form-urlencoded, multipart/form-data or text/plain, and does not add unusual headers. Simple requests are sent straight away, cookies and all, with no preflight. This is by design, because ordinary HTML forms have always worked this way.
Content-Type. A header that says what format the body is in. application/json means "this body is JSON", a structured text format like {"name": "John"}. text/plain means "this is just plain text".
WAF (Web Application Firewall). A filter that sits in front of a website and inspects incoming requests for known attack patterns, like database-injection code or script tags. Think of a security guard at the door who checks bags against a list of known dangerous items. If your bag contains something not on the list, the guard waves you through.
BFF (Backend-for-Frontend). A pattern where a modern frontend has its own dedicated server layer in front of the shared backend. Here, the modern frontend was built with a framework called Next.js.
AngularJS. An older JavaScript framework for building web pages. The site still ran an old AngularJS application under the path /legacy/ for backward compatibility.
Legacy. Old software kept running because something still depends on it. It usually gets less attention from security teams than the shiny new product.
Step-up authentication. Asking the user to prove again that it is really them, right before a sensitive action: re-enter your password, type a code from your phone, touch a security key. Like a bank asking for your PIN again before a large transfer.
Account takeover (ATO). Exactly what it sounds like: an attacker gains control of someone else's account.
Password reset flow. The "forgot my password" feature. It sends a reset link to the email address on the account. Whoever controls that email address controls the reset, and therefore the account.
The target: two front doors, one kitchen
The website had two separate frontends talking to the same backend:
- A modern Next.js BFF, tightly configured:
SameSite=Laxcookies, strict CORS, and CSRF tokens validated on every request that changes something. - A legacy AngularJS application, still live for backward compatibility, reachable under the path
/legacy/.
This pattern, a hardened new frontend next to a half-retired old one, is very common in large companies partway through a rebuild. Security teams harden what they are actively building and put off what is "being phased out". But the old frontend shared the same backend, the same session cookies and the same user data as the new one. A hole there is just as dangerous as a hole in the flagship product, and it gets far less scrutiny.
The feature at the centre: changing your email
The endpoint at the centre of the chain lets a user update profile fields, including their email address. An endpoint is one specific address on the server that does one specific job, like a counter in a large office building. This one was:
PUT /legacy/rest/v2/user HTTP/1.1Host: target.exampleContent-Type: application/jsonX-CSRF-Token: <stok value>Cookie: JSESSIONID=...; deh=...
{"eMailAddress":"[redacted]","firstName":"John","lastName":"Doe"
Line by line:
PUT /legacy/rest/v2/user HTTP/1.1: use thePUTmethod (replace a record) on the path/legacy/rest/v2/user, speaking version 1.1 of HTTP.Host: target.example: the name of the server being talked to.Content-Type: application/json: the body is in JSON format.X-CSRF-Token: <stok value>: the CSRF token, taken from a cookie calledstok. This is the double-submit pattern described above.Cookie: JSESSIONID=...; deh=...: the session cookies that identify the logged-in user.- The body
{"eMailAddress":"[redacted]","firstName":"John","lastName":"Doe"is the JSON being sent: a new email address, first name and last name. (The original snippet is missing its closing brace; that is how it appears in the report.)
Why this endpoint mattered so much: on this site the email change was applied instantly. No confirmation link was sent to the new address. No notification went to the old address. No password re-entry or second factor was required. A flag called eMailAddressVerified silently flipped to False, but nothing downstream checked it. And the password reset flow trusted the email field. So whoever controls the email on the account controls password reset, and therefore the account.
This is the kind of endpoint worth attacking first in any assessment. Anything that changes the recovery or contact email, adds an SSH key, adds an API token or changes multi-factor settings is a "crown jewel" mutation. Spend disproportionate time there before moving on to lower-impact features.
The starting position
The researcher worked against the two frontends sharing one backend. The legacy frontend sent an X-CSRF-Token header derived from a stok cookie. Session cookies carried Secure and HttpOnly. CORS reflected only same-origin requests. A WAF sat in front of the whole stack.
Every defence looked correct in isolation. Asked whether CSRF was exploitable here, the researcher would have said no. The report does not name the program or the software versions in use.
Breaking the chain, link by link
Misconfiguration 1: the CSRF token is present but never checked
The frontend diligently sent the X-CSRF-Token header, taken from the stok cookie. The server was supposed to confirm the two matched. The researcher simply dropped the header:
PUT /legacy/rest/v2/user HTTP/1.1Cookie: JSESSIONID=...; deh=...
{"eMailAddress":"[redacted]"}
Line by line:
PUT /legacy/rest/v2/user HTTP/1.1: the same profile-update request as before.Cookie: JSESSIONID=...; deh=...: the session cookies, unchanged. This is what makes the server treat the request as coming from a logged-in user.- The body asks to change the email to
[redacted]. - Notice what is missing: the
X-CSRF-Tokenheader. The cloakroom ticket has been removed entirely.
The server answered 200 OK, which means "done". Then the researcher sent garbage in place of the token, and that was accepted too. The token was being generated and sent, but never validated. The lock was painted on the door.
Why does this happen in the real world? Double-submit CSRF protection is often built as a frontend habit rather than a server rule. Someone writes the Angular code that attaches the header to every request, ships it, and the team ticks the "CSRF protection" box. Nobody writes the server-side check that actually rejects requests with a missing or wrong token.
A very plausible cause on Spring-based backends (Spring is a popular Java framework for building web servers) looks like this:
@Configurationpublic class SecurityConfig {
@Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf(csrf -> csrf .ignoringRequestMatchers("/legacy/**") ); return http.build(); }}
Line by line:
@Configurationmarks this class as configuration for the framework.public class SecurityConfig {starts the class that holds security settings.@Beanmarks a method whose result the framework should manage.public SecurityFilterChain filterChain(HttpSecurity http): builds the chain of security checks applied to every request..csrf(csrf -> csrf ...): configure CSRF protection..ignoringRequestMatchers("/legacy/**"): switch CSRF protection off for every path starting with/legacy/. The**means "anything below this".return http.build();: finish building the configuration.
That single line disables CSRF enforcement for the entire legacy path prefix, including an endpoint that changes the account recovery email. This is worth hunting for on any target: when CSRF protection is inconsistent across an app's endpoints, the inconsistency is very often a URL-pattern exclusion added once as a temporary unblock during a migration and never revisited.
The fix is to keep CSRF enforcement and use a cookie-based token repository:
http.csrf(csrf -> csrf .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()));
Line by line:
http.csrf(csrf -> csrf ...): configure CSRF protection..csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()): store the token in a cookie that JavaScript is allowed to read, so the frontend can copy it into the header, while the server still checks that the header and cookie match.
Testing tip. Never assume a CSRF token is validated just because it appears in requests. Always test: omit it entirely, send an empty string, send another valid user's token, send a stale or expired token. Automated scanners often miss this because they see the token being sent and label the endpoint "protected".
Misconfiguration 2: cookies that travel to other sites
Even with CSRF validation broken, the attack still needs the browser to attach the session cookies to a request coming from another site. Since 2020, Chrome and most major browsers default cookies to SameSite=Lax, which blocks cookies on cross-site requests that are not top-level navigations with safe methods. That default alone kills most classic CSRF.
This application explicitly overrode the default:
Set-Cookie: JSESSIONID=...; Path=/legacy; Secure; HttpOnly; SameSite=NoneSet-Cookie: deh=...; Path=/legacy; HttpOnly; Secure; SameSite=Non
Line by line:
Set-Cookie:is the header a server uses to give the browser a cookie.JSESSIONID=...: the name and value of the session cookie.Path=/legacy: only send this cookie for paths under/legacy.Secure: only send it over HTTPS.HttpOnly: JavaScript cannot read it.SameSite=None: send it on requests from other sites too.- The second line does the same for a cookie called
deh, with the same settings.
SameSite=None tells the browser to send the cookie on every request, cross-site or not, as long as it is HTTPS. Platforms set this deliberately when the app must work inside third-party iframes (embedded widgets, single sign-on flows, partner integrations), because SameSite=Lax or Strict cookies do not survive inside an iframe. A typical server-side implementation of that decision:
Cookie session = new Cookie("JSESSIONID", sessionId);session.setHttpOnly(true);session.setSecure(true);session.setPath("/legacy");response.addHeader("Set-Cookie", String.format("%s=%s; Path=%s; HttpOnly; Secure; SameSite=None", session.getName(), session.getValue(), session.getPath()));
Line by line:
Cookie session = new Cookie("JSESSIONID", sessionId);: create a cookie namedJSESSIONIDholding the session identifier.session.setHttpOnly(true);: make it unreadable to JavaScript.session.setSecure(true);: send it only over HTTPS.session.setPath("/legacy");: scope it to the/legacypath.response.addHeader("Set-Cookie", ...): add the header that sends the cookie to the browser.String.format("%s=%s; Path=%s; HttpOnly; Secure; SameSite=None", ...): build the cookie text, filling in the name, value and path, and ending withSameSite=None.
The problem is that the decision is made at the cookie level, not the endpoint level. The browser has no concept of "send this cookie cross-site only for the embed flow, but not for this other endpoint that changes my email". Once SameSite=None is set, every endpoint reachable with that cookie inherits the cross-site exposure.
Both cookies also carried Path=/legacy, a weak, incidental scoping control that limits where the cookie is sent at all. It did not matter here, because the vulnerable endpoint lives under /legacy itself.
Testing tip. Always check Set-Cookie headers across every subdomain and path prefix the app serves, not just the main login response. Teams often harden the main domain's cookies while a legacy path, an embedded-widget subdomain or an internal API carries looser settings on the same session identifier.
Misconfiguration 3: nobody checks where the request came from
This is the one that, in hindsight, should have stopped everything else cold. Every forged request in the chain carried an Origin header pointing straight at the attacker's domain:
Origin: https://evil.comReferer: https://evil.com/poc.html
Line by line:
Origin: https://evil.com: the request came from a page onevil.com.Referer: https://evil.com/poc.html: the specific page that triggered it, a file calledpoc.html(proof of concept).
These headers are added by the browser, so a server that checks them can tell where a request came from. So a server that checks them can reliably tell whether a request came from its own site or from somewhere else.
The OWASP CSRF Prevention Cheat Sheet (OWASP is a well-known non-profit that publishes security guidance) recommends server-side Origin or Referer validation explicitly as a defence-in-depth layer. It exists precisely to catch the case where token-based CSRF protection fails or is missing on an endpoint, as happened here. A minimal filter would have caught the entire chain regardless of what happened with tokens, cookies or content types:
public class OriginCheckFilter extends OncePerRequestFilter {
private static final Set<String> ALLOWED_ORIGINS = Set.of( "https://app.target.example", "https://target.example" ); @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { if (isStateChanging(request.getMethod())) { String origin = request.getHeader("Origin"); String referer = request.getHeader("Referer"); boolean trusted = (origin != null && ALLOWED_ORIGINS.contains(origin)) || (origin == null && referer != null && ALLOWED_ORIGINS.stream().anyMatch(referer::startsWith)); if (!trusted) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Origin not allowed"); return; } } chain.doFilter(request, response); } private boolean isStateChanging(String method) { return Set.of("POST", "PUT", "PATCH", "DELETE").contains(method); }}
Line by line:
public class OriginCheckFilter extends OncePerRequestFilter {: a filter that runs once for every incoming request.private static final Set<String> ALLOWED_ORIGINS = Set.of("https://app.target.example", "https://target.example");: the only two sites allowed to make state-changing requests.protected void doFilterInternal(...): the code that runs for each request.if (isStateChanging(request.getMethod())) {: only bother for requests that change something.String origin = request.getHeader("Origin");: read theOriginheader.String referer = request.getHeader("Referer");: read theRefererheader.boolean trusted = (origin != null && ALLOWED_ORIGINS.contains(origin)) || (origin == null && referer != null && ALLOWED_ORIGINS.stream().anyMatch(referer::startsWith));: the request is trusted ifOriginis one of the allowed sites, or, whenOriginis absent, ifRefererstarts with an allowed site.if (!trusted) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Origin not allowed"); return; }: if not trusted, answer403 Forbiddenand stop.chain.doFilter(request, response);: otherwise let the request continue.private boolean isStateChanging(String method) { return Set.of("POST", "PUT", "PATCH", "DELETE").contains(method); }: treatPOST,PUT,PATCHandDELETEas state-changing.
Such a check is cheap and does not depend on any cookie setting or body-parsing behaviour, which makes it resilient to the content-type and method-override tricks used later. The server here never looked at either header. Had it rejected requests whose Origin did not match target.example, misconfigurations 1, 2, 4 and 5 would have been irrelevant, because the request would have been rejected before any of them mattered.
A quick way to probe this with curl:
curl -i -X PUT https://target.example/legacy/rest/v2/user \ -H "Origin: https://evil.com" \ -H "Content-Type: application/json" \ -b "JSESSIONID=<session>; deh=<session>" \ -d '{"eMailAddress":"[redacted]"}'
Line by line:
curl: the command-line tool for sending HTTP requests.-i: also show the response headers.-X PUT: use thePUTmethod.https://target.example/legacy/rest/v2/user: the endpoint.-H "Origin: https://evil.com": pretend the request came fromevil.com.-H "Content-Type: application/json": say the body is JSON.-b "JSESSIONID=<session>; deh=<session>": send the session cookies.-d '{"eMailAddress":"[redacted]"}': the body, asking to change the email.
If the response is identical regardless of what Origin says, that confirms a second, independent gap rather than a restatement of the token issue.
Testing tip. When you find an endpoint that can be abused via CSRF, always check in your captured traffic whether Origin and Referer are present and whether the server's behaviour changes when you alter or strip them.
The CORS wall
At this point the chain had broken CSRF validation, cookies that travel cross-site, and no Origin check as a backstop. CORS was still technically in the way. Sending Content-Type: application/json cross-site triggers a CORS preflight (an OPTIONS request the browser sends first to ask permission), and the server only reflected Access-Control-Allow-Origin for same-origin requests. The preflight fails and the browser never sends the real request.
This is where a lot of testers stop and move on. It is also where knowing the spec pays off. CORS preflighting is only triggered by non-simple requests. The Fetch Standard (the official document that defines how browsers fetch things) lists a small set of content types that are exempt:
application/x-www-form-urlencodedmultipart/form-datatext/plain
If an endpoint will process a body sent under one of these, the browser classifies it as a simple request: no preflight, sent directly, cookies and all. CORS was never designed to stop this. The mechanism exists to protect against unauthorised reading of cross-site responses, not unauthorised submission of cross-site requests with side effects. CORS is a response-confidentiality control, not a request-integrity control. Plain HTML <form> submissions have always been able to hit any endpoint cross-site; CORS just stops JavaScript from reading back what happened. If the endpoint changes state as a side effect of being hit, and does not separately validate CSRF or Origin, CORS buys you nothing.
Misconfiguration 4: text/plain is parsed as JSON
PUT /legacy/rest/v2/user HTTP/1.1Content-Type: text/plain
{"eMailAddress":"[redacted]"}
Line by line:
PUT /legacy/rest/v2/user HTTP/1.1: the same profile-update request.Content-Type: text/plain: the body is declared as plain text, not JSON. This is one of the content types that makes a request "simple" for CORS purposes.- The body is still JSON, asking to change the email to
[redacted].
The server returned 200 OK and the email changed. It did not care that the declared content type was text/plain; it looked at the body, recognised JSON and parsed it. This is a well-known behaviour in Java/Spring stacks using permissive HttpMessageConverter chains (a converter is the component that turns a raw body into a usable object). It is often caused by a converter registered to accept a broader range of content types than it should:
@Beanpublic [redacted] jacksonConverter() { [redacted] converter = new [redacted]();
converter.setSupportedMediaTypes(List.of( MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN )); return converter;}
Line by line:
@Bean: register this method's result with the framework.public [redacted] jacksonConverter() {: a converter that turns JSON text into Java objects.[redacted] converter = new [redacted]();: create the converter.converter.setSupportedMediaTypes(List.of(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN));: tell it to accept both JSON and plain text as input.return converter;: hand it back to the framework.
Just as commonly, it is a hand-rolled fallback parser sitting ahead of the framework's normal content negotiation:
@PutMapping("/legacy/rest/v2/user")public ResponseEntity<?> updateUser(@RequestBody String rawBody) { UserUpdateRequest req = objectMapper.readValue(rawBody, UserUpdateRequest.class); userService.update(req); return ResponseEntity.ok(req);}
Line by line:
@PutMapping("/legacy/rest/v2/user"): this method handlesPUTrequests to that path.public ResponseEntity<?> updateUser(@RequestBody String rawBody) {: take the raw body as a plain string, without declaring any expected content type.UserUpdateRequest req = objectMapper.readValue(rawBody, UserUpdateRequest.class);: try to parse the raw string as JSON into a user-update object, whatever the declared content type was.userService.update(req);: apply the update.return ResponseEntity.ok(req);: answer200 OK.
The underlying cause is almost always the same: a developer wanted the API to be forgiving of clients that forget to set Content-Type correctly, and implemented "if it looks like JSON, parse it as JSON" instead of strictly enforcing the declared type. The fix is to bind the endpoint to a converter that enforces consumes:
@PutMapping(value = "/legacy/rest/v2/user", consumes = MediaType.APPLICATION_JSON_VALUE)public ResponseEntity<?> updateUser(@RequestBody UserUpdateRequest req) { userService.update(req); return ResponseEntity.ok(req);}
Line by line:
@PutMapping(value = "/legacy/rest/v2/user", consumes = MediaType.APPLICATION_JSON_VALUE): handlePUTrequests to that path, but only when the declared content type isapplication/json.public ResponseEntity<?> updateUser(@RequestBody UserUpdateRequest req) {: take the body already parsed into a user-update object.userService.update(req);: apply the update.
With consumes set strictly to application/json, a request sent as text/plain gets rejected with 415 Unsupported Media Type before it reaches application logic.
That leniency is the vulnerability. The Content-Type header becomes purely cosmetic from the browser's perspective: you can tell the browser "this is a CORS-safe simple request" while telling the server "but parse it as structured JSON anyway". The two parties disagree about what the request is, and that disagreement is exactly the gap CORS falls into.
A cheap retest for every JSON endpoint:
curl -i -X PUT https://target.example/legacy/rest/v2/user \ -H "Content-Type: text/plain" \ -b "JSESSIONID=<session>; deh=<session>" \ -d '{"eMailAddress":"[redacted]"}'
Line by line:
curl -i -X PUT https://target.example/legacy/rest/v2/user: send aPUTto the endpoint and show the response headers.-H "Content-Type: text/plain": declare the body as plain text.-d '{"eMailAddress":"[redacted]"}': the JSON body, asking to change the email.
This is cheap, fast, and catches a whole class of CORS-preflight bypasses that automated scanners routinely miss because they only vary payloads, not Content-Type.
Misconfiguration 5: the method can be overridden
One obstacle remained: HTML forms can only send GET or POST, and the endpoint is PUT. Even with everything else broken, a plain form submission sends POST /legacy/rest/v2/user, which either 404s (not found), 405s (method not allowed), or hits an unrelated handler.
POST /legacy/rest/v2/user?_method=PUT HTTP/1.1Content-Type: text/plain
{"eMailAddress":"[redacted]"}
Line by line:
POST /legacy/rest/v2/user?_method=PUT HTTP/1.1: send aPOST(which a form can do) to the endpoint, with a query-string parameter_method=PUT.Content-Type: text/plain: a simple content type, so no preflight.
The server returned 200 OK: it read _method=PUT and internally re-routed the POST as a PUT. In Spring this is typically enabled with a single filter bean:
@Beanpublic HiddenHttpMethodFilter hiddenHttpMethodFilter() { return new HiddenHttpMethodFilter();}
Line by line:
@Bean: register this filter with the framework.public HiddenHttpMethodFilter hiddenHttpMethodFilter() {: a filter that looks for a hidden method override.return new HiddenHttpMethodFilter();: create and return it.
Method override (the _method query parameter, or the X-HTTP-Method-Override header) dates back to an era when not all HTTP clients, proxies and browsers reliably supported PUT, DELETE or PATCH. Rails (_method), Spring (HiddenHttpMethodFilter) and many other frameworks ship it as an opt-in convenience, and it is frequently left enabled long after the compatibility reason has disappeared. It is rarely flagged in review because it looks like harmless REST tooling, not an access control mechanism. Functionally, it collapses the HTTP verb space: any endpoint behind any verb becomes reachable via a plain POST, the one verb a raw HTML form can forge cross-site.
The server also accepted X-HTTP-Method-Override as a header, but headers other than a small CORS-safelisted set trigger preflight, so the query-string variant is the one that matters for exploitation here. Not every bypass vector is equally useful for CSRF; only the ones compatible with simple requests are.
A probe for the override:
curl -i -X POST "https://target.example/legacy/rest/v2/user?_method=PUT" \ -H "Content-Type: text/plain" \ -b "JSESSIONID=<session>; deh=<session>" \ -d '{"eMailAddress":"[redacted]"}'
Line by line:
curl -i -X POST "https://target.example/legacy/rest/v2/user?_method=PUT": send aPOSTto the endpoint with_method=PUTin the query string, and show the response headers.
If this is honoured, the CSRF attack surface expands from GET/POST endpoints to every endpoint in the API.
Misconfiguration 6: no step-up authentication
Per NIST SP 800-63B section 4.3 (NIST is the US standards body for technology) and RFC 9470 (an official document defining a way to ask for extra proof of identity), security-critical operations such as changing a recovery email, resetting multi-factor authentication or adding a payment method should require fresh proof that it is really you: a fresh password, a code from an authenticator app, a touch on a security key. This endpoint required none of it. A live session cookie was enough to change the single most security-relevant field on the account. A reasonable version of what is missing:
@PutMapping(value = "/legacy/rest/v2/user", consumes = MediaType.APPLICATION_JSON_VALUE)public ResponseEntity<?> updateUser(@RequestBody UserUpdateRequest req, @RequestHeader("X-Reauth-Token") String reauthToken, HttpSession session) {
if (req.getEMailAddress() != null) { // Changing the recovery email is sensitive: require a fresh // re-authentication token, issued within the last few minutes, // not just a valid long-lived session cookie. if (!reauthService.isRecentlyVerified(session, reauthToken)) { return ResponseEntity.status(401).body("Re-authentication required"); } } userService.update(req); return ResponseEntity.ok(req);}
Line by line:
@PutMapping(value = "/legacy/rest/v2/user", consumes = MediaType.APPLICATION_JSON_VALUE): handlePUTrequests to that path, only with a JSON body.public ResponseEntity<?> updateUser(@RequestBody UserUpdateRequest req, @RequestHeader("X-Reauth-Token") String reauthToken, HttpSession session) {: also read a re-authentication token from a header and the current session.if (req.getEMailAddress() != null) {: if the request changes the email address...if (!reauthService.isRecentlyVerified(session, reauthToken)) {: ...check that the user recently proved who they are.return ResponseEntity.status(401).body("Re-authentication required");: if not, answer401 Unauthorizedand refuse.userService.update(req); return ResponseEntity.ok(req);: otherwise apply the update and answer200 OK.
Step-up authentication is the control that should have independently stopped the chain even if CSRF, Origin validation, CORS and content-type handling were all airtight. It exists to limit the damage when something upstream fails.
Misconfiguration 7: no email verification loop
The new email took effect immediately. eMailAddressVerified flipped to False, but that flag is cosmetic if nothing reads it. The password reset flow sent its link to whatever address currently sat in that field, verified or not. No confirmation email went to the old address either, which is the control that would have given the real user a chance to notice and react.
The OWASP Account Takeover Prevention Cheat Sheet is explicit about this pattern. A safer flow:
public void requestEmailChange(User user, String newEmail) { String token = tokenService.generate(); pendingEmailChanges.save(user.getId(), newEmail, token, Instant.now().plus(Duration.ofHours(1)));
mailer.send(newEmail, "Confirm your new email", confirmLink(token)); mailer.send(user.getCurrentEmail(), "Your email change was requested", "If this wasn't you, secure your account now.");}public void confirmEmailChange(String token) { PendingChange change = pendingEmailChanges.consume(token) .orElseThrow(() -> new InvalidTokenException()); userService.setEmail(change.getUserId(), change.getNewEmail());}
Line by line:
public void requestEmailChange(User user, String newEmail) {: start an email change request.String token = tokenService.generate();: create a random one-time token.pendingEmailChanges.save(user.getId(), newEmail, token, Instant.now().plus(Duration.ofHours(1)));: remember the requested change, with the token, for one hour.mailer.send(newEmail, "Confirm your new email", confirmLink(token));: email a confirmation link to the new address.mailer.send(user.getCurrentEmail(), "Your email change was requested", "If this wasn't you, secure your account now.");: also warn the old address.public void confirmEmailChange(String token) {: handle the click on the confirmation link.PendingChange change = pendingEmailChanges.consume(token).orElseThrow(() -> new InvalidTokenException());: look up the pending change by token, and fail if it is invalid or expired.userService.setEmail(change.getUserId(), change.getNewEmail());: only now make the new address the real one.
Email changes should require the new address to confirm via a link before it becomes authoritative, and notify the old address regardless, specifically to catch exactly this kind of attack in progress.
Misconfiguration 8: no session invalidation after a sensitive change
After the email changed, the victim's existing session stayed fully alive. Nothing forced re-authentication, and no other active sessions were invalidated.
This matters for attacker timing. Without session invalidation, the attacker does not need to race the victim or act within a narrow window; they can let the victim keep using the app undisturbed, with no visible sign anything happened, while separately triggering a password reset to the now-hijacked address at their leisure. A minimal mitigation:
public void onEmailChanged(Long userId) { userService.markEmailChanged(userId); sessionRegistry.invalidateAllExcept(userId, currentSessionId()); mailer.send(user.getPreviousEmail(), "Your account email just changed");}
Line by line:
public void onEmailChanged(Long userId) {: run this whenever a user's email changes.userService.markEmailChanged(userId);: record the change.sessionRegistry.invalidateAllExcept(userId, currentSessionId());: log out every other active session for that user, keeping only the current one.mailer.send(user.getPreviousEmail(), "Your account email just changed");: notify the old address.
Forcing re-authentication, or at minimum invalidating other active sessions, whenever a recovery-critical field changes is a standard control, touched on in NIST 800-63B's guidance on session management after credential or authenticator changes. Its absence here turns a narrow exploitation window into an indefinite one.
Why the WAF did not help
It is worth circling back to the WAF mentioned at the start, because its silence here is itself a useful lesson.
WAFs work mainly by matching request content against signatures for known attack classes: database-injection syntax, script tags, path traversal sequences, known exploit strings for specific vulnerabilities. What they are generally not built to reason about is business logic: whether this request, from this origin, to this endpoint, with a session cookie belonging to this user, represents a legitimate action.
The final exploit request is, from a pure pattern-matching standpoint, almost perfectly unremarkable:
POST /legacy/rest/v2/user?_method=PUT HTTP/1.1Content-Type: text/plainCookie: JSESSIONID=<valid session>; deh=<valid session>
{"eMailAddress":"[redacted]","x":"="}
Line by line:
POST /legacy/rest/v2/user?_method=PUT HTTP/1.1: aPOSTthat the server will treat as aPUTbecause of_method=PUT.Cookie: JSESSIONID=<valid session>; deh=<valid session>: the victim's own, completely legitimate session cookies.- The body is valid JSON asking to change the email to
[redacted], with an extra ignored fieldxwhose value is=.
There is no database syntax, no script tags, no traversal sequences, no known malicious signature. The body is syntactically valid, boring JSON. The session cookie is completely legitimate, it is the victim's own. The only thing wrong with the request is context: it originated from evil.com, and no control downstream of the WAF ever checked that context. A WAF in front of this traffic has nothing to flag. WAFs catch malicious payloads; they do not catch malicious contexts, and CSRF is fundamentally a context problem.
The chain, end to end
| # | Misconfiguration | What it defeats |
|---|---|---|
| 1 | CSRF token sent, not validated server-side | Primary CSRF defence |
| 2 | SameSite=None on session cookies |
Browser's built-in CSRF mitigation |
| 3 | No Origin/Referer validation | Defence-in-depth CSRF backstop |
| 4 | text/plain parsed as JSON |
CORS preflight requirement |
| 5 | _method=PUT override |
HTML form's GET/POST-only limitation |
| 6 | No step-up authentication | Defence-in-depth for sensitive actions |
| 7 | No email verification / no old-email notice | Blast-radius containment, victim awareness |
| 8 | No session invalidation after sensitive change | Attacker's exploitation time window |
Break any single link and the exploit either stops working or shrinks dramatically in impact. No individual finding here would score above "Medium" on its own in most bug bounty triage; the severity lives entirely in the composition.
Proof of concept
A proof of concept (PoC) is a small demonstration that shows the attack actually works. Here it is a single HTML file:
<!DOCTYPE html><html><head><title>Loading...</title></head><body> <h1>Please wait...</h1> <form id="csrf" action="https://target.example/legacy/rest/v2/user?_method=PUT" method="POST" enctype="text/plain"> <input type="hidden" name='{"eMailAddress":"[redacted]","x":"' value='"}'> </form> <script>document.getElementById('csrf').submit();</script></body></html>
Line by line:
<!DOCTYPE html><html><head><title>Loading...</title></head><body>: a normal, minimal web page. The title says "Loading..." to look harmless.<h1>Please wait...</h1>: a reassuring heading, so the victim does not suspect anything.<form id="csrf" action="https://target.example/legacy/rest/v2/user?_method=PUT" method="POST" enctype="text/plain">: a form that, when submitted, sends aPOSTto the target endpoint with_method=PUT, encoded as plain text. Theidlets the script find it.<input type="hidden" name='{"eMailAddress":"[redacted]","x":"' value='"}'>: a hidden field whose name and value are crafted so that the browser's plain-text encoding produces valid JSON.<script>document.getElementById('csrf').submit();</script>: immediately submit the form as soon as the page loads. The victim does not have to click anything.
The text/plain form-encoding trick
This is the part of the PoC that tends to confuse people the first time they see it, so it is worth walking through carefully.
When a browser serialises a <form enctype="text/plain">, it does not JSON-encode anything; it writes name=value pairs, one per line, literally. Normally that produces garbage from a JSON parser's perspective. But if you choose the field name and value carefully, the browser's plain name=value concatenation lands exactly on valid JSON syntax:
name: {"eMailAddress":"[redacted]","x":"value: "}
Line by line:
name:is the field's name, which starts a JSON object and opens a string for the email address.value:is the field's value, which closes the string and the object.
You can verify this encoding behaviour in a browser console without touching the target:
const form = document.createElement('form');form.enctype = 'text/plain';
const input = document.createElement('input');input.name = '{"eMailAddress":"[redacted]","x":"';input.value = '"}';form.appendChild(input);// This mirrors what the browser sends as the body:console.log(`${input.name}=${input.value}`);// {"eMailAddress":"[redacted]","x":"="}
Line by line:
const form = document.createElement('form');: create a form in memory.form.enctype = 'text/plain';: set its encoding to plain text.const input = document.createElement('input');: create an input field.input.name = '{"eMailAddress":"[redacted]","x":"';: set the field's name to the first half of the JSON.input.value = '"}';: set the field's value to the second half.form.appendChild(input);: put the field in the form.console.log(${input.name}=${input.value});: print what the browser will send, which isname=valuejoined by an equals sign.- The comment shows the result:
{"eMailAddress":"[redacted]","x":"="}.
Concatenated by the browser as name=value:
{"eMailAddress":"[redacted]","x":"="}
The = character the browser inserts between name and value does not break anything: it lands inside the string value of the "x" property, which the server-side JSON parser treats as an arbitrary ignored field. The attacker-controlled eMailAddress value sits cleanly inside its own properly-quoted string, untouched by the encoding mechanics. This technique for smuggling attacker-controlled JSON through a form's text/plain encoding only works because of misconfiguration 4. If the server enforced Content-Type: application/json, the construction would be rejected outright regardless of how clever the encoding is.
What the server actually receives
POST /legacy/rest/v2/user?_method=PUT HTTP/1.1Host: target.exampleContent-Type: text/plainOrigin: https://evil.comReferer: https://evil.com/poc.htmlCookie: JSESSIONID=<victim-session>; deh=<victim-session>
{"eMailAddress":"[redacted]","x":"="}
{ "eMailAddress": "[redacted]", "eMailAddressVerified": "False"}
Line by line:
POST /legacy/rest/v2/user?_method=PUT HTTP/1.1: aPOSTthat the server will treat as aPUT.Host: target.example: the target server.Origin: https://evil.com: the request came from the attacker's site. This is the crucial line.Referer: https://evil.com/poc.html: the specific attacker page that triggered it.Cookie: JSESSIONID=<victim-session>; deh=<victim-session>: the victim's own session cookies, attached automatically by the browser.- The first JSON block is the body the server receives.
- The second JSON block is the result: the email is now
[redacted], and the verified flag isFalse.
The Origin: https://evil.com header is right there in the request, completely unvalidated (misconfiguration 3). That is really the whole story in one line. CORS governs whether JavaScript on evil.com is allowed to read the response; it says nothing about whether the browser is allowed to send the request. Simple requests are sent unconditionally, and the Access-Control-Allow-Origin response header only determines whether the attacker's script can see what came back. Since this attack does not need to read the response, it is a pure state-changing side effect, and CORS was never in a position to stop it, no matter how strictly it was configured.
CSRF tokens, SameSite cookies and Origin validation are the actual anti-CSRF controls. CORS is not one of them, despite how often it is treated as if it were.
Root cause
The chain rests on eight individually unremarkable misconfigurations, each of which shows up in automated scanner output as informational or gets closed in triage as not exploitable given other controls:
- The double-submit CSRF token was generated client-side and sent by the Angular interceptor, but no backend filter rejected requests missing or mismatching it. The likely root cause is a URL-pattern exclusion such as
.ignoringRequestMatchers("/legacy/**")in the security configuration. - Session cookies were set with
SameSite=None, a deliberate decision for iframe embedding applied at the cookie level rather than the endpoint level, so every endpoint under/legacyinherited cross-site exposure. - The server never validated
OriginorReferer, so the defence-in-depth layer that would have caught the token failure was absent. - The server parsed JSON bodies sent as
text/plain, likely through a permissiveHttpMessageConverterregistration or a hand-rolled fallback parser, so the browser could classify the request as a CORS-simple request while the server still parsed structured JSON. HiddenHttpMethodFilter(or equivalent) was enabled, so a plainPOSTwith?_method=PUTwas re-routed as aPUT, making the endpoint reachable from an HTML form.- No step-up authentication was required for a change to the recovery email.
- No verification loop gated the new email, and no notice went to the old address.
- No session invalidation followed the sensitive change.
The WAF did not stop it because the final request contains no malicious payload syntax, only a legitimate-looking body from an illegitimate origin, and signature-based WAFs have nothing to key on.
Impact
An attacker who can lure a logged-in victim to a single HTML page can change the victim's account email with zero interaction beyond loading the page. Because the password reset flow trusts the email field, the attacker then controls password reset and therefore the account: full account takeover. The victim's session stays alive and nothing visible happens, so the attacker can trigger the reset at their own leisure rather than racing the victim.
The report does not describe any preconditions beyond the victim's browser loading the page.
Fix
Each link has a direct fix:
- Validate CSRF tokens server-side on every endpoint that changes something, including legacy or deprecated ones. Do not assume token generation implies token validation.
- Scope
SameSite=Nonecookies as narrowly as possible. If it is needed for iframe embedding, consider splitting session concerns: a narrowly-scoped embed token versus the primary session cookie, so the high-privilege cookie does not inherit cross-site exposure it does not need. - Add server-side Origin/Referer allowlisting as defence-in-depth on all state-changing endpoints, independent of token validation.
- Enforce the declared
Content-Typestrictly. Reject bodies that do not match the declared type instead of auto-detecting and parsing anyway. - Disable or tightly restrict HTTP method override in production, or require it to come with the same CSRF and auth checks as the real verb would.
- Require step-up authentication (password re-entry, authenticator code, security key) before any change to recovery email, phone, multi-factor settings or credentials.
- Gate email changes behind a verification loop: the new address must confirm via link before becoming authoritative, and the old address always receives a notice regardless.
- Invalidate other active sessions (or force re-authentication) whenever a recovery-critical field changes, to cap the attacker's exploitation window.
Variants to test
- CSRF token present but not validated. Omit the token entirely, send an empty string, send another valid user's token, send a stale or expired token. A
200response to any of these means generation exists but validation does not. - Cookie attributes across every subdomain and path prefix. Check
Set-Cookieon legacy paths, embedded-widget subdomains and partner-facing subdomains, not just the main login response. A positive result is a looserSameSiteor missingSecureon the same session identifier used elsewhere. - Origin/Referer validation independently of tokens. Alter or strip
OriginandRefererand compare responses. Identical behaviour regardless ofOriginconfirms a second, independent gap. - JSON endpoints retested with
text/plainandmultipart/form-data. A positive result is the body still parsing and the state change still applying under a safelisted content type. - Method override support. Try
_method,X-HTTP-Method-OverrideandX-Method-Overrideon frameworks known to support them (Rails, Spring, Laravel, legacy Express middlewares). A positive result is aPOSTbeing handled as the overridden verb, which turns the CSRF surface from GET/POST only into every verb. - Recovery-critical endpoints. Prioritise anything that touches email, phone, multi-factor settings, SSH/API keys or password. A positive result is any of these changing without step-up authentication.
- WAF assumptions. If the exploit request contains no malicious payload syntax, only a legitimate-looking body from an illegitimate origin, expect a signature-based WAF to have nothing to key on.
- Chaining before triage. Ask what stops the exploit end to end before accepting partial mitigations as sufficient. A program might reasonably close "CSRF token not validated" as low severity if they believe
SameSitecookies are the backstop, and close "SameSite=Nonepresent" as accepted risk if they believe CORS blocks exploitation. Each individual triage can be locally reasonable and still collectively wrong.
Closing thoughts
None of these eight bugs would have made a dent alone. That is exactly why this is worth writing up in full rather than as eight separate low-severity tickets: the real finding is the chain itself, and the real skill being demonstrated is recognising that a "fully defended" surface is only as strong as its least-reviewed component. Legacy apps, convenience features like method override, permissive parsers, and controls that exist on paper but are not backed by server-side enforcement are where that weakest link usually lives. A WAF out front and a security-conscious new frontend next door do not change that; they just make it easier to assume the weakest link does not exist.
Glossary
- API (Application Programming Interface): the part of a website that does the actual work behind the pages you see, like the kitchen behind a restaurant's dining room.
- Account takeover (ATO): an attacker gaining control of someone else's account.
- BFF (Backend-for-Frontend): a dedicated server layer in front of a shared backend, built for one specific frontend.
- Cookie: a small piece of text a website asks your browser to store and send back with later requests, used to remember that you are logged in.
- CORS (Cross-Origin Resource Sharing): a browser rule about whether JavaScript from one site may read responses from another site. It does not stop requests from being sent.
- CSRF (Cross-Site Request Forgery): tricking a logged-in user's browser into sending a state-changing request to a site, using the user's own cookies.
- CSRF token: a random value a site expects back with state-changing requests, which another site cannot read or guess.
Content-Type: a request header saying what format the body is in, such asapplication/jsonortext/plain.- Double-submit cookie: a CSRF technique where the token is stored in a cookie and copied into a header, and the server checks that the two match.
- Endpoint: one specific address on a server that performs one specific job.
- Header: extra information attached to a request or response, separate from the body, like the envelope of a letter.
HttpOnly: a cookie setting that stops JavaScript from reading the cookie.- HTTP method: the word in a request saying what kind of action it is:
GET(read),POST(submit),PUT(replace),DELETE(remove). - Iframe: a way to embed one website inside another page.
- JSON: a structured text format for data, like
{"name": "John"}. - Method override: a feature that lets a
POSTrequest be treated as another method such asPUT, usually via_methodor a header. - NIST: the US standards body for technology, which publishes security guidance.
- Origin: a request header saying which website the request came from.
- OWASP: a non-profit that publishes widely used web security guidance.
- Password reset flow: the "forgot my password" feature, which sends a reset link to the email address on the account.
- Preflight: an extra
OPTIONSrequest a browser sends before a non-simple cross-site request, to ask the target whether the other site may read the response. - Proof of concept (PoC): a small demonstration showing that an attack actually works.
Referer: a request header saying which page triggered the request.- Request: a message your browser sends to a server asking it to do something.
SameSite: a cookie setting controlling whether the cookie is sent on requests coming from other sites.LaxandStrictrestrict it;Noneallows it everywhere.Secure: a cookie setting that only sends the cookie over encrypted HTTPS connections.- Session: the server's record that a particular browser is logged in as a particular user.
- Simple request: a cross-site request using a safelisted content type (
application/x-www-form-urlencoded,multipart/form-data,text/plain) and no unusual headers, which the browser sends without a preflight. - Spring: a popular Java framework for building web servers.
- Step-up authentication: asking the user to prove again that it is really them, right before a sensitive action.
- WAF (Web Application Firewall): a filter in front of a website that checks requests against known attack patterns.