// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What the library must do with input nobody wrote. //! //! Everything here is a property rather than an example: not "this packet //! decodes to that" -- the unit tests have those -- but "whatever arrives, //! decoding terminates, stays inside its buffers, and if it claims to have //! understood the input then encoding it and decoding it again gives the same //! answer". A round trip is what catches an encoder and a decoder that have //! drifted apart, which a test written against a fixed example cannot see. //! //! The netascii codecs exist four times over: a function, a writer, and a //! reader in each direction. They must agree with each other however their //! input is chunked and however small their buffers are, since the boundary //! between two reads is exactly where a two byte escape can be split. //! //! The last target is a whole transfer, run against a client made of fuzzed //! packets over the loopback interface. It is slow next to the others, and it //! is the one that exercises the state machine rather than a parser. //! //! Each target is an ordinary test as well as a fuzz target. Without `--fuzz` //! it runs the seeds beside it, so `zig build test` exercises the same //! properties on input that has already been interesting once. With `zig //! build fuzz --fuzz` Zig's own fuzzer drives them, guided by coverage, and //! `zig build fuzz-run` drives them with a loop of our own. //! //! # Knobs //! //! A target that needs to choose something -- a mode, a buffer size, a line //! ending convention -- takes the choice from the first bytes of its input, //! reduced modulo the number of choices. `Smith.value` would be the obvious //! way, but it reads eight bytes per answer and turns anything out of range //! into the range's minimum, so mutated input would almost always choose the //! first option. A byte taken modulo `n` chooses them all. 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 tftp = @import("tftp"); const Packet = tftp.Packet; const netascii = tftp.netascii; /// 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` the session target runs its transfers on. It has to support /// `concurrent`, since the server and the client run at once, so the tests and /// the driver each set it to a threaded one. pub var session_io: Io = undefined; /// The byte at `index`, or zero past the end. Knobs are read with this so that /// a short input still chooses something. fn knob(input: []const u8, index: usize) u8 { return if (index < input.len) input[index] else 0; } /// The input after its first `n` knob bytes. fn after(input: []const u8, n: usize) []const u8 { return input[@min(n, input.len)..]; } /// Line endings of every kind, for netascii to translate. Repeated to make /// content long enough to take several blocks. const lines = "one\ntwo\r\nthree\rfour\n"; // -- packets --------------------------------------------------------------- /// Builds packet seeds at compile time from their parts. fn cat(comptime parts: anytype) []const u8 { comptime var bytes: []const u8 = ""; inline for (parts) |part| bytes = bytes ++ part; return bytes; } // Each seed begins with its knob byte, which chooses the mode and block size // that DATA packets are decoded with. const packet_seeds = [_][]const u8{ cat(.{ "\x00", "\x00\x01", "file.txt\x00", "octet\x00" }), cat(.{ "\x00", "\x00\x02", "file.txt\x00", "netascii\x00" }), cat(.{ "\x00", "\x00\x01", "a\r\nb\r\x00c\x00", "NetAscii\x00", "blksize\x001428\x00", "tsize\x000\x00", "timeout\x005\x00" }), cat(.{ "\x00", "\x00\x02", "f\x00", "mail\x00", "BLKSIZE\x007\x00", "unknown\x00x\x00" }), cat(.{ "\x00", "\x00\x01", "f\x00", "octet\x00", "blksize\x00512" }), cat(.{ "\x00", "\x00\x03", "\x00\x01", "hello" }), cat(.{ "\x05", "\x00\x03", "\xff\xff", "12345678" }), cat(.{ "\x06", "\x00\x03", "\x00\x02", "123456789" }), cat(.{ "\x00", "\x00\x04", "\x00\x07" }), cat(.{ "\x00", "\x00\x05", "\x00\x01", "File not found\x00" }), cat(.{ "\x00", "\x00\x05", "\x00\x2a", "\x00" }), cat(.{ "\x00", "\x00\x06", "blksize\x008\x00", "tsize\x001234\x00" }), cat(.{ "\x00", "\x00\x07" }), cat(.{ "\x00", "\x00" }), "", }; /// The block sizes a DATA packet is decoded with, chosen by the knob byte. const blocksizes = [_]?u16{ null, 8, 512, 1428, 65464 }; /// Whatever arrives, decoding either fails or produces a packet that survives /// being encoded and decoded again. fn packetProperty(input: []const u8) !void { const choice = knob(input, 0); const options: Packet.DecodeOptions = .{ .mode = switch (choice % 4) { 0 => .octet, 1 => .netascii, 2 => .mail, else => null, }, .blocksize = blocksizes[(choice / 4) % blocksizes.len], }; const data = after(input, 1); const decode_buf = try backing.create(Packet.Buffer); defer backing.destroy(decode_buf); const packet = Packet.decode(data, decode_buf, options) catch return; const encode_buf = try backing.create(Packet.Buffer); defer backing.destroy(encode_buf); // Encoding can expand a filename, since a bare LF goes out as CR LF, so a // packet decoded from a full sized datagram need not fit in one again. const encoded = packet.encode(encode_buf) catch |err| switch (err) { error.WriteFailed => return, // Encoding reads only from fixed readers over memory it was handed. else => |e| return e, }; const again_buf = try backing.create(Packet.Buffer); defer backing.destroy(again_buf); const again = try Packet.decode(encoded, again_buf, options); try testing.expectEqual(packet.opcode(), again.opcode()); switch (packet) { inline .rrq, .wrq => |p, tag| { const q = @field(again, @tagName(tag)); try testing.expectEqualStrings(p.filename, q.filename); try testing.expectEqual(p.mode, q.mode); try testing.expectEqual(p.options, q.options); try optionsInRange(p.options); }, .data => |p| { try testing.expectEqual(p.block, again.data.block); try testing.expectEqualStrings(p.data, again.data.data); try testing.expectEqual(p.last, again.data.last); try testing.expect(p.data.len <= options.blocksize orelse 512); }, .ack => |p| try testing.expectEqual(p.block, again.ack.block), .err => |p| { try testing.expectEqual(p.code, again.err.code); try testing.expectEqualStrings(p.msg.?, again.err.msg.?); }, .oack => |p| { try testing.expectEqual(p.options, again.oack.options); try optionsInRange(p.options); }, } } /// Every option that was accepted is within the range its RFC allows. fn optionsInRange(options: Packet.Options) !void { if (options.blocksize) |b| try testing.expect(b >= 8 and b <= 65464); if (options.timeout) |t| try testing.expect(t >= 1); } test "fuzz packets" { for (packet_seeds) |seed| try packetProperty(seed); try testing.fuzz({}, fuzzPacket, .{}); } fn fuzzPacket(_: void, smith: *Smith) !void { const buffer = try backing.alloc(u8, packet_max); defer backing.free(buffer); const len = smith.slice(buffer); try packetProperty(buffer[0..len]); } /// A knob byte and the largest datagram. const packet_max = 1 + Packet.BUFFER_LENGTH; // -- options --------------------------------------------------------------- const option_seeds = [_][]const u8{ "blksize\x001428\x00", "blksize\x0065464\x00timeout\x00255\x00tsize\x0018446744073709551615\x00", "blksize\x0065465\x00timeout\x000\x00tsize\x0018446744073709551616\x00", "BlkSize\x00+8\x00TIMEOUT\x00 1\x00", "blksize\x00512", "blksize", "\x00\x00\x00", "", }; /// Whatever arrives, the options decoded are in range and survive being /// encoded and decoded again. fn optionProperty(input: []const u8) !void { var reader: Io.Reader = .fixed(input); const options = try Packet.Options.decode(&reader); try optionsInRange(options); var out: [128]u8 = undefined; var writer: Io.Writer = .fixed(&out); try options.encode(&writer); var again_reader: Io.Reader = .fixed(writer.buffered()); try testing.expectEqual(options, try Packet.Options.decode(&again_reader)); try testing.expectEqual(options.empty(), writer.buffered().len == 0); } test "fuzz options" { for (option_seeds) |seed| try optionProperty(seed); try testing.fuzz({}, fuzzOptions, .{}); } fn fuzzOptions(_: void, smith: *Smith) !void { var buffer: [1024]u8 = undefined; const len = smith.slice(&buffer); try optionProperty(buffer[0..len]); } // -- netascii -------------------------------------------------------------- // Each seed begins with four knob bytes: the line ending convention, and the // buffer and chunk sizes the codecs are run with. const netascii_seeds = [_][]const u8{ "\x00\x00\x00\x00hello", "\x01\x01\x01\x01one\ntwo\n", "\x02\x02\x02\x02one\r\ntwo\r\n", "\x00\x03\x05\x07a\rb\r\nc\n\r", "\x01\x00\x00\x00\r\x00\r\n\r\x00\n", "\x02\x01\x02\x03\r\r\r\n\n\n\x00", "\x00\x07\x07\x07bad\rcr", "\x01\x06\x06\x06trailing\r", "\x02\x05\x04\x03", }; const LineSeparator = netascii.LineSeparator; const host: LineSeparator = if (builtin.os.tag == .windows) .crlf else .lf; /// A reader over `source` that hands out at most `step` bytes at a time, /// buffering in a buffer of its own size. It is what makes a codec meet the /// end of its child's buffer in the middle of an escape. const Trickle = struct { interface: Io.Reader, source: []const u8, step: usize, fn init(source: []const u8, buffer: []u8, step: usize) Trickle { return .{ .interface = .{ .buffer = buffer, .seek = 0, .end = 0, .vtable = &.{ .stream = stream }, }, .source = source, .step = step, }; } fn stream(r: *Io.Reader, w: *Io.Writer, limit: Io.Limit) Io.Reader.StreamError!usize { const self: *Trickle = @alignCast(@fieldParentPtr("interface", r)); if (self.source.len == 0) return error.EndOfStream; const n = @min(self.step, self.source.len, @backingInt(limit)); const written = try w.write(self.source[0..n]); self.source = self.source[written..]; return written; } }; /// Reads everything from `reader` into a new slice, `read_step` bytes at a /// time, or fails as the reader does. fn readAll(reader: *Io.Reader, read_step: usize) ![]u8 { var out: Io.Writer.Allocating = .init(backing); errdefer out.deinit(); while (true) { _ = reader.stream(&out.writer, .limited(read_step)) catch |err| switch (err) { error.EndOfStream => break, error.ReadFailed => return error.ReadFailed, error.WriteFailed => return error.OutOfMemory, }; } return out.toOwnedSlice(); } /// Every codec agrees with every other, whatever the chunking. fn netasciiProperty(input: []const u8) !void { switch (knob(input, 0) % 3) { 0 => try netasciiFor(.cr, input), 1 => try netasciiFor(.lf, input), else => try netasciiFor(.crlf, input), } } fn netasciiFor(comptime linesep: LineSeparator, input: []const u8) !void { // A child buffer of two bytes at least, since that is what the readers // need to see an escape whole; a reader buffer of none at all upwards; and // a step of at least one byte. const child_len = 2 + knob(input, 1) % 7; const buffer_len = knob(input, 2) % 8; const step = 1 + knob(input, 3) % 16; const text = after(input, 4); var child_buf: [8]u8 = undefined; var buffer: [8]u8 = undefined; // Encoding: the reader, trickled, agrees with the reader given everything // at once, and on the host with the function. const encoded = encoded: { var whole: Io.Reader = .fixed(text); var reference: netascii._EncodeReader(linesep) = .init(&whole, &.{}); const expected = try readAll(&reference.interface, std.math.maxInt(usize)); errdefer backing.free(expected); var trickle: Trickle = .init(text, child_buf[0..child_len], step); var encoder: netascii._EncodeReader(linesep) = .init(&trickle.interface, buffer[0..buffer_len]); const got = try readAll(&encoder.interface, step); defer backing.free(got); try testing.expectEqualStrings(expected, got); if (linesep == host) { var function_input: Io.Reader = .fixed(text); var function_output: Io.Writer.Allocating = .init(backing); defer function_output.deinit(); try netascii.encode(&function_input, &function_output.writer); try testing.expectEqualStrings(expected, function_output.written()); } break :encoded expected; }; defer backing.free(encoded); // What encoding produces is always netascii, and decodes. Under `.lf` it // decodes to exactly what was encoded; under the others a lone LF comes // back as a line ending, so the property is that a second round trip // changes nothing more. { const once = try roundTrip(linesep, text); defer backing.free(once); if (linesep == .lf) try testing.expectEqualStrings(text, once); const twice = try roundTrip(linesep, once); defer backing.free(twice); try testing.expectEqualStrings(once, twice); } // Decoding arbitrary input: the reader, trickled, and the writer, fed in // steps, agree on whether it is netascii and on what it decodes to, and on // the host so does the function. var trickle: Trickle = .init(text, child_buf[0..child_len], step); var reader: netascii._DecodeReader(linesep) = .init(&trickle.interface, buffer[0..buffer_len]); const read_result = readAll(&reader.interface, step); defer if (read_result) |bytes| backing.free(bytes) else |_| {}; if (read_result) |_| { try testing.expectEqual(null, reader.err); } else |err| { try testing.expectEqual(error.ReadFailed, err); try testing.expectEqual(error.UnescapedCR, reader.err.?); } var written: Io.Writer.Allocating = .init(backing); defer written.deinit(); var decoder_buf: [8]u8 = undefined; var decoder: netascii._Decoder(linesep) = .init(&written.writer, decoder_buf[0..child_len]); const write_result = write: { var rest = text; while (rest.len > 0) { const n = @min(step, rest.len); decoder.interface.writeAll(rest[0..n]) catch |err| break :write err; rest = rest[n..]; } decoder.interface.flush() catch |err| break :write err; }; if (read_result) |bytes| { try write_result; try testing.expectEqualStrings(bytes, written.written()); } else |_| { try testing.expectError(error.WriteFailed, write_result); try testing.expectEqual(error.UnescapedCR, decoder.err.?); } if (linesep == host) { var function_input: Io.Reader = .fixed(text); var function_output: Io.Writer.Allocating = .init(backing); defer function_output.deinit(); const function_result = netascii.decode(&function_input, &function_output.writer); if (read_result) |bytes| { _ = try function_result; try testing.expectEqualStrings(bytes, function_output.written()); } else |_| { try testing.expectError(error.UnescapedCR, function_result); } } } /// Encodes `text` and decodes it again, returning what comes back. fn roundTrip(comptime linesep: LineSeparator, text: []const u8) ![]u8 { var source: Io.Reader = .fixed(text); var encoder: netascii._EncodeReader(linesep) = .init(&source, &.{}); const encoded = try readAll(&encoder.interface, std.math.maxInt(usize)); defer backing.free(encoded); var wire: Io.Reader = .fixed(encoded); var decoder: netascii._DecodeReader(linesep) = .init(&wire, &.{}); return readAll(&decoder.interface, std.math.maxInt(usize)); } test "fuzz netascii" { for (netascii_seeds) |seed| try netasciiProperty(seed); try testing.fuzz({}, fuzzNetascii, .{}); } fn fuzzNetascii(_: void, smith: *Smith) !void { var buffer: [2048]u8 = undefined; const len = smith.slice(&buffer); try netasciiProperty(buffer[0..len]); } // -- whole transfers ------------------------------------------------------- /// An application serving one file and collecting another. const FuzzApp = struct { written: Io.Writer.Allocating, /// The client's address, which every request must report. client: Io.net.IpAddress = undefined, /// What every read is answered with: long enough to take several blocks /// at a small block size, with line endings for netascii to translate. const content = std.mem.asBytes(&@as([40][lines.len]u8, @splat(lines.*))); pub const Read = struct { interface: Io.Reader, pub fn reader(self: *Read, _: Io, _: Allocator) !*Io.Reader { return &self.interface; } pub fn size(self: *Read, _: Io) ?u64 { return self.interface.buffer.len; } pub fn deinit(_: *Read, _: Io, _: Allocator) void {} }; pub fn readFrom(self: *const FuzzApp, _: Io, _: Allocator, request: tftp.Request) !Read { if (!request.remote.eql(&self.client)) return error.WrongRemote; if (std.mem.startsWith(u8, request.filename, "missing")) return error.FileNotFound; return .{ .interface = .fixed(content) }; } pub const Write = struct { app: *FuzzApp, pub fn writer(self: *Write, _: Io, _: Allocator) !*Io.Writer { return &self.app.written.writer; } pub fn reserve(_: *Write, _: Io, size: u64) !void { if (size > 4096) return error.NoSpaceLeft; } pub fn finish(_: *Write, _: Io) !void {} pub fn deinit(_: *Write, _: Io, _: Allocator) void {} }; pub fn writeTo(self: *FuzzApp, _: Io, _: Allocator, request: tftp.Request) !Write { if (!request.remote.eql(&self.client)) return error.WrongRemote; if (std.mem.startsWith(u8, request.filename, "denied")) return error.PermissionDenied; return .{ .app = self }; } }; /// A request built from knob bytes: a read or a write, in a mode, of a file, /// with some set of options. Built rather than taken whole from the input, /// since a request that does not decode goes no further and the `packets` /// target already covers decoding. const SessionRequest = struct { write: bool, mode: Packet.Mode, filename: []const u8, options: Packet.Options, const knobs = 6; const filenames = [_][]const u8{ "f", "missing", "denied", "" }; // Seven and 65465 are out of range, and are ignored rather than refused. const requested_blocksizes = [_]u16{ 8, 9, 512, 7, 65464, 65465 }; // 5000 is more than `FuzzApp.Write.reserve` accepts. const sizes = [_]u64{ 0, 5, 5000 }; fn init(input: []const u8) SessionRequest { const option_bits = knob(input, 3); return .{ .write = knob(input, 0) % 2 == 1, .mode = switch (knob(input, 1) % 3) { 0 => .octet, 1 => .netascii, else => .mail, }, .filename = filenames[knob(input, 2) % filenames.len], .options = .{ .blocksize = if (option_bits & 1 != 0) requested_blocksizes[knob(input, 4) % requested_blocksizes.len] else null, .timeout = if (option_bits & 2 != 0) 1 else null, .transfer_size = if (option_bits & 4 != 0) sizes[knob(input, 5) % sizes.len] else null, }, }; } /// The request as a datagram. Options are written raw, so that an out of /// range one reaches the server as a client would send it. fn encode(self: SessionRequest, buf: []u8) ![]const u8 { var w: Io.Writer = .fixed(buf); try w.writeInt(u16, if (self.write) 2 else 1, .big); try w.print("{s}\x00{t}\x00", .{ self.filename, self.mode }); if (self.options.blocksize) |b| try w.print("blksize\x00{d}\x00", .{b}); if (self.options.timeout) |t| try w.print("timeout\x00{d}\x00", .{t}); if (self.options.transfer_size) |t| try w.print("tsize\x00{d}\x00", .{t}); return w.buffered(); } /// The block size the server will use: the requested one if it is in /// range, and 512 otherwise. fn blocksize(self: SessionRequest) u16 { const b = self.options.blocksize orelse return 512; return if (b >= 8 and b <= 65464) b else 512; } /// Whether the application refuses the request outright. fn refused(self: SessionRequest) bool { if (std.mem.startsWith(u8, self.filename, "missing") and !self.write) return true; if (std.mem.startsWith(u8, self.filename, "denied") and self.write) return true; if (self.write) if (self.options.transfer_size) |size| return size > 4096; return false; } }; /// One packet of the client's script. const Op = union(enum) { ack: u16, data: struct { block: u16, payload: []const u8 }, /// Bytes sent as they are, which may or may not be a packet. raw: []const u8, err, fn encode(self: Op, mode: Packet.Mode, buf: []u8) ![]const u8 { const packet: Packet = switch (self) { .ack => |block| .{ .ack = .{ .block = block } }, .data => |d| .{ .data = .{ .block = d.block, .mode = mode, .data = d.payload } }, .raw => |bytes| return bytes, .err => .{ .err = .{ .code = .not_defined, .msg = "script" } }, }; return packet.encode(buf); } }; /// The client's script, decoded from the input an operation at a time. /// /// Every byte sequence is a script: the first byte of each operation chooses /// its kind modulo the number of kinds, and the bytes after it its fields. A /// mutation therefore changes one operation rather than, as a length prefix /// would, shifting every one after it into nonsense. /// /// Two of the kinds follow the transfer rather than naming a block: the next /// ACK in sequence, and a full block of DATA in sequence. A block number drawn /// from the input is almost never the one the server is waiting for, and /// without these a script would rarely get past the first block. const Script = struct { rest: []const u8, blocksize: u16, /// The last block acknowledged or sent in sequence. acked: u16 = 0, sent: u16 = 0, /// Room for a full block of DATA, filled with one byte. fill: [1024]u8 = undefined, fn init(bytes: []const u8, blocksize: u16) Script { return .{ .rest = bytes, .blocksize = blocksize }; } /// The next operation, or null at the end of the script. fn next(self: *Script) ?Op { if (self.rest.len == 0) return null; switch (self.take() % 6) { 0 => return .{ .ack = self.take() }, 1 => { const block = self.take(); const len = @min(self.take() % 24, self.rest.len); defer self.rest = self.rest[len..]; return .{ .data = .{ .block = block, .payload = self.rest[0..len] } }; }, 2 => { const len = @min(self.take() % 16, self.rest.len); defer self.rest = self.rest[len..]; return .{ .raw = self.rest[0..len] }; }, 3 => { self.acked +%= 1; return .{ .ack = self.acked }; }, 4 => { // A full block, unless blocks are too big to be worth filling, // when it is the short one that ends the transfer. self.sent +%= 1; const byte = self.take(); const len = if (self.blocksize <= self.fill.len) self.blocksize else byte % 24; @memset(self.fill[0..len], byte); return .{ .data = .{ .block = self.sent, .payload = self.fill[0..len] } }; }, else => return .err, } } fn take(self: *Script) u8 { const byte = knob(self.rest, 0); self.rest = after(self.rest, 1); return byte; } }; /// Builds a session seed from its knobs and its operations. fn session(comptime knobs: []const u8, comptime ops: []const u8) []const u8 { return knobs ++ ops; } // Knobs: write, mode, filename, option bits, block size, size. Then the // script: 0 is ACK n, 1 is DATA n with a length and payload, 2 is raw bytes // with a length, 3 is the next ACK, 4 is the next full block of DATA filled // with a byte, and 5 is an ERROR. const session_seeds = [_][]const u8{ // Reads. session("\x00\x00\x00\x00\x00\x00", "\x00\x01\x00\x02"), session("\x00\x01\x00\x01\x00\x00", "\x00\x00\x00\x01\x00\x01\x00\x02\x00\x03"), session("\x00\x00\x00\x07\x00\x00", "\x00\x00\x00\x01\x00\x05"), session("\x00\x00\x01\x00\x00\x00", "\x00\x01"), session("\x00\x00\x00\x00\x00\x00", "\x02\x02\x00\x09\x00\x01"), session("\x00\x00\x00\x01\x00\x00", "\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03"), session("\x00\x01\x00\x01\x00\x00", "\x03\x03\x03\x00\x02\x03\x03\x03\x03\x03\x03\x03"), // Writes. session("\x01\x00\x00\x00\x00\x00", "\x01\x01\x05hello"), session("\x01\x00\x00\x01\x00\x00", "\x01\x01\x0812345678\x01\x01\x0812345678\x01\x02\x03abc\x01\x02\x03abc"), session("\x01\x01\x00\x00\x00\x00", "\x01\x01\x03a\rb"), session("\x01\x00\x00\x04\x00\x01", "\x01\x01\x05hello"), session("\x01\x00\x00\x04\x00\x02", "\x01\x01\x01x"), session("\x01\x00\x00\x01\x00\x00", "\x01\x01\x09123456789"), session("\x01\x00\x02\x00\x00\x00", "\x01\x01\x01x"), session("\x01\x00\x00\x01\x00\x00", "\x01\x01\x0812345678\x00\x01\x01\x02\x01x"), session("\x01\x00\x00\x01\x00\x00", "\x04a\x04b\x04c\x04d\x01\x05\x02ef"), session("\x01\x00\x00\x01\x01\x00", "\x04a\x04b\x04b\x01\x02\x09xxxxxxxxx\x04c\x01\x04\x00"), session("\x01\x01\x00\x01\x00\x00", "\x04\r\x04\n\x04a\x01\x04\x00"), "", }; /// A whole transfer, driven by whatever a client sends. /// /// The input is a request, built from its first bytes, and then a script of /// packets the client sends once the server has answered the request. The /// client does not wait for the server between packets, and ends with an /// ERROR so that a transfer the script left in the middle is not waited out. /// /// The properties are the ones a server owes to any client: that it does not /// crash, leak or hang whatever it is sent, that everything it sends back is a /// well formed packet, and, in octet mode, that it sends the right bytes and /// writes the right bytes. fn sessionProperty(input: []const u8) !void { const io = session_io; const Server = tftp.Server(FuzzApp); const request: SessionRequest = .init(input); var app: FuzzApp = .{ .written = .init(backing) }; defer app.written.deinit(); const loopback = try Io.net.IpAddress.parseLiteral("127.0.0.1:0"); var server: Server = .init(&app, loopback); const client = try loopback.bind(io, .{ .mode = .dgram, .protocol = .udp }); defer client.close(io); app.client = client.address; // The server takes ownership of the request. var request_buf: [128]u8 = undefined; const datagram = try backing.dupe(u8, try request.encode(&request_buf)); var future = io.concurrent(Server.handleIncomingMessage, .{ &server, io, backing, loopback, loopback, client.address, datagram }) catch |err| { backing.free(datagram); return err; }; defer future.cancel(io) catch {}; // Every request is answered, if only with an ERROR, and that answer comes // from the transfer's own port, which is where the rest of the script // goes. var message_buf: Packet.Buffer = undefined; const first = try client.receiveTimeout(io, &message_buf, .{ .duration = .{ .clock = .awake, .raw = .fromSeconds(5) }, }); const transfer = first.from; try expectWellFormed(request, first.data); var script: Script = .init(after(input, SessionRequest.knobs), request.blocksize()); var packet_buf: Packet.Buffer = undefined; while (script.next()) |op| try client.send(io, &transfer, try op.encode(request.mode, &packet_buf)); try client.send(io, &transfer, try Op.encode(.err, request.mode, &packet_buf)); try future.await(io); // Whatever else the server said. It has finished, so anything it sent is // already waiting. while (true) { const message = client.receiveTimeout(io, &message_buf, .{ .duration = .{ .clock = .awake, .raw = .fromMilliseconds(1) }, }) catch |err| switch (err) { error.Timeout => break, else => |e| return e, }; try expectWellFormed(request, message.data); } if (request.write and request.mode == .octet) { const expected = try expectedWrite(request, after(input, SessionRequest.knobs)); defer backing.free(expected); try testing.expectEqualStrings(expected, app.written.written()); } } /// What a correct server writes for `script`, up to the first operation whose /// effect is not certain: raw bytes might be any packet at all, and an ACK or /// an ERROR ends a write. Up to there, the server has acted on every packet in /// order, since the loopback interface neither drops nor reorders them. fn expectedWrite(request: SessionRequest, script_bytes: []const u8) ![]u8 { var out: std.ArrayList(u8) = .empty; errdefer out.deinit(backing); if (request.refused()) return out.toOwnedSlice(backing); const blocksize = request.blocksize(); var block: u16 = 0; var script: Script = .init(script_bytes, blocksize); while (script.next()) |op| switch (op) { .data => |d| { // Longer than a block is an illegal operation, which ends it. if (d.payload.len > blocksize) break; if (d.block != block +% 1) continue; try out.appendSlice(backing, d.payload); block = d.block; if (d.payload.len < blocksize) break; }, .ack, .raw, .err => break, }; return out.toOwnedSlice(backing); } /// Everything a server sends must decode, whatever it was sent, and in octet /// mode every block of a read must be the right part of the file. fn expectWellFormed(request: SessionRequest, datagram: []const u8) !void { const buf = try backing.create(Packet.Buffer); defer backing.destroy(buf); const packet = try Packet.decode(datagram, buf, .{ .mode = request.mode, .blocksize = 65464 }); if (request.write or request.mode != .octet or packet != .data) return; const blocksize = request.blocksize(); const start = @min(@as(usize, packet.data.block -| 1) * blocksize, FuzzApp.content.len); const end = @min(start + blocksize, FuzzApp.content.len); try testing.expectEqualStrings(FuzzApp.content[start..end], packet.data.data); } test "fuzz whole transfers" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); session_io = threaded.io(); // A failed transfer is logged, and failing is most of what these do. testing.log_level = .err; defer testing.log_level = .warn; for (session_seeds) |seed| try sessionProperty(seed); try testing.fuzz({}, fuzzSession, .{}); } fn fuzzSession(_: void, smith: *Smith) !void { var buffer: [2048]u8 = undefined; const len = smith.slice(&buffer); try sessionProperty(buffer[0..len]); } // -- the client ------------------------------------------------------------ /// A client's request, built from knob bytes: a `get` or a `put`, in a mode, /// asking for some set of options, and for a `put`, a file of some length. const ClientRequest = struct { put: bool, mode: Packet.Mode, blocksize: ?u16, timeout: ?u8, size: bool, /// What a `put` uploads. content: []const u8, const knobs = 5; const requested_blocksizes = [_]u16{ 8, 512, 1428, 65464 }; const lengths = [_]usize{ 0, 5, 512, 1000, 3000 }; /// What a `put` uploads a prefix of: long enough for several blocks at a /// small size, with line endings for netascii to translate. const text = std.mem.asBytes(&@as([160][lines.len]u8, @splat(lines.*)))[0..3000]; fn init(input: []const u8) ClientRequest { const bits = knob(input, 2); return .{ .put = knob(input, 0) % 2 == 1, .mode = switch (knob(input, 1) % 3) { 0 => .octet, 1 => .netascii, else => .mail, }, .blocksize = if (bits & 1 != 0) requested_blocksizes[knob(input, 3) % requested_blocksizes.len] else null, .timeout = if (bits & 2 != 0) 1 else null, .size = bits & 4 != 0, .content = text[0..lengths[knob(input, 4) % lengths.len]], }; } /// The size of the blocks the script sends in sequence: what was asked /// for, or the default. The server is the script, so it may send blocks /// of a size the client never agreed to, which is part of the point. fn blocksize_(self: ClientRequest) u16 { return self.blocksize orelse 512; } }; /// One packet of a scripted server, and where it comes from. const ServerOp = struct { packet: union(enum) { packet: Packet, raw: []const u8 }, /// Whether it comes from a port that is not the transfer's. stray: bool = false, }; /// A scripted server, decoded from the input an operation at a time, the /// mirror of `Script`: every byte sequence is a script, and two kinds follow /// the transfer rather than naming a block. /// /// Those two follow the direction as well. To a client uploading, the next /// thing in sequence is an ACK; to one downloading, it is a block of DATA, a /// full one or the short one that ends the file. Kinds that ignore the /// direction would spend half of every script on packets the client has to /// refuse, and the transfer would seldom get far enough to test anything. const ServerScript = struct { rest: []const u8, blocksize: u16, mode: Packet.Mode, /// Whether the client is uploading. put: bool, /// The next ACK in sequence, from zero, and the last DATA sent in /// sequence. acked: u16 = 0, sent: u16 = 0, fill: [1024]u8 = undefined, const oack_blocksizes = [_]u16{ 8, 512, 1024, 1428, 65464, 7 }; const oack_sizes = [_]u64{ 0, 5, 3000, std.math.maxInt(u64) }; fn next(self: *ServerScript) ?ServerOp { if (self.rest.len == 0) return null; switch (self.take() % 8) { 0 => return .{ .packet = .{ .packet = .{ .ack = .{ .block = self.take() } } } }, 1 => { const block = self.take(); const len = @min(self.take() % 24, self.rest.len); defer self.rest = self.rest[len..]; return .{ .packet = .{ .packet = .{ .data = .{ .block = block, .mode = self.mode, .data = self.rest[0..len] } } } }; }, 2 => { const len = @min(self.take() % 16, self.rest.len); defer self.rest = self.rest[len..]; return .{ .packet = .{ .raw = self.rest[0..len] } }; }, // The next thing in sequence, and the last: the next ACK either // way to an upload, and to a download a full block, or a short // one. 3, 4 => |kind| { if (self.put) { defer self.acked +%= 1; return .{ .packet = .{ .packet = .{ .ack = .{ .block = self.acked } } } }; } self.sent +%= 1; const byte = self.take(); const len = if (kind == 3 and self.blocksize <= self.fill.len) self.blocksize else byte % 24; @memset(self.fill[0..len], byte); return .{ .packet = .{ .packet = .{ .data = .{ .block = self.sent, .mode = self.mode, .data = self.fill[0..len] } } } }; }, 5 => { const flags = self.take(); var options: Packet.Options = .{}; if (flags & 1 != 0) options.blocksize = oack_blocksizes[self.take() % oack_blocksizes.len]; if (flags & 2 != 0) options.timeout = 1 + self.take() % 2; if (flags & 4 != 0) options.transfer_size = oack_sizes[self.take() % oack_sizes.len]; return .{ .packet = .{ .packet = .{ .oack = .{ .options = options } } } }; }, 6 => return .{ .packet = .{ .packet = .{ .err = .{ .code = @fromBackingInt(@intCast(self.take() % 9)), .msg = "script" } } } }, else => return .{ .packet = .{ .packet = .{ .ack = .{ .block = self.take() } } }, .stray = true }, } } fn take(self: *ServerScript) u8 { const byte = knob(self.rest, 0); self.rest = after(self.rest, 1); return byte; } }; // Knobs: put, mode, option bits (1 block size, 2 timeout, 4 size), block // size, length. Then the server's script: 0 is ACK n, 1 is DATA n with a // length and payload, 2 is raw bytes, 3 is the next in sequence (an ACK to a // put, a full block filled with a byte to a get), 4 is the same but a short // block to a get, 5 is an OACK, 6 is an ERROR, and 7 is an ACK from another // port. const client_seeds = [_][]const u8{ // Gets. session("\x00\x00\x00\x00\x00", "\x03a\x01\x02\x03xyz"), session("\x00\x00\x01\x00\x00", "\x05\x01\x00\x03a\x03b\x01\x03\x02zz"), session("\x00\x00\x01\x00\x00", "\x05\x01\x01\x03a"), session("\x00\x00\x05\x01\x00", "\x05\x05\x01\x02\x03a\x01\x02\x00"), session("\x00\x00\x01\x02\x00", "\x01\x01\x05short"), session("\x00\x00\x00\x00\x00", "\x05\x01\x01"), session("\x00\x00\x00\x00\x00", "\x06\x01"), session("\x00\x01\x00\x00\x00", "\x01\x01\x03a\rb"), session("\x00\x01\x00\x00\x00", "\x01\x01\x06a\r\nb\r\x00"), session("\x00\x00\x00\x00\x00", "\x03a\x07\x01\x01\x02\x01x"), session("\x00\x00\x00\x00\x00", "\x03a\x03a\x01\x01\x09aaaaaaaaa\x01\x02\x00"), session("\x00\x00\x00\x00\x00", "\x02\x04\x00\x09\x00\x01"), session("\x00\x00\x00\x00\x00", "\x03a\x03b\x03c\x03d\x03e\x03f\x04\x05"), session("\x00\x00\x01\x00\x00", "\x05\x01\x00\x03a\x03b\x03c\x03d\x03e\x03f\x03g\x03h\x03i\x04\x03"), // Puts. session("\x01\x00\x00\x00\x01", "\x03\x03"), session("\x01\x00\x00\x00\x03", "\x03\x03\x00\x01\x03\x03"), session("\x01\x00\x05\x00\x02", "\x05\x05\x00\x01\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03"), session("\x01\x01\x00\x00\x03", "\x03\x03\x03\x03"), session("\x01\x00\x01\x01\x01", "\x03\x03"), session("\x01\x00\x01\x00\x01", "\x05\x01\x03\x03"), session("\x01\x00\x00\x00\x01", "\x06\x03"), "", }; /// A whole transfer from the client's side, against a server made of /// whatever the input says. /// /// The client sends its request to a listening socket, and the script is /// answered from a socket of its own, as a server would, and then an ERROR /// ends whatever the script left in the middle. A stray from a third socket /// is only ever sent once the transfer's own port has spoken, since the /// first answer from the server's host is the one the client locks onto. /// /// The properties are what a client owes any server: that it does not /// crash, leak or hang, that everything it sends is a well formed packet, /// and that when it reports success it tells the truth: a `put` has sent the /// whole file, and an octet `get` has written as many bytes as it says. fn clientProperty(input: []const u8) !void { const io = session_io; const request: ClientRequest = .init(input); const loopback = try Io.net.IpAddress.parseLiteral("127.0.0.1:0"); const listener = try loopback.bind(io, .{ .mode = .dgram, .protocol = .udp }); defer listener.close(io); const server = try loopback.bind(io, .{ .mode = .dgram, .protocol = .udp }); defer server.close(io); const stray = try loopback.bind(io, .{ .mode = .dgram, .protocol = .udp }); defer stray.close(io); var written: Io.Writer.Allocating = .init(backing); defer written.deinit(); var source: Io.Reader = .fixed(request.content); var future = try io.concurrent(runClient, .{ io, listener.address, request, &written.writer, &source }); defer _ = future.cancel(io) catch {}; // The request, which is where the answers go. var message_buf: Packet.Buffer = undefined; const first = try listener.receiveTimeout(io, &message_buf, .{ .duration = .{ .clock = .awake, .raw = .fromSeconds(5) }, }); try expectClientPacket(request, first.data); const client = first.from; var script: ServerScript = .{ .rest = after(input, ClientRequest.knobs), .blocksize = request.blocksize_(), .mode = request.mode, .put = request.put, }; var spoken = false; var packet_buf: Packet.Buffer = undefined; while (script.next()) |op| { if (op.stray and !spoken) continue; const bytes = switch (op.packet) { .packet => |p| try p.encode(&packet_buf), .raw => |r| r, }; try (if (op.stray) stray else server).send(io, &client, bytes); if (!op.stray) spoken = true; } const end: Packet = .{ .err = .{ .code = .not_defined, .msg = "end of script" } }; try server.send(io, &client, try end.encode(&packet_buf)); const result = future.await(io); // Everything the client sent, wherever it went. for ([_]Io.net.Socket{ listener, server, stray }) |socket| while (true) { const message = socket.receiveTimeout(io, &message_buf, .{ .duration = .{ .clock = .awake, .raw = .fromMilliseconds(1) }, }) catch |err| switch (err) { error.Timeout => break, else => |e| return e, }; try expectClientPacket(request, message.data); }; const outcome = result catch return; if (request.put) { // Success means every block was acknowledged, so all of it went. if (request.mode == .octet) try testing.expectEqual(request.content.len, outcome.bytes); } else if (request.mode == .octet) { try testing.expectEqual(written.written().len, outcome.bytes); } } fn runClient( io: Io, server: Io.net.IpAddress, request: ClientRequest, writer: *Io.Writer, reader: *Io.Reader, ) anyerror!tftp.Client.Result { const client: tftp.Client = .init(server); if (request.put) return client.put(io, "fuzz", reader, .{ .mode = request.mode, .blocksize = request.blocksize, .timeout = request.timeout, .size = if (request.size) request.content.len else null, }); return client.get(io, "fuzz", writer, .{ .mode = request.mode, .blocksize = request.blocksize, .timeout = request.timeout, .size = request.size, }); } /// Everything a client sends must decode. fn expectClientPacket(request: ClientRequest, datagram: []const u8) !void { const buf = try backing.create(Packet.Buffer); defer backing.destroy(buf); _ = try Packet.decode(datagram, buf, .{ .mode = request.mode, .blocksize = 65464 }); } test "fuzz the client" { var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); session_io = threaded.io(); testing.log_level = .err; defer testing.log_level = .warn; for (client_seeds) |seed| try clientProperty(seed); try testing.fuzz({}, fuzzClient, .{}); } fn fuzzClient(_: void, smith: *Smith) !void { var buffer: [2048]u8 = undefined; const len = smith.slice(&buffer); try clientProperty(buffer[0..len]); } // -- the same targets, for a driver that is not the test runner ------------- /// One fuzz target, addressable by name. /// /// `zig build test` reaches these through the `test` blocks above and Zig's /// own fuzzer would reach them through `std.testing.fuzz`. This is the third /// way in, for `tools/fuzz.zig`. pub const Target = struct { name: []const u8, run: *const fn (input: []const u8) anyerror!void, /// Inputs worth mutating: the same seeds the tests above run, which are /// what stands in for the coverage feedback a real fuzzer would have. 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. content_max: usize, }; /// Wraps one of the `fuzz*` functions above so that it takes raw bytes. 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 = "packets", .run = Driven(fuzzPacket).run, .corpus = &packet_seeds, .content_max = packet_max }, .{ .name = "options", .run = Driven(fuzzOptions).run, .corpus = &option_seeds, .content_max = 1024 }, .{ .name = "netascii", .run = Driven(fuzzNetascii).run, .corpus = &netascii_seeds, .content_max = 2048 }, .{ .name = "session", .run = Driven(fuzzSession).run, .corpus = &session_seeds, .content_max = 2048 }, .{ .name = "client", .run = Driven(fuzzClient).run, .corpus = &client_seeds, .content_max = 2048 }, };