Skip to main content
Be Bitwise

Memory Safety in Web Servers

Web Application Exploitation (Low-Level Perspective) · Advanced Exploitation track

7 min read

In this module

Web Servers as Attack Targets

When most people think about web security, they think about SQL injection, cross-site scripting, authentication bypass. Those are application-layer bugs — code running on top of the web server. But the web server itself — the software that listens on port 80 or 443, parses HTTP requests, and dispatches them to application code — is also a target. And because the most widely deployed web servers are written in C, they carry the same memory corruption risks you've already studied.

nginx, Apache httpd, and lighttpd collectively serve the majority of the world's web traffic. Each is written in C and handles complex, attacker-controlled input on every request. Every HTTP header, every URL, every request body is data that an attacker fully controls. If the server's parsing code contains a buffer overflow, an integer overflow, or a use-after-free, the attacker can potentially gain remote code execution on the server - without ever needing valid credentials.

The HTTP Parsing Attack Surface

An HTTP request is a structured text format with significant complexity:

text
POST /api/upload?filename=report.pdf HTTP/1.1
Host: example.com
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary
Content-Length: 48291
Transfer-Encoding: chunked
X-Custom-Header: ...potentially very long value...
[body data]

The web server must parse the method, URL, query parameters, HTTP version, and an arbitrary number of headers - each with a name and value that can be nearly any length. It must handle chunked transfer encoding, multipart bodies, and various content encodings. Every one of these parsing steps is an opportunity for a memory safety bug.

Consider what happens when a header value is longer than the buffer allocated for it. A well-written server will reject the request or dynamically resize its buffer. A server with a bug might write past the end of a fixed-size buffer, corrupting adjacent memory on the heap or stack.

Attack Surface

The attack surface of a program is the set of all inputs and interfaces through which an attacker can provide data. For a web server, this includes HTTP headers, URLs, query strings, request bodies, TLS handshake parameters, and any protocol it speaks. Larger attack surfaces mean more opportunities for bugs.

Real Vulnerabilities in nginx

nginx is known for clean, well-audited code, yet it has still had memory safety vulnerabilities. Understanding these demonstrates that even carefully written C code can contain exploitable bugs.

CVE-2013-2028 is the textbook case. nginx 1.3.9 added support for chunked request bodies, where each chunk starts with its length in hex. The parser accumulated that length into a signed 64-bit off_t without checking for overflow, so a chunk size like FFFFFFFFFFFFFFF0 came out negative. When nginx later discarded the request body, it picked the smaller of that size and its 4 KB stack buffer, and the negative number won. Passed to recv() as a size_t, it turned into an enormous length, and the attacker's bytes ran straight off the end of the stack buffer.

Turning that into code execution still meant beating ASLR and the stack canary, and public exploits did so by brute-forcing against nginx's worker processes, which restart with the same layout after a crash.

The pattern is common: a mismatch between how much memory is allocated and how much data is written. In C, nothing prevents this mismatch at compile time. The language trusts the programmer to get it right.

Real Vulnerabilities in Apache httpd

Apache httpd has had numerous memory safety issues over its long history. One significant example is the Optionsbleed vulnerability (CVE-2017-9798), which was conceptually similar to Heartbleed but in a different context. A use-after-free bug in the handling of the HTTP OPTIONS method caused Apache to leak fragments of server memory in the Allow header of responses. An attacker could send repeated OPTIONS requests and collect leaked memory contents, potentially including fragments of other users' requests, authentication tokens, or configuration data.

Another category involves Apache's module architecture. Apache loads dynamic modules (mod_ssl, mod_cgi, mod_rewrite, etc.) that process requests in various ways. Each module adds to the attack surface. A vulnerability in any module runs with the same privileges as the main server process.

Buffer Overflows in URL Parsing

URL parsing is deceptively complex. A URL can contain percent-encoded characters (%20 for space), Unicode sequences, path traversal components (../), and extremely long path segments. The server must decode, normalise, and validate URLs before using them.

Percent-decoding on its own only shrinks data: three input bytes (%41) become one output byte. The overflow comes from sizing the destination by something other than the input. A fixed-size buffer filled from a URL whose length was never checked is the classic case. Expansion is real in the next step, though, when servers convert between character encodings: each ISO-8859-1 byte above 0x7F becomes two UTF-8 bytes, and a single 2-byte UTF-16 unit can become three. A buffer sized for the input length is then too small. Path normalisation is the other common culprit, when it fails to account for an edge case and writes beyond the allocated buffer.

c
/* Simplified vulnerable pattern */
char decoded_url[MAX_URL_LEN];
size_t encoded_len = strlen(encoded_url);
/* Bug: encoded_len is never checked against MAX_URL_LEN. */
/* Decoding shrinks %XX triplets, but a long plain path */
/* still runs straight past the end of decoded_url */
url_decode(decoded_url, encoded_url, encoded_len);

The fix for such bugs is straightforward: always calculate the maximum possible decoded length, allocate sufficient space, and check bounds during decoding. But in a large codebase with many code paths, every path must be correct. A single oversight is sufficient for an exploit.

Integer Overflows in Content-Length

The Content-Length header tells the server how many bytes to expect in the request body. It is a number provided by the client - the attacker. Integer overflow bugs arise when the server performs arithmetic on this value without checking for overflow.

For example, if a server allocates content_length + 1 bytes (to add a null terminator), and content_length is set to the maximum value of a 32-bit or 64-bit integer, the addition wraps around to a very small number. The server allocates a tiny buffer, then reads the full content length into it - a massive heap overflow.

c
/* If content_length is SIZE_MAX, this overflows to 0 */
char *body = malloc(content_length + 1);
/* Reads SIZE_MAX bytes into a 0-byte (or very small) buffer */
read_body(connection, body, content_length);

Modern web servers use safe integer arithmetic functions that check for overflow before performing the operation, but legacy code and third-party modules may not.

Why Memory-Safe Languages Matter

The fundamental problem is that C does not prevent any of these bugs. The language provides no bounds checking, no integer overflow detection, and no use-after-free prevention. Every safety property must be manually maintained by the programmer.

That's the push behind rewriting critical infrastructure in memory-safe languages. Cloudflare's Pingora — a Rust-based proxy that replaced their nginx deployment — demonstrates that memory-safe alternatives can match C's performance while eliminating whole categories of vulnerabilities.

Realistically though, the vast majority of deployed web server infrastructure is still C code. nginx and Apache aren't going anywhere soon. Understanding their memory safety risks remains essential for anyone doing security work, whether you're auditing code, hardening servers, or building mitigations.

Defensive Measures

Web servers deploy several defences against memory corruption:

  • ASLR and PIE: Web server binaries are compiled as position-independent executables with full ASLR, randomizing code and data addresses.
  • Stack canaries: Detect stack buffer overflows before the function returns.
  • Sandboxing: Some servers drop privileges after binding to port 80/443, running request handlers as an unprivileged user.
  • Worker process isolation: nginx uses a multi-process model where a master process manages worker processes. A crash in one worker does not take down the entire server.
  • Strict input validation: Modern servers impose limits on header sizes, URL lengths, and request body sizes, rejecting requests that exceed them.

These mitigations raise the bar; they don't move the goalposts. As long as the parsing code is written in C, memory corruption remains a possibility.