Something went wrong. Try again.
QUIC for Zig 0.17: RFC 9000-9002 with TLS 1.3, as a sans-I/O core plus a socket layer, with datagrams, multipath and raw public keys.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What this must do with input nobody wrote.//!//! There is one target so far, because there is one thing here that reads//! attacker-controlled input: header protection removal. The key schedule is//! driven by secrets rather than by the wire, and the AEAD is the standard//! library's.
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 quic = @import("quic");
pub var backing: Allocator = if (builtin.is_test) testing.allocator else undefined;pub var io: Io = if (builtin.is_test) testing.io else undefined;
// -- header protection ------------------------------------------------------
const header_seeds = [_][]const u8{ &quic.rfc9001.client_protected_packet, &quic.rfc9001.server_protected_packet, "", "\x00",};
/// Removing header protection and applying it again is the identity, whatever/// the octets are.////// Which is the property with teeth here. A receiver removes protection/// *before* it can authenticate anything — the packet number it needs for the/// AEAD nonce is itself protected — so this code runs on unauthenticated/// input from anyone who can reach the port. It must not read outside the/// packet and must not disagree with itself about how long the packet number/// is.fn headerProperty(input: []const u8) !void { if (input.len < 1) return;
var packet: [2048]u8 = undefined; const len = @min(input.len, packet.len); @memcpy(packet[0..len], input[0..len]);
const keys: quic.protection.Keys = .initialKeys(&quic.rfc9001.destination_connection_id, .server);
// A number offset anywhere in the packet, including places a real header // would never put one. for (0..@min(len, 40)) |number_offset| { var work: [2048]u8 = undefined; @memcpy(work[0..len], packet[0..len]);
const sample = quic.protection.sampleOf(work[0..len], number_offset) orelse continue; var number: [4]u8 = work[number_offset..][0..4].*; const before_first = work[0]; const before_number = number;
const pn_len = quic.protection.removeHeader(&keys, sample, &work[0], &number); if (pn_len < 1 or pn_len > 4) return error.ImpossiblePacketNumberLength; // The length must agree with the two bits the unmasking just revealed. if (pn_len != (work[0] & 0x03) + 1) return error.LengthDisagreesWithFirstByte;
// Only the bits §5.4.1 permits may have moved. const permitted: u8 = if (before_first & 0x80 != 0) 0x0f else 0x1f; if ((before_first & ~permitted) != (work[0] & ~permitted)) { return error.UnmaskedAProtectedBit; }
// And putting it back gives exactly what arrived. The sample is taken // from the ciphertext, which header protection never touches, so it // is the same both ways. quic.protection.protectHeader(&keys, sample, &work[0], number[0..pn_len]); if (work[0] != before_first) return error.FirstByteDidNotRoundTrip; if (!std.mem.eql(u8, before_number[0..pn_len], number[0..pn_len])) { return error.PacketNumberDidNotRoundTrip; } }}
test "fuzz header protection" { for (header_seeds) |seed| try headerProperty(seed); try testing.fuzz({}, fuzzHeader, .{});}
fn fuzzHeader(_: void, smith: *Smith) !void { var buffer: [512]u8 = undefined; const len = smith.slice(&buffer); try headerProperty(buffer[0..len]);}
// -- whole datagrams --------------------------------------------------------
const datagram_seeds = [_][]const u8{ &quic.rfc9001.client_protected_packet, &quic.rfc9001.server_protected_packet, // A long header with nothing after it. &.{ 0xc0, 0x00, 0x00, 0x00, 0x01 }, // A short header. &.{ 0x40, 1, 2, 3, 4, 5, 6, 7, 8, 0xaa }, // A Version Negotiation packet, whose first octet means nothing. &.{ 0x80, 0, 0, 0, 0, 0, 0 }, "",};
/// A datagram from anyone who can reach the port is read, and read wrongly,/// without reading outside it.////// This is the whole attack surface of a QUIC endpoint before authentication./// `open` parses a header, removes header protection with keys the sender/// very likely does not have, reconstructs a packet number out of the result/// and hands the rest to an AEAD — and every length involved comes from the/// datagram or from a mask computed over it. None of it may be trusted, and/// the property is simply that whatever arrives, the answer is an error or a/// packet, never a crash and never a read past the end.fn datagramProperty(input: []const u8, connection_id_len: u8) !void { var datagram: [2048]u8 = undefined; const len = @min(input.len, datagram.len); @memcpy(datagram[0..len], input[0..len]); const cid_len = @min(connection_id_len, quic.packet.max_connection_id_len);
// Parsing alone must be total in the sense that matters: an error or a // header whose offsets are all inside the datagram. if (quic.packet.parse(datagram[0..len], cid_len)) |h| { if (h.end > len) return error.HeaderEndsPastTheDatagram; if (h.kind.hasNumber() and h.number_offset > h.end) { return error.NumberBeginsAfterTheEnd; } for ([_][]const u8{ h.destination, h.source, h.token }) |field| { if (field.len == 0) continue; const start = @intFromPtr(field.ptr) - @intFromPtr(&datagram); if (start + field.len > len) return error.FieldRunsPastTheDatagram; } if (h.destination.len > quic.packet.max_connection_id_len) return error.ConnectionIdTooLong; } else |_| {}
// And then the whole receive path, with keys the sender does not have. const keys: quic.protection.Keys = .initialKeys(&quic.rfc9001.destination_connection_id, .server); var out: [2048]u8 = undefined; _ = quic.packet.open(&keys, 0, datagram[0..len], cid_len, &out) catch {};}
test "fuzz datagrams" { for (datagram_seeds) |seed| { for ([_]u8{ 0, 8, 20, 255 }) |cid_len| try datagramProperty(seed, cid_len); } try testing.fuzz({}, fuzzDatagram, .{});}
fn fuzzDatagram(_: void, smith: *Smith) !void { var buffer: [1500]u8 = undefined; const len = smith.slice(&buffer); const cid_len = smith.value(u8); try datagramProperty(buffer[0..len], cid_len);}
// -- variable-length integers -----------------------------------------------
const varint_seeds = [_][]const u8{ &.{ 0xc2, 0x19, 0x7c, 0x5e, 0xff, 0x14, 0xe8, 0x8c }, &.{ 0x9d, 0x7f, 0x3e, 0x7d }, &.{ 0x7b, 0xbd }, &.{0x25}, &.{ 0x40, 0x25 }, "",};
/// Every first octet names a length, the value never exceeds 2^62-1, and a/// value written out reads back as itself.////// The round trip is one-directional on purpose. §16 permits a non-minimal/// encoding, so parse-then-write is *not* the identity on octets — writing/// 37 gives one octet whether it arrived as one or as two — and a test that/// expected otherwise would be enforcing a rule QUIC does not have.fn varintProperty(input: []const u8) !void { const got = quic.varint.parse(input) catch return; if (got.len != quic.varint.lengthOf(input[0])) return error.LengthDisagreesWithFirstOctet; if (got.len > input.len) return error.ReadPastTheEnd; if (got.value > quic.varint.max) return error.ValueOutOfRange;
var buf: [8]u8 = undefined; const written = quic.varint.write(&buf, got.value); if (written.len > got.len) return error.ReEncodingGrew; const again = try quic.varint.parse(written); if (again.value != got.value) return error.RoundTripChangedTheValue;}
test "fuzz varints" { for (varint_seeds) |seed| try varintProperty(seed); try testing.fuzz({}, fuzzVarint, .{});}
fn fuzzVarint(_: void, smith: *Smith) !void { var buffer: [16]u8 = undefined; const len = smith.slice(&buffer); try varintProperty(buffer[0..len]);}
// -- frames -----------------------------------------------------------------
const frame_seeds = [_][]const u8{ &.{0x01}, // PING &.{ 0x06, 0x00, 0x02, 'h', 'i' }, // CRYPTO &.{ 0x02, 50, 0, 1, 10, 0, 4 }, // ACK with one extra range &.{ 0x03, 10, 0, 0, 0, 1, 2, 3 }, // ACK with ECN &.{ 0x08, 0x04, 'a', 'b' }, // STREAM, no length &.{ 0x0f, 0x04, 0x0a, 0x03, 'x', 'y', 'z' }, // STREAM, all bits &.{ 0x1c, 0x07, 0x06, 0x00 }, // CONNECTION_CLOSE // draft-ietf-quic-address-discovery-01's OBSERVED_ADDRESS, both families: // a four-octet type, a sequence number, the address and a port -- the // shape whose truncations are the interesting inputs. &.{ 0x80, 0x9f, 0x81, 0xa6, 0x03, 192, 0, 2, 1, 0x03, 0x55 }, &([_]u8{ 0x80, 0x9f, 0x81, 0xa7, 0x00 } ++ @as([15]u8, @splat(0)) ++ [_]u8{ 1, 0x1f, 0x90 }), // draft-ietf-quic-multipath-21's PATH_ACK with ECN and one extra range, // and a PATH_NEW_CONNECTION_ID: an ACK and a NEW_CONNECTION_ID each with // a path in front, which is where a parser that reused the bodies wrong // would come apart. &.{ 0x3f, 0x01, 50, 0, 1, 10, 0, 4, 1, 0, 2 }, &([_]u8{ 0x7e, 0x78, 0x02, 0x01, 0x00, 0x04, 1, 2, 3, 4 } ++ @as([16]u8, @splat(0x5a))), // n0's NAT traversal, as noq writes them: ADD_ADDRESS and REACH_OUT, // which have OBSERVED_ADDRESS's shape at other codepoints, and // REMOVE_ADDRESS. &.{ 0x80, 0x3d, 0x7f, 0x90, 0x2a, 0x7f, 0x00, 0x00, 0x01, 0x10, 0x92 }, &([_]u8{ 0x80, 0x3d, 0x7f, 0x93, 0x2a } ++ @as([15]u8, @splat(0)) ++ [_]u8{ 0x01, 0x10, 0x92 }), &.{ 0x80, 0x3d, 0x7f, 0x94, 0x0a }, // draft-ietf-quic-ack-frequency-14's ACK_FREQUENCY, four varints of // three widths, and IMMEDIATE_ACK, which is nothing but its type. &.{ 0x40, 0xaf, 0x01, 0x0a, 0x80, 0x00, 0x61, 0xa8, 0x01 }, &.{0x1f}, &@as([40]u8, @splat(0)), // PADDING "",};
/// A packet payload is a sequence of frames and nothing else, so a parser/// that mistakes one frame's length reads the next frame's octets as part of/// it — silently, because there is no length, no count and no terminator to/// disagree with.////// The property is that the iterator either refuses the payload or accounts/// for every octet of it exactly once, and that every slice a frame hands/// back points inside the payload it came from.fn frameProperty(input: []const u8) !void { var it = quic.frame.Iterator.init(input); var consumed: usize = 0; var count: usize = 0;
while (true) { const before = it.at; const f = it.next() catch return; if (f == null) break; count += 1;
// Every frame moves the cursor forward, or the iterator would not // terminate. A zero-length frame is not a thing QUIC has. if (it.at <= before) return error.FrameConsumedNothing; if (it.at > input.len) return error.IteratorRanPastTheEnd; consumed = it.at;
// Whatever a frame borrowed points inside the payload it came from. const fr = f.?; var borrowed: [2][]const u8 = .{ &.{}, &.{} }; switch (fr) { .crypto => |c| borrowed[0] = c.data, .stream => |st| borrowed[0] = st.data, .new_token => |t| borrowed[0] = t, .connection_close => |c| borrowed[0] = c.reason, .ack => |a| borrowed[0] = a.encoded_ranges, .new_connection_id => |n| { borrowed[0] = n.id; borrowed[1] = n.token[0..]; }, else => {}, } for (borrowed) |slice| { if (slice.len == 0) continue; const start = @intFromPtr(slice.ptr); const base = @intFromPtr(input.ptr); if (start < base) return error.FrameBorrowedBeforeTheStart; if (start - base + slice.len > input.len) return error.FrameBorrowedPastTheEnd; }
// Anything the parser accepted, the writer can write -- and reading // that back gives the same frame. This is where the encoder gets its // real coverage: the hand-written cases in `frame.zig` cover one // shape of each type, and the fuzzer reaches the field values and // varint widths nobody would think to write down. // // PADDING is excluded because it is the one frame where the two are // deliberately asymmetric: `write` emits a run and `parse` sees the // first octet of it. if (fr != .padding) { var buf: [2048]u8 = undefined; if (quic.frame.write(&buf, fr)) |written| { const again = quic.frame.parse(buf[0..written]) catch return error.RefusedItsOwnOutput; if (again.len != written) return error.ReparsedToADifferentLength; if (@as(quic.frame.Kind, again.frame) != @as(quic.frame.Kind, fr)) { return error.ReparsedToADifferentKind; } // And writing it a second time is stable, which is what makes // the encoding canonical for anything it produces. var twice: [2048]u8 = undefined; const again_len = quic.frame.write(&twice, again.frame) catch return error.CouldNotRewriteItsOwnOutput; if (!std.mem.eql(u8, buf[0..written], twice[0..again_len])) { return error.RewritingChangedTheOctets; } } else |_| {} }
// An ACK's ranges are walked lazily, so they are their own hazard: // §19.3.1's arithmetic is subtractive and every step of it can go // below zero on input like this. A range that does is a connection // error, so giving up on the payload at that point is correct -- and // it has to be said explicitly, because this loop is nested and // `break` in a `while` *condition* leaves the enclosing loop rather // than the one being written. That is not a hypothetical: it is the // bug this comment replaced, and it made a legitimate refusal look // like octets left unaccounted for. if (fr == .ack) { var ranges = fr.ack.ranges(); walk: while (true) { const r = (ranges.next() catch break :walk) orelse break :walk; if (r.smallest > r.largest) return error.RangeIsInsideOut; if (r.largest > fr.ack.largest) return error.RangeAboveLargestAcknowledged; } } }
// A payload the iterator accepted whole is one it accounted for entirely: // frames "always fit within a single QUIC packet" (§12.4), so there is no // such thing as a remainder. if (consumed != input.len and count > 0) return error.LeftOctetsBehind;}
test "fuzz frames" { for (frame_seeds) |seed| try frameProperty(seed); try testing.fuzz({}, fuzzFrame, .{});}
fn fuzzFrame(_: void, smith: *Smith) !void { var buffer: [1024]u8 = undefined; const len = smith.slice(&buffer); try frameProperty(buffer[0..len]);}
// -- acknowledgement tracking -----------------------------------------------
/// Whatever sequence of packet numbers arrives, the ACK frame built from it/// describes exactly the ones still being remembered — no more and no fewer.////// The "no more" half is what has teeth. An ACK that claimed a packet which/// never arrived would tell the peer to stop retransmitting something that/// was lost, and the peer has no way to find out. §19.3.1's encoding is/// subtractive and its arithmetic is easy to get one out, which is exactly/// the mistake that produces a claim about the wrong packet.fn ackProperty(input: []const u8) !void { var t: quic.ack.Tracker = .{}; var expected: std.ArrayList(u64) = .empty; defer expected.deinit(backing);
// The input is read as a sequence of packet numbers, kept small enough // that runs and gaps both happen often. for (input) |b| { const number: u64 = b; t.record(number, b & 1 == 0); for (expected.items) |e| { if (e == number) break; } else try expected.append(backing, number); } if (t.isEmpty()) return;
// The ranges are disjoint, descending, and never adjacent — two ranges // that touched would be two spellings of one set. var previous: ?quic.ack.Range = null; for (t.ranges[0..t.len]) |r| { if (r.smallest > r.largest) return error.RangeIsInsideOut; if (previous) |p| { if (r.largest + 1 >= p.smallest) return error.RangesTouchOrOverlap; } previous = r; }
var buf: [512]u8 = undefined; const len = t.writeAck(&buf, 0) catch return;
// Everything the frame claims was actually recorded. const got = try quic.frame.parse(buf[0..len]); if (got.len != len) return error.AckReparsedToADifferentLength; const a = got.frame.ack;
var claimed: usize = 0; const first = try a.firstRange(); var n = first.smallest; while (n <= first.largest) : (n += 1) { if (!t.contains(n)) return error.AcknowledgedAPacketThatNeverArrived; claimed += 1; } var it = a.ranges(); while (try it.next()) |r| { var m = r.smallest; while (m <= r.largest) : (m += 1) { if (!t.contains(m)) return error.AcknowledgedAPacketThatNeverArrived; claimed += 1; } }
// And everything still remembered is claimed. Only what the bound // dropped may be missing, so the count is compared against the tracker // rather than against the input. var remembered: usize = 0; for (t.ranges[0..t.len]) |r| remembered += @intCast(r.largest - r.smallest + 1); if (claimed != remembered) return error.AckDidNotDescribeEverythingRemembered;}
test "fuzz acks" { for ([_][]const u8{ "", "\x00", "\x01\x02\x03", "\x00\x02\x04\x06" }) |seed| { try ackProperty(seed); } try testing.fuzz({}, fuzzAck, .{});}
fn fuzzAck(_: void, smith: *Smith) !void { var buffer: [256]u8 = undefined; const len = smith.slice(&buffer); try ackProperty(buffer[0..len]);}
// -- stream reassembly ------------------------------------------------------
/// Whatever fragments arrive, what comes out is a prefix of what went in,/// delivered once each and in order.////// The oracle is a shadow copy: every octet the reassembler hands back must/// equal the octet the *first* fragment to cover that offset carried, since a/// later fragment disagreeing with an earlier one must not be able to rewrite/// bytes that have already been delivered.fn reassemblyProperty(input: []const u8) !void { var window: [64]u8 = undefined; var bits: [8]u8 = undefined; var r = quic.reassembly.Reassembler.init(&window, &bits);
// A shadow of the whole stream, and which offsets have been written. var shadow: [512]u8 = @splat(0); var known: [512]bool = @splat(false);
var at: usize = 0; var delivered: u64 = 0; while (at + 2 <= input.len) { // Each fragment is an offset and a length, both kept small so that // overlaps and gaps are common rather than rare. const offset: u64 = delivered + (input[at] % 80); const len = @min(@as(usize, input[at + 1] % 24), input.len - at - 2); const data = input[at + 2 ..][0..len]; at += 2 + len;
r.insert(offset, data) catch continue;
for (data, 0..) |b, i| { const o = offset + i; if (o >= shadow.len) break; if (!known[@intCast(o)]) { known[@intCast(o)] = true; shadow[@intCast(o)] = b; } }
// Whatever is readable must match the shadow, and must start exactly // where the last delivery ended. const readable = r.readable(); if (r.nextOffset() != delivered) return error.OffsetMovedWithoutConsuming; for (readable, 0..) |b, i| { const o = delivered + i; if (o >= shadow.len) break; if (!known[@intCast(o)]) return error.DeliveredAnOctetThatNeverArrived; if (b != shadow[@intCast(o)]) return error.DeliveredTheWrongOctet; }
// Consume some of it, which is what a caller does after handing the // bytes to TLS. const take = readable.len / 2; r.consume(take); delivered += take; if (r.nextOffset() != delivered) return error.OffsetDisagreesWithWhatWasConsumed; }}
test "fuzz reassembly" { for ([_][]const u8{ "", "\x00\x04abcd", "\x04\x04efgh\x00\x04abcd", "\x00\x04abcd\x00\x04ABCD", }) |seed| try reassemblyProperty(seed); try testing.fuzz({}, fuzzReassembly, .{});}
fn fuzzReassembly(_: void, smith: *Smith) !void { var buffer: [512]u8 = undefined; const len = smith.slice(&buffer); try reassemblyProperty(buffer[0..len]);}
// -- path MTU ---------------------------------------------------------------
/// A search driven by arbitrary answers, against §14's invariants.////// The answers here are the input: any probe may be acknowledged or lost in/// any order, including answers to sizes that were never sent. What must hold/// whatever a peer does is that the search never claims a size larger than/// one that was acknowledged, never goes below §14.1's guaranteed minimum,/// and terminates — a search that could be kept going forever would be a way/// to make an endpoint send probes indefinitely.fn mtuProperty(input: []const u8) !void { var search: quic.mtu.Search = .{}; search.begin();
var acknowledged: usize = quic.mtu.base; var steps: usize = 0;
var at: usize = 0; while (at + 2 <= input.len) : (at += 2) { const action = input[at] % 3; const number: u64 = input[at + 1];
switch (action) { 0 => { const size = search.next() orelse continue; // §14.2: a probe is always larger than what is already known // to work, or it would be asking a question with a known // answer. if (size <= search.current) return error.ProbedSomethingAlreadyKnown; if (size > quic.mtu.ceiling) return error.ProbedPastTheCeiling; search.sent(size, number); steps += 1; }, 1 => { const probing = search.probing; search.acknowledged(number); // A size is only adopted if it was the one outstanding. if (search.current > acknowledged and search.current != probing) { return error.AdoptedASizeNobodyAcknowledged; } acknowledged = @max(acknowledged, search.current); }, else => search.lost(number), }
// §14.1: the floor is what every path is guaranteed to carry, and a // search that went below it would be refusing to send at all. if (search.current < quic.mtu.base) return error.WentBelowTheGuarantee; if (search.current > acknowledged) return error.ClaimedMoreThanWasAcknowledged; // The search asks a bounded number of questions: it is a binary // search over a range of a few hundred octets, so a peer that // answered forever could not make it probe forever. if (steps > 64) return error.ProbedTooManyTimes; }}
test "fuzz path mtu" { for ([_][]const u8{ "", "\x00\x01\x01\x01", "\x00\x01\x02\x01\x00\x02\x02\x02", "\x01\x09\x02\x09", }) |seed| try mtuProperty(seed); try testing.fuzz({}, fuzzMtu, .{});}
fn fuzzMtu(_: void, smith: *Smith) !void { var buffer: [512]u8 = undefined; const len = smith.slice(&buffer); try mtuProperty(buffer[0..len]);}
// -- stateless reset --------------------------------------------------------
/// Datagrams a peer chose, against the tokens this endpoint is holding.////// §10.3.1 has this comparison run on every datagram that could not be/// processed, which makes it the one check an attacker can feed arbitrary/// octets to for the life of a connection. A false positive is a connection/// somebody else tore down; a token leaked through timing is the means to do/// it on purpose.fn resetProperty(input: []const u8) !void { var rng_impl: std.Random.DefaultPrng = .init(0x9e5e); const rng = rng_impl.random(); const key: quic.stateless_reset.Key = @splat(0x11);
// Tokens for four connection IDs, derived the way §10.3.2 describes. var tokens: [4][quic.stateless_reset.token_len]u8 = undefined; for (&tokens, 0..) |*t, i| t.* = quic.stateless_reset.token(key, &[_]u8{@intCast(i)});
// Arbitrary octets are not a reset. The only way to make one is to hold // a token, which is the whole security property — and the reason the // token is derived from a key an attacker does not have. if (quic.stateless_reset.matches(input, &tokens)) { // Unless the input happens to end in one, which a fuzzer will not // find by chance but a corpus derived from one might. var ends_in_token = false; if (input.len >= quic.stateless_reset.token_len) { const trailing = input[input.len - quic.stateless_reset.token_len ..]; for (tokens) |t| { if (std.mem.eql(u8, &t, trailing)) ends_in_token = true; } } if (!ends_in_token) return error.MatchedSomethingThatIsNotAReset; }
// And a reset this endpoint writes is always one §10.3 would recognise: // short header, fixed bit set, long enough to pass for a packet, and // strictly shorter than whatever provoked it. var at: usize = 0; while (at < input.len) : (at += 1) { const received: usize = input[at]; var out: [256]u8 = undefined; const written = quic.stateless_reset.write(&out, rng, tokens[0], received) catch |e| { switch (e) { // §10.3: below 21 octets a reset cannot pass for a packet, so // there is nothing useful to send. error.NoSpace => continue, } }; if (written.len >= received) return error.NotShorterThanWhatProvokedIt; if (written.len < quic.stateless_reset.min_len) return error.TooShortToPassForAPacket; if (written[0] & 0x80 != 0) return error.NotAShortHeader; if (written[0] & 0x40 == 0) return error.FixedBitNotSet; if (!quic.stateless_reset.matches(written, &tokens)) { return error.WroteAResetItWouldNotRecognise; } }}
test "fuzz stateless reset" { for ([_][]const u8{ "", "\x00", "\x16\x2b\xff", "\x50" }) |seed| try resetProperty(seed); try testing.fuzz({}, fuzzReset, .{});}
fn fuzzReset(_: void, smith: *Smith) !void { var buffer: [512]u8 = undefined; const len = smith.slice(&buffer); try resetProperty(buffer[0..len]);}
// -- paths ------------------------------------------------------------------
/// Challenges and responses in whatever order the input asks for.////// The adversary here is an endpoint forging a source address. §8.2 is the/// defence — eight unpredictable octets that must come back — and the/// properties are the two things that make it a defence: a path is validated/// only by the data that was actually sent to it, and an unvalidated path/// gets no more than three times what it sent, so a forged address cannot/// make this endpoint into an amplifier aimed at somebody else.fn pathProperty(input: []const u8) !void { var rng_impl: std.Random.DefaultPrng = .init(0x901d); const rng = rng_impl.random(); var paths: quic.path.Paths = .init(0); // The challenge outstanding on each path, as this test remembers it. var issued: [4]?[quic.path.challenge_len]u8 = @splat(null);
var at: usize = 0; while (at + 3 <= input.len) : (at += 3) { const action = input[at] % 4; const id: quic.path.Id = input[at + 1] % 4; const filler = input[at + 2];
switch (action) { 0 => { const known = paths.observe(id) catch continue; known.received +|= filler; }, 1 => { const data = paths.challenge(id, rng, at) catch continue; // Remember what was actually sent, so that a validation can // be checked against it. §8.2 allows challenging a path that // is already validated -- "an endpoint might check that a // peer is still in possession of its address after a period // of quiescence" -- so being validated is not a reason to // stop tracking one. issued[id] = data; }, 2 => { // A response with data nobody sent, which is what an attacker // who can forge a source address but not read the packets // sent to it is reduced to. var guess: [quic.path.challenge_len]u8 = @splat(filler); if (paths.onResponse(guess)) |validated| { // §8.2.3: "path validation succeeds when a PATH_RESPONSE // frame is received that contains the data that was sent // in a previous PATH_CHALLENGE". Anything else validating // a path would mean a guess had worked. const sent = issued[validated.id] orelse return error.ValidatedByDataNeverSent; if (!std.mem.eql(u8, &sent, &guess)) { return error.ValidatedByTheWrongData; } } // And the real one, which must validate the path it was sent // on and no other. if (issued[id]) |data| { if (paths.onResponse(data)) |validated| { if (validated.id != id) return error.ValidatedSomebodyElsesPath; issued[id] = null; } } }, else => { paths.owe(id, @splat(filler)); if (paths.nextOwed()) |owed| paths.sentResponse(owed.data); }, }
// §21.1.1.1: the allowance for an unvalidated path never exceeds // three times what arrived from it, whatever sequence of frames a // peer sends. for (&paths.entries) |*known| { if (!known.in_use or known.validated) continue; const allowance = paths.sendable(known.id); if (allowance > known.received *| quic.path.Paths.amplification_factor) { return error.AllowedMoreThanThreeTimesWhatArrived; } } // A response that succeeded spends its challenge, so the same data // cannot validate twice — §8.2.2's "an endpoint MUST NOT send more // than one PATH_RESPONSE frame in response to one PATH_CHALLENGE // frame" has a mirror here. for (&paths.entries) |*known| { if (!known.in_use or known.challenge != null) continue; if (issued[known.id]) |data| { if (paths.onResponse(data) != null) return error.ValidatedBySpentData; } } }}
test "fuzz paths" { for ([_][]const u8{ "", "\x00\x01\xff", "\x01\x01\x00\x02\x01\x00", "\x03\x01\x07\x03\x01\x07", "\x00\x01\x10\x01\x01\x00\x02\x01\x00", }) |seed| try pathProperty(seed); try testing.fuzz({}, fuzzPaths, .{});}
fn fuzzPaths(_: void, smith: *Smith) !void { var buffer: [512]u8 = undefined; const len = smith.slice(&buffer); try pathProperty(buffer[0..len]);}
// -- connection identifiers -------------------------------------------------
/// NEW_CONNECTION_ID and RETIRE_CONNECTION_ID frames a peer chose.////// The interesting input is the pair of sequence numbers. §19.15 makes a/// Retire Prior To above the Sequence Number a FRAME_ENCODING_ERROR, a/// repeated sequence naming a different identifier a PROTOCOL_VIOLATION, and/// a repeated *frame* no error at all — three answers to what looks like one/// question. §5.1.1 then caps how many may be held at once, which is the part/// that bounds memory: a peer that could make an endpoint hold identifiers/// without limit would be choosing how much it allocates.fn identifierProperty(input: []const u8) !void { var issued: quic.connection_id.Issued = .init(&.{ 1, 2, 3, 4 }); var received: quic.connection_id.Received = .init(&.{ 9, 8, 7, 6 }); const limit: u64 = quic.connection_id.capacity;
var at: usize = 0; while (at + 4 <= input.len) : (at += 4) { const action = input[at] % 3; const sequence: u64 = input[at + 1]; const retire_prior_to: u64 = input[at + 2]; const length = @max(@as(usize, input[at + 3] % 21), 1);
switch (action) { 0 => { var id: [21]u8 = undefined; for (&id, 0..) |*b, i| b.* = @truncate(sequence +% i); const token: [16]u8 = @splat(@truncate(sequence)); received.offer(sequence, retire_prior_to, id[0..length], token, limit) catch |e| { switch (e) { // Each is a legitimate answer, and each is a // different connection error at the caller. error.FrameEncodingError, error.ProtocolViolation, error.ConnectionIdLimitError, => continue, else => return e, } }; // §5.1.1's cap, which is the whole reason the limit is // advertised: "if the number of active connection IDs exceeds // the value advertised in its active_connection_id_limit // transport parameter, an endpoint MUST close the connection". if (received.active() > limit) return error.HeldMoreThanWasPromised; }, 1 => { // Too many retirements unacknowledged is an answer too. received.retire(sequence) catch |e| switch (e) { error.ConnectionIdLimitError => continue, else => return e, }; if (received.active() > limit) return error.HeldMoreThanWasPromised; }, else => { issued.retire(sequence) catch |e| switch (e) { error.ProtocolViolation => continue, else => return e, }; // Nothing retired is still accepted: §5.1.1 has an endpoint // answer to an identifier "until its peer invalidates the // connection ID", and answering to one after that would be // answering for a connection the peer has stopped addressing. for (&issued.entries) |*entry| { if (!entry.in_use) continue; if (!issued.accepts(entry.id())) return error.StoppedAnsweringToOneItIssued; } }, }
// The identifier in use is always one of the peer's, and a spare is // never the one in use — §9.5 rests on that being true. if (received.current()) |current| { if (received.spare(current)) |other| { if (std.mem.eql(u8, current, other)) return error.SpareWasTheOneInUse; } } if (issued.active() > quic.connection_id.capacity) return error.IssuedMoreThanItCanHold; }}
test "fuzz connection identifiers" { for ([_][]const u8{ "", "\x00\x01\x00\x04", "\x00\x02\x02\x04\x00\x01\x00\x04", "\x00\x01\x05\x04", "\x02\x00\x00\x00\x02\x09\x00\x00", }) |seed| try identifierProperty(seed); try testing.fuzz({}, fuzzIdentifiers, .{});}
fn fuzzIdentifiers(_: void, smith: *Smith) !void { var buffer: [512]u8 = undefined; const len = smith.slice(&buffer); try identifierProperty(buffer[0..len]);}
// -- transport parameters ---------------------------------------------------
/// The extension body a peer sends, on arbitrary octets.////// §8.2 of RFC 9001 puts these in the TLS handshake, which means they are the/// first structured thing an endpoint parses from its peer — and for a server/// they arrive in a ClientHello from an unvalidated address, before anything/// has been authenticated at all. Everything in them is a varint a peer chose,/// including the lengths.fn parameterProperty(input: []const u8) !void { for ([_]quic.parameters.Side{ .client, .server }) |from| { var storage: quic.parameters.IdStorage = .{}; const p = quic.parameters.parse(input, &storage, from) catch |e| switch (e) { error.TransportParameterError => continue, else => return e, };
// Anything accepted satisfies §18.2's ranges, since `validate` runs // before the parse returns. try p.validate(from);
// And anything accepted can be written back out. The encoding is not // canonical — §16 permits a varint in any of four widths, and §18.2 // makes an absent parameter and one carrying its default the same // statement — so this is not a byte-for-byte round trip. What it is // is the claim that parsing produces nothing the writer cannot // express, which is what stops a parsed value being unrepresentable // in the connection that has to act on it. var buffer: [1024]u8 = undefined; const written = quic.parameters.write(&p, &buffer, from) catch |e| switch (e) { error.NoSpace => continue, else => return e, }; var second: quic.parameters.IdStorage = .{}; const back = quic.parameters.parse(written, &second, from) catch return error.WroteSomethingItCannotRead;
if (back.initial_max_data != p.initial_max_data) return error.LostAValueInTheRoundTrip; if (back.max_datagram_frame_size != p.max_datagram_frame_size) { return error.LostAValueInTheRoundTrip; } if (back.max_ack_delay != p.max_ack_delay) return error.LostAValueInTheRoundTrip; if (back.ack_delay_exponent != p.ack_delay_exponent) return error.LostAValueInTheRoundTrip; if (back.initial_max_streams_bidi != p.initial_max_streams_bidi) { return error.LostAValueInTheRoundTrip; } if (back.disable_active_migration != p.disable_active_migration) { return error.LostAValueInTheRoundTrip; } const first_id = p.initial_source_connection_id orelse continue; const second_id = back.initial_source_connection_id orelse return error.LostTheConnectionId; if (!std.mem.eql(u8, first_id, second_id)) return error.LostTheConnectionId; }}
test "fuzz transport parameters" { for ([_][]const u8{ "", "\x04\x01\x03", "\x0f\x04\x01\x02\x03\x04", "\x3a\x04junk\x04\x01\x2a", "\x04\x08\x01", }) |seed| try parameterProperty(seed); try testing.fuzz({}, fuzzParameters, .{});}
fn fuzzParameters(_: void, smith: *Smith) !void { var buffer: [512]u8 = undefined; const len = smith.slice(&buffer); try parameterProperty(buffer[0..len]);}
// -- streams ----------------------------------------------------------------
/// STREAM frames a peer chose, against §4's accounting.////// Flow control is where a receiver's memory is decided by numbers the sender/// writes, so every one of them is hostile input: an offset near 2^62, a/// length that overlaps what has already arrived, a FIN that contradicts an/// earlier one, data after the end. The properties are the ones §4 promises/// and a receiver's memory safety rests on — that nothing is accepted past/// the advertised limit, that the limit charged is the highest offset reached/// rather than the octets that crossed the network, and that a stream ends in/// exactly one place.fn streamProperty(input: []const u8) !void { var buffer: [256]u8 = undefined; var present: [32]u8 = undefined; const limit: u64 = 256; var r: quic.stream.Recv = .init(&buffer, &present, limit);
var charged_total: u64 = 0; var highest: u64 = 0; var final: ?u64 = null;
var at: usize = 0; while (at + 3 <= input.len) { // An offset that is usually in range and occasionally absurd, which // is what a peer trying to make a receiver allocate would send. const offset: u64 = if (input[at] & 0x80 != 0) @as(u64, input[at]) << 55 else input[at]; const len = @min(@as(usize, input[at + 1] % 32), input.len - at - 3); const fin = input[at + 2] & 1 == 1; const data = input[at + 3 ..][0..len]; at += 3 + len;
const charged = r.receive(offset, data, fin) catch |e| switch (e) { // Each of these is a legitimate answer to a hostile frame, and // each is a connection error the caller turns into a close. error.FlowControlError, error.FinalSizeError, error.WindowExceeded => continue, else => return e, }; charged_total += charged;
// §4.1: the limit is on the highest offset reached, so what has been // charged in total is exactly that -- never the number of octets that // arrived, which a peer can inflate without limit by retransmitting. highest = @max(highest, offset + len); if (r.credit.used != highest) return error.ChargedSomethingOtherThanTheHighestOffset; if (charged_total != r.credit.used) return error.ChargesDoNotSumToWhatWasUsed; if (r.credit.used > limit) return error.AcceptedPastTheAdvertisedLimit;
// §4.5: "Once a final size for a stream is known, it cannot change." if (fin) { if (final) |known| { if (known != offset + len) return error.FinalSizeChanged; } final = offset + len; } if (final) |known| { if (r.final_size != known) return error.ForgotTheFinalSize; // And nothing may sit past it. if (r.data.nextOffset() + r.readable().len > known) { return error.DeliveredPastTheEnd; } }
// What is readable is always a prefix, and taking some of it never // moves what has not been read. const readable = r.readable(); const before = r.data.nextOffset(); const take = readable.len / 2; r.consume(take); if (r.data.nextOffset() != before + take) return error.ConsumedMoreThanWasTaken; // §4.2: the advertised limit only ever grows. if (r.limitToAdvertise(limit) < limit) return error.AdvertisedLimitWentBackwards; }}
test "fuzz streams" { for ([_][]const u8{ "", "\x00\x04\x00abcd", "\x00\x04\x01abcd\x00\x04\x01abcd", "\x00\x04\x01abcd\x04\x04\x00efgh", "\xff\x04\x00abcd", }) |seed| try streamProperty(seed); try testing.fuzz({}, fuzzStream, .{});}
fn fuzzStream(_: void, smith: *Smith) !void { var buffer: [512]u8 = undefined; const len = smith.slice(&buffer); try streamProperty(buffer[0..len]);}
// -- loss recovery ----------------------------------------------------------
/// Sending and acknowledging in whatever order the input asks for, checking/// what RFC 9002 promises about the result.////// The adversary here is the peer's ACK frame, which is the one input to loss/// recovery that an attacker writes directly. It may acknowledge packets that/// were never sent, ranges covering the whole 62-bit number space, the same/// packet forever, or nothing at all -- and none of that may make this/// endpoint declare a packet lost that the RFC says is still in flight, or/// spend unbounded time or memory answering.fn recoveryProperty(input: []const u8) !void { var storage: [quic.recovery.max_tracked]quic.recovery.Sent = undefined; var space: quic.recovery.Space = .{ .sent = &storage }; var rtt: quic.recovery.Rtt = .{}; var cc: quic.congestion.Controller = .{}; var now: quic.recovery.Instant = 0; var next_number: u64 = 0; const floor = quic.congestion.minimumWindow(quic.congestion.min_datagram_size);
var acked: [quic.recovery.max_tracked]quic.recovery.Sent = undefined; var lost: [quic.recovery.max_tracked]quic.recovery.Sent = undefined;
var at: usize = 0; while (at + 3 <= input.len) : (at += 3) { const action = input[at] % 4; const a = input[at + 1]; const b = input[at + 2]; now += @as(u64, a) * std.time.ns_per_ms;
switch (action) { 0 => { const eliciting = b % 4 != 0; _ = space.onSent(.{ .number = next_number, .time = now, .ack_eliciting = eliciting, .size = b, .crypto_offset = next_number * 8, .crypto_len = b % 32, }); if (eliciting) cc.onSent(b); next_number += 1; }, 1 => { // An acknowledgement of a range that may name anything at // all, including numbers never sent and numbers acknowledged // before. const largest = @as(u64, a) * 3 + b; const smallest = if (b > a) 0 else largest -| b; space.onLargestAcked(largest); for (space.ackRange(smallest, largest, &acked)) |sent| { // Nothing may come back that was not sent, and nothing // may come back twice: `ackRange` removes what it // returns. if (sent.number >= next_number) return error.AcknowledgedAPacketNeverSent; if (space.isInFlight(sent.number)) return error.AcknowledgedPacketStillInFlight; if (sent.number < smallest or sent.number > largest) { return error.AcknowledgedOutsideTheRange; } if (sent.time <= now) { rtt.sample(now - sent.time, @as(u64, b) * std.time.ns_per_ms, 25 * std.time.ns_per_ms, b % 2 == 0); cc.onRttSample(now); } cc.onAcked(sent, now); } }, 2 => { const largest = space.largest_acked; const gone = space.detectLost(&rtt, now, &lost); cc.onLost(gone, rtt.probeTimeout(25 * std.time.ns_per_ms), now); for (gone) |sent| { // §6.1: both thresholds are measured against a *later* // packet having been acknowledged. Nothing at or above // the largest acknowledged can be declared lost, and // nothing can be declared lost at all before something // has been acknowledged. const l = largest orelse return error.LostWithoutAnAcknowledgement; if (sent.number >= l) return error.LostSomethingNotYetOvertaken; if (space.isInFlight(sent.number)) return error.LostPacketStillInFlight; } }, else => { // The timers must agree with the state: a loss time is armed // only when something is waiting on it. if (space.lossTime(&rtt)) |_| { if (space.inFlight() == 0) return error.LossTimerWithNothingInFlight; if (space.largest_acked == null) return error.LossTimerWithoutAnAcknowledgement; } // And the probe timeout is a duration, never zero, whatever // samples have been fed to the estimator. if (rtt.probeTimeout(0) < quic.recovery.granularity) return error.ProbeTimeoutBelowGranularity; if (rtt.lossDelay() < quic.recovery.granularity) return error.LossDelayBelowGranularity; }, }
// The whole point of the bound: a peer that acknowledges nothing // cannot make this grow. if (space.inFlight() > quic.recovery.max_tracked) return error.TrackedMoreThanTheBound;
// §7.2: the window never falls below two packets, however much loss // a peer manufactures. A sender whose window reached zero could send // nothing at all and would never recover, which is a way to kill a // connection from off the path. if (cc.window < floor) return error.WindowBelowTheMinimum; if (cc.available() > cc.window) return error.MoreAvailableThanTheWindow; }}
test "fuzz recovery" { for ([_][]const u8{ "", "\x00\x01\x08", "\x00\x01\x08\x00\x01\x08\x00\x01\x08\x01\x00\x02\x02\x00\x00", "\x01\xff\xff\x02\xff\xff\x03\x00\x00", }) |seed| try recoveryProperty(seed); try testing.fuzz({}, fuzzRecovery, .{});}
fn fuzzRecovery(_: void, smith: *Smith) !void { var buffer: [512]u8 = undefined; const len = smith.slice(&buffer); try recoveryProperty(buffer[0..len]);}
// -- whole connections ------------------------------------------------------
/// A server connection fed arbitrary datagrams answers with nothing it should/// not, and survives.////// This is every layer at once on input a peer chose: packet parsing, header/// protection removal, AEAD, frame parsing, CRYPTO reassembly and a TLS/// handshake. It is also where §5.2 of RFC 9000's amplification rule lives —/// an endpoint must not answer a packet it could not process — so the/// property is not only that nothing crashes but that **nothing is sent** in/// reply to a datagram that carried nothing readable.const fuzz_limits: quic.parameters.Parameters = .{ .initial_max_data = 4096, .initial_max_stream_data_bidi_local = 2048, .initial_max_stream_data_bidi_remote = 2048, .initial_max_streams_bidi = 4, .initial_max_streams_uni = 4, .initial_max_stream_data_uni = 2048, // RFC 9221 §3: without this the DATAGRAM path is reachable only as far as // the PROTOCOL_VIOLATION that refuses it, and the queueing behind it is // never exercised at all. .max_datagram_frame_size = 1200,};
fn connectionProperty(input: []const u8) !void { var rng_impl = std.Random.DefaultPrng.init(0x9001); const rng = rng_impl.random();
// Parameters that permit streams, so that a datagram which does reach the // application level finds the stream machinery armed rather than a // connection that refuses everything before parsing it. const server_parameters = comptime encoded: { var buffer: [128]u8 = undefined; var p = fuzz_limits; p.initial_source_connection_id = &[_]u8{ 0x5e, 0x51 }; p.original_destination_connection_id = &[_]u8{ 0x83, 0x94, 0xc8, 0xf0 }; const written = quic.parameters.write(&p, &buffer, .server) catch unreachable; break :encoded buffer[0..written.len].*; };
var server_tls: quic.tls_handshake.Server = .init(.{ .auth = null, .transport_parameters = &server_parameters, .alpn_protocols = &.{"doq"}, .rng = rng, }); // Heap rather than stack: a connection holds three reassembly windows and // is far too big for a fuzzer's frame. const server = backing.create(quic.Connection) catch return; defer backing.destroy(server); const memory = backing.create(quic.Connection.Storage(.{})) catch return; defer backing.destroy(memory); server.init(.{ .memory = memory.memory(), .role = .server, .handshake = server_tls.handshake(), .local_id = &.{ 0x5e, 0x51 }, .local = fuzz_limits, });
var datagram: [2048]u8 = undefined; const len = @min(input.len, datagram.len); @memcpy(datagram[0..len], input[0..len]);
const established_before = server.isEstablished(); if (server.receive(datagram[0..len], 0, 0)) |_| {} else |_| { // A connection error is a legitimate answer to a hostile datagram. // What must not happen is a crash, and what must not happen next is // the connection carrying on as though nothing had: §10.2 says // "violations of the protocol lead to an immediate close", so the // connection must be ending rather than open. const state = server.closeState() orelse return error.SurvivedItsOwnError; if (state == .open) return error.SurvivedItsOwnError;
// And what it sends on the way out is one packet, still inside §5.2's // amplification limit -- an endpoint must not be usable as a // reflector by closing it. var closing: [2048]u8 = undefined; if (server.send(&closing, 1) catch null) |out| { if (out.bytes.len > 3 * len) return error.AmplifiedWhileClosing; } // §10.2.1's rate limit: nothing follows it unprompted. if (server.send(&closing, 2) catch null) |_| return error.RepeatedItselfUnprompted; return; }
// Nothing arbitrary can establish a connection: that needs a ClientHello // this endpoint's TLS accepted, which needs a key share and transport // parameters and an agreed protocol. if (!established_before and server.isEstablished()) { return error.EstablishedByNoise; }
var out: [2048]u8 = undefined; const reply = server.send(&out, 0) catch return; if (reply) |answer| { const wire = answer.bytes; // §5.2 of RFC 9000: a server may not send more than three times what // it has received from an address it has not validated. Answering a // datagram at all means something in it was read, and the answer is // bounded either way. if (wire.len > 3 * len) return error.AmplifiedBeyondThreeTimes; // Whatever it sent is a packet, which is the same oracle the // `datagrams` target applies to the other direction. const h = try quic.packet.parse(wire, 2); if (h.end > wire.len) return error.SentAPacketPastItsOwnDatagram; }}
test "fuzz connections" { for ([_][]const u8{ "", "\x00", "\xc0\x00\x00\x00\x01" }) |seed| { try connectionProperty(seed); } try testing.fuzz({}, fuzzConnection, .{});}
fn fuzzConnection(_: void, smith: *Smith) !void { var buffer: [1500]u8 = undefined; const len = smith.slice(&buffer); try connectionProperty(buffer[0..len]);}
// -- the table the standalone driver reads ----------------------------------
// -- the octets this endpoint puts on a stream ------------------------------//// Every target above is about something that *arrived*: a header, a datagram,// a frame, an acknowledgement, a peer's stream. `outgoing.Outgoing` is the// other direction — the window a producer writes into, and the source of every// STREAM frame this endpoint sends — and nothing fuzzed it.//// Which is where a fault was. §19.8 of RFC 9000 permits a FIN in a STREAM// frame carrying no data, so an endpoint that flushes its last octets and then// ends the stream is within the letter of the specification — and is answered// by Quad9's DNS-over-HTTP/3 server with silence. No close, no reset, both// packets acknowledged, nothing to read. The rule this file implements instead// is that the end travels with the last octet, and that is a property of the// chunks it hands out rather than of anything a peer sends, so no target that// feeds this library bytes could ever have reached it.//// So: a script of writes, sends, acknowledgements and losses, run against a// model that remembers what the producer wrote. Every chunk is then asked// whether it carries the octets that were written at the offset they were// written to, and whether the end of the stream travelled where it should.
/// As much of a stream as this target will produce. Eight times the window/// below it, so that `compact` runs, `base` leaves zero, and a chunk's offset/// stops being an index into the buffer — which is the arithmetic worth/// fuzzing, since every offset on the wire is absolute and exactly one place/// reconciles the two.const max_send_stream = 2048;
/// The window itself, deliberately small for the same reason.const send_window = 256;
/// A chunk handed out and not yet acknowledged or declared lost: what a/// recovery module would be holding, and the only ranges it is meaningful to/// acknowledge or lose. Marking a range lost that was never sent is a caller/// error rather than an input, so the script cannot ask for one.const Flight = struct { offset: u64, len: usize };
fn sendProperty(input: []const u8) !void { var buffer_a: [send_window]u8 = undefined; var buffer_b: [send_window]u8 = undefined; var o: quic.outgoing.Outgoing = .init(&buffer_a);
// The model: everything the producer wrote, and which of it has been // handed out at least once. var written: [max_send_stream]u8 = undefined; var written_len: usize = 0; var emitted: [max_send_stream]bool = @splat(false);
var flight: [32]Flight = undefined; var flight_len: usize = 0; // Whether the producer ended the stream while octets it had written had // yet to be sent for the first time. var unsent_at_finish = false;
var at: usize = 0; while (at + 2 <= input.len) { const op = input[at] % 6; const arg = input[at + 1]; at += 2;
step: switch (op) { // Write. `write` asserts the stream has not been finished, so the // script cannot ask for that: it is a contract the connection // above keeps, not an input a peer can supply. 0, 1 => { if (o.finished) break :step; const want = @min(@as(usize, arg % 64) + 1, max_send_stream - written_len); if (want == 0) break :step; var bytes: [64]u8 = undefined; // Octets that depend on their offset, so that a chunk carrying // the wrong part of the window is a mismatch rather than a // coincidence. for (0..want) |i| bytes[i] = @truncate(written_len + i); o.write(bytes[0..want]) catch break :step; // BufferFull: wait. @memcpy(written[written_len..][0..want], bytes[0..want]); written_len += want; }, // Finish. What the window looked like at this exact moment is // the whole of what makes a bare FIN honest or not later on, and // there is no way to ask afterwards -- so it is recorded here. 2 => { // New data specifically, not `pending`: a retransmission // outstanding at this moment is not an octet that has yet to // go, and counting it called a legitimate bare FIN a fault // the first time this was written. if (!o.finished) unsent_at_finish = o.len > o.sent; o.finish(); }, // Send: the operation this whole target exists to look at. 3 => { const max = @as(usize, arg % 64) + 1; const chunk = o.next(max) orelse { // §3.1: nothing to say. Then nothing may be waiting to be // said, or a connection with room in its packet would // have stopped sending a stream that is not done. if (o.pending()) return error.NothingToSendButSomethingPending; break :step; }; if (!o.pending()) return error.SomethingToSendButNothingPending;
if (chunk.data.len > max) return error.ChunkLargerThanAskedFor; const end = chunk.offset + chunk.data.len; // Never past what the producer wrote: an octet on the wire // that nobody produced is whatever the window happened to // hold, which is the shape of an information leak. if (end > written_len) return error.SentPastWhatWasWritten;
// §13.3: "the contents of the frame" are what a retransmission // carries, so this holds for a chunk's first journey and every // one after it -- the octets are the ones the producer wrote, // at the offset it wrote them to. const from: usize = @intCast(chunk.offset); if (!std.mem.eql(u8, chunk.data, written[from..][0..chunk.data.len])) { return error.SentOctetsThatWereNeverWritten; }
if (chunk.fin) { // A FIN on a stream the producer has not ended would be // this endpoint deciding the message was over. if (!o.finished) return error.EndedAStreamTheProducerDidNot; // §4.5: the final size is "one higher than the offset of // the byte with the largest offset sent", and it is the // frame carrying the end that states it. A FIN anywhere // but the end states a different one. if (end != written_len) return error.EndedTheStreamSomewhereOtherThanItsEnd;
// The Quad9 property, and the one worth stating carefully // because the obvious statement of it is not a property at // all. §19.8 permits a FIN in a frame carrying no data, // and there are two ways to reach one honestly: a stream // with no octets in it, whose end can travel no other way; // and a producer that finished after everything it wrote // had already gone, where there is no longer a frame to // put the end on. Neither is a fault. // // What is a fault is ending a stream that still had octets // waiting and then sending those octets and the end // separately -- because then there *was* a last frame to // put it on. That is the shape Quad9 answers with silence, // and `unsent_at_finish` is the only thing that tells the // two apart. Asserting instead that every octet had gone // out before the bare FIN looks like the same check and is // satisfied by the bug: putting the FIN in a frame of its // own is exactly what "every octet has already gone" means. if (chunk.data.len == 0 and unsent_at_finish) { return error.TheFinTravelledAlone; } }
for (emitted[from..][0..chunk.data.len]) |*seen| seen.* = true; if (chunk.data.len > 0 and flight_len < flight.len) { flight[flight_len] = .{ .offset = chunk.offset, .len = chunk.data.len }; flight_len += 1; } o.advance(chunk); }, // Acknowledge one of the ranges actually sent, whole or in part. 4 => { if (flight_len == 0) break :step; const i = @as(usize, arg) % flight_len; const f = flight[i]; const len = @max(@as(usize, 1), @as(usize, arg / 8) % (f.len + 1)); o.onAcked(f.offset, @min(len, f.len)); flight_len -= 1; flight[i] = flight[flight_len]; }, // Declare one lost, which §13.3 answers by sending it again. else => { if (flight_len == 0) break :step; const i = @as(usize, arg) % flight_len; const f = flight[i]; o.markLost(f.offset, f.len); flight_len -= 1; flight[i] = flight[flight_len]; }, }
// -- what must be true after every operation ----------------------
// §4.5: a final size exists exactly when the producer has said there // is no more, and it is what was written. if (o.finalSize()) |size| { if (!o.finished) return error.AFinalSizeBeforeTheEnd; if (size != written_len) return error.AFinalSizeOtherThanWhatWasWritten; } else if (o.finished) { return error.NoFinalSizeAfterTheEnd; }
// `pending` and `next` are two ways of asking one question, and a // connection asks the cheap one to decide whether to build a packet // at all. If they ever disagree, a stream either stalls with octets // nobody asks for or wakes a sender that has nothing to say. if (o.pending() != (o.next(1) != null)) return error.PendingDisagreesWithNext;
// Deliberately not checked here: that `allAcked` is false while // anything is still pending. It is not, and it should not be -- a // stream finished with no octets at all has everything acknowledged // the moment it is finished, while the frame carrying its end has yet // to go out. §3.1's "Data Recvd" is the composite of that and // `fin_sent`, and `stream.Send` is what composes them: it consults // `allAcked` only from `data_sent`, which it enters only once // `fin_sent` is true. Asserting it at this layer failed on the third // seed, and the property was the thing that was wrong. }
// Run it to a standstill: whatever the script left waiting must be able to // leave, and must do so in a bounded number of frames. A window that can // be asked for a chunk for ever is a connection that never makes progress, // and the shape that produces one -- a zero-length chunk that advances // nothing -- is exactly what `advance` has to guard against. var rounds: usize = 0; while (o.pending()) : (rounds += 1) { if (rounds > 4 * max_send_stream) return error.PendingForEver; const chunk = o.next(64) orelse return error.PendingWithNothingToSend; const from: usize = @intCast(chunk.offset); if (chunk.offset + chunk.data.len > written_len) return error.SentPastWhatWasWritten; if (!std.mem.eql(u8, chunk.data, written[from..][0..chunk.data.len])) { return error.SentOctetsThatWereNeverWritten; } for (emitted[from..][0..chunk.data.len]) |*seen| seen.* = true; o.advance(chunk); }
// And once it has stopped, every octet the producer wrote has been on the // wire at least once. A window that drops an octet it never sent is a // stream that stalls with both ends waiting for the other. for (emitted[0..written_len]) |seen| { if (!seen) return error.StoppedWithAnOctetNeverSent; }
// `rehome` is part of the same path -- it is how a connection grows a // window -- and it must move the held octets without changing any offset. // Checked here rather than in the loop so that what it moves is whatever // the script happened to leave held. o.rehome(&buffer_b); if (o.finalSize()) |size| { if (size != written_len) return error.RehomingChangedTheFinalSize; } o.markLost(0, written_len); var again: usize = 0; while (o.pending()) : (again += 1) { if (again > 4 * max_send_stream) return error.PendingForEver; const chunk = o.next(64) orelse break; if (chunk.data.len == 0) break; const from: usize = @intCast(chunk.offset); if (!std.mem.eql(u8, chunk.data, written[from..][0..chunk.data.len])) { return error.RehomingMovedTheOctets; } o.advance(chunk); }}
const send_seeds = [_][]const u8{ // Write, finish, send: the shortest path to a FIN riding the last octet, // and the one that fails the moment `next` stops putting it there. &.{ 0, 8, 2, 0, 3, 40 }, // Write, send, finish, send. A bare FIN, and an honest one: the octets // had already gone when the producer finished, so there was no longer a // frame to put the end on. Pinned because it is what a property tightened // one notch too far would refuse. &.{ 0, 8, 3, 40, 2, 0, 3, 40 }, // Finish with nothing written: the other honest bare FIN, and the only // way a stream of no octets can end at all. &.{ 2, 0, 3, 40 }, // Enough to drive the window past its own length, with losses. &.{ 0, 63, 3, 20, 5, 0, 3, 20, 4, 0, 0, 63, 3, 30, 2, 0, 3, 30 },};
fn fuzzSend(_: void, smith: *Smith) !void { var buffer: [512]u8 = undefined; const len = smith.slice(&buffer); try sendProperty(buffer[0..len]);}
test "fuzz what goes out on a stream" { for (send_seeds) |seed| try sendProperty(seed); try testing.fuzz({}, fuzzSend, .{});}
pub const Target = struct { name: []const u8, run: *const fn (input: []const u8) anyerror!void, corpus: []const []const u8, content_max: usize, slices: usize = 1,};
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 = "headers", .run = Driven(fuzzHeader).run, .corpus = &header_seeds, .content_max = 512 }, .{ .name = "datagrams", .run = Driven(fuzzDatagram).run, .corpus = &datagram_seeds, .content_max = 1500 }, .{ .name = "varints", .run = Driven(fuzzVarint).run, .corpus = &varint_seeds, .content_max = 16 }, .{ .name = "frames", .run = Driven(fuzzFrame).run, .corpus = &frame_seeds, .content_max = 1024 }, .{ .name = "acks", .run = Driven(fuzzAck).run, .corpus = &.{}, .content_max = 256 }, .{ .name = "reassembly", .run = Driven(fuzzReassembly).run, .corpus = &.{}, .content_max = 512 }, .{ .name = "mtu", .run = Driven(fuzzMtu).run, .corpus = &.{}, .content_max = 512 }, .{ .name = "resets", .run = Driven(fuzzReset).run, .corpus = &.{}, .content_max = 512 }, .{ .name = "paths", .run = Driven(fuzzPaths).run, .corpus = &.{}, .content_max = 512 }, .{ .name = "identifiers", .run = Driven(fuzzIdentifiers).run, .corpus = &.{}, .content_max = 512 }, .{ .name = "parameters", .run = Driven(fuzzParameters).run, .corpus = &.{}, .content_max = 512 }, .{ .name = "streams", .run = Driven(fuzzStream).run, .corpus = &.{}, .content_max = 512 }, .{ .name = "recovery", .run = Driven(fuzzRecovery).run, .corpus = &.{}, .content_max = 512 }, .{ .name = "connections", .run = Driven(fuzzConnection).run, .corpus = &.{}, .content_max = 1500 }, .{ .name = "sends", .run = Driven(fuzzSend).run, .corpus = &send_seeds, .content_max = 512 },};