// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A whole SNMP message: what goes in a datagram. //! //! There are two wrappers, not three. Versions 1 and 2c share one -- a //! version number, a community string, and a PDU -- and differ only in what //! they permit inside it. Version 3 replaces it entirely with a header that //! knows nothing about any particular security model and a *scoped* PDU that //! may be encrypted, which is why it is a separate variant rather than a //! third field on the first. //! //! ``` //! v1/v2c: SEQUENCE { version INTEGER, community OCTET STRING, pdu } //! ``` //! //! ## Decoding is version-first, deliberately //! //! The version is the first thing in the message and it decides how to read //! the rest, so `decode` reads it and dispatches rather than taking the //! version from the caller. A caller who asked for v2c and was answered in v1 //! wants to know that, not to have the reply reinterpreted. //! //! ## What borrows //! //! Everything. The community string and every OCTET STRING value point into //! the datagram; only the varbind list's backing slice is allocated. That is //! deliberate -- a walk decodes thousands of these -- and it means a decoded //! `Message` must not outlive the buffer it was read from. const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const testing = std.testing; const asn1 = @import("asn1"); const ObjectId = asn1.ObjectId; const Pdu = @import("Pdu.zig"); const Value = @import("Value.zig"); const VarBind = @import("VarBind.zig"); const Version = @import("Version.zig").Version; const Message = @This(); /// The greatest size of a message this will read, which is also the largest a /// UDP datagram can be: 65535 less the 8-byte UDP header and the 20-byte IPv4 /// header. It is what `msgMaxSize` is set to for v3 and what a receive buffer /// is sized at. pub const max_size = 65507; body: Body, pub const Body = union(enum) { /// Versions 1 and 2c, which are the same message with different rules. community: Community, }; pub const Community = struct { version: Version, /// The shared secret, sent in the clear. This is the whole of SNMPv1 and /// v2c security, which is why v3 exists. community: []const u8, pdu: Pdu, }; pub const DecodeError = Pdu.DecodeError || error{ /// A version number that is not 0, 1 or 3. UnknownVersion, /// A version whose wrapper this does not implement yet. UnsupportedVersion, }; pub fn version(m: Message) Version { return switch (m.body) { .community => |c| c.version, }; } pub fn pdu(m: Message) Pdu { return switch (m.body) { .community => |c| c.pdu, }; } /// A v1 or v2c message carrying `p`. pub fn init(v: Version, community: []const u8, p: Pdu) Message { std.debug.assert(v.isCommunityBased()); return .{ .body = .{ .community = .{ .version = v, .community = community, .pdu = p } } }; } pub fn encode(m: Message, e: *asn1.Encoder) asn1.Encoder.Error!void { switch (m.body) { .community => |c| { try e.begin(.sequence); try e.integerTagged(.integer, i32, @backingInt(c.version)); try e.primitive(.octet_string, c.community); try c.pdu.encode(e); try e.end(); }, } } /// The whole message as a freshly allocated slice, which is what gets handed /// to a socket. pub fn encodeAlloc(m: Message, gpa: Allocator) (asn1.Encoder.Error)![]u8 { var e: asn1.Encoder = .init(gpa); defer e.deinit(); try m.encode(&e); return e.toOwnedSlice(); } /// Reads one message out of `bytes`, which is one datagram. /// /// The varbind list is allocated from `gpa`; everything else points into /// `bytes`. pub fn decode(bytes: []const u8, gpa: Allocator) DecodeError!Message { var outer: asn1.Decoder = .init(bytes); const el = try outer.expect(.sequence); // A datagram holds exactly one message. Anything after it is either a // second message nobody asked for or padding, and neither is something to // guess about. try outer.expectEnd(); var d = el.decoder(); const number = try d.integer(i32); const v: Version = switch (number) { 0 => .v1, 1 => .v2c, 3 => .v3, else => return error.UnknownVersion, }; if (!v.isCommunityBased()) return error.UnsupportedVersion; const community = try d.octetString(); var p = try Pdu.decode(try d.next(), v, gpa); errdefer p.deinit(gpa); try d.expectEnd(); return .{ .body = .{ .community = .{ .version = v, .community = community, .pdu = p } } }; } /// Frees what `decode` allocated. pub fn deinit(m: *Message, gpa: Allocator) void { switch (m.body) { .community => |*c| c.pdu.deinit(gpa), } m.* = undefined; } // -- tests ------------------------------------------------------------------ fn oid(text: []const u8) ObjectId { return ObjectId.parse(text) catch unreachable; } /// The exact bytes net-snmp 5.9.5.2 sends for /// /// snmpget -v2c -c public -d 127.0.0.1:1 1.3.6.1.2.1.1.1.0 /// /// read off its `-d` hex dump. This is the oracle in its cheapest form: a /// real implementation's output, checked in, needing nothing installed to /// test against. const netsnmp_v2c_get = [_]u8{ 0x30, 0x29, 0x02, 0x01, 0x01, // version 1 (= v2c) 0x04, 0x06, 'p', 'u', 'b', 'l', 'i', 'c', // community 0xa0, 0x1c, // GetRequest [0] 0x02, 0x04, 0x01, 0xbd, 0x03, 0x11, // request-id 0x02, 0x01, 0x00, // error-status 0x02, 0x01, 0x00, // error-index 0x30, 0x0e, // varbind list 0x30, 0x0c, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x02, 0x01, 0x01, 0x01, 0x00, 0x05, 0x00, }; test "net-snmp's own GetRequest, decoded and re-encoded byte for byte" { var m = try Message.decode(&netsnmp_v2c_get, testing.allocator); defer m.deinit(testing.allocator); try testing.expectEqual(Version.v2c, m.version()); try testing.expectEqualStrings("public", m.body.community.community); const p = m.pdu(); try testing.expectEqual(Pdu.Kind.get_request, p.kind); try testing.expectEqual(@as(?i32, 0x01bd0311), p.requestId()); try testing.expectEqual(Pdu.ErrorStatus.no_error, p.body.standard.error_status); try testing.expectEqual(@as(i32, 0), p.body.standard.error_index); try testing.expectEqual(@as(usize, 1), p.varBinds().len); try testing.expect(oid("1.3.6.1.2.1.1.1.0").eql(p.varBinds()[0].name)); try testing.expectEqual( std.meta.Tag(Value.Data).null, std.meta.activeTag(p.varBinds()[0].value.data), ); // And back out again, identically. This is the assertion that matters: // it says our encoder agrees with net-snmp's to the byte, and because the // request-id comes from the captured bytes rather than from us, it does // not depend on the random one net-snmp picked. const again = try m.encodeAlloc(testing.allocator); defer testing.allocator.free(again); try testing.expectEqualSlices(u8, &netsnmp_v2c_get, again); } test "building the same request from scratch" { // The other direction: given the same inputs net-snmp had, produce the // same bytes. Only possible because the request-id is an input. const bindings = [_]VarBind{.request(oid("1.3.6.1.2.1.1.1.0"))}; const m = Message.init(.v2c, "public", Pdu.get(0x01bd0311, &bindings)); const bytes = try m.encodeAlloc(testing.allocator); defer testing.allocator.free(bytes); try testing.expectEqualSlices(u8, &netsnmp_v2c_get, bytes); } test "a v1 message differs only in the version octet" { const bindings = [_]VarBind{.request(oid("1.3.6.1.2.1.1.1.0"))}; const m = Message.init(.v1, "public", Pdu.get(0x01bd0311, &bindings)); const bytes = try m.encodeAlloc(testing.allocator); defer testing.allocator.free(bytes); // Same length, and one byte different: the version. try testing.expectEqual(netsnmp_v2c_get.len, bytes.len); try testing.expectEqual(@as(u8, 0x00), bytes[4]); try testing.expectEqualSlices(u8, netsnmp_v2c_get[5..], bytes[5..]); } test "a response with an error, as a v1 agent reports a missing object" { // This is what the Catalyst and snmpd both answer to // `snmpget -v1 ... 1.3.6.1.2.1.31.1.1.1.6.1`: noSuchName in the PDU, // with the index of the offending binding, and the binding echoed back // unchanged. A v2c agent instead says noError and puts an exception // marker in the varbind -- the same question, two different shapes of // answer. const bindings = [_]VarBind{.request(oid("1.3.6.1.2.1.31.1.1.1.6.1"))}; const m = Message.init(.v1, "public", .{ .kind = .response, .body = .{ .standard = .{ .request_id = 42, .error_status = .no_such_name, .error_index = 1, .bindings = &bindings, } }, }); const bytes = try m.encodeAlloc(testing.allocator); defer testing.allocator.free(bytes); var back = try Message.decode(bytes, testing.allocator); defer back.deinit(testing.allocator); try testing.expectEqual(Version.v1, back.version()); try testing.expectEqual(Pdu.ErrorStatus.no_such_name, back.pdu().body.standard.error_status); try testing.expectEqual(@as(i32, 1), back.pdu().body.standard.error_index); } test "the v2c shape of the same answer" { const bindings = [_]VarBind{.{ .name = oid("1.3.6.1.2.1.1.99.0"), .value = .{ .data = .no_such_object }, }}; const m = Message.init(.v2c, "public", .{ .kind = .response, .body = .{ .standard = .{ .request_id = 42, .bindings = &bindings } }, }); const bytes = try m.encodeAlloc(testing.allocator); defer testing.allocator.free(bytes); var back = try Message.decode(bytes, testing.allocator); defer back.deinit(testing.allocator); try testing.expectEqual(Pdu.ErrorStatus.no_error, back.pdu().body.standard.error_status); try testing.expectEqual( std.meta.Tag(Value.Data).no_such_object, std.meta.activeTag(back.pdu().varBinds()[0].value.data), ); // And the same message read as v1 is refused, because SNMPv1 has no such // marker. A decoder that let it through would be inventing a value the // version cannot express. var v1 = bytes; v1[4] = 0x00; try testing.expectError(error.WrongVersion, Message.decode(v1, testing.allocator)); } test "a version number nobody defines" { var bytes = netsnmp_v2c_get; for ([_]u8{ 2, 4, 0x7f }) |number| { bytes[4] = number; try testing.expectError(error.UnknownVersion, Message.decode(&bytes, testing.allocator)); } // Version 3 is known and its wrapper is not implemented yet, which is a // different answer from "no such version". bytes[4] = 3; try testing.expectError(error.UnsupportedVersion, Message.decode(&bytes, testing.allocator)); } test "a datagram that is not one message" { // Truncated at every length, none of which may panic or read past the // end. This is the property the fuzzer generalises. for (0..netsnmp_v2c_get.len) |len| { _ = Message.decode(netsnmp_v2c_get[0..len], testing.allocator) catch continue; // A prefix that decodes cleanly would mean the outer length was not // being honoured. return error.TestUnexpectedResult; } // Two messages in one datagram, which is one more than a datagram holds. var doubled: [netsnmp_v2c_get.len * 2]u8 = undefined; @memcpy(doubled[0..netsnmp_v2c_get.len], &netsnmp_v2c_get); @memcpy(doubled[netsnmp_v2c_get.len..], &netsnmp_v2c_get); try testing.expectError(error.TrailingData, Message.decode(&doubled, testing.allocator)); } test "an empty community, which is legal and occasionally used" { const bindings = [_]VarBind{.request(oid("1.3.6.1.2.1.1.1.0"))}; const m = Message.init(.v2c, "", Pdu.get(1, &bindings)); const bytes = try m.encodeAlloc(testing.allocator); defer testing.allocator.free(bytes); var back = try Message.decode(bytes, testing.allocator); defer back.deinit(testing.allocator); try testing.expectEqualStrings("", back.body.community.community); }