Something went wrong. Try again.
The WebSocket Protocol (RFC 6455) for Zig: framing, a client, and a server handshake on zig-http
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What this library must do with input nobody wrote.//!//! Every target is a property rather than an example — `tests/e2e.zig` has//! the examples, and pins them octet for octet. The properties here are the//! ones that would be a vulnerability if they were false://!//! * `conversations` runs whole WebSocket conversations through the server//! and then *parses what came back*, insisting that it is a whole number of//! well-formed frames, none of them masked, with nothing left over. A//! server that can be made to emit a frame whose declared length does not//! match the octets after it has desynchronised the stream, and everything//! the peer reads afterwards is something the server never sent.//! * `frames` insists that a header the parser accepted is one it would write//! out the same way, which is the canonical-form property: two encodings of//! one frame is how two conformant implementations come to disagree about//! where a frame ends.//! * `handshakes` insists that `101` is only ever answered to a request that//! really carried a well-formed key, and that the accept token is the one//! the key determines.//!//! Each is an ordinary test as well, so `zig build test` runs the seeds//! beside it.
const builtin = @import("builtin");const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;const testing = std.testing;const Smith = std.testing.Smith;
const http = @import("http");const ws = @import("websocket");const wss = @import("websocket_server");
/// The allocator the targets run against.////// Under `zig build test` that is the testing allocator, which reports a leak/// as a failure. `tools/fuzz.zig` cannot name it — it is not a test build —/// so it sets this to a checked allocator of its own instead.pub var backing: Allocator = if (builtin.is_test) testing.allocator else undefined;
/// The `Io` for targets that need one. None here does: a WebSocket/// conversation over the HTTP/1.x driver needs no concurrency, and running it/// on `Io.failing` is the stronger test — a library that reached for I/O it/// had not been given would fail loudly. Declared because `tools/fuzz.zig` is/// the same file in every one of these projects and sets it unconditionally.pub var io: Io = if (builtin.is_test) testing.io else undefined;
// -- frame headers ----------------------------------------------------------
const frame_seeds = [_][]const u8{ // RFC 6455 §5.7, every example it prints. &.{ 0x81, 0x05, 'H', 'e', 'l', 'l', 'o' }, &.{ 0x81, 0x85, 0x37, 0xfa, 0x21, 0x3d, 0x7f, 0x9f, 0x4d, 0x51, 0x58 }, &.{ 0x01, 0x03, 'H', 'e', 'l' }, &.{ 0x80, 0x02, 'l', 'o' }, &.{ 0x89, 0x05, 'H', 'e', 'l', 'l', 'o' }, &.{ 0x82, 0x7e, 0x01, 0x00 }, &.{ 0x82, 0x7f, 0, 0, 0, 0, 0, 1, 0, 0 }, // Shapes that must be refused. &.{ 0x81, 0x7e, 0x00, 0x7c }, &.{ 0x81, 0x7f, 0x80, 0, 0, 0, 0, 0, 0, 0 }, // And ones that have not all arrived. &.{0x81}, &.{},};
/// A header the parser accepted is one it would write out the same way.////// Which is worth more than it sounds. The length has three encodings and/// only one of them is legal for any given length, so "parse then write gives/// back what came in" is exactly the statement that the parser refused the/// other two — and that is the whole of the non-minimal-length rule, checked/// against every input rather than against the four examples in `frame.zig`.fn frameProperty(input: []const u8) !void { const parsed = ws.frame.parse(input) catch return orelse return;
if (parsed.len > input.len) return error.ParserReadPastTheEnd; if (parsed.len < 2 or parsed.len > ws.frame.max_header_len) return error.ImpossibleHeaderLength; if (parsed.len != parsed.header.len()) return error.LengthDisagreesWithHeader;
var out: [ws.frame.max_header_len]u8 = undefined; const written = parsed.header.write(&out); if (!std.mem.eql(u8, input[0..parsed.len], written)) return error.NotCanonical;
// And reading it back gives the same header, which is the other half of // the round trip. const again = (ws.frame.parse(written) catch return error.RefusedItsOwnOutput) orelse return error.TruncatedItsOwnOutput; if (!std.meta.eql(parsed.header, again.header)) return error.WriteThenParseChangedIt;
// A masking key is present exactly when the frame said it would be. const says_masked = input[1] & 0x80 != 0; if (says_masked != (parsed.header.mask != null)) return error.MaskDisagreesWithFlag;}
test "fuzz frames" { for (frame_seeds) |seed| try frameProperty(seed); try testing.fuzz({}, fuzzFrame, .{});}
fn fuzzFrame(_: void, smith: *Smith) !void { var buffer: [64]u8 = undefined; const len = smith.slice(&buffer); try frameProperty(buffer[0..len]);}
// -- masking ----------------------------------------------------------------
/// §5.3's transformation is its own inverse, whatever the key, the offset or/// the size of the pieces it is applied in.////// The offset is the part that can be wrong: a payload arriving in two reads/// is unmasked in two calls, and a second call that started the key again/// from zero would corrupt everything after the first chunk — while still/// round-tripping perfectly if the test happened to use one chunk.fn maskProperty(key: [4]u8, data: []u8, chunk: usize) !void { const original = try backing.dupe(u8, data); defer backing.free(original);
ws.frame.applyMask(key, 0, data); ws.frame.applyMask(key, 0, data); if (!std.mem.eql(u8, original, data)) return error.MaskIsNotAnInvolution;
// Masked whole, unmasked in pieces. ws.frame.applyMask(key, 0, data); const take = @max(1, chunk); var at: usize = 0; while (at < data.len) { const n = @min(take, data.len - at); ws.frame.applyMask(key, at, data[at..][0..n]); at += n; } if (!std.mem.eql(u8, original, data)) return error.PiecewiseMaskDisagrees;}
test "fuzz masking" { var data = [_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; try maskProperty(.{ 0xde, 0xad, 0xbe, 0xef }, &data, 1); try maskProperty(.{ 0, 0, 0, 0 }, &data, 3); try maskProperty(.{ 0xff, 0xff, 0xff, 0xff }, &data, 7); try maskProperty(.{ 1, 2, 3, 4 }, data[0..0], 1); try testing.fuzz({}, fuzzMask, .{});}
fn fuzzMask(_: void, smith: *Smith) !void { var buffer: [512]u8 = undefined; const len = smith.slice(&buffer); const key: [4]u8 = .{ smith.value(u8), smith.value(u8), smith.value(u8), smith.value(u8) }; const chunk: usize = smith.value(u4); try maskProperty(key, buffer[0..len], chunk);}
// -- close codes ------------------------------------------------------------
/// The three codes an application may be told and a peer may not send are/// never sendable, and the ranges of §7.4.2 are what they say they are.fn closeCodeProperty(value: u16) !void { const code: ws.Code = @enumFromInt(value); const sendable = code.isSendable();
if (value < 1000 and sendable) return error.BelowTheRangeIsSendable; if (value > 4999 and sendable) return error.AboveTheRangeIsSendable; if (value >= 3000 and value <= 4999 and !sendable) return error.PrivateRangeRefused; switch (value) { 1004, 1005, 1006, 1015 => if (sendable) return error.ReservedCodeIsSendable, else => {}, }}
test "fuzz close codes" { // Exhaustive, because there are only 65536 of them and a property checked // on every value of its domain is not a property, it is a proof. var value: u32 = 0; while (value <= std.math.maxInt(u16)) : (value += 1) { try closeCodeProperty(@intCast(value)); }}
// -- whole conversations ----------------------------------------------------
const handshake_request = "GET /echo HTTP/1.1\r\n" ++ "Host: a.example\r\n" ++ "Upgrade: websocket\r\n" ++ "Connection: Upgrade\r\n" ++ "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n" ++ "Sec-WebSocket-Version: 13\r\n" ++ "\r\n";
const conversation_seeds = [_][]const u8{ // A masked "Hello", then a close. "\x81\x85\x37\xfa\x21\x3d\x7f\x9f\x4d\x51\x58" ++ "\x88\x80\x00\x00\x00\x00", // A fragmented message. "\x01\x83\x00\x00\x00\x00Hel" ++ "\x80\x82\x00\x00\x00\x00lo", // A ping. "\x89\x85\x00\x00\x00\x00Hello", // Unmasked, which a server must refuse. "\x81\x05Hello", // A reserved bit and a reserved opcode. "\xc1\x80\x00\x00\x00\x00", "\x83\x80\x00\x00\x00\x00", // A close with a code that may not be sent. "\x88\x82\x00\x00\x00\x00\x03\xed", "",};
/// A whole conversation, and then the thing the octets must be.fn conversationProperty(input: []const u8) !void { const client = try std.mem.concat(backing, u8, &.{ handshake_request, input }); defer backing.free(client);
var c: http.transport.memory.Connection = try .init(backing, client, .{}); defer c.deinit();
var conn = c.connection(); try http.http1.serve(Io.failing, backing, &conn, .initStateless(echo), .{ .send_date = false, .server_name = null, });
const written = c.written(); // The handshake is pinned octet for octet in `tests/e2e.zig`; here it is // only the thing the frames come after. const head_end = std.mem.indexOf(u8, written, "\r\n\r\n") orelse return; if (!std.mem.startsWith(u8, written, "HTTP/1.1 101 ")) return; try checkServerFrames(written[head_end + 4 ..]);}
fn echo(req: *http.server.Request, res: *http.server.Response) anyerror!void { var buffer: [1024]u8 = undefined; var conn = wss.accept(req, res, .{ .buffer = &buffer }) catch |err| { return wss.refuse(res, err); }; while (try conn.receive()) |message| { try conn.send(message.kind, message.data); }}
/// Everything a server may write, and nothing else.fn checkServerFrames(bytes: []const u8) !void { var at: usize = 0; var closed = false; var fragmenting = false;
while (at < bytes.len) { // A frame that runs off the end is the failure this whole target // exists to find: a peer reading it would take the next frame's // header for payload and never resynchronise. const parsed = (ws.frame.parse(bytes[at..]) catch return error.ServerWroteAnUnparseableFrame) orelse return error.ServerWroteATruncatedHeader; const header = parsed.header;
// §5.1: "A server MUST NOT mask any frames that it sends to the // client." if (header.mask != null) return error.ServerMaskedAFrame; // No extension was negotiated, so the server may not set one either. if (header.rsv1 or header.rsv2 or header.rsv3) return error.ServerSetAReservedBit; if (!header.opcode.isDefined()) return error.ServerSentAReservedOpcode;
if (header.opcode.isControl()) { if (!header.fin) return error.ServerFragmentedAControlFrame; if (header.payload_len > ws.frame.max_control_payload_len) { return error.ServerSentAnOversizedControlFrame; } }
// §5.5.1: "The application MUST NOT send any more data frames after // sending a Close frame." if (closed) return error.ServerWroteAfterClosing; if (header.opcode == .close) { closed = true; // A Close body is either empty or a code and a reason, never one // stray octet -- and the code has to be one this endpoint is // allowed to send. const payload = bytes[at + parsed.len ..]; if (header.payload_len == 1) return error.ServerSentAOneOctetClose; if (header.payload_len >= 2) { if (payload.len < 2) return error.ServerWroteATruncatedFrame; const code: ws.Code = @enumFromInt(std.mem.readInt(u16, payload[0..2], .big)); if (!code.isSendable()) return error.ServerSentAReservedCloseCode; } }
// Fragmentation, from the other side: the server must not start a // message while one of its own is in progress, or continue one that // is not. switch (header.opcode) { .text, .binary => { if (fragmenting) return error.ServerInterleavedMessages; fragmenting = !header.fin; }, .continuation => { if (!fragmenting) return error.ServerContinuedNothing; fragmenting = !header.fin; }, else => {}, }
const total = parsed.len +| @as(usize, @intCast(header.payload_len)); if (total > bytes.len - at) return error.ServerWroteATruncatedFrame; at += total; }
if (fragmenting) return error.ServerLeftAMessageUnfinished;}
test "fuzz conversations" { for (conversation_seeds) |seed| try conversationProperty(seed); try testing.fuzz({}, fuzzConversation, .{});}
fn fuzzConversation(_: void, smith: *Smith) !void { var buffer: [4096]u8 = undefined; const len = smith.slice(&buffer); try conversationProperty(buffer[0..len]);}
// -- the opening handshake --------------------------------------------------
const handshake_seeds = [_][]const u8{ handshake_request, "GET / HTTP/1.1\r\nHost: a\r\n\r\n", "GET / HTTP/1.1\r\nHost: a\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n", "GET / HTTP/1.1\r\nHost: a\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" ++ "Sec-WebSocket-Version: 13\r\nSec-WebSocket-Key: short\r\n\r\n", "POST / HTTP/1.1\r\nHost: a\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" ++ "Sec-WebSocket-Version: 13\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n", "",};
/// A `101` is only ever the answer to a handshake that really had a key, and/// the token that goes with it is the one that key determines.////// The second half is the interesting one. `Sec-WebSocket-Accept` is the only/// thing a client checks before it starts speaking a different protocol on/// the same socket, so a server that could be made to produce one for a key/// it was not given is a server that can be made to open a WebSocket to/// something that was not asking for one.fn handshakeProperty(input: []const u8) !void { var c: http.transport.memory.Connection = try .init(backing, input, .{}); defer c.deinit();
var conn = c.connection(); try http.http1.serve(Io.failing, backing, &conn, .initStateless(echo), .{ .send_date = false, .server_name = null, });
const written = c.written(); if (!std.mem.startsWith(u8, written, "HTTP/1.1 101 ")) return;
// It switched. So the request must have carried a well-formed key, and // the response must carry exactly its token. const key = fieldOf(input, "sec-websocket-key:") orelse return error.SwitchedWithoutAKey; const decoder = std.base64.standard.Decoder; const decoded_len = decoder.calcSizeForSlice(key) catch return error.SwitchedOnAKeyThatIsNotBase64; if (decoded_len != 16) return error.SwitchedOnAKeyOfTheWrongLength;
const version = fieldOf(input, "sec-websocket-version:") orelse return error.SwitchedWithoutAVersion; if (!std.mem.eql(u8, version, "13")) return error.SwitchedOnTheWrongVersion;
var expected: [ws.handshake.accept_token_len]u8 = undefined; const token = ws.handshake.acceptToken(key, &expected); const sent = fieldOf(written, "sec-websocket-accept:") orelse return error.SwitchedWithoutAToken; if (!std.mem.eql(u8, token, sent)) return error.TokenIsNotTheKeysToken;
// §9.1: an extension is never answered, because none is implemented. if (fieldOf(written, "sec-websocket-extensions:") != null) { return error.AnsweredWithAnExtension; } // §4.2.2: a subprotocol may only be one the client offered. This handler // offers none at all, so it may never appear. if (fieldOf(written, "sec-websocket-protocol:") != null) { return error.AnsweredWithASubprotocol; }}
/// The value of a field in a head, found without a parser, so that a bug in/// the one under test cannot hide one here.fn fieldOf(head: []const u8, name_colon: []const u8) ?[]const u8 { var at: usize = 0; while (at < head.len) { const line_end = std.mem.indexOfPos(u8, head, at, "\r\n") orelse return null; const line = head[at..line_end]; if (line.len == 0) return null; // the end of the head if (line.len > name_colon.len and std.ascii.eqlIgnoreCase(line[0..name_colon.len], name_colon)) { return std.mem.trim(u8, line[name_colon.len..], " \t"); } at = line_end + 2; } return null;}
test "fuzz handshakes" { for (handshake_seeds) |seed| try handshakeProperty(seed); try testing.fuzz({}, fuzzHandshake, .{});}
fn fuzzHandshake(_: void, smith: *Smith) !void { var buffer: [2048]u8 = undefined; const len = smith.slice(&buffer); try handshakeProperty(buffer[0..len]);}
// -- the table the standalone driver reads ----------------------------------
pub const Target = struct { name: []const u8, run: *const fn (input: []const u8) anyerror!void, corpus: []const []const u8, /// The buffer this target reads its input into. /// /// `Smith.slice` yields an *empty* slice for a length larger than the /// buffer rather than a truncated one, so a generator that does not know /// this number hands the target nothing at all most of the time. content_max: usize, /// How many `Smith.slice` calls this target makes before it starts asking /// for values. The generator writes exactly this many length-prefixed /// chunks and then the numbers, so that a `Smith.value` lands on a number /// rather than on the next chunk's length header. slices: usize = 1,};
/// Wraps a `testing.fuzz` entry point so the standalone driver can call it/// with a plain slice.fn Driven(comptime one: fn (void, *Smith) anyerror!void) type { return struct { fn run(input: []const u8) anyerror!void { var smith: Smith = .{ .in = input }; return one({}, &smith); } };}
pub const all = [_]Target{ .{ .name = "frames", .run = Driven(fuzzFrame).run, .corpus = &frame_seeds, .content_max = 64 }, .{ .name = "masking", .run = Driven(fuzzMask).run, .corpus = &.{}, .content_max = 512 }, .{ .name = "conversations", .run = Driven(fuzzConversation).run, .corpus = &conversation_seeds, .content_max = 4096 }, .{ .name = "handshakes", .run = Driven(fuzzHandshake).run, .corpus = &handshake_seeds, .content_max = 2048 },};
const oracle_testing = std.testing;
test "the server-frame oracle finds what it is for" { // An oracle that never fails is a test that never ran, and this one is // reached only through a fuzzer — so it is checked here against the // things it exists to catch.
// A frame whose declared length runs off the end. This is the one that // matters: a peer would read the next frame's header as payload and // never resynchronise. try oracle_testing.expectError( error.ServerWroteATruncatedFrame, checkServerFrames("\x81\x05Hel"), ); // A header that is not all there. try oracle_testing.expectError( error.ServerWroteATruncatedHeader, checkServerFrames("\x81"), ); // §5.1: a server never masks. try oracle_testing.expectError( error.ServerMaskedAFrame, checkServerFrames("\x81\x85\x00\x00\x00\x00Hello"), ); try oracle_testing.expectError( error.ServerSetAReservedBit, checkServerFrames("\xc1\x00"), ); try oracle_testing.expectError( error.ServerSentAReservedOpcode, checkServerFrames("\x83\x00"), ); try oracle_testing.expectError( error.ServerFragmentedAControlFrame, checkServerFrames("\x09\x00"), ); // §5.5.1: nothing after a Close. try oracle_testing.expectError( error.ServerWroteAfterClosing, checkServerFrames("\x88\x02\x03\xe8" ++ "\x81\x02hi"), ); try oracle_testing.expectError( error.ServerSentAReservedCloseCode, checkServerFrames("\x88\x02\x03\xed"), ); try oracle_testing.expectError( error.ServerSentAOneOctetClose, checkServerFrames("\x88\x01\x03"), ); try oracle_testing.expectError( error.ServerInterleavedMessages, checkServerFrames("\x01\x01a" ++ "\x81\x01b"), ); try oracle_testing.expectError( error.ServerContinuedNothing, checkServerFrames("\x80\x01a"), ); try oracle_testing.expectError( error.ServerLeftAMessageUnfinished, checkServerFrames("\x01\x01a"), );
// And what a conformant server actually writes passes. try checkServerFrames(""); try checkServerFrames("\x81\x05Hello"); try checkServerFrames("\x01\x03Hel" ++ "\x89\x00" ++ "\x80\x02lo"); try checkServerFrames("\x8a\x05Hello" ++ "\x88\x02\x03\xe8"); try checkServerFrames("\x88\x00");}