// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What the decoders must do with a datagram nobody wrote. //! //! Everything here is a property rather than an example: not "these bytes are //! that message" -- the unit tests have those, and one of them is net-snmp's //! own output -- but "whatever arrives, the parser terminates, stays inside //! its buffer, frees what it allocated, and if it claims to have understood //! the input then writing it back out and reading it again gives the same //! answer". //! //! That last part is the one worth having. Round-tripping is what catches a //! decoder and an encoder that have drifted apart, and in SNMP it is load //! bearing beyond tidiness: SNMPv3 computes an HMAC over the octets of the //! message, so if a message has two encodings then "the message" is not a //! well-defined thing to authenticate. The encoder must emit exactly one //! spelling and the decoder must accept exactly that one. //! //! SNMP is also a *datagram* protocol, which makes the threat model blunter //! than a stream protocol's: anyone who can reach the port can deliver 65507 //! arbitrary bytes with a forged source address, and there is no handshake //! before it. Every length in here is attacker-controlled, so every //! allocation driven by one is bounded, and the version field decides how the //! rest is read -- which is why the version is fuzzed rather than fixed. 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 snmp = @import("snmp"); const asn1 = snmp.asn1; const ObjectId = snmp.ObjectId; const Message = snmp.protocol.Message; const Pdu = snmp.Pdu; const Value = snmp.Value; const VarBind = snmp.VarBind; const Version = snmp.Version; const Mibs = snmp.Mibs; /// 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; // -- whole messages --------------------------------------------------------- /// net-snmp's own GetRequest, which is the seed worth having: a mutated real /// message reaches parts of the decoder that random bytes never will. const netsnmp_v2c_get = "\x30\x29" ++ "\x02\x01\x01" ++ "\x04\x06public" ++ "\xa0\x1c" ++ "\x02\x04\x01\xbd\x03\x11" ++ "\x02\x01\x00" ++ "\x02\x01\x00" ++ "\x30\x0e\x30\x0c" ++ "\x06\x08\x2b\x06\x01\x02\x01\x01\x01\x00" ++ "\x05\x00"; /// And the v3 engine-discovery request, also captured from net-snmp. Its /// wrapper is not implemented yet, so what this asserts today is that the /// decoder says so rather than misreading it -- which is exactly the property /// that must keep holding once v3 lands. const netsnmp_v3_discovery = "\x30\x3e" ++ "\x02\x01\x03" ++ "\x30\x11\x02\x04\x68\xbc\xf4\xc5\x02\x03\x00\xff\xe3\x04\x01\x04\x02\x01\x03" ++ "\x04\x10\x30\x0e\x04\x00\x02\x01\x00\x02\x01\x00\x04\x00\x04\x00\x04\x00" ++ "\x30\x14\x04\x00\x04\x00" ++ "\xa0\x0e\x02\x04\x6d\x77\x05\x81\x02\x01\x00\x02\x01\x00\x30\x00"; const message_seeds = [_][]const u8{ netsnmp_v2c_get, netsnmp_v3_discovery, // The same request at v1, which is one byte different. "\x30\x29\x02\x01\x00\x04\x06public\xa0\x1c\x02\x04\x01\xbd\x03\x11\x02\x01\x00\x02\x01\x00\x30\x0e\x30\x0c\x06\x08\x2b\x06\x01\x02\x01\x01\x01\x00\x05\x00", // A response carrying each of the interesting value types. "\x30\x1e\x02\x01\x01\x04\x06public\xa2\x11\x02\x01\x01\x02\x01\x00\x02\x01\x00\x30\x06\x30\x04\x06\x01\x2b\x05\x00", // Versions nobody defines, and the one that is known but unsupported. "\x30\x29\x02\x01\x02\x04\x06public\xa0\x1c\x02\x04\x01\xbd\x03\x11\x02\x01\x00\x02\x01\x00\x30\x0e\x30\x0c\x06\x08\x2b\x06\x01\x02\x01\x01\x01\x00\x05\x00", "\x30\x05\x02\x01\x7f\x04\x00", // Empty community, and no PDU at all. "\x30\x05\x02\x01\x01\x04\x00", // An outer length that lies, in both directions. "\x30\x7f\x02\x01\x01", "\x30\x00", "\x30\x84\x7f\xff\xff\xff", // The indefinite form, which these rules forbid. "\x30\x80", // Two messages in one datagram. netsnmp_v2c_get ++ netsnmp_v2c_get, // Nothing at all. "", "\x00", }; /// Whatever the datagram is: decoding terminates, and anything that decodes /// re-encodes to the identical bytes. fn messageProperty(input: []const u8) !void { var m = Message.decode(input, backing) catch return; defer m.deinit(backing); // A community-based message's community points into the input rather than // being copied, and must be a real subslice of it. const community = m.body.community.community; if (community.len != 0) { const offset = @intFromPtr(community.ptr) - @intFromPtr(input.ptr); try testing.expect(offset + community.len <= input.len); } // The version decides what is legal inside, so whatever came back must be // consistent with it. const version = m.version(); try testing.expect(version.isCommunityBased()); const p = m.pdu(); if (p.kind == .trap_v1) try testing.expect(version.hasV1Trap()); switch (p.kind) { .get_bulk_request, .inform_request, .snmpv2_trap, .report => { try testing.expect(version.hasBulkAndInform()); }, else => {}, } for (p.varBinds()) |vb| { try testing.expect(vb.name.len >= ObjectId.min_len); switch (vb.value.data) { .counter64 => try testing.expect(version.hasCounter64()), .no_such_object, .no_such_instance, .end_of_mib_view => { try testing.expect(version.hasExceptions()); }, else => {}, } } // The round trip. A decoded message must re-encode to exactly what it was // read from, or "the octets of the message" is ambiguous -- and SNMPv3 // authenticates exactly those octets. const again = try m.encodeAlloc(backing); defer backing.free(again); try testing.expectEqualSlices(u8, input, again); // And reading it a second time must agree with the first. var twice = try Message.decode(again, backing); defer twice.deinit(backing); try testing.expectEqual(version, twice.version()); try testing.expectEqual(p.kind, twice.pdu().kind); try testing.expectEqual(p.requestId(), twice.pdu().requestId()); try testing.expectEqual(p.varBinds().len, twice.pdu().varBinds().len); } test "fuzz messages" { for (message_seeds) |seed| try messageProperty(seed); try testing.fuzz({}, fuzzMessage, .{}); } fn fuzzMessage(_: void, smith: *Smith) !void { var buffer: [4096]u8 = undefined; const len = smith.slice(&buffer); try messageProperty(buffer[0..len]); } // -- a PDU on its own ------------------------------------------------------- const pdu_seeds = [_][]const u8{ // One of each kind, minimally. "\xa0\x0b\x02\x01\x01\x02\x01\x00\x02\x01\x00\x30\x00", "\xa1\x0b\x02\x01\x01\x02\x01\x00\x02\x01\x00\x30\x00", "\xa2\x0b\x02\x01\x01\x02\x01\x00\x02\x01\x00\x30\x00", "\xa3\x0b\x02\x01\x01\x02\x01\x00\x02\x01\x00\x30\x00", // GetBulk, whose middle two integers are unsigned where the others are // an error status and an index. "\xa5\x0b\x02\x01\x07\x02\x01\x00\x02\x01\x0a\x30\x00", // And a GetBulk with a negative in a slot that cannot hold one. "\xa5\x0b\x02\x01\x07\x02\x01\xff\x02\x01\x0a\x30\x00", // The v1 trap, which is a different structure entirely. "\xa4\x1f\x06\x06\x2b\x06\x01\x04\x01\x09\x40\x04\x7f\x00\x00\x01\x02\x01\x02\x02\x01\x00\x43\x04\x01\xb3\xfc\xc3\x30\x00", // Tags that are no PDU: [9], and the wrong class. "\xa9\x00", "\x60\x00", "\x30\x00", // A varbind list claiming more than is there. "\xa0\x05\x02\x01\x01\x30\x7f", "", }; fn pduProperty(input: []const u8) !void { // The version matters here, so try each -- a PDU legal in one is not // legal in another, and that rule is what this is checking. for ([_]Version{ .v1, .v2c }) |version| { var d: asn1.Decoder = .init(input); const el = d.next() catch continue; var p = Pdu.decode(el, version, backing) catch continue; defer p.deinit(backing); if (p.kind == .trap_v1) { try testing.expect(version.hasV1Trap()); try testing.expectEqual(@as(?i32, null), p.requestId()); } else { try testing.expect(p.requestId() != null); } try testing.expect(p.varBinds().len <= Pdu.max_bindings); var e: asn1.Encoder = .init(backing); defer e.deinit(); try p.encode(&e); try testing.expectEqualSlices(u8, input[0..e.buffered().len], e.buffered()); } } test "fuzz pdus" { for (pdu_seeds) |seed| try pduProperty(seed); try testing.fuzz({}, fuzzPdu, .{}); } fn fuzzPdu(_: void, smith: *Smith) !void { var buffer: [2048]u8 = undefined; const len = smith.slice(&buffer); try pduProperty(buffer[0..len]); } // -- a single value --------------------------------------------------------- const value_seeds = [_][]const u8{ "\x02\x01\x2a", // INTEGER 42 "\x02\x05\x01\x02\x03\x04\x05", // INTEGER too wide for i32 "\x04\x03abc", // OCTET STRING "\x05\x00", // NULL "\x05\x01\x00", // NULL with content "\x06\x08\x2b\x06\x01\x02\x01\x01\x01\x00", // OID "\x40\x04\xc0\xa8\x04\x40", // IpAddress 192.168.4.64 "\x40\x03\x01\x02\x03", // IpAddress of the wrong length "\x41\x03\x02\x26\x53", // Counter32 "\x41\x05\x00\xff\xff\xff\xff", // Counter32 at the top of its range "\x41\x01\xff", // Counter32 that is negative "\x42\x02\x03\xe8", // Gauge32 "\x43\x04\x01\xb3\xfc\xc3", // TimeTicks, the switch's uptime "\x44\x02\x01\x02", // Opaque "\x46\x09\x00\xff\xff\xff\xff\xff\xff\xff\xff", // Counter64 at the top "\x45\x00", // APPLICATION 5, which SMIv2 removed "\x80\x00", // noSuchObject "\x81\x00", // noSuchInstance "\x82\x00", // endOfMibView "\x83\x00", // CONTEXT 3, undefined "\x80\x01\x00", // an exception carrying something "", }; fn valueProperty(input: []const u8) !void { var d: asn1.Decoder = .init(input); const el = d.next() catch return; for ([_]Version{ .v1, .v2c }) |version| { const value = Value.decode(el, version) catch continue; // A version 1 message can carry none of the four types SNMPv2 added. switch (value.data) { .counter64 => try testing.expect(version.hasCounter64()), .no_such_object, .no_such_instance, .end_of_mib_view => { try testing.expect(version.hasExceptions()); }, else => {}, } // The tag the value reports is the tag it was read under. try testing.expect(value.tag().eql(el.tag)); // Re-encoding gives the identical element. var e: asn1.Encoder = .init(backing); defer e.deinit(); try value.encode(&e); try testing.expectEqualSlices(u8, input[0..e.buffered().len], e.buffered()); // And rendering it never fails and never runs off its buffer. The // longest thing a value prints is a 128-arc OID or a long string, so // the buffer is sized for the worst case rather than the usual one. var printed: [4096]u8 = undefined; var w: Io.Writer = .fixed(&printed); // A 4096-byte OCTET STRING renders to more than 4096 bytes as hex, so // running out of room is this buffer being too small rather than a // bug -- what is being checked is that nothing panics or writes past // the end. w.print("{f}", .{value}) catch {}; } } test "fuzz values" { for (value_seeds) |seed| try valueProperty(seed); try testing.fuzz({}, fuzzValue, .{}); } fn fuzzValue(_: void, smith: *Smith) !void { var buffer: [1024]u8 = undefined; const len = smith.slice(&buffer); try valueProperty(buffer[0..len]); } // -- a variable binding ----------------------------------------------------- const varbind_seeds = [_][]const u8{ "\x30\x0c\x06\x08\x2b\x06\x01\x02\x01\x01\x01\x00\x05\x00", // A binding with a third field, which the definition has no room for. "\x30\x0e\x06\x08\x2b\x06\x01\x02\x01\x01\x01\x00\x05\x00\x05\x00", // A binding with no value. "\x30\x0a\x06\x08\x2b\x06\x01\x02\x01\x01\x01\x00", // A name that is not an OID. "\x30\x04\x02\x01\x01\x05\x00", // A sparse instance index, as the Catalyst's interfaces are numbered. "\x30\x11\x06\x0b\x2b\x06\x01\x02\x01\x02\x02\x01\x02\xce\x75\x04\x02hi", "\x30\x00", "", }; fn varBindProperty(input: []const u8) !void { var d: asn1.Decoder = .init(input); const el = d.next() catch return; const vb = VarBind.decode(el, .v2c) catch return; try testing.expect(vb.name.len >= ObjectId.min_len); try testing.expect(vb.name.len <= ObjectId.max_len); // A name is its own prefix and orders equal to itself, whatever it is. try testing.expect(vb.name.startsWith(vb.name)); try testing.expectEqual(std.math.Order.eq, vb.name.order(vb.name)); var e: asn1.Encoder = .init(backing); defer e.deinit(); try vb.encode(&e); try testing.expectEqualSlices(u8, input[0..e.buffered().len], e.buffered()); } test "fuzz varbinds" { for (varbind_seeds) |seed| try varBindProperty(seed); try testing.fuzz({}, fuzzVarBind, .{}); } fn fuzzVarBind(_: void, smith: *Smith) !void { var buffer: [1024]u8 = undefined; const len = smith.slice(&buffer); try varBindProperty(buffer[0..len]); } // -- the table the standalone driver reads ---------------------------------- pub const Target = struct { name: []const u8, run: *const fn (input: []const u8) anyerror!void, corpus: []const []const u8, /// The buffer this target reads its input into. /// /// `Smith.slice` yields an *empty* slice for a length larger than the /// buffer rather than a truncated one, so a generator that does not know /// this number hands the target nothing at all most of the time and /// reports millions of iterations having tested the empty string. content_max: usize, flavor: Flavor = .binary, pub const Flavor = enum { text, binary }; }; // -- OIDs as a person types them -------------------------------------------- /// A MIB with the shapes that matter: a spine, a scalar, a table column, and /// a name that is also a prefix of another name. const test_mib = \\FUZZ-MIB DEFINITIONS ::= BEGIN \\org OBJECT IDENTIFIER ::= { iso 3 } \\dod OBJECT IDENTIFIER ::= { org 6 } \\internet OBJECT IDENTIFIER ::= { dod 1 } \\mgmt OBJECT IDENTIFIER ::= { internet 2 } \\mib-2 OBJECT IDENTIFIER ::= { mgmt 1 } \\system OBJECT IDENTIFIER ::= { mib-2 1 } \\sysDescr OBJECT-TYPE \\ SYNTAX OCTET STRING \\ MAX-ACCESS read-only \\ STATUS current \\ ::= { system 1 } \\sysDescrExtra OBJECT-TYPE \\ SYNTAX OCTET STRING \\ MAX-ACCESS read-only \\ STATUS current \\ ::= { system 99 } \\END ; const oid_text_seeds = [_][]const u8{ // The forms a person types, which is what this parser is for. "1.3.6.1.2.1.1.1.0", ".1.3.6.1.2.1.1.1.0", "sysDescr.0", ".sysDescr.0", "FUZZ-MIB::sysDescr.0", "system.1.0", ".iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0", // A name that is a prefix of another, in both orders. "sysDescr", "sysDescrExtra", // Shapes that are nearly one of the above. "", ".", "..", "1..2", "::", "::sysDescr", "sysDescr::", "FUZZ-MIB::", "-1", "1.-1", "4294967295", "4294967296", "1.4294967296", "0.0", "2.999", "3.1", // A hundred and twenty-nine arcs, one past the limit RFC 3416 sets: // ".1" a hundred and twenty-seven times, which with `**` gone from the // language is a splat of two-byte arrays laid end to end. "1.3" ++ @as([254]u8, @bitCast(@as([127][2]u8, @splat(".1".*)))), }; /// Whatever the text is: parsing terminates, and it either yields an OID that /// is well formed and writes back out to something this same parser reads as /// the same OID, or it is refused. /// /// The round trip is the part worth having. `Mibs.name` is what a person sees /// and `Mibs.parse` is what they type back in, so a spelling this prints and /// cannot read is a real defect --- `-Of` output pasted into the next command /// is exactly that loop. fn oidTextProperty(mibs: *const Mibs, text: []const u8) !void { const oid = mibs.parse(text) catch |err| switch (err) { error.UnknownName, error.BadOid => return, }; // Well formed: RFC 3416 caps an OID at 128 sub-identifiers, and BER needs // at least two to pack the first arc into one. const subs = oid.slice(); try testing.expect(subs.len >= 2); try testing.expect(subs.len <= ObjectId.max_len); try testing.expect(subs[0] <= 2); if (subs[0] < 2) try testing.expect(subs[1] < 40); // Every style writes something this reads back as the same OID. for ([_]Mibs.Style{ .numeric, .module, .short, .full }) |style| { var buffer: [4096]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try mibs.name(oid, style, &w); const printed = w.buffered(); const again = mibs.parse(printed) catch |err| { std.debug.print( "\n {s} printed as {t} is \"{s}\", which will not parse: {t}\n", .{ text, style, printed, err }, ); return error.PrintedFormDoesNotParse; }; if (!again.eql(oid)) { std.debug.print( "\n {s} printed as {t} is \"{s}\", which reads back as a different OID\n", .{ text, style, printed }, ); return error.RoundTripChangedTheOid; } } } test "fuzz OID text" { var mibs: Mibs = .init(backing); defer mibs.deinit(); try mibs.addSource(test_mib); _ = try mibs.resolve(); var empty: Mibs = .init(backing); defer empty.deinit(); for (oid_text_seeds) |seed| { try oidTextProperty(&mibs, seed); // With nothing loaded every name is unknown, which must be a refusal // rather than a different answer. try oidTextProperty(&empty, seed); } try testing.fuzz(&mibs, fuzzOidText, .{}); } fn fuzzOidText(mibs: *Mibs, smith: *Smith) !void { var buffer: [512]u8 = undefined; const len = smith.slice(&buffer); try oidTextProperty(mibs, buffer[0..len]); } /// The standalone driver has no `testing.fuzz`, so it reaches the target /// through here. /// /// The MIBs are built and thrown away per input rather than kept, which looks /// wasteful and is not optional: `tools/fuzz.zig` counts outstanding /// allocations after *every* input, so anything held across them is reported /// as a leak on all of them. Parsing twenty lines of MIB is microseconds, and /// an honest leak check is worth more than those. fn oidTextRun(input: []const u8) anyerror!void { var mibs: Mibs = .init(backing); defer mibs.deinit(); try mibs.addSource(test_mib); _ = try mibs.resolve(); var smith: Smith = .{ .in = input }; return fuzzOidText(&mibs, &smith); } 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 = "messages", .run = Driven(fuzzMessage).run, .corpus = &message_seeds, .content_max = 4096, }, .{ .name = "pdus", .run = Driven(fuzzPdu).run, .corpus = &pdu_seeds, .content_max = 2048, }, .{ .name = "values", .run = Driven(fuzzValue).run, .corpus = &value_seeds, .content_max = 1024, }, .{ .name = "varbinds", .run = Driven(fuzzVarBind).run, .corpus = &varbind_seeds, .content_max = 1024, }, .{ .name = "v3", .run = Driven(fuzzV3).run, .corpus = &v3_seeds, .content_max = 4096, }, .{ .name = "seal", .run = Driven(fuzzSeal).run, .corpus = &v3_seeds, .content_max = 4096, }, .{ .name = "privacy", .run = Driven(fuzzPrivacy).run, .corpus = &v3_seeds, .content_max = 2048, }, .{ .name = "oid-text", .run = oidTextRun, .corpus = &oid_text_seeds, .content_max = 512, }, .{ .name = "usm-params", .run = Driven(fuzzUsmParams).run, .corpus = &usm_params_seeds, .content_max = 1024, }, }; // -- version 3 messages ------------------------------------------------------ const V3 = snmp.protocol.V3; const usm = snmp.usm; /// net-snmp's own engine-discovery request, and mutations of it. A real /// message is the seed worth having: it reaches parts of the decoder random /// bytes never will, and the v3 wrapper has four nested levels for a mutation /// to land in. const v3_seeds = [_][]const u8{ netsnmp_v3_discovery, // An authenticated message, with a twelve-octet digest field. "\x30\x51\x02\x01\x03\x30\x11\x02\x04\x00\x00\x00\x07\x02\x03\x00\xff\xe3" ++ "\x04\x01\x05\x02\x01\x03" ++ "\x04\x23\x30\x21\x04\x07\x80\x00\x1f\x88\x01\x02\x03\x02\x01\x03\x02\x02\x30\x39" ++ "\x04\x07someone\x04\x0c123456789012\x04\x00" ++ "\x30\x14\x04\x00\x04\x00\xa0\x0e\x02\x04\x00\x00\x00\x07\x02\x01\x00\x02\x01\x00\x30\x00", // Privacy claimed with a plaintext body, and the reverse. "\x30\x3e\x02\x01\x03\x30\x11\x02\x04\x68\xbc\xf4\xc5\x02\x03\x00\xff\xe3" ++ "\x04\x01\x07\x02\x01\x03\x04\x10\x30\x0e\x04\x00\x02\x01\x00\x02\x01\x00" ++ "\x04\x00\x04\x00\x04\x00\x30\x14\x04\x00\x04\x00\xa0\x0e\x02\x04\x6d\x77" ++ "\x05\x81\x02\x01\x00\x02\x01\x00\x30\x00", // Privacy without authentication, which RFC 3412 forbids. "\x30\x3e\x02\x01\x03\x30\x11\x02\x04\x68\xbc\xf4\xc5\x02\x03\x00\xff\xe3" ++ "\x04\x01\x02\x02\x01\x03\x04\x10\x30\x0e\x04\x00\x02\x01\x00\x02\x01\x00" ++ "\x04\x00\x04\x00\x04\x00\x30\x14\x04\x00\x04\x00\xa0\x0e\x02\x04\x6d\x77" ++ "\x05\x81\x02\x01\x00\x02\x01\x00\x30\x00", // A Report, which is what a USM failure comes back as. "\x30\x3f\x02\x01\x03\x30\x11\x02\x04\x00\x00\x00\x01\x02\x03\x00\xff\xe3" ++ "\x04\x01\x00\x02\x01\x03\x04\x10\x30\x0e\x04\x00\x02\x01\x00\x02\x01\x00" ++ "\x04\x00\x04\x00\x04\x00\x30\x15\x04\x00\x04\x00\xa8\x0f\x02\x01\x01" ++ "\x02\x01\x00\x02\x01\x00\x30\x04\x30\x02\x06\x00", // msgFlags of the wrong length, and msgMaxSize below the floor. "\x30\x0c\x02\x01\x03\x30\x07\x02\x01\x01\x02\x01\x01\x04\x00", // Truncated everywhere. "\x30\x05\x02\x01\x03\x30\x00", "\x30\x03\x02\x01\x03", "", }; /// Whatever the datagram is: decoding terminates, and anything that decodes /// re-encodes to the identical bytes. fn v3Property(input: []const u8) !void { var m = V3.decode(input, backing) catch return; defer if (m.scoped) |*s| s.pdu.deinit(backing); // The invariants the decoder promises. try testing.expect(m.header.flags.isValid()); try testing.expect(m.header.max_size >= V3.min_max_size); try testing.expectEqual(V3.security_model_usm, m.header.security_model); try testing.expect(m.parameters.engine_boots >= 0); try testing.expect(m.parameters.engine_time >= 0); try testing.expect(m.parameters.user_name.len <= V3.Parameters.max_user_name); // The privacy flag and the shape of the body must agree, which is the // check that stops a peer presenting ciphertext as plaintext. try testing.expectEqual(m.header.flags.priv, m.scoped == null); // Everything borrowed must really be a subslice of the input. for ([_][]const u8{ m.parameters.engine_id, m.parameters.user_name, m.parameters.auth_parameters, m.parameters.privacy_parameters, m.encrypted, }) |borrowed| { if (borrowed.len == 0) continue; const offset = @intFromPtr(borrowed.ptr) - @intFromPtr(input.ptr); try testing.expect(offset + borrowed.len <= input.len); } // Round trip. Same argument as for the v1/v2c messages, and it matters // more here: SNMPv3 authenticates the octets of the message, so a message // with two encodings would have two valid digests. var e: asn1.Encoder = .init(backing); defer e.deinit(); const body: V3.Body = if (m.scoped) |s| .{ .plaintext = s } else .{ .encrypted = m.encrypted }; try V3.encode(&e, m.header, m.parameters, body); try testing.expectEqualSlices(u8, input, e.buffered()); // And the digest field must be findable in what we just wrote -- or // sealing would write somewhere else. const rewritten = try backing.dupe(u8, e.buffered()); defer backing.free(rewritten); if (V3.locateAuthParameters(rewritten)) |field| { try testing.expectEqual(m.parameters.auth_parameters.len, field.len); if (field.len != 0) { try testing.expectEqualSlices(u8, m.parameters.auth_parameters, field); } } } test "fuzz v3" { for (v3_seeds) |seed| try v3Property(seed); try testing.fuzz({}, fuzzV3, .{}); } fn fuzzV3(_: void, smith: *Smith) !void { var buffer: [4096]u8 = undefined; const len = smith.slice(&buffer); try v3Property(buffer[0..len]); } // -- sealing and checking ---------------------------------------------------- /// Sealing then checking is the identity, and a message that has been sealed /// must not verify under any other key -- for whatever the message is. fn sealProperty(input: []const u8) !void { // The message has to be structurally valid to have a digest field at all, // so anything else is nothing to test. var m = V3.decode(input, backing) catch return; defer if (m.scoped) |*s| s.pdu.deinit(backing); const protocol: usm.AuthProtocol = switch (m.parameters.auth_parameters.len) { 12 => .hmac_md5_96, 16 => .hmac_sha224_128, 24 => .hmac_sha256_192, 32 => .hmac_sha384_256, 48 => .hmac_sha512_384, else => return, }; const key: [usm.AuthProtocol.max_key_length]u8 = @splat(0x5a); const message = try backing.dupe(u8, input); defer backing.free(message); V3.seal(message, protocol, key[0..protocol.keyLength()]) catch return; // Sealing is idempotent: it zeroes the field first, so a second seal // digests the same bytes rather than a message containing the first // digest. const once = try backing.dupe(u8, message); defer backing.free(once); try V3.seal(message, protocol, key[0..protocol.keyLength()]); try testing.expectEqualSlices(u8, once, message); // What was sealed verifies. { const scratch = try backing.dupe(u8, message); defer backing.free(scratch); try testing.expect(V3.checkAuth(scratch, protocol, key[0..protocol.keyLength()])); } // And does not under a different key. { const other: [usm.AuthProtocol.max_key_length]u8 = @splat(0xa5); const scratch = try backing.dupe(u8, message); defer backing.free(scratch); try testing.expect(!V3.checkAuth(scratch, protocol, other[0..protocol.keyLength()])); } // Nor after a single bit anywhere in the message changes. Picking the // last octet rather than sweeping, because the message may be large and // this runs on every input. { const scratch = try backing.dupe(u8, message); defer backing.free(scratch); scratch[scratch.len - 1] ^= 1; try testing.expect(!V3.checkAuth(scratch, protocol, key[0..protocol.keyLength()])); } } test "fuzz seal" { for (v3_seeds) |seed| try sealProperty(seed); try testing.fuzz({}, fuzzSeal, .{}); } fn fuzzSeal(_: void, smith: *Smith) !void { var buffer: [4096]u8 = undefined; const len = smith.slice(&buffer); try sealProperty(buffer[0..len]); } // -- privacy ----------------------------------------------------------------- /// Both privacy protocols: encrypt then decrypt is the identity, for any key, /// salt and length -- which is where a mode with a final partial block goes /// wrong, and a scoped PDU is whatever length it happens to be. fn privacyProperty(input: []const u8) !void { const key_len = 16; if (input.len < key_len + 8) return; const key = input[0..key_len]; const salt: usm.Salt = .{ .bytes = input[key_len..][0..8].* }; const plaintext = input[key_len + 8 ..]; if (plaintext.len == 0 or plaintext.len > 2048) return; // AES-CFB needs no padding, so the ciphertext is exactly as long. { var buffer: [2048]u8 = undefined; const ciphertext = usm.Aes.encrypt(key, 1, 12345, salt, plaintext, &buffer); try testing.expectEqual(plaintext.len, ciphertext.len); var back: [2048]u8 = undefined; const decrypted = usm.Aes.decrypt(key, 1, 12345, salt, ciphertext, &back); try testing.expectEqualSlices(u8, plaintext, decrypted); // The IV is boots || time || salt, so a different time is a different // keystream. That is a real v3 failure mode after a resynchronisation, // not a hypothetical one. const wrong = usm.Aes.decrypt(key, 1, 12346, salt, ciphertext, &back); if (plaintext.len >= 16) try testing.expect(!std.mem.eql(u8, plaintext, wrong)); } // DES-CBC pads to a block, and the padding comes back: a receiver finds // the real end from the BER length inside rather than from a scheme. { var buffer: [2048 + 8]u8 = undefined; const ciphertext = usm.Des.encrypt(key, salt, plaintext, &buffer); try testing.expectEqual(usm.Des.paddedLength(plaintext.len), ciphertext.len); try testing.expectEqual(@as(usize, 0), ciphertext.len % 8); var back: [2048 + 8]u8 = undefined; const decrypted = try usm.Des.decrypt(key, salt, ciphertext, &back); try testing.expectEqualSlices(u8, plaintext, decrypted[0..plaintext.len]); // A ciphertext that is not whole blocks was not made by this mode. if (ciphertext.len > 1) { try testing.expectError( error.NotBlockAligned, usm.Des.decrypt(key, salt, ciphertext[0 .. ciphertext.len - 1], &back), ); } } } test "fuzz privacy" { for (v3_seeds) |seed| try privacyProperty(seed); try testing.fuzz({}, fuzzPrivacy, .{}); } fn fuzzPrivacy(_: void, smith: *Smith) !void { var buffer: [2048]u8 = undefined; const len = smith.slice(&buffer); try privacyProperty(buffer[0..len]); } // -- the USM security parameters on their own -------------------------------- const usm_params_seeds = [_][]const u8{ "\x30\x0e\x04\x00\x02\x01\x00\x02\x01\x00\x04\x00\x04\x00\x04\x00", "\x30\x21\x04\x07\x80\x00\x1f\x88\x01\x02\x03\x02\x01\x03\x02\x02\x30\x39" ++ "\x04\x07someone\x04\x0c123456789012\x04\x00", // Negative boots and time, which would break the window arithmetic. "\x30\x0e\x04\x00\x02\x01\xff\x02\x01\x00\x04\x00\x04\x00\x04\x00", "\x30\x0e\x04\x00\x02\x01\x00\x02\x01\xff\x04\x00\x04\x00\x04\x00", // A user name longer than the 32 octets the ASN.1 allows. "\x30\x30\x04\x00\x02\x01\x00\x02\x01\x00\x04\x21" ++ @as([33]u8, @splat('x')) ++ "\x04\x00\x04\x00", "\x30\x00", "", }; fn usmParamsProperty(input: []const u8) !void { const p = V3.Parameters.decode(input) catch return; try testing.expect(p.engine_boots >= 0); try testing.expect(p.engine_time >= 0); try testing.expect(p.user_name.len <= V3.Parameters.max_user_name); var e: asn1.Encoder = .init(backing); defer e.deinit(); try p.encode(&e); try testing.expectEqualSlices(u8, input, e.buffered()); } test "fuzz usm parameters" { for (usm_params_seeds) |seed| try usmParamsProperty(seed); try testing.fuzz({}, fuzzUsmParams, .{}); } fn fuzzUsmParams(_: void, smith: *Smith) !void { var buffer: [1024]u8 = undefined; const len = smith.slice(&buffer); try usmParamsProperty(buffer[0..len]); }