Something went wrong. Try again.
A reader for SNMP MIB modules: SMIv1 and SMIv2, in Zig.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What the lexer must do with a file nobody wrote.//!//! MIB modules arrive from vendors, out of tarballs and web pages and support//! tickets, and three of the 2,852 in the corpus this was built against are//! already malformed enough that net-snmp refuses them. So the property that//! matters is not that a broken file parses -- it must not -- but that a//! broken file **terminates**: a lexer that can loop is a tool that hangs on//! whatever a vendor sends, and the person holding it has no idea why.//!//! Everything here is a property rather than an example. The unit tests carry//! the examples, and several of them are reductions of real files.
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 smi = @import("smi");const Lexer = smi.Lexer;const Parser = smi.Parser;const Clauses = smi.clauses;const DisplayHint = smi.DisplayHint;const Token = smi.Token;
/// What the parser allocates its arena from. The lexer allocates nothing, so/// this existed unused until there was a parser target.pub var backing: Allocator = if (builtin.is_test) testing.allocator else undefined;
const seeds = [_][]const u8{ "IF-MIB DEFINITIONS ::= BEGIN\nIMPORTS ifIndex FROM RFC1213-MIB;\nEND", "mib-2 OBJECT IDENTIFIER ::= { mgmt 1 }", "ifEntry OBJECT-TYPE\n SYNTAX IfEntry\n MAX-ACCESS not-accessible\n STATUS current\n INDEX { ifIndex }\n ::= { ifTable 1 }", // The comment rule, both ways round. "SYNTAX INTEGER -- a comment -- (0..255)", "-- ------------------------------------------------\nEND", "-- unterminated", // Strings: multi-line, doubled quotes, and never closed. "DESCRIPTION \"one\ntwo \"\"quoted\"\" three\"", "\"never closed", // The quoted radix forms, and one without a radix. "'0A1B'H '1010'B 'xyz'", // Identifiers at their edges. "mib-2 IF-MIB dot11_6ghz abc- _leading", // The three real malformed files, reduced. "DESCRIPTION \"something\".\nREVISION \"202009020000Z\"", "DESCRIPTION \"a maximum of 32Gbit.\"\n fiftyG (14) - 50GBit.", "END\n</PRE></BODY></HTML>", // Punctuation that nearly means something. ":", "::", "::=", ".", "..", "...", "|", ";", "",};
/// Whatever the bytes are: lexing terminates, every token is inside the/// source, and the tokens tile it without overlapping or skipping backwards.fn lexProperty(source: []const u8, options: Lexer.Options) !void { var l: Lexer = .init(source, options); var previous_end: usize = 0; var count: usize = 0;
while (true) { const t = l.next(); if (t.tag == .end_of_file) { // The end token sits at the end and is empty. try testing.expect(t.start == t.end); try testing.expect(t.end <= source.len); break; }
// Inside the source, non-empty, and forwards. A token that did not // advance is the shape an infinite loop takes. try testing.expect(t.start < t.end); try testing.expect(t.end <= source.len); try testing.expect(t.start >= previous_end); previous_end = t.end;
// The text is a real subslice, so a diagnostic can quote it. const text = t.text(source); try testing.expectEqual(t.end - t.start, text.len);
// A keyword's text really is one, and a reference's first character // really does decide which it is -- that distinction is what the // parser reads to tell a type from a value. switch (t.tag) { .keyword => try testing.expect(Lexer.keywords.has(text)), .type_reference => { try testing.expect(std.ascii.isUpper(text[0])); try testing.expect(!Lexer.keywords.has(text)); }, .value_reference => { try testing.expect(std.ascii.isLower(text[0])); try testing.expect(!Lexer.keywords.has(text)); }, .string => { try testing.expect(text.len >= 2); try testing.expect(text[0] == '"' and text[text.len - 1] == '"'); }, .hex_string, .binary_string => { try testing.expect(text.len >= 3); try testing.expect(text[0] == '\''); }, .number => for (text, 0..) |c, i| { try testing.expect((c >= '0' and c <= '9') or (i == 0 and c == '-')); }, else => {}, }
count += 1; // A token is at least one byte, so there cannot be more tokens than // bytes. Exceeding that means `next` returned without consuming. if (count > source.len) return error.LexerDidNotAdvance; }}
test "fuzz lexer" { for (seeds) |seed| { try lexProperty(seed, .{}); // Both readings of the comment rule, and both of the underscore // rule: each is a different path through `next`, and a file that // lexes under one may not under the other. try lexProperty(seed, .{ .double_hyphen_ends_comment = false }); try lexProperty(seed, .{ .allow_underscores = false }); try lexProperty(seed, .{ .double_hyphen_ends_comment = false, .allow_underscores = false, }); } try testing.fuzz({}, fuzzLexer, .{});}
fn fuzzLexer(_: void, smith: *Smith) !void { var buffer: [4096]u8 = undefined; const len = smith.slice(&buffer); const source = buffer[0..len]; try lexProperty(source, .{}); try lexProperty(source, .{ .double_hyphen_ends_comment = false }); try lexProperty(source, .{ .allow_underscores = false });}
// -- the parser -------------------------------------------------------------
/// Whole modules, because the parser's interesting failures are about where/// one assignment ends and the next begins, and that needs an assignment on/// either side to go wrong between.const module_seeds = [_][]const u8{ // The shape that silently dropped everything below it: a type assignment // immediately above a macro definition whose name is a keyword. It // parsed, reported no error, and lost two thirds of SNMPv2-SMI. \\SNMPv2-SMI DEFINITIONS ::= BEGIN \\ExtUTCTime ::= OCTET STRING(SIZE(11 | 13)) \\MODULE-IDENTITY MACRO ::= \\BEGIN \\ TYPE NOTATION ::= "LAST-UPDATED" value(Update ExtUTCTime) \\ Text ::= value(IA5String) \\END \\zeroDotZero OBJECT-IDENTITY \\ STATUS current \\ DESCRIPTION "A value used for null identifiers." \\ ::= { 0 0 } \\END , \\IF-MIB DEFINITIONS ::= BEGIN \\IMPORTS ifIndex, ifDescr FROM RFC1213-MIB \\ MODULE-IDENTITY, OBJECT-TYPE, Counter32 FROM SNMPv2-SMI; \\ifMIB MODULE-IDENTITY \\ LAST-UPDATED "200006140000Z" \\ ORGANIZATION "IETF" \\ ::= { mib-2 31 } \\ifEntry OBJECT-TYPE \\ SYNTAX IfEntry \\ MAX-ACCESS not-accessible \\ STATUS current \\ INDEX { ifIndex } \\ ::= { ifTable 1 } \\ifInOctets OBJECT-TYPE \\ SYNTAX Counter32 \\ DEFVAL { 0 } \\ ::= { ifEntry 10 } \\END , \\SNMPv2-TC DEFINITIONS ::= BEGIN \\TEXTUAL-CONVENTION MACRO ::= \\BEGIN \\ TYPE NOTATION ::= DisplayPart \\END \\DisplayString ::= TEXTUAL-CONVENTION \\ DISPLAY-HINT "255a" \\ STATUS current \\ DESCRIPTION "text" \\ SYNTAX OCTET STRING (SIZE (0..255)) \\END , \\M DEFINITIONS ::= BEGIN \\a OBJECT IDENTIFIER ::= { iso org(3) dod(6) 1 } \\b OBJECT IDENTIFIER ::= { a 2 } \\END , // Truncated, unbalanced, and never terminated: the three ways a real // file arrives broken. "M DEFINITIONS ::= BEGIN", "M DEFINITIONS ::= BEGIN x ::= { ( } END", "M DEFINITIONS ::= BEGIN x OBJECT IDENTIFIER ::= { iso 1 }", "",};
/// Whatever the bytes are: parsing terminates, and it either produces a/// module whose every string points into the source, or a diagnostic that/// points into the source. Never a hang, a crash, or a success holding a/// slice of something else.fn parseProperty(source: []const u8, options: Lexer.Options) !void { var arena: std.heap.ArenaAllocator = .init(backing); defer arena.deinit();
var diagnostic: ?Parser.Diagnostic = null; const module = Parser.parseWithDiagnostic(arena.allocator(), source, options, &diagnostic) catch |e| { switch (e) { // Nothing at all, which is a file and not a fault. error.NoModule => return, error.ParseFailed => { // A failure says where, and where is inside the source. The // line number is derived from the offset, so it has to be // computable without walking off the end. const d = diagnostic orelse return error.FailedWithoutDiagnostic; try testing.expect(d.offset <= source.len); try testing.expect(d.line(source) >= 1); return; }, else => return e, } };
try expectSubslice(source, module.name); for (module.imports) |import| { try expectSubslice(source, import.from); for (import.symbols) |symbol| try expectSubslice(source, symbol); } for (module.assignments) |a| { try expectSubslice(source, a.name); try testing.expect(a.offset <= source.len); try expectSubslice(source, a.body);
// `hasOid` is what the registry reads to decide whether to place an // assignment, so the two must not disagree: a kind that claims an OID // and has none would be placed as a node with no position. if (a.kind.hasOid()) try testing.expect(a.oid != null); if (a.oid) |parts| { try testing.expect(parts.len > 0); for (parts) |part| switch (part) { .number => {}, .name => |name| try expectSubslice(source, name), .named_number => |nn| try expectSubslice(source, nn.name), }; }
// Whatever is in the list is findable by name, which is the only // thing a caller does with a module. try testing.expect(module.find(a.name) != null);
// The clause pass, over the span the parser kept. It allocates, so an // input that makes it leak or run away is a finding here rather than // in whatever loads a vendor MIB. Everything it returns points into // the body, for the same reason the assignment's strings do. const c = try Clauses.parse(arena.allocator(), a.body, options); if (c.syntax) |syntax| try expectSubslice(source, syntax.name); if (c.display_hint) |hint| try expectSubslice(source, hint); if (c.description) |text| try expectSubslice(source, text); if (c.defval) |text| try expectSubslice(source, text); if (c.augments) |name| try expectSubslice(source, name); if (c.index) |columns| for (columns) |column| try expectSubslice(source, column.name); for (c.objects) |name| try expectSubslice(source, name); for (c.revisions) |revision| { try expectSubslice(source, revision.date); try expectSubslice(source, revision.description); } }}
/// That a string really points into `source`, rather than merely comparing/// equal to something in it. A parser that copied, or that handed back a/// slice of a temporary, would pass an equality check and dangle in use.fn expectSubslice(source: []const u8, text: []const u8) !void { if (text.len == 0) return; // `OCTET STRING` and `OBJECT IDENTIFIER` are two tokens in the file and // one name here, so their spelling is a literal rather than a slice of // the source. They are the only two. if (std.mem.eql(u8, text, "OCTET STRING")) return; if (std.mem.eql(u8, text, "OBJECT IDENTIFIER")) return; if (std.mem.eql(u8, text, "SEQUENCE OF")) return; const start = @intFromPtr(text.ptr); const base = @intFromPtr(source.ptr); try testing.expect(start >= base); try testing.expect(start + text.len <= base + source.len);}
test "fuzz parser" { for (module_seeds) |seed| { try parseProperty(seed, .{}); try parseProperty(seed, .{ .double_hyphen_ends_comment = false }); try parseProperty(seed, .{ .allow_underscores = false }); } // The lexer's seeds too: a fragment of a module is exactly the input the // parser is most likely to be lost in. for (seeds) |seed| try parseProperty(seed, .{}); try testing.fuzz({}, fuzzParser, .{});}
fn fuzzParser(_: void, smith: *Smith) !void { var buffer: [8192]u8 = undefined; const len = smith.slice(&buffer); const source = buffer[0..len]; try parseProperty(source, .{}); try parseProperty(source, .{ .double_hyphen_ends_comment = false });}
// -- display hints ----------------------------------------------------------
/// Every hint that appears in net-snmp's or Cisco's MIBs, plus the shapes/// that nearly are one.const hint_seeds = [_][]const u8{ "1x:", "255a", "d", "d-1", "d-2", "2x:", "1d.1d.1d.1d", "1d.1d.1d.1d%4d", "1d.1d.1d.1d:2d", "2d-1d-1d,1d:1d:1d.1d", "2d-1d-1d,1d:1d:1d.1d,1a1d:1d", "2x:2x:2x:2x:2x:2x:2x:2x", "2x:2x:2x:2x:2x:2x:2x:2x%4d", "*1x:/1x:", "255t", "1a", // Not hints, and each must be refused rather than half-read. "", "q", "1", "0x", "d-", "*", "*x", "1x:1", "999999999999d",};
/// A hint either parses and then renders anything without running away, or is/// refused. Rendering must terminate whatever the octets are: the pieces are/// reused when the octets outlast them, and a `*` count comes from the data/// itself, which is the shape a loop would take.fn hintProperty(text: []const u8, octets: []const u8) !void { var arena: std.heap.ArenaAllocator = .init(backing); defer arena.deinit();
var hint = DisplayHint.parse(arena.allocator(), text) catch |e| switch (e) { error.NotAHint => return, else => return e, }; defer hint.deinit(arena.allocator());
// Bounded so that a runaway is a failure rather than a hang. Two bytes of // output per octet is generous for every format but binary, which is // eight, so ten per octet plus the separators covers it. var buffer: [64 * 1024]u8 = undefined; var w: Io.Writer = .fixed(&buffer); hint.renderOctets(octets, &w) catch return error.HintRanAway;
var integer_buffer: [128]u8 = undefined; var iw: Io.Writer = .fixed(&integer_buffer); try hint.renderInteger(-1, &iw); iw = .fixed(&integer_buffer); try hint.renderInteger(std.math.maxInt(i64), &iw); iw = .fixed(&integer_buffer); try hint.renderInteger(std.math.minInt(i64), &iw);}
test "fuzz display hints" { for (hint_seeds) |seed| { try hintProperty(seed, ""); try hintProperty(seed, &.{ 0, 1, 2, 3, 4, 5, 6, 7, 8 }); try hintProperty(seed, "a string of characters"); // A leading count of 255 with nothing behind it, which is what a `*` // hint reads to decide how many repeats to do. try hintProperty(seed, &.{255}); } try testing.fuzz({}, fuzzHint, .{});}
fn fuzzHint(_: void, smith: *Smith) !void { var text_buffer: [64]u8 = undefined; var octet_buffer: [256]u8 = undefined; const text = smith.slice(&text_buffer); const octets = smith.slice(&octet_buffer); try hintProperty(text_buffer[0..text], octet_buffer[0..octets]);}
// -- the table the standalone driver reads ----------------------------------
pub const Target = struct { name: []const u8, run: *const fn (input: []const u8) anyerror!void, corpus: []const []const u8, /// The buffer this target reads its input into. /// /// `Smith.slice` yields an *empty* slice for a length larger than the /// buffer rather than a truncated one, so a generator that does not know /// this number hands the target nothing at all most of the time. content_max: usize, /// Which bytes the standalone driver mutates towards. flavor: Flavor,
pub const Flavor = enum { mib, hint };};
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 = "lexer", .run = Driven(fuzzLexer).run, .corpus = &seeds, .content_max = 4096, .flavor = .mib, }, .{ .name = "hint", .run = Driven(fuzzHint).run, .corpus = &hint_seeds, .content_max = 64, .flavor = .hint, }, .{ .name = "parser", .run = Driven(fuzzParser).run, .corpus = &module_seeds, .content_max = 8192, .flavor = .mib, },};