Something went wrong. Try again.
An SNMP manager library and command line tools for Zig, covering versions 1, 2c and 3.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The value half of a variable binding: SNMP's `ObjectSyntax`, which is an//! ASN.1 CHOICE over a dozen alternatives.//!//! Four of them are ordinary universal types and the rest are SNMP's own,//! tagged `[APPLICATION n]` or `[CONTEXT n]`. That is what makes SNMP's use of//! BER distinctive: `Counter32` and `Gauge32` are both a 32-bit unsigned//! integer and are different types, distinguishable only by their tag, because//! the difference is what the number *means* -- a counter wraps and only its//! difference is meaningful, a gauge is a level and its value is.//!//! ## What borrows and what does not//!//! `octet_string` and `@"opaque"` point into the datagram they were decoded//! from and are **not** copied, which is what makes decoding a walk's worth of//! replies free. They are valid for exactly as long as that buffer is. An//! `ObjectId` is a value and is copied, because it is fixed-size and a walk//! compares them constantly.//!//! ## Which values are legal when//!//! `counter64` arrived with SNMPv2 (RFC 1902) and the three exception markers//! with its PDU definitions (RFC 3416), so none of the four may appear in a//! version 1 message. An agent will not send them to a v1 request -- the//! Catalyst answers `noSuchName` where it would have sent a `Counter64` -- but//! a decoder cannot rely on the other end being well behaved, so `Version`//! carries the rule and `decode` takes one.
const std = @import("std");const Io = std.Io;const testing = std.testing;
const asn1 = @import("asn1");const z46 = @import("z46");const macaddress = @import("macaddress");
const ObjectId = asn1.ObjectId;const Version = @import("Version.zig").Version;
const Value = @This();
/// SNMP's `ObjectSyntax`. The field names are the SMIv2 type names in snake/// case, so that a reader with RFC 2578 open can find them.pub const Data = union(enum) { /// `Integer32`, and plain `INTEGER`: SNMP narrows both to 32 bits signed. integer: i32, /// Borrowed from the decoded buffer. octet_string: []const u8, /// What every varbind in a request carries, since a request says which /// object it wants and not what it is. null, object_id: ObjectId, /// Four octets, and not an OCTET STRING of four octets -- the tag differs. ip_address: z46.Ipv4Address, /// Wraps, and only its difference between two readings means anything. counter32: u32, /// Also `Unsigned32`: the same tag, and SMIv2 gives them the same /// encoding, so they cannot be told apart on the wire. gauge32: u32, /// Hundredths of a second since something the object's definition names. timeticks: u32, /// An encoding inside an encoding. Borrowed. @"opaque": []const u8, /// SNMPv2 and later only. counter64: u64, /// The object does not exist and never will on this agent. no_such_object, /// The object exists but this instance of it does not. no_such_instance, /// There is nothing after this OID in the view. How a walk ends. end_of_mib_view,};
data: Data,
pub const application = struct { pub const ip_address: asn1.Tag = .application(0, false); pub const counter32: asn1.Tag = .application(1, false); pub const gauge32: asn1.Tag = .application(2, false); pub const timeticks: asn1.Tag = .application(3, false); pub const @"opaque": asn1.Tag = .application(4, false); // 5 was `NsapAddress`, which SMIv2 removed. pub const counter64: asn1.Tag = .application(6, false);};
pub const exception = struct { pub const no_such_object: asn1.Tag = .context(0, false); pub const no_such_instance: asn1.Tag = .context(1, false); pub const end_of_mib_view: asn1.Tag = .context(2, false);};
pub const DecodeError = asn1.DecodeError || error{ /// A value this version of SNMP does not define: a `Counter64` or an /// exception marker in a version 1 message. WrongVersion,};
/// The tag this value is carried under.pub fn tag(v: Value) asn1.Tag { return switch (v.data) { .integer => .integer, .octet_string => .octet_string, .null => .null, .object_id => .object_identifier, .ip_address => application.ip_address, .counter32 => application.counter32, .gauge32 => application.gauge32, .timeticks => application.timeticks, .@"opaque" => application.@"opaque", .counter64 => application.counter64, .no_such_object => exception.no_such_object, .no_such_instance => exception.no_such_instance, .end_of_mib_view => exception.end_of_mib_view, };}
pub fn encode(v: Value, e: *asn1.Encoder) asn1.Encoder.Error!void { switch (v.data) { .integer => |n| try e.integerTagged(.integer, i32, n), .octet_string => |s| try e.primitive(.octet_string, s), .null => try e.null(), .object_id => |oid| try e.objectId(oid), // An IpAddress is its four octets in order, which is the one place // SNMP encodes an address as bytes rather than as a number. .ip_address => |a| try e.primitive(application.ip_address, &a.octets), .counter32 => |n| try e.integerTagged(application.counter32, u32, n), .gauge32 => |n| try e.integerTagged(application.gauge32, u32, n), .timeticks => |n| try e.integerTagged(application.timeticks, u32, n), .@"opaque" => |s| try e.primitive(application.@"opaque", s), .counter64 => |n| try e.integerTagged(application.counter64, u64, n), // The exceptions carry nothing: the tag is the whole message. .no_such_object, .no_such_instance, .end_of_mib_view, => try e.primitive(v.tag(), ""), }}
pub fn decode(el: asn1.Element, version: Version) DecodeError!Value { // Every type here is primitive, and RFC 3417 §2.1 says so: SNMP forbids // the constructed form of a simple type. Without this check a constructed // OCTET STRING -- `24 03 ...` where `04 03 ...` was meant -- decodes to // the same value and re-encodes to different bytes, which is a second // spelling of one message. The fuzzer's round-trip property is what // caught it, and the reason it matters is that SNMPv3 authenticates the // octets of the message and not its meaning. if (el.tag.constructed) return error.UnexpectedTag;
const data: Data = switch (el.tag.class) { .universal => switch (@as(asn1.Universal, @fromBackingInt(@intCast(el.tag.number)))) { .integer => .{ .integer = try el.integer(i32) }, .octet_string => .{ .octet_string = el.content }, .null => blk: { if (el.content.len != 0) return error.InvalidValue; break :blk .null; }, .object_identifier => .{ .object_id = try el.objectId() }, else => return error.UnexpectedTag, }, .application => switch (el.tag.number) { 0 => blk: { // Exactly four octets. A shorter one is what a buggy agent // sends and it must not be read as a number. if (el.content.len != 4) return error.InvalidValue; break :blk .{ .ip_address = .{ .octets = el.content[0..4].* } }; }, 1 => .{ .counter32 = try counter(u32, el.content) }, 2 => .{ .gauge32 = try counter(u32, el.content) }, 3 => .{ .timeticks = try counter(u32, el.content) }, 4 => .{ .@"opaque" = el.content }, 6 => blk: { if (!version.hasCounter64()) return error.WrongVersion; break :blk .{ .counter64 = try counter(u64, el.content) }; }, else => return error.UnexpectedTag, }, .context => blk: { if (!version.hasExceptions()) return error.WrongVersion; if (el.content.len != 0) return error.InvalidValue; break :blk switch (el.tag.number) { 0 => .no_such_object, 1 => .no_such_instance, 2 => .end_of_mib_view, else => return error.UnexpectedTag, }; }, .private => return error.UnexpectedTag, }; return .{ .data = data };}
/// The content of an unsigned application type.////// These are unsigned, so `asn1.decodeInteger` already refuses a negative --/// but the top of the range needs a leading zero octet to stay positive, so a/// `Counter32` of 0xffffffff is five octets and that is minimal rather than/// padded. Agents also differ here: some send a `Counter32` in four octets/// with the high bit set, which is a negative INTEGER by the encoding rules/// and is what `WrongVersion`'s neighbour `InvalidValue` is for.fn counter(comptime T: type, content: []const u8) DecodeError!T { return asn1.decodeInteger(T, content);}
/// Renders the value the way net-snmp's tools do, because the differential/// test runs both and compares the output.////// The type prefix is part of it -- `Counter32: 17` rather than `17` -- since/// two values of different types and the same number are different answers.pub fn format(v: Value, w: *Io.Writer) Io.Writer.Error!void { switch (v.data) { .integer => |n| try w.print("INTEGER: {d}", .{n}), .octet_string => |s| try formatOctetString(s, w), .null => try w.writeAll("\"\""), .object_id => |oid| try w.print("OID: {f}", .{oid}), .ip_address => |a| try w.print("IpAddress: {f}", .{a}), .counter32 => |n| try w.print("Counter32: {d}", .{n}), .gauge32 => |n| try w.print("Gauge32: {d}", .{n}), .timeticks => |n| try formatTimeticks(n, w), .@"opaque" => |s| { try w.writeAll("OPAQUE: "); try formatHex(s, w); }, .counter64 => |n| try w.print("Counter64: {d}", .{n}), .no_such_object => try w.writeAll("No Such Object available on this agent at this OID"), .no_such_instance => try w.writeAll("No Such Instance currently exists at this OID"), .end_of_mib_view => try w.writeAll("No more variables left in this MIB View"), }}
/// An OCTET STRING as `STRING:` when it looks like text and `Hex-STRING:`/// when it does not, which is net-snmp's heuristic.////// Note that a printable string may still contain newlines -- the Catalyst's/// `sysDescr` is four lines of IOS banner -- so one varbind is not one line of/// output, and anything comparing this output has to know that.fn formatOctetString(s: []const u8, w: *Io.Writer) Io.Writer.Error!void { if (isPrintable(s)) { try w.print("STRING: {s}", .{s}); } else { try w.writeAll("Hex-STRING: "); try formatHex(s, w); }}
/// Whether every octet is something a terminal can show. Tab, newline and/// carriage return count: a multi-line `sysDescr` is still text.fn isPrintable(s: []const u8) bool { for (s) |c| { if (c == '\t' or c == '\n' or c == '\r') continue; if (c < 0x20 or c >= 0x7f) return false; } return true;}
fn formatHex(s: []const u8, w: *Io.Writer) Io.Writer.Error!void { for (s, 0..) |byte, i| { if (i != 0) try w.writeByte(' '); try w.print("{X:0>2}", .{byte}); }}
/// `Timeticks: (28572867) 3 days, 7:22:08.67`, which is what net-snmp prints:/// the raw hundredths in parentheses and then the same thing for humans.fn formatTimeticks(hundredths: u32, w: *Io.Writer) Io.Writer.Error!void { const centiseconds = hundredths % 100; const total_seconds = hundredths / 100; const seconds = total_seconds % 60; const minutes = (total_seconds / 60) % 60; const hours = (total_seconds / 3600) % 24; const days = total_seconds / 86400;
try w.print("Timeticks: ({d}) ", .{hundredths}); if (days == 1) { try w.writeAll("1 day, "); } else if (days != 0) { try w.print("{d} days, ", .{days}); } try w.print("{d}:{d:0>2}:{d:0>2}.{d:0>2}", .{ hours, minutes, seconds, centiseconds });}
/// An OCTET STRING rendered as a MAC address, for the `PhysAddress` and/// `MacAddress` textual conventions.////// Not part of `format`, because whether six octets are an address or six/// octets is a question about the *object*, which lives in a MIB this library/// does not read. A caller who knows it is asking for `ifPhysAddress` can ask/// for this.pub fn asMacAddress(v: Value) ?macaddress.MacAddress { const s = switch (v.data) { .octet_string => |s| s, else => return null, }; if (s.len != 6) return null; // `MacAddress` holds a `u48`, and a MAC on the wire is most significant // octet first -- which is the order SNMP hands them over too. return .{ .data = std.mem.readInt(u48, s[0..6], .big) };}
// -- tests ------------------------------------------------------------------
fn expectRoundTrip(value: Value, version: Version, expected: []const u8) !void { var e: asn1.Encoder = .init(testing.allocator); defer e.deinit(); try value.encode(&e); try testing.expectEqualSlices(u8, expected, e.buffered());
var d: asn1.Decoder = .init(e.buffered()); const back = try Value.decode(try d.next(), version); try testing.expectEqual(std.meta.activeTag(value.data), std.meta.activeTag(back.data)); try d.expectEnd();}
test "the universal types" { try expectRoundTrip(.{ .data = .{ .integer = 42 } }, .v2c, &.{ 0x02, 0x01, 42 }); try expectRoundTrip(.{ .data = .{ .integer = -1 } }, .v2c, &.{ 0x02, 0x01, 0xff }); try expectRoundTrip(.{ .data = .{ .octet_string = "abc" } }, .v2c, "\x04\x03abc"); try expectRoundTrip(.{ .data = .null }, .v2c, &.{ 0x05, 0x00 }); try expectRoundTrip( .{ .data = .{ .object_id = try ObjectId.parse("1.3.6.1.2.1.1.1.0") } }, .v2c, &.{ 0x06, 0x08, 0x2b, 6, 1, 2, 1, 1, 1, 0 }, );}
test "the application types" { try expectRoundTrip( .{ .data = .{ .ip_address = .init(192, 168, 4, 64) } }, .v2c, &.{ 0x40, 0x04, 192, 168, 4, 64 }, ); try expectRoundTrip(.{ .data = .{ .counter32 = 140883 } }, .v2c, &.{ 0x41, 0x03, 0x02, 0x26, 0x53 }); try expectRoundTrip(.{ .data = .{ .gauge32 = 1000 } }, .v2c, &.{ 0x42, 0x02, 0x03, 0xe8 }); try expectRoundTrip(.{ .data = .{ .timeticks = 28572867 } }, .v2c, &.{ 0x43, 0x04, 0x01, 0xb3, 0xfc, 0xc3 }); try expectRoundTrip(.{ .data = .{ .@"opaque" = "\x01\x02" } }, .v2c, &.{ 0x44, 0x02, 0x01, 0x02 }); try expectRoundTrip(.{ .data = .{ .counter64 = 140883 } }, .v2c, &.{ 0x46, 0x03, 0x02, 0x26, 0x53 });}
test "an unsigned value at the top of its range needs a leading zero" { // 0xffffffff is positive, so the encoding takes five octets to keep the // sign bit clear. That is minimal for an unsigned type, and a decoder // that rejected a leading zero outright would refuse a legal Counter32. try expectRoundTrip( .{ .data = .{ .counter32 = std.math.maxInt(u32) } }, .v2c, &.{ 0x41, 0x05, 0x00, 0xff, 0xff, 0xff, 0xff }, ); try expectRoundTrip( .{ .data = .{ .counter64 = std.math.maxInt(u64) } }, .v2c, &.{ 0x46, 0x09, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, );}
test "the exception markers carry nothing" { try expectRoundTrip(.{ .data = .no_such_object }, .v2c, &.{ 0x80, 0x00 }); try expectRoundTrip(.{ .data = .no_such_instance }, .v2c, &.{ 0x81, 0x00 }); try expectRoundTrip(.{ .data = .end_of_mib_view }, .v2c, &.{ 0x82, 0x00 });}
test "version 1 has neither Counter64 nor the exceptions" { // The Catalyst demonstrates this: ifHCInOctets is a Counter64 under v2c // and noSuchName under v1, from the same agent at the same OID. A v1 // decoder that accepted one would be inventing a value SNMPv1 cannot // express. for ([_][]const u8{ &.{ 0x46, 0x03, 0x02, 0x25, 0xd3 }, &.{ 0x80, 0x00 }, &.{ 0x81, 0x00 }, &.{ 0x82, 0x00 }, }) |bytes| { var d: asn1.Decoder = .init(bytes); const el = try d.next(); try testing.expectError(error.WrongVersion, Value.decode(el, .v1)); // And the same bytes are fine under v2c. _ = try Value.decode(el, .v2c); }}
test "content that is not the value its tag claims" { // A NULL with content, an IpAddress that is not four octets, and an // exception marker carrying something. for ([_][]const u8{ &.{ 0x05, 0x01, 0x00 }, &.{ 0x40, 0x03, 1, 2, 3 }, &.{ 0x40, 0x05, 1, 2, 3, 4, 5 }, &.{ 0x80, 0x01, 0x00 }, }) |bytes| { var d: asn1.Decoder = .init(bytes); try testing.expectError(error.InvalidValue, Value.decode(try d.next(), .v2c)); } // A Counter32 whose content is negative: unsigned means unsigned. var d: asn1.Decoder = .init(&.{ 0x41, 0x01, 0xff }); try testing.expectError(error.InvalidValue, Value.decode(try d.next(), .v2c)); // A tag SNMP does not define at all. var d2: asn1.Decoder = .init(&.{ 0x45, 0x00 }); try testing.expectError(error.UnexpectedTag, Value.decode(try d2.next(), .v2c));}
fn expectFormat(value: Value, expected: []const u8) !void { var buffer: [512]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try w.print("{f}", .{value}); try testing.expectEqualStrings(expected, w.buffered());}
test "rendering, as net-snmp renders it" { try expectFormat(.{ .data = .{ .integer = -7 } }, "INTEGER: -7"); try expectFormat(.{ .data = .{ .counter32 = 140883 } }, "Counter32: 140883"); try expectFormat(.{ .data = .{ .gauge32 = 0 } }, "Gauge32: 0"); try expectFormat(.{ .data = .{ .counter64 = 140883 } }, "Counter64: 140883"); try expectFormat(.{ .data = .{ .ip_address = .init(192, 168, 4, 64) } }, "IpAddress: 192.168.4.64"); try expectFormat( .{ .data = .{ .object_id = try ObjectId.parse("1.3.6.1.4.1.9.1.2191") } }, "OID: .1.3.6.1.4.1.9.1.2191", ); try expectFormat(.{ .data = .no_such_object }, "No Such Object available on this agent at this OID"); try expectFormat(.{ .data = .end_of_mib_view }, "No more variables left in this MIB View");}
test "Timeticks, the way the switch reported its uptime" { // The real reading from the Catalyst: 28572867 hundredths. try expectFormat(.{ .data = .{ .timeticks = 28572867 } }, "Timeticks: (28572867) 3 days, 7:22:08.67"); try expectFormat(.{ .data = .{ .timeticks = 0 } }, "Timeticks: (0) 0:00:00.00"); try expectFormat(.{ .data = .{ .timeticks = 307 } }, "Timeticks: (307) 0:00:03.07"); // Exactly one day is singular, which net-snmp is careful about. try expectFormat(.{ .data = .{ .timeticks = 8640000 } }, "Timeticks: (8640000) 1 day, 0:00:00.00"); try expectFormat(.{ .data = .{ .timeticks = 17280000 } }, "Timeticks: (17280000) 2 days, 0:00:00.00");}
test "a string is text or it is hex" { try expectFormat(.{ .data = .{ .octet_string = "GigabitEthernet0/1" } }, "STRING: GigabitEthernet0/1"); // The multi-line case, which is the one that breaks a line-oriented diff. try expectFormat( .{ .data = .{ .octet_string = "Cisco IOS Software\nCopyright (c) 1986-2021" } }, "STRING: Cisco IOS Software\nCopyright (c) 1986-2021", ); // Not printable, so hex -- a MAC address being the usual case. try expectFormat( .{ .data = .{ .octet_string = "\x00\x1b\x54\xc2\x00\x01" } }, "Hex-STRING: 00 1B 54 C2 00 01", ); try expectFormat(.{ .data = .{ .octet_string = "" } }, "STRING: ");}
test "six octets read as a MAC address, when the caller knows they are one" { const value: Value = .{ .data = .{ .octet_string = "\x00\x1b\x54\xc2\x00\x01" } }; const mac = value.asMacAddress().?; var buffer: [64]u8 = undefined; var w: Io.Writer = .fixed(&buffer); try w.print("{f}", .{&mac}); // Whatever zig-macaddress's default spelling is, it is that library's // business; what matters here is that the octets survived. try testing.expect(std.mem.indexOf(u8, w.buffered(), "1b") != null or std.mem.indexOf(u8, w.buffered(), "1B") != null);
// The wrong length, and the wrong type, are both null rather than a // guess. try testing.expectEqual(@as(?macaddress.MacAddress, null), (Value{ .data = .{ .octet_string = "abc" } }).asMacAddress()); try testing.expectEqual(@as(?macaddress.MacAddress, null), (Value{ .data = .{ .integer = 1 } }).asMacAddress());}
test "the constructed form of a simple type is not a value" { // RFC 3417 §2.1 forbids it, and accepting it would give every value two // encodings: `24 03 ...` alongside `04 03 ...`, decoding alike and // re-encoding differently. for ([_][]const u8{ "\x24\x03abc", // constructed OCTET STRING "\x22\x01\x2a", // constructed INTEGER "\x25\x00", // constructed NULL "\x26\x01\x2b", // constructed OBJECT IDENTIFIER "\x60\x04\x01\x02\x03\x04", // constructed IpAddress "\x61\x01\x01", // constructed Counter32 "\xa0\x00", // constructed noSuchObject }) |bytes| { var d: asn1.Decoder = .init(bytes); try testing.expectError(error.UnexpectedTag, Value.decode(try d.next(), .v2c)); }}