The Buffer Curse: A tale of unusual exploitation in Web Application
A PHP application reflects user input without proper validation and uses a CSP nonce for protection. By sending a large input to the 'sbox' parameter, the attacker can overflow the output buffer, causing the CSP header to be ignored and enabling reflected XSS.
Published on infosecwriteups.com
Have you ever developed an application before? No matter what medium that you built, either it’s a mobile, desktop/GUI or web application, each requires a good and precise planning to create it.
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 write-up about a deliberately built PHP sandbox page that reflects user input and protects itself with a Content-Security-Policy header carrying a per-request nonce. The page is called a "Free Sandbox Canvas": it accepts a canvas GET parameter and echoes it inside an <h3> element, so the feature is a simple HTML reflection playground. The researcher says the challenge was inspired by justCTF 2020 and modified to share the same concept: bypassing CSP through the way PHP handles output buffering.

The security model of the page rests on two things: a strict CSP header (default-src 'none'; object-src 'none'; base-uri 'none'; script-src 'nonce-$rand_nonce') and a nonce that is regenerated on every request from openssl_random_pseudo_bytes and hashed with SHA512. A second GET parameter, sbox, feeds a secure_nonce function that is meant to mix attacker-supplied data into the nonce derivation and to complain loudly when the value does not start with nonce-.
Setup
The only tool the researcher names is BurpSuite, used to intercept requests and inspect responses. No accounts, roles or versions are mentioned. The precondition for the attack is the default PHP output buffer size: the report states that the default storage of the output buffer holds up to 4KB, exactly 4096 bytes, as written in the php.ini directory, and that if the buffer exceeds it PHP sends the data back in a forced buffer flush, either to PHP FastCGI or whatever PHP backend is used.
Finding it
The researcher starts from the idea that output buffering is not a security feature by itself but can become an exploitation vector when code is poorly designed. The relevant behaviour is that the body of a response is written into the buffer before the HTTP headers are sent, because no data is returned before the header in the script. If enough body data is produced to exceed the buffer, the flush happens and the headers, CSP included, are effectively ignored.
The vulnerable script is given in full:
<?phpfunction secure_nonce($sbox){ $rm = hash('sha512',random_bytes(16)); $rn = hash('sha512',random_bytes(16)); $rv = hash('sha512',random_bytes(16)); $tnonce = array($rm=>random_int(8,16), $rn => random_int(8,16), $rv => random_int(8,16)); $newcollider = ""; $x = 0; while( $x < 4){ if(substr(htmlspecialchars($sbox,ENT_QUOTES), 0, 6) !== "nonce-"){ trigger_error(htmlspecialchars($sbox,ENT_QUOTES) . " should've had a nonce."); } $newcollider .= $sbox; $newcollider .= $tnonce[$rm]; $newcollider .= $tnonce[$rn]; $newcollider .= $tnonce[$rv]; $x++; } return $newcollider;}$rand = openssl_random_pseudo_bytes(random_int(0xff,0xffff));$rand_nonce = hash('sha512',bin2hex($rand));$temp = $rand_nonce;if(isset($_GET['sbox'])){ $additional_data = secure_nonce($_GET['sbox']); try{ $rand_nonce = hash('sha512',(hash('sha512',$rand_nonce) . hash('sha512',$additional_data))); } catch(Exception $e){ $rand_nonce = $temp; }}if(isset($_GET['canvas'])){ header("Content-Security-Policy: default-src 'none'; object-src 'none'; base-uri 'none'; script-src 'nonce-$rand_nonce'"); header("X-XSS-Protection: 1"); header("X-Frame-Options: DENY"); header("X-Content-Type-Options: nosniff"); header("Pragma: no-cache"); header("Cache-Control: no-cache, no-store, must-revalidate, max-age=0, s-maxage=0"); echo "<p>Free Sandbox Canvas, insert your whatever fancy HTML here!<p></br><h3>{$_GET['canvas']}</h3>";}else{ show_source(__FILE__);}?>
Several things stand out. The canvas parameter is reflected directly into the page with no validation, so every character is accepted, including >, ;, ', ", ., #, % and similar. That is a classic reflected XSS vector, but the CSP header requires an exact nonce stored in $rand_nonce for any script to execute, and default-src 'none' blocks resource loading.

The nonce derivation is the second point of interest:
$rand = openssl_random_pseudo_bytes(random_int(0xff,0xffff));$rand_nonce = hash('sha512',bin2hex($rand));$temp = $rand_nonce;if(isset($_GET['sbox'])){ $additional_data = secure_nonce($_GET['sbox']); try{ $rand_nonce = hash('sha512',(hash('sha512',$rand_nonce) . hash('sha512',$additional_data))); } catch(Exception $e){ $rand_nonce = $temp; }}
The researcher considers whether the random number could yield 0 or NULL, since in PHP 8 the second parameter of openssl_random_pseudo_bytes might be nullable, but notes that no flags are passed as a second parameter, so that path is closed. The sbox value is processed by secure_nonce and the returned value is appended to a SHA512 hash of $rand_nonce and hashed again.
The secure_nonce function itself is described as absurd: sbox is concatenated with hashed random data, and unlike canvas it is filtered by htmlspecialchars. If the prefix of sbox does not start with nonce-, an output error is raised through trigger_error.

No nonce- prefix specified

Nonce- prefix used
The key observation is that the attacker controls the input, and therefore controls the output reflected to the browser. The error path through trigger_error is the attack vector: it lets the attacker generate body data before the headers are sent.
Exploitation
Step 1: confirm the CSP header is present
The researcher intercepts a request with BurpSuite and inspects the response to confirm that the CSP really is in the header.


Step 2: populate sbox with junk buffer data
The sbox parameter is filled with junk so that the CSP header would be ignored.

Step 3: exceed 4096 bytes
The first attempt is not enough. More data is added so that the buffer is more than 4096 bytes, driven by the warning triggered by the sbox value.

Step 4: observe the result
The CSP is no longer reflected in the application's response and the request, including the JavaScript execution, is triggered. The researcher shows this from the client's browser.


The report does not include the exact request line, payload string or response body for these steps; the screenshots are the only record of them.
Root cause
The bug is that the application's response body is not sent first, but the header should be. The body data is sent to the output buffer before the HTTP header because there is no data returned before the header. When the attacker supplies enough data through sbox to exceed the default PHP output buffer size of 4096 bytes, the forced flush happens and the CSP inside the header is ignored. The sbox parameter is the perfect spot to control because it triggers the trigger_error warning.
The existing defences did not stop it: the nonce is random and one-time, the CSP is strict, and sbox is filtered by htmlspecialchars, but none of that matters once the header itself never reaches the client. The report frames this as a design problem rather than a missing filter: relying only on security-centric middleware is not enough.
Impact
The impact is reflected XSS on the sandbox page: the researcher shows JavaScript execution in the client's browser despite the CSP. The report does not describe any specific victim, data or account being affected, and the page is presented as a challenge-style sandbox rather than a production asset. The attack uses a sbox value large enough to exceed the 4096-byte buffer.
Fix
The report does not describe a fix being applied. The general direction it argues for is that developers should not rely only on security-centric middleware and should prioritise good code construction, thinking about what happens later in the request lifecycle.
Variants to test
- Other error-triggering parameters. Any parameter that reaches
trigger_error, a warning or a notice before theheader()call can be used the same way. A positive result is a response where the CSP header is missing while the body contains the reflected input. - Different buffer sizes. The 4096-byte figure is the default; a target with a smaller configured buffer needs less data. A positive result is the same missing header with a shorter payload.
- Reflection points after the header call. If the reflection happens after
header()but the error output happens before it, the same split still applies. A positive result is script execution in the browser with the CSP absent from the response. - Nonce derivation with user input. Where a nonce is mixed with user-controlled data, check whether the mixing can be influenced or whether an exception path falls back to a predictable value. A positive result is a nonce that can be reproduced or predicted across requests.
htmlspecialcharson one parameter only. Compare parameters that are filtered with parameters that are not; the unfiltered one is the reflection candidate. A positive result is a reflected payload that survives into the body unchanged.
What happened, in plain words
A security researcher modified a challenge written in the PHP programming language. The page is called a "Free Sandbox Canvas" and it takes GET parameter input and reflects it back on the page. Think of it like a whiteboard where you write a word and the board repeats it back to you.

The page tries to protect itself with a browser feature called Content-Security-Policy, or CSP. CSP is a set of rules the website sends to your browser saying "only run code that comes from these places, and only load images from these places". The page also uses a special one-time password called a nonce, which changes on every visit, so that only scripts carrying that exact password are allowed to run.
Despite all that, the researcher found a way to make the browser run his own JavaScript anyway in his own browser. It exploits the order in which PHP sends things to the browser: the page body can be sent before the security rules, and if the body is big enough, PHP flushes it out early and the security rules never arrive. The CSP is not reflected in the application's response, and the JavaScript execution is triggered.
This is a beginner-friendly walkthrough of how that works, why each step was taken, and what it teaches about building secure web pages.
Prelude

Before the technical part, the researcher sets the scene. Every application, whether it runs on a phone, on a desktop or in a web browser, needs careful planning. A developer is expected to use well-maintained frameworks and good coding habits so the result is solid.
Testing the software also needs measurements. One of those measurements is security. There are many security frameworks that help teams protect valuable data (the report links to an article calling such data "crown jewels"). Some frameworks even include built-in security components, such as middleware.
Middleware is software that sits between the incoming request and your application code, like a security guard at the door of a building who checks every visitor before letting them in. It can add security headers, check logins, or block suspicious traffic.
But the researcher asks a pointed question: if you rely on that guard, are you sure you have done enough? The rest of the article shows a case where the guard was there, but the building had a side door.
Code's Maestro

The example is written in PHP, a programming language that runs on web servers and produces the pages your browser displays. The researcher notes that PHP is still widely used in 2023, for example through the Laravel framework.
Many vulnerabilities appear when a developer writes backend logic poorly. The most common ones start with unfiltered user input: the application takes text from a visitor and uses it without checking it. Other examples include insecure deserialisation (turning stored data back into objects without checking it is safe) and similar issues. These common causes are usually easy to prevent, and many developers already review their code for them.
But sometimes the output of the code itself becomes the security concern. That produces an unusual attack path, similar to unsafe memory handling in a web page. In other words: the problem is not only what goes in, but what comes out and in which order.
HTTP Buffering
There is a concept in programming called Output Buffering. Its job is to store data in a temporary holding area, called a buffer, before it is printed out. The buffer acts as a middle layer.
A useful everyday comparison: imagine a restaurant kitchen. The cook (the PHP script) prepares dishes, but instead of handing each plate straight to the customer, the plates go onto a serving counter (the buffer). A waiter (the flush) carries them to the table when the counter is full or when the cook says "serve now".
The report gives a Python example of buffer control:
class Unbuffered(object): def __init__(self, stream): self.stream = stream def write(self, data): self.stream.write(data) self.stream.flush() def writelines(self, datas): self.stream.writelines(datas) self.stream.flush() def __getattr__(self, attr): return getattr(self.stream, attr)
Line by line, in plain words:
class Unbuffered(object):defines a new blueprint calledUnbuffered. The name suggests it does not hold data back.def __init__(self, stream):is the setup step that runs when the blueprint is used. It receives astream, which is wherever the output should go (for example the screen or a file).self.stream = streamstores that destination so the other steps can use it later.def write(self, data):defines what happens when someone writes text. It immediately passes the text to the destination withself.stream.write(data).self.stream.flush()then forces the destination to push the text out right away, instead of waiting.def writelines(self, datas):does the same for a list of lines: it writes them all and then flushes.def __getattr__(self, attr):forwards any other request (like asking for a property) to the underlying stream, so the wrapper behaves like the original object.
In this example, a user can assign the Unbuffered class to the stdout handler (the standard output channel), and every piece of data is moved out when flush is called.
The same idea applies to Output Buffering in PHP. It controls how much output PHP stores internally before pushing data to the client. Importantly, this does not include headers and cookies. Headers are the small pieces of information sent before the page body, such as security rules and content type. Cookies are small pieces of data the browser stores and sends back on later requests.
Without output buffering, the flow looks like this:

The data source is the PHP script. As soon as the script calls a function that outputs something to the browser, it is shown immediately. There is no waiting counter.
With output buffering, the flow is different. The PHP script hands data to a container-like middle layer first, the output buffer:

The stored data in the buffer (the truck in the diagram) is delivered to the client's browser when the application reaches a call to flush() or ob_flush(). Those are PHP functions that tell the buffer "send what you have now". This is what happens internally when output buffering is used.
By default, the output buffer holds up to 4KB, exactly 4096 bytes, as written in the php.ini configuration file. If the buffer exceeds that size, PHP sends the data out in a forced buffer flush, either to PHP FastCGI or whatever PHP backend is used. FastCGI is a way for a web server to pass requests to PHP; think of it as the pipe between the front desk and the kitchen.
Attacker's Exordium

On its own, output buffering is not a security threat. But it can become an exploitation vector when an attacker spots code that is poorly designed and has no security thinking behind it.
Exploitation vector means the path or method an attacker uses to carry out an attack, like the route a burglar takes into a house.
Inspired by justCTF 2020 (a capture-the-flag competition, where players solve security puzzles), the researcher modified a challenge that shares the same concept: bypassing a modern security layer called Content-Security Policy (CSP).
Bypassing means getting around a protection without breaking it directly, the way you might walk around a fence instead of climbing it.
A quick look at CSP, quoting the MDN Web Docs:
Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks. These attacks are used for everything from data theft, to site defacement, to malware distribution.
Cross-Site Scripting (XSS) is a vulnerability where an attacker manages to get their own JavaScript code to run inside someone else's browser, on a website the victim trusts. The attacker's code then acts as if it were part of the site: it can read what the victim sees, steal session cookies, or change the page. Think of it as someone slipping a fake page into a book you are reading, so you believe the fake page belongs to the book.
Developers see CSP as a defence against XSS because CSP consists of directives (rules about whether to load a specific resource or script) and sources (where resources may be loaded from).
How is CSP implemented? Before writing it, a developer needs to decide what they expect. If they want to load resources only from the same domain, they can use the default-src directive with the 'self' source. There is an exception for images: if they also want to allow images from a specific domain (for example, medium.com) plus their own domain, they can use the img-src directive with multiple sources: 'self' medium.com.
These rules can be written in two places:
- HTTP Headers
Content-Security-policy: default-src 'self'; img-src 'self' medium.com;
- Meta HTML Tag
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src 'self' medium.com;">
What these mean in plain words:
Content-Security-policy:is the name of the header. Everything after the colon is the rule set.default-src 'self'says: by default, only load things from the same website ('self').img-src 'self' medium.comsays: for images specifically, allow the same website and also medium.com.- The semicolons separate the directives, like sentences in a paragraph.
- The
<meta>version does the same thing but is written inside the HTML page instead of in the header.http-equivtells the browser to treat this tag as if it were an HTTP header, andcontentholds the rules.
Once the rules are written, a developer can test them with the CSP Evaluator at https://csp-evaluator.withgoogle.com/.
Suppose the developer puts a secure CSP in the HTTP header and allows resources only from the same domain. If JavaScript needs to run in the application, the developer uses a cryptographic approach: a side attribute on the script tag called nonce. It is often used in authentication as well.

Image References: https://en.wikipedia.org/wiki/Cryptographic_nonce
A nonce is a number used once. The report stresses that it should be a one-time-use randomly generated number, so it should not be statically assigned. A fresh random value must be generated each time, because the developer does not want attackers to predict the value and reuse it in their own script tag.
A useful comparison: a nonce is like a single-use ticket at a concert. The guard at the door checks the ticket number against the list for tonight. If you could guess tonight's number, you could print your own ticket.
Below is a PHP script that takes a maximum of 2 GET parameter inputs from the user and renders them back, so the user's input is reflected.
GET parameters are the pieces of information you see in a web address after a question mark, like ?name=Alex. They are sent to the server as part of the request. Reflected means the server takes your input and puts it back into the page it sends you.
<?phpfunction secure_nonce($sbox){ $rm = hash('sha512',random_bytes(16)); $rn = hash('sha512',random_bytes(16)); $rv = hash('sha512',random_bytes(16)); $tnonce = array($rm=>random_int(8,16), $rn => random_int(8,16), $rv => random_int(8,16)); $newcollider = ""; $x = 0; while( $x < 4){ if(substr(htmlspecialchars($sbox,ENT_QUOTES), 0, 6) !== "nonce-"){ trigger_error(htmlspecialchars($sbox,ENT_QUOTES) . " should've had a nonce."); } $newcollider .= $sbox; $newcollider .= $tnonce[$rm]; $newcollider .= $tnonce[$rn]; $newcollider .= $tnonce[$rv]; $x++; } return $newcollider;}$rand = openssl_random_pseudo_bytes(random_int(0xff,0xffff));$rand_nonce = hash('sha512',bin2hex($rand));$temp = $rand_nonce;if(isset($_GET['sbox'])){ $additional_data = secure_nonce($_GET['sbox']); try{ $rand_nonce = hash('sha512',(hash('sha512',$rand_nonce) . hash('sha512',$additional_data))); } catch(Exception $e){ $rand_nonce = $temp; }}if(isset($_GET['canvas'])){ header("Content-Security-Policy: default-src 'none'; object-src 'none'; base-uri 'none'; script-src 'nonce-$rand_nonce'"); header("X-XSS-Protection: 1"); header("X-Frame-Options: DENY"); header("X-Content-Type-Options: nosniff"); header("Pragma: no-cache"); header("Cache-Control: no-cache, no-store, must-revalidate, max-age=0, s-maxage=0"); echo "<p>Free Sandbox Canvas, insert your whatever fancy HTML here!<p></br><h3>{$_GET['canvas']}</h3>";}else{ show_source(__FILE__);}?>
This is a lot at once, so let us walk through it in plain words, block by block.
The secure_nonce function
function secure_nonce($sbox){starts a function namedsecure_noncethat takes one input,$sbox(the value of thesboxGET parameter).$rm = hash('sha512',random_bytes(16));creates a random 16-byte value, hashes it with the SHA512 algorithm, and stores the result in$rm. Hashing turns data into a fixed-length fingerprint; the same input always gives the same fingerprint, but you cannot easily turn the fingerprint back into the input. SHA512 is one such hashing algorithm.- The next two lines do the same for
$rnand$rv, giving three random fingerprints. $tnonce = array($rm=>random_int(8,16), $rn => random_int(8,16), $rv => random_int(8,16));builds a lookup table (an array) where each random fingerprint is a key, and each key maps to a random integer between 8 and 16.$newcollider = "";starts an empty text string that will collect the result.$x = 0;sets a counter to zero.while( $x < 4){repeats the following block four times.if(substr(htmlspecialchars($sbox,ENT_QUOTES), 0, 6) !== "nonce-"){checks whether the first six characters of the cleaned-up$sboxare not equal tononce-.htmlspecialcharsconverts special characters like<,>,&,'and"into harmless HTML entities, so they display as text instead of being treated as code.ENT_QUOTEStells it to convert both single and double quotes.substr(..., 0, 6)takes the first six characters.trigger_error(htmlspecialchars($sbox,ENT_QUOTES) . " should've had a nonce.");raises a warning message if the check failed.trigger_erroris a PHP function that produces an error or warning message. This is the important line for the attack, because it produces output.$newcollider .= $sbox;appends the raw$sboxvalue to the result string.- The next three lines append the three random integers from the lookup table.
$x++;increases the counter by one, so the loop runs four times in total.return $newcollider;sends the collected string back to whoever called the function.
The nonce calculation
$rand = openssl_random_pseudo_bytes(random_int(0xff,0xffff));generates a random number of random bytes.openssl_random_pseudo_bytesis a PHP function for generating cryptographically strong random bytes.random_int(0xff,0xffff)picks a random length between 255 and 65535.$rand_nonce = hash('sha512',bin2hex($rand));converts the random bytes to a hexadecimal string withbin2hex, then hashes that with SHA512. The result is the nonce.$temp = $rand_nonce;keeps a backup copy of the nonce.if(isset($_GET['sbox'])){checks whether thesboxparameter was provided in the URL.$additional_data = secure_nonce($_GET['sbox']);passes the user'ssboxvalue into the function above and stores the result.try{begins a block where errors can be caught.$rand_nonce = hash('sha512',(hash('sha512',$rand_nonce) . hash('sha512',$additional_data)));hashes the current nonce, hashes the additional data, joins the two hashes together, and hashes the result again. The new nonce now depends on the user's input.} catch(Exception $e){catches any exception thrown inside the try block.$rand_nonce = $temp;falls back to the backup nonce if something went wrong.
The page output
if(isset($_GET['canvas'])){checks whether thecanvasparameter was provided.header("Content-Security-Policy: default-src 'none'; object-src 'none'; base-uri 'none'; script-src 'nonce-$rand_nonce'");sends the CSP header.default-src 'none'blocks everything by default.object-src 'none'blocks plugin content like Flash.base-uri 'none'blocks the<base>tag, which could otherwise change how relative links resolve.script-src 'nonce-$rand_nonce'allows scripts only if they carry the exact nonce value.header("X-XSS-Protection: 1");asks the browser to enable its built-in XSS filter.header("X-Frame-Options: DENY");stops the page from being embedded in a frame on another site, which prevents clickjacking (tricking users into clicking something they did not intend).header("X-Content-Type-Options: nosniff");stops the browser from guessing the content type, which can prevent some attacks.header("Pragma: no-cache");andheader("Cache-Control: no-cache, no-store, must-revalidate, max-age=0, s-maxage=0");tell the browser and any caches not to store the page.echo "<p>Free Sandbox Canvas, insert your whatever fancy HTML here!<p></br><h3>{$_GET['canvas']}</h3>";prints the page body. The user'scanvasvalue is inserted directly inside an<h3>heading, with no filtering.}else{ show_source(__FILE__);}if nocanvasparameter is given, the script shows its own source code withshow_source.
What are the key points from this script? Should there not be an attack vector to trigger XSS?
Bypassing CSP

There are some workarounds for an attacker with advanced techniques and knowledge to bypass a CSP header. They apply only if the CSP itself might be controllable, or if the developer trusts sources that may have a JSON Callback. A JSON callback is a way for a site to return data wrapped in a function call, which can end up executing JavaScript. However, this scenario is a little different. Let us look closer.
header("Content-Security-Policy: default-src 'none'; object-src 'none'; base-uri 'none'; script-src 'nonce-$rand_nonce'"); header("X-XSS-Protection: 1"); header("X-Frame-Options: DENY"); header("X-Content-Type-Options: nosniff"); header("Pragma: no-cache"); header("Cache-Control: no-cache, no-store, must-revalidate, max-age=0, s-maxage=0"); echo "<p>Free Sandbox Canvas, insert your whatever fancy HTML here!<p></br><h3>{$_GET['canvas']}</h3>";
This is the same output block as before, shown again so we can focus on it. In plain words:
- The first line sends the CSP header with a nonce that changes per request.
- The next five lines send extra protective headers.
- The last line prints the page body, inserting the
canvasvalue directly into the HTML.
The application accepts a GET parameter controlled by the user, and a common attack vector is visible: there is improper input validation, because the result of the GET parameter is reflected directly. All characters are accepted, including dangerous ones like >, ;, ', ", ., #, % and so on.

Unfortunately, it is not that easy, because the CSP header says JavaScript execution needs an exact nonce, stored in the $rand_nonce variable. Besides that, resource loading is strict, since default-src only allows resources from the same domain.
$rand = openssl_random_pseudo_bytes(random_int(0xff,0xffff));$rand_nonce = hash('sha512',bin2hex($rand));$temp = $rand_nonce;if(isset($_GET['sbox'])){ $additional_data = secure_nonce($_GET['sbox']); try{ $rand_nonce = hash('sha512',(hash('sha512',$rand_nonce) . hash('sha512',$additional_data))); } catch(Exception $e){ $rand_nonce = $temp; }}
Line by line:
$rand = openssl_random_pseudo_bytes(random_int(0xff,0xffff));makes a random blob of bytes, with a random length between 255 and 65535.$rand_nonce = hash('sha512',bin2hex($rand));turns the blob into a hex string and hashes it. This is the starting nonce.$temp = $rand_nonce;saves a copy in case something fails.if(isset($_GET['sbox'])){runs the next part only if the URL containssbox.$additional_data = secure_nonce($_GET['sbox']);processes the user'ssboxvalue through the function we saw earlier.try{starts a block where errors can be caught.$rand_nonce = hash('sha512',(hash('sha512',$rand_nonce) . hash('sha512',$additional_data)));mixes the old nonce and the user data together and hashes the result. The final nonce now depends on the user's input.} catch(Exception $e){catches any exception.$rand_nonce = $temp;falls back to the saved copy if an exception happened.
The $rand_nonce is calculated from a number generated by openssl_random_pseudo_bytes and hashed with the SHA512 algorithm. At first, you might think the random number could yield 0 or NULL, since in PHP 8 the second parameter of openssl_random_pseudo_bytes might be nullable. But no flags are passed as a second parameter, so that path is closed.
There is also another user-controlled GET parameter, sbox, which is processed by the secure_nonce function. The final returned value is appended to another SHA512-hashed $rand_nonce and hashed again.
function secure_nonce($sbox){ $rm = hash('sha512',random_bytes(16)); $rn = hash('sha512',random_bytes(16)); $rv = hash('sha512',random_bytes(16)); $tnonce = array($rm=>random_int(8,16), $rn => random_int(8,16), $rv => random_int(8,16)); $newcollider = ""; $x = 0; while( $x < 4){ if(substr(htmlspecialchars($sbox,ENT_QUOTES), 0, 6) !== "nonce-"){ trigger_error(htmlspecialchars($sbox,ENT_QUOTES) . " should've had a nonce."); } $newcollider .= $sbox; $newcollider .= $tnonce[$rm]; $newcollider .= $tnonce[$rn]; $newcollider .= $tnonce[$rv]; $x++; } return $newcollider;}
This is the same function as before, repeated for focus. In plain words:
- Three random fingerprints are created with
hash('sha512',random_bytes(16)). - A lookup table maps each fingerprint to a random integer between 8 and 16.
- The loop runs four times.
- Each time, it checks whether the first six characters of the cleaned
$sboxarenonce-. If not, it raises a warning withtrigger_error. - It appends the raw
$sboxand the three random integers to the result string. - Finally it returns the collected string.
This function is pretty absurd, because sbox is concatenated with hashed random data. Unlike the canvas parameter, sbox is filtered by htmlspecialchars, and there will be an output error if the sbox prefix does not start with nonce-.

No nonce- prefix specified

Nonce- prefix used
Now remember how the output buffer handles the PHP script and transfers data back to the client's browser. Since we can control our input, we can also control the output of the script that is reflected to the browser. The attack vector comes from the error, specifically from the trigger_error function.
The bug is that the application's response body will not be sent first, but the header should be. The body data is sent to the output buffer before the HTTP header, because there is no data returned before the header. This means the CSP inside the header will be ignored if we provide enough data more than the default PHP output_buffer size (4096 bytes). The sbox parameter is the perfect spot for the attacker to control, because it triggers the error.
We will use BurpSuite to intercept the request and see the response from the application. BurpSuite is a tool that sits between your browser and the website, letting you pause, inspect and change requests and responses. Think of it as a transparent mail sorting office where you can read and rewrite letters before they are delivered.
We can confirm that the CSP really is in the header.


Now we will populate the sbox parameter with junk buffer data so that the CSP header would be ignored.

This is not enough. Let us add more data so that the buffer is more than 4096 bytes, driven by the warning triggered by sbox.

As we can see, the CSP is not reflected in the application's response, and our request, including the JavaScript execution, is triggered. This can be shown from the client's browser.


Further Research
Although modern security layers keep getting updated and new security innovations are born, developers should also prioritise good code construction by not only relying on security-centric middleware. This will make them think more about what could happen later.
Love my content?
https://trakteer.id/felix-alexander-swfnt/tip?open=true
References
- Everything About Output Buffering in PHP (phpfashion.com)
- CSP source values - HTTP | MDN (developer.mozilla.org)
- Content Security Policy (CSP) Bypass (book.hacktricks.xyz)
- How to fix "Headers already sent" error in PHP (stackoverflow.com)
Glossary
- API: a way for one piece of software to talk to another, like a waiter taking your order to the kitchen.
- Buffer: a temporary holding area for data before it is sent or processed, like a serving counter in a restaurant.
- Bypass: getting around a protection without breaking it directly.
- Content-Security-Policy (CSP): a set of rules a website sends to the browser saying which scripts, images and other resources are allowed to load.
- Cookie: a small piece of data a website asks the browser to store and send back on later requests.
- Cross-Site Scripting (XSS): a vulnerability where an attacker's JavaScript runs inside a victim's browser on a trusted website.
- Directive: a single rule inside a CSP, such as
default-srcorimg-src. - Exploitation vector: the path or method an attacker uses to carry out an attack.
- FastCGI: a way for a web server to pass requests to a PHP backend.
- Flush: forcing buffered data to be sent out immediately.
- GET parameter: a piece of data in a URL after the question mark, sent to the server as part of the request.
- Hash / SHA512: a function that turns data into a fixed-length fingerprint; SHA512 is one such algorithm.
- Header: small pieces of information sent before the page body, such as security rules and content type.
- htmlspecialchars: a PHP function that converts special characters like
<and>into harmless HTML entities. - HTTP: the protocol browsers and web servers use to exchange requests and responses.
- JavaScript: the programming language that runs in web browsers and makes pages interactive.
- JSON callback: a way for a site to return data wrapped in a function call, which can end up executing JavaScript.
- Middleware: software that sits between the incoming request and the application code, like a security guard at a door.
- Nonce: a number used once, generated randomly for each request, used to authorise specific scripts.
- Output buffering: storing output in a temporary buffer before sending it to the client.
- PHP: a programming language that runs on web servers and produces web pages.
- php.ini: the configuration file that controls PHP settings, including the output buffer size.
- Reflected: when a server takes user input and puts it back into the page it sends.
- Source (CSP): where a resource may be loaded from, such as
'self'or a domain name. - trigger_error: a PHP function that produces an error or warning message.
- Unfiltered user input: text from a visitor that the application uses without checking it.