// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The SNMPv3 message: RFC 3412's wrapper and RFC 3414's security //! parameters. //! //! ``` //! SEQUENCE { //! msgVersion INTEGER (3) //! msgGlobalData SEQUENCE { msgID, msgMaxSize, msgFlags, msgSecurityModel } //! msgSecurityParameters OCTET STRING -- holding USM's own SEQUENCE //! msgData CHOICE { ScopedPDU | OCTET STRING of ciphertext } //! } //! ``` //! //! Two things about that shape are worth saying before the code. //! //! **`msgSecurityParameters` is an OCTET STRING whose content is itself BER.** //! The wrapper is deliberately ignorant of the security model -- USM is only //! one of them -- so the header carries a number saying which model applies //! and an opaque blob for that model to read. So there is an encoding inside //! an encoding, and `asn1.Encoder.raw` is how an already-encoded thing is //! spliced in. //! //! **The scoped PDU is either plaintext or ciphertext, distinguished by the //! tag.** A plaintext one is a SEQUENCE; an encrypted one is an OCTET STRING. //! Nothing else in the message says which, so the privacy flag and the tag //! have to agree and a decoder that trusted only one of them could be steered. //! //! ## The authentication ordering problem //! //! `msgAuthenticationParameters` holds an HMAC computed over **the whole //! message including that field**. RFC 3414 §6.3.1 resolves the circularity //! by having the sender write the right number of zero octets there, finish //! and digest the complete message, and then replace the zeroes in place. //! //! Finding those zeroes again is the fiddly part. Recording an offset while //! encoding does not survive, because closing an enclosing element inserts //! its length bytes and shifts everything after them. Searching for a run of //! zeroes would find the wrong run sooner or later. So this decodes the //! finished message and takes the field's address from the decoder: every //! `Element.content` is a subslice of the buffer it was read from, so the //! offset falls out of pointer arithmetic and cannot be stale. const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const assert = std.debug.assert; const testing = std.testing; const asn1 = @import("asn1"); const usm = @import("../usm.zig"); const Pdu = @import("Pdu.zig"); const VarBind = @import("VarBind.zig"); const Version = @import("Version.zig").Version; /// The security model number in the header. USM is 3; 1 and 2 were SNMPv1 /// and v2c retro-fitted into the framework, and nothing else is deployed. pub const security_model_usm: i32 = 3; /// RFC 3412 §6.5: the smallest `msgMaxSize` a sender may claim to accept. pub const min_max_size: i32 = 484; /// `msgFlags`, a single octet. pub const Flags = packed struct(u8) { auth: bool = false, priv: bool = false, /// Whether the receiver should answer a failure with a Report PDU. /// /// Engine discovery depends entirely on this: the discovery request is /// unauthenticated and *deliberately wrong*, and the Report that comes /// back is the answer. With the flag clear the agent would drop it /// silently and discovery could not happen. reportable: bool = false, _padding: u5 = 0, pub fn level(f: Flags) usm.SecurityLevel { if (f.priv) return .auth_priv; if (f.auth) return .auth_no_priv; return .no_auth_no_priv; } pub fn fromLevel(l: usm.SecurityLevel, reportable: bool) Flags { return .{ .auth = l != .no_auth_no_priv, .priv = l == .auth_priv, .reportable = reportable, }; } /// `priv` without `auth` is forbidden by RFC 3412 §6.4: encryption with /// no authentication is worse than useless, because a receiver would /// decrypt whatever it was sent and act on it. pub fn isValid(f: Flags) bool { return !(f.priv and !f.auth); } }; /// The header that every v3 message carries, whatever the security model. pub const Header = struct { /// Matches a reply to its request at the message layer, which is a /// different identifier from the PDU's request-id and exists because the /// PDU may be encrypted when the reply arrives. id: i32, max_size: i32 = 65507, flags: Flags, security_model: i32 = security_model_usm, }; /// RFC 3414 §2.4's `UsmSecurityParameters`, which lives inside an OCTET /// STRING in the header. pub const Parameters = struct { /// Whose clock and whose keys. Empty in a discovery request, because the /// whole point is that we do not know it yet. engine_id: []const u8 = "", engine_boots: i32 = 0, engine_time: i32 = 0, /// At most 32 octets, per the ASN.1. user_name: []const u8 = "", /// The HMAC, or empty when unauthenticated. auth_parameters: []const u8 = "", /// The privacy salt, or empty. privacy_parameters: []const u8 = "", pub const max_user_name = 32; pub fn encode(p: Parameters, e: *asn1.Encoder) asn1.Encoder.Error!void { try e.begin(.sequence); try e.primitive(.octet_string, p.engine_id); try e.integer(i32, p.engine_boots); try e.integer(i32, p.engine_time); try e.primitive(.octet_string, p.user_name); try e.primitive(.octet_string, p.auth_parameters); try e.primitive(.octet_string, p.privacy_parameters); try e.end(); } pub fn decode(bytes: []const u8) asn1.DecodeError!Parameters { var outer: asn1.Decoder = .init(bytes); const el = try outer.expect(.sequence); try outer.expectEnd(); var d = el.decoder(); const p: Parameters = .{ .engine_id = try d.octetString(), .engine_boots = try d.integer(i32), .engine_time = try d.integer(i32), .user_name = try d.octetString(), .auth_parameters = try d.octetString(), .privacy_parameters = try d.octetString(), }; try d.expectEnd(); // Negative boots or time is meaningless and would break the time // window arithmetic, so it is malformed rather than merely odd. if (p.engine_boots < 0 or p.engine_time < 0) return error.InvalidValue; if (p.user_name.len > max_user_name) return error.InvalidValue; return p; } }; /// The PDU with the context it applies to. /// /// `context_engine_id` names which engine's objects are meant, which matters /// for a proxy: an agent may serve objects belonging to something behind it. /// For a plain agent it is the agent's own engine ID, and empty means "yours". pub const ScopedPdu = struct { context_engine_id: []const u8 = "", context_name: []const u8 = "", pdu: Pdu, pub fn encode(s: ScopedPdu, e: *asn1.Encoder) asn1.Encoder.Error!void { try e.begin(.sequence); try e.primitive(.octet_string, s.context_engine_id); try e.primitive(.octet_string, s.context_name); try s.pdu.encode(e); try e.end(); } pub fn decode(el: asn1.Element, gpa: Allocator) Pdu.DecodeError!ScopedPdu { if (!el.tag.eql(.sequence)) return error.UnexpectedTag; var d = el.decoder(); const context_engine_id = try d.octetString(); const context_name = try d.octetString(); // Always v3's rules inside a v3 message: Counter64 and the exception // markers are all legal here. var pdu = try Pdu.decode(try d.next(), .v3, gpa); errdefer pdu.deinit(gpa); try d.expectEnd(); return .{ .context_engine_id = context_engine_id, .context_name = context_name, .pdu = pdu, }; } }; /// A whole v3 message, decoded. pub const Message = struct { header: Header, parameters: Parameters, /// Null when the message arrived encrypted and has not been decrypted /// yet, in which case `encrypted` holds the ciphertext. scoped: ?ScopedPdu, encrypted: []const u8 = "", }; pub const DecodeError = Pdu.DecodeError || error{ /// `msgVersion` was not 3. NotVersion3, /// A security model this does not implement. UnsupportedSecurityModel, /// `msgFlags` was not exactly one octet, or asked for privacy without /// authentication. InvalidFlags, /// The privacy flag and the shape of `msgData` disagree. InconsistentPrivacy, /// `msgMaxSize` below the floor RFC 3412 sets. MaxSizeTooSmall, }; /// Encodes a message whose `auth_parameters` is however many zero octets the /// protocol needs, ready for `seal`. pub fn encode( e: *asn1.Encoder, header: Header, parameters: Parameters, body: Body, ) asn1.Encoder.Error!void { try e.begin(.sequence); try e.integerTagged(.integer, i32, @intFromEnum(Version.v3)); try e.begin(.sequence); try e.integer(i32, header.id); try e.integer(i32, header.max_size); try e.primitive(.octet_string, &[_]u8{@bitCast(header.flags)}); try e.integer(i32, header.security_model); try e.end(); // The security parameters are BER inside an OCTET STRING, so they are // encoded on their own and spliced in. var inner: asn1.Encoder = .init(e.gpa); defer inner.deinit(); try parameters.encode(&inner); try e.primitive(.octet_string, inner.buffered()); switch (body) { .plaintext => |s| try s.encode(e), .encrypted => |bytes| try e.primitive(.octet_string, bytes), } try e.end(); } pub const Body = union(enum) { plaintext: ScopedPdu, encrypted: []const u8, }; /// Reads a v3 message. The PDU is left encrypted when the privacy flag is /// set; `open` is what decrypts it. pub fn decode(bytes: []const u8, gpa: Allocator) DecodeError!Message { var outer: asn1.Decoder = .init(bytes); const el = try outer.expect(.sequence); try outer.expectEnd(); var d = el.decoder(); if (try d.integer(i32) != @intFromEnum(Version.v3)) return error.NotVersion3; const header_el = try d.expect(.sequence); var h = header_el.decoder(); const id = try h.integer(i32); const max_size = try h.integer(i32); const flags_bytes = try h.octetString(); const security_model = try h.integer(i32); try h.expectEnd(); if (flags_bytes.len != 1) return error.InvalidFlags; const flags: Flags = @bitCast(flags_bytes[0]); if (!flags.isValid()) return error.InvalidFlags; if (max_size < min_max_size) return error.MaxSizeTooSmall; if (security_model != security_model_usm) return error.UnsupportedSecurityModel; const parameters = try Parameters.decode(try d.octetString()); const data = try d.next(); try d.expectEnd(); // The flag and the tag must agree. Taking either alone would let a peer // present ciphertext as plaintext or the other way round. if (flags.priv) { if (!data.tag.eql(.octet_string)) return error.InconsistentPrivacy; return .{ .header = .{ .id = id, .max_size = max_size, .flags = flags, .security_model = security_model }, .parameters = parameters, .scoped = null, .encrypted = data.content, }; } if (!data.tag.eql(.sequence)) return error.InconsistentPrivacy; return .{ .header = .{ .id = id, .max_size = max_size, .flags = flags, .security_model = security_model }, .parameters = parameters, .scoped = try ScopedPdu.decode(data, gpa), .encrypted = "", }; } /// The `msgAuthenticationParameters` field inside `message`, as a writable /// slice of it. /// /// Found by decoding rather than by remembering an offset, because closing an /// element inserts its length and moves everything after it -- so an offset /// recorded during encoding is stale by the time the message is finished. /// Every `Element.content` is a subslice of the buffer it was read from, so /// the address falls out of the decode and cannot be wrong. pub fn locateAuthParameters(message: []u8) ?[]u8 { var outer: asn1.Decoder = .init(message); const el = outer.expect(.sequence) catch return null; var d = el.decoder(); _ = d.integer(i32) catch return null; _ = d.expect(.sequence) catch return null; const params_el = d.expect(.octet_string) catch return null; var inner: asn1.Decoder = .init(params_el.content); const seq = inner.expect(.sequence) catch return null; var p = seq.decoder(); _ = p.octetString() catch return null; // engine id _ = p.integer(i32) catch return null; // boots _ = p.integer(i32) catch return null; // time _ = p.octetString() catch return null; // user name const auth = p.expect(.octet_string) catch return null; if (auth.content.len == 0) return message[0..0]; // The content is a subslice of `message`, so its offset is the difference // of the pointers. `@constCast` is sound here because `message` was // mutable on the way in and every slice below it points into it. const offset = @intFromPtr(auth.content.ptr) - @intFromPtr(message.ptr); assert(offset + auth.content.len <= message.len); return message[offset..][0..auth.content.len]; } /// Fills in the HMAC over the finished message, in place. /// /// `message` must already carry `protocol.digestLength()` zero octets in /// `msgAuthenticationParameters`, which `encode` arranges when it is given /// the right number. pub fn seal(message: []u8, protocol: usm.AuthProtocol, key: []const u8) error{NoAuthField}!void { if (protocol == .none) return; const field = locateAuthParameters(message) orelse return error.NoAuthField; if (field.len != protocol.digestLength()) return error.NoAuthField; // Zeroed first, so that sealing a message twice gives the same answer as // sealing it once -- otherwise the second digest would be taken over the // first one. @memset(field, 0); var digest: [usm.AuthProtocol.max_digest_length]u8 = undefined; const out = digest[0..protocol.digestLength()]; usm.authenticate(protocol, key, message, out); @memcpy(field, out); } /// Checks the HMAC on a received message. /// /// The received digest is copied out and the field zeroed before computing, /// which is the same dance as sending. The buffer is modified and left /// zeroed, which is fine for a datagram that has already been decoded. pub fn checkAuth(message: []u8, protocol: usm.AuthProtocol, key: []const u8) bool { if (protocol == .none) return true; const field = locateAuthParameters(message) orelse return false; if (field.len != protocol.digestLength()) return false; var received: [usm.AuthProtocol.max_digest_length]u8 = undefined; @memcpy(received[0..field.len], field); @memset(field, 0); return usm.verify(protocol, key, message, received[0..field.len]); } // -- tests ------------------------------------------------------------------ fn oid(text: []const u8) asn1.ObjectId { return asn1.ObjectId.parse(text) catch unreachable; } /// The engine-discovery request net-snmp 5.9.5.2 sends, read off the hex dump /// from /// /// snmpget -v3 -l authNoPriv -u authmd5 -a MD5 -A md5authpass -d -r0 -t1 \ /// 127.0.0.1:1 1.3.6.1.2.1.1.1.0 /// /// Everything in it is empty or zero except the two identifiers, because that /// is exactly what discovery is: a deliberately unanswerable request whose /// Report carries the engine's own parameters back. const netsnmp_v3_discovery = [_]u8{ 0x30, 0x3e, 0x02, 0x01, 0x03, // msgVersion 3 0x30, 0x11, // msgGlobalData 0x02, 0x04, 0x68, 0xbc, 0xf4, 0xc5, // msgID 0x02, 0x03, 0x00, 0xff, 0xe3, // msgMaxSize 65507 0x04, 0x01, 0x04, // msgFlags reportable 0x02, 0x01, 0x03, // msgSecurityModel USM 0x04, 0x10, // msgSecurityParameters 0x30, 0x0e, 0x04, 0x00, // engine id, empty 0x02, 0x01, 0x00, // boots 0 0x02, 0x01, 0x00, // time 0 0x04, 0x00, // user name, empty 0x04, 0x00, // auth params, empty 0x04, 0x00, // privacy params, empty 0x30, 0x14, // scoped PDU 0x04, 0x00, // context engine id 0x04, 0x00, // context name 0xa0, 0x0e, // GetRequest 0x02, 0x04, 0x6d, 0x77, 0x05, 0x81, // request-id 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x30, 0x00, // no bindings }; test "net-snmp's engine-discovery request, decoded and re-encoded byte for byte" { var m = try decode(&netsnmp_v3_discovery, testing.allocator); defer if (m.scoped) |*s| s.pdu.deinit(testing.allocator); try testing.expectEqual(@as(i32, 0x68bcf4c5), m.header.id); // 65507, which is the largest a UDP datagram can be -- and the same // number this library uses for its own receive buffer. try testing.expectEqual(@as(i32, 65507), m.header.max_size); try testing.expectEqual(security_model_usm, m.header.security_model); // Reportable and nothing else, which is what makes discovery work. try testing.expect(m.header.flags.reportable); try testing.expect(!m.header.flags.auth); try testing.expect(!m.header.flags.priv); try testing.expectEqual(usm.SecurityLevel.no_auth_no_priv, m.header.flags.level()); // Every identifier empty: we do not know the engine yet and are not // claiming to be anybody. try testing.expectEqualStrings("", m.parameters.engine_id); try testing.expectEqual(@as(i32, 0), m.parameters.engine_boots); try testing.expectEqual(@as(i32, 0), m.parameters.engine_time); try testing.expectEqualStrings("", m.parameters.user_name); try testing.expectEqualStrings("", m.parameters.auth_parameters); const scoped = m.scoped.?; try testing.expectEqualStrings("", scoped.context_engine_id); try testing.expectEqual(Pdu.Kind.get_request, scoped.pdu.kind); try testing.expectEqual(@as(usize, 0), scoped.pdu.varBinds().len); // And out again, identically. var e: asn1.Encoder = .init(testing.allocator); defer e.deinit(); try encode(&e, m.header, m.parameters, .{ .plaintext = scoped }); try testing.expectEqualSlices(u8, &netsnmp_v3_discovery, e.buffered()); } test "privacy without authentication is refused" { // RFC 3412 §6.4: encrypting without authenticating is worse than useless, // because a receiver would decrypt whatever it was handed and act on it. var bytes = netsnmp_v3_discovery; // msgFlags is at a known offset in this fixture; set priv without auth. bytes[20] = 0x02; try testing.expectError(error.InvalidFlags, decode(&bytes, testing.allocator)); try testing.expect(!(Flags{ .priv = true }).isValid()); try testing.expect((Flags{ .auth = true, .priv = true }).isValid()); try testing.expect((Flags{}).isValid()); } test "the privacy flag and the shape of the data must agree" { // Claiming privacy while sending a plaintext SEQUENCE, which would // otherwise let a peer choose which reading applies. var bytes = netsnmp_v3_discovery; bytes[20] = 0x03; // auth and priv try testing.expectError(error.InconsistentPrivacy, decode(&bytes, testing.allocator)); } test "a version that is not 3, and a security model that is not USM" { { var bytes = netsnmp_v3_discovery; bytes[4] = 0x01; try testing.expectError(error.NotVersion3, decode(&bytes, testing.allocator)); } { var bytes = netsnmp_v3_discovery; // msgSecurityModel's value octet. bytes[23] = 0x02; try testing.expectError(error.UnsupportedSecurityModel, decode(&bytes, testing.allocator)); } } test "msgMaxSize below the floor RFC 3412 sets" { var e: asn1.Encoder = .init(testing.allocator); defer e.deinit(); try encode(&e, .{ .id = 1, .max_size = min_max_size - 1, .flags = .{ .reportable = true }, }, .{}, .{ .plaintext = .{ .pdu = Pdu.get(1, &.{}) } }); try testing.expectError(error.MaxSizeTooSmall, decode(e.buffered(), testing.allocator)); } test "sealing finds the digest field, and sealing twice is idempotent" { const key = [_]u8{0xab} ** 20; const zeros = [_]u8{0} ** 12; var e: asn1.Encoder = .init(testing.allocator); defer e.deinit(); try encode(&e, .{ .id = 7, .flags = .fromLevel(.auth_no_priv, true), }, .{ .engine_id = "\x80\x00\x1f\x88\x01\x02\x03", .engine_boots = 3, .engine_time = 12345, .user_name = "someone", // The placeholder the digest replaces. .auth_parameters = &zeros, }, .{ .plaintext = .{ .pdu = Pdu.get(7, &.{}) } }); const message = try testing.allocator.dupe(u8, e.buffered()); defer testing.allocator.free(message); // Before sealing, the field is where the zeroes are. const field = locateAuthParameters(message).?; try testing.expectEqual(@as(usize, 12), field.len); try testing.expectEqualSlices(u8, &zeros, field); try seal(message, .hmac_sha1_96, &key); try testing.expect(!std.mem.eql(u8, &zeros, locateAuthParameters(message).?)); // Sealing again must give the same answer: `seal` zeroes the field first, // so the second digest is over the same bytes as the first rather than // over a message containing the first digest. const once = try testing.allocator.dupe(u8, message); defer testing.allocator.free(once); try seal(message, .hmac_sha1_96, &key); try testing.expectEqualSlices(u8, once, message); // And it checks out, while one bit of the message does not. try testing.expect(checkAuth(message, .hmac_sha1_96, &key)); // `checkAuth` leaves the field zeroed, so reseal before tampering. try seal(message, .hmac_sha1_96, &key); message[message.len - 1] ^= 0x01; try testing.expect(!checkAuth(message, .hmac_sha1_96, &key)); } test "sealing a message with no room for a digest" { // An unauthenticated message has an empty field, so there is nothing to // fill in and saying so beats writing somewhere else. var e: asn1.Encoder = .init(testing.allocator); defer e.deinit(); try encode(&e, .{ .id = 1, .flags = .{ .reportable = true } }, .{}, .{ .plaintext = .{ .pdu = Pdu.get(1, &.{}) }, }); const message = try testing.allocator.dupe(u8, e.buffered()); defer testing.allocator.free(message); try testing.expectError(error.NoAuthField, seal(message, .hmac_md5_96, &[_]u8{0} ** 16)); // With no protocol there is nothing to do and it is not an error. try seal(message, .none, ""); // A field of the wrong size for the protocol is refused rather than // truncated. try testing.expect(!checkAuth(message, .hmac_md5_96, &[_]u8{0} ** 16)); try testing.expect(checkAuth(message, .none, "")); } test "a full authPriv round trip, through the encoder and back" { const user: usm.User = .{ .name = "privaes", .level = .auth_priv, .auth = .hmac_sha1_96, .priv = .aes_128_cfb, .auth_password = "shaauthpass", .priv_password = "aesprivpass", }; const engine_id = [_]u8{ 0x80, 0x00, 0x1f, 0x88, 0x80, 0x01, 0x02, 0x03 }; var keys = usm.Keys.derive(user, &engine_id); const boots: u32 = 5; const time: u32 = 54321; const salt = usm.Aes.salt(0x1122334455667788); // Encode the scoped PDU, then encrypt it. That order is forced: the // ciphertext is what goes in the message, so the plaintext has to exist // first and separately. const bindings = [_]VarBind{.request(oid("1.3.6.1.2.1.1.1.0"))}; var scoped_encoder: asn1.Encoder = .init(testing.allocator); defer scoped_encoder.deinit(); try (ScopedPdu{ .context_engine_id = &engine_id, .pdu = Pdu.get(99, &bindings), }).encode(&scoped_encoder); var ciphertext_buffer: [1024]u8 = undefined; const ciphertext = usm.Aes.encrypt( keys.privKey(), boots, time, salt, scoped_encoder.buffered(), &ciphertext_buffer, ); var e: asn1.Encoder = .init(testing.allocator); defer e.deinit(); try encode(&e, .{ .id = 1234, .flags = .fromLevel(.auth_priv, true), }, .{ .engine_id = &engine_id, .engine_boots = @intCast(boots), .engine_time = @intCast(time), .user_name = user.name, .auth_parameters = &([_]u8{0} ** 12), .privacy_parameters = &salt.bytes, }, .{ .encrypted = ciphertext }); const message = try testing.allocator.dupe(u8, e.buffered()); defer testing.allocator.free(message); try seal(message, user.auth, keys.authKey()); // Now read it back the way a receiver would. const received = try testing.allocator.dupe(u8, message); defer testing.allocator.free(received); var m = try decode(received, testing.allocator); try testing.expect(m.header.flags.priv); try testing.expectEqual(@as(?ScopedPdu, null), m.scoped); try testing.expectEqualStrings(user.name, m.parameters.user_name); try testing.expectEqualSlices(u8, &salt.bytes, m.parameters.privacy_parameters); try testing.expect(m.encrypted.len > 0); // The digest checks out on a copy, since checking zeroes the field. { const scratch = try testing.allocator.dupe(u8, message); defer testing.allocator.free(scratch); try testing.expect(checkAuth(scratch, user.auth, keys.authKey())); } // And the plaintext comes back. var plain_buffer: [1024]u8 = undefined; const plain = usm.Aes.decrypt( keys.privKey(), @intCast(m.parameters.engine_boots), @intCast(m.parameters.engine_time), .{ .bytes = m.parameters.privacy_parameters[0..8].* }, m.encrypted, &plain_buffer, ); try testing.expectEqualSlices(u8, scoped_encoder.buffered(), plain); var inner: asn1.Decoder = .init(plain); var scoped = try ScopedPdu.decode(try inner.next(), testing.allocator); defer scoped.pdu.deinit(testing.allocator); try testing.expectEqual(@as(?i32, 99), scoped.pdu.requestId()); try testing.expect(oid("1.3.6.1.2.1.1.1.0").eql(scoped.pdu.varBinds()[0].name)); } test "security parameters that are not parameters" { for ([_][]const u8{ "", // nothing "\x30\x00", // an empty sequence "\x30\x02\x04\x00", // only the engine id // Negative boots, which would break the time window arithmetic. "\x30\x0e\x04\x00\x02\x01\xff\x02\x01\x00\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" ++ ("x" ** 33) ++ "\x04\x00\x04\x00", }) |bytes| { try testing.expect(std.meta.isError(Parameters.decode(bytes))); } } test "the flags round-trip through every level" { for ([_]usm.SecurityLevel{ .no_auth_no_priv, .auth_no_priv, .auth_priv }) |level| { for ([_]bool{ false, true }) |reportable| { const f: Flags = .fromLevel(level, reportable); try testing.expectEqual(level, f.level()); try testing.expectEqual(reportable, f.reportable); try testing.expect(f.isValid()); // And through the single octet that actually goes on the wire. const byte: u8 = @bitCast(f); const back: Flags = @bitCast(byte); try testing.expectEqual(level, back.level()); try testing.expectEqual(reportable, back.reportable); } } // The bit values RFC 3412 §6.4 assigns, checked against the octet // net-snmp actually sent: 0x04 is reportable alone. try testing.expectEqual(@as(u8, 0x04), @as(u8, @bitCast(Flags{ .reportable = true }))); try testing.expectEqual(@as(u8, 0x01), @as(u8, @bitCast(Flags{ .auth = true }))); try testing.expectEqual(@as(u8, 0x03), @as(u8, @bitCast(Flags{ .auth = true, .priv = true }))); try testing.expectEqual(@as(u8, 0x07), @as(u8, @bitCast(Flags{ .auth = true, .priv = true, .reportable = true, }))); }