Skip to content

TopicPartition.metadata over-reads the heap (and can SIGSEGV) when committed metadata isn't NUL-terminated #2430

Open

Description

Description

TopicPartition_setup() copies partition metadata with strdup(), but librdkafka hands metadata over as a sized buffer (rd_kafka_topic_partition_t.metadata + metadata_size) and does not promise a trailing NUL. When a consumer group's offsets were committed by a client that sends the metadata's exact length without a terminator (kafka-python, the Java client, and others: the Kafka protocol's metadata field is a length-prefixed string), the buffer librdkafka returns has no NUL, and strdup() reads past its end.

Effects, depending on what follows the buffer in the heap:

  • .metadata comes back longer than what was committed, with trailing garbage from neighbouring heap memory,
  • reading .metadata raises UnicodeDecodeError when that garbage isn't valid UTF-8, or
  • the process crashes with SIGSEGV when strlen() runs into a page it can't read.

confluent-kafka's own commits don't hit this, because the commit path stores the terminator (rktpar->metadata_size = strlen(tp->metadata) + 1, confluent_kafka.c:1978 on master). The bug shows only when the group was committed by another client, so an application that only reads offsets (a monitoring tool, a lag exporter) is exposed to whatever every other client in the cluster wrote.

We hit this in production: a service reading consumer group offsets with AdminClient.list_consumer_group_offsets() segfaulted within minutes on a group with ~2,000 partitions, each carrying 256–317 bytes of metadata written by a client that doesn't store a NUL. The process preloads jemalloc, whose exact size classes pack the 256-byte buffers back to back in one slab, so strlen() walked across 16 neighbouring buffers into an inaccessible guard page (SEGV_ACCERR). With glibc malloc, a 256-byte buffer is usually followed by a zero byte, so the same data often reads back correctly and the bug goes unnoticed; other sizes, such as 248 bytes, over-read on every run (see below).

Backtrace from the core (confluent-kafka 2.13.2, librdkafka 2.13.2 with two unrelated downstream patches, CPython 3.13, linux x86_64):

Program terminated with signal SIGSEGV (si_code 2 = SEGV_ACCERR), fault address 0x7fad72bff000
#0  __strlen_avx2
#1  __GI___strdup (s=0x7fad72bfe000 "...")
#2  c_part_to_py            confluent_kafka/cimpl.cpython-313-x86_64-linux-gnu.so
#3  c_parts_to_py           confluent_kafka/cimpl.cpython-313-x86_64-linux-gnu.so
#4..#10 librdkafka          (OffsetFetch result delivery)
#11 start_thread            librdkafka background thread (rdk:bg)

The partition being converted had metadata_size = 256 and a metadata buffer at 0x7fad72bfe000 with no NUL byte anywhere in its 4 KiB page.

Where it is in the code (master, src/confluent_kafka/src/confluent_kafka.c):

  • c_part_to_py() (:1748) passes rktpar->metadata to TopicPartition_new0() but drops rktpar->metadata_size.
  • TopicPartition_setup() (:1486) then does self->metadata = strdup(metadata).

c_part_to_py() is the only C-side reader of partition metadata, so every API that returns TopicPartitions with metadata goes through it. We reproduced it through both AdminClient.list_consumer_group_offsets() and Consumer.committed().

Suggested fix: pass metadata_size through TopicPartition_new0() into TopicPartition_setup() and copy exactly metadata_size bytes plus a NUL. That is correct both for unterminated buffers and for confluent-committed ones (whose metadata_size already counts the NUL, so the copy just ends with two). I'm happy to open a PR; we carry this change as a downstream patch on 2.13.2 (DataDog/integrations-core#25483), and it stopped the crash in production.

How to reproduce

The over-read doesn't need a crash to show: commit metadata of known length with a client that doesn't store a NUL, read it back through confluent-kafka, and compare. With glibc malloc on 64-bit Linux, a length of 248 bytes shows it on every run: the allocation's usable size then ends exactly at the next chunk's header, so strlen() finds non-zero bytes past (nearly) every buffer. (Lengths like 256 leave slack after the buffer that is often zero, so under glibc they show it only sometimes; under jemalloc they show it almost every time.)

  1. Start a single-node broker:

    docker run -d --name kafka -p 9092:9092 apache/kafka:4.2.0
  2. In a Linux environment (or container) with the broker reachable, install the clients:

    pip install confluent-kafka==2.16.1 kafka-python==2.2.3
  3. Commit 248 bytes of metadata, without a terminator, on 16 partitions using kafka-python:

    # commit_unterminated.py
    from kafka import KafkaAdminClient, KafkaConsumer
    from kafka.admin import NewTopic
    from kafka.structs import OffsetAndMetadata, TopicPartition
    
    BOOTSTRAP, TOPIC, GROUP, PARTITIONS = "localhost:9092", "overread-repro", "overread-repro-group", 16
    METADATA = "m" * 248
    
    KafkaAdminClient(bootstrap_servers=BOOTSTRAP).create_topics([NewTopic(TOPIC, PARTITIONS, 1)])
    consumer = KafkaConsumer(bootstrap_servers=BOOTSTRAP, group_id=GROUP, enable_auto_commit=False)
    # kafka-python 2.2.x: OffsetAndMetadata(offset, metadata, leader_epoch)
    consumer.commit({TopicPartition(TOPIC, p): OffsetAndMetadata(0, METADATA, -1) for p in range(PARTITIONS)})
    consumer.close()
  4. Read it back with confluent-kafka and compare lengths:

    # read_back.py
    from confluent_kafka import ConsumerGroupTopicPartitions
    from confluent_kafka.admin import AdminClient
    
    GROUP = "overread-repro-group"
    admin = AdminClient({"bootstrap.servers": "localhost:9092"})
    result = admin.list_consumer_group_offsets([ConsumerGroupTopicPartitions(GROUP)])[GROUP].result(timeout=30)
    lengths = sorted({len(tp.metadata) for tp in result.topic_partitions if tp.metadata is not None})
    print("committed 248 bytes; returned lengths:", lengths)
    python commit_unterminated.py
    python read_back.py

Expected: returned lengths: [248].

Actual (PyPI wheel 2.16.1, aarch64, glibc; 5 of 5 runs): committed 248 bytes; returned lengths: [249, 250]. Consumer.committed() on the same group returns 15 of 16 partitions wrong. When the extra bytes aren't valid UTF-8, reading .metadata raises UnicodeDecodeError instead.

Closer to our production case: 256-byte metadata on 2,048 partitions, read with list_consumer_group_offsets() and LD_PRELOAD=libjemalloc.so.2. With the same PyPI wheel, 6 of 6 runs fail with UnicodeDecodeError: 'utf-8' codec can't decode byte ... in position 65283 (positions 65,282–65,285): strlen() ran about 64 KiB past a 256-byte buffer. With glibc, all 3 runs of that shape read back correctly. None of our local runs segfaulted; the crash needs the run of non-zero bytes to reach an unreadable page, as it did in production.

AddressSanitizer (master built with -fsanitize=address, same 256 × 2,048 read) reports it on the first read, independent of the allocator:

ERROR: AddressSanitizer: heap-buffer-overflow
READ of size 268 at 0x51100001a540 thread T-1
0x51100001a540 is located 0 bytes after 256-byte region [0x51100001a440,0x51100001a540)
    #0 strdup
    #1 TopicPartition_setup   src/confluent_kafka/src/confluent_kafka.c:1486
    #2 TopicPartition_new0    src/confluent_kafka/src/confluent_kafka.c:1740
    #3 c_part_to_py           src/confluent_kafka/src/confluent_kafka.c:1749
    #4 c_parts_to_py          src/confluent_kafka/src/confluent_kafka.c:1769
    #5 Admin_c_SingleGroupResult_to_py  src/confluent_kafka/src/Admin.c:5290
    #6 Admin_c_GroupResults_to_py       src/confluent_kafka/src/Admin.c:5333
    #7 Admin_background_event_cb        src/confluent_kafka/src/Admin.c:5776
    #8 rd_kafka_call_background_event_cb  librdkafka src/rdkafka_background.c:51

Checklist

  • confluent-kafka-python and librdkafka version: found on 2.13.2 / 2.13.2; reproduced on the 2.16.1 PyPI wheel (bundled librdkafka 2.16.0) and on master
  • Apache Kafka broker version: reproduced on 3.9.1 and 4.2.0
  • Client configuration: {'bootstrap.servers': ...} (defaults otherwise)
  • Operating system: Linux x86_64 and aarch64 (glibc), CPython 3.13; jemalloc preloaded in production
  • Provide client logs: not useful here; the failure is a memory read in the C extension, with no client error
  • Provide broker log excerpts: not relevant (the broker returns the metadata exactly as committed)
  • Critical issue: process crash (SIGSEGV) on reading offsets

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions