// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A notification sink: where traps and informs arrive. //! //! This is the other direction, and it is not simply the client backwards. A //! request/response client knows what it asked and matches a reply to it; a //! receiver is told things by strangers, unprompted, over UDP, with a source //! address that anybody can forge. So the posture is different throughout -- //! nothing here trusts a datagram further than it has to, and every accessor //! is written on the assumption that the sender is not cooperating. //! //! ## Traps and informs are the same message with different obligations //! //! A **trap** is fire and forget: the sender does not know whether it arrived //! and will not send it again. An **inform** is the same notification with an //! acknowledgement -- the sender retries until it gets a Response, so an //! inform that is not acknowledged arrives repeatedly, and one acknowledged //! twice is not a problem. `acknowledge` is what ends that, and RFC 3416 //! §4.2.7 says the reply echoes the request-id and the variable bindings //! back. //! //! Forgetting to acknowledge does not fail loudly. It makes the sender retry, //! which looks like duplicate notifications at the application and like a //! working system everywhere else. //! //! ## Who is authoritative differs between a trap and an inform //! //! Under SNMPv3 this is the thing to get right, and it is visible in what //! net-snmp sends. A **trap** is self-contained: the sender is the //! authoritative engine, so the message carries the *sender's* engine ID, //! boots and time, its `reportable` flag is clear, and there is no exchange //! beforehand. A receiver authenticates it by deriving keys against the //! engine ID in the message. //! //! An **inform** is the other way round, because the sender needs an //! acknowledgement it can trust: the *receiver* is authoritative. So a sender //! begins by discovering the receiver's engine -- an unauthenticated //! `reportable` message with everything empty -- and cannot send the inform //! at all until that is answered. A receiver with no engine of its own and no //! Report to send is a receiver that v3 informs time out against, which is //! exactly what net-snmp's sender does when nothing answers. //! //! So this answers discovery, which is the one place a notification sink has //! to say something unprompted. //! //! ## Port 162 needs privilege //! //! Which is why the NixOS test exists and why these tests use a high port: a //! receiver on the real port has to be started by something that can bind it. 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 protocol = @import("protocol.zig"); const usm = @import("usm.zig"); const Message = protocol.Message; const V3 = protocol.V3; const ObjectId = asn1.ObjectId; const Pdu = protocol.Pdu; const Value = protocol.Value; const VarBind = protocol.VarBind; const Version = protocol.Version; const Receiver = @This(); /// Where a notification is sent unless told otherwise. pub const default_port = 162; /// `sysUpTime.0` and `snmpTrapOID.0`, which RFC 3416 §4.2.6 requires as the /// first two bindings of every SNMPv2 notification. pub const sysUpTime = "1.3.6.1.2.1.1.3.0"; pub const snmpTrapOID = "1.3.6.1.6.3.1.1.4.1.0"; io: Io, socket: Io.net.Socket, options: Options, buffer: []u8, /// Our own clock's origin, for the `msgAuthoritativeEngineTime` we report to /// a sender discovering us. started_at: i96, /// Derived keys, by user and by the engine they are bound to. keys: KeyCache = .{}, /// Where a privacy salt for an acknowledgement comes from. salt_counter: u64 = 0, pub const Options = struct { /// Accept only notifications carrying this community, or any if null. /// /// A community string is no protection -- it arrives in the clear from a /// forgeable address -- but refusing the ones that do not match keeps /// somebody else's misconfigured device out of the log. community: ?[]const u8 = null, /// Which versions to accept. A receiver that does not expect v1 traps /// should say so rather than decode them. accept_v1: bool = true, accept_v2c: bool = true, /// The v3 users this receiver knows. Empty means v3 notifications are /// ignored, since there would be nothing to authenticate them with. users: []const usm.User = &.{}, /// This receiver's own `snmpEngineID`, which it reports to a sender /// discovering it and which an inform is authenticated against. /// /// Required for v3 informs and unused for v3 traps, where the sender is /// the authoritative engine. There is no sensible default: RFC 3411 §5 /// builds one from an enterprise number, and inventing somebody else's /// would be worse than asking. `engineId` builds one. engine_id: []const u8 = "", /// How many times this receiver has restarted, which a sender uses for /// replay detection. A receiver that keeps no state across restarts /// should still count them, or a restart looks like a replay. engine_boots: u32 = 1, }; /// An `snmpEngineID` in RFC 3411 §5's format 5: the enterprise number with /// the top bit set, the format byte, and then octets of your choosing. /// /// The enterprise number is the caller's to supply because it identifies /// *them*: 8072 is net-snmp's, and using it would be claiming to be net-snmp. pub fn engineId(enterprise: u32, octets: []const u8) error{TooLong}![32]u8 { if (octets.len > 27) return error.TooLong; var out: [32]u8 = @splat(0); std.mem.writeInt(u32, out[0..4], enterprise | 0x8000_0000, .big); out[4] = 5; @memcpy(out[5..][0..octets.len], octets); return out; } /// The length `engineId` produced, for slicing what it returned. pub fn engineIdLength(octets_len: usize) usize { return 5 + octets_len; } /// Keys are a megabyte of hashing each, so they are derived once per user and /// engine and kept. A receiver hears from several senders, each its own /// engine, so this is keyed by both. const KeyCache = struct { /// Small and fixed: a notification sink hears from a handful of engines, /// and an unbounded cache keyed by something a stranger controls is a way /// to be made to allocate. const capacity = 16; entries: [capacity]Entry = @splat(.{}), len: usize = 0, /// Where the next eviction lands, so a seventeenth engine replaces the /// oldest rather than being refused. next: usize = 0, const Entry = struct { user: usize = 0, engine: [32]u8 = @splat(0), engine_len: usize = 0, keys: usm.Keys = .{}, used: bool = false, }; fn find(c: *KeyCache, user: usize, engine: []const u8) ?*const usm.Keys { for (c.entries[0..c.len]) |*entry| { if (!entry.used or entry.user != user) continue; if (std.mem.eql(u8, entry.engine[0..entry.engine_len], engine)) return &entry.keys; } return null; } fn put(c: *KeyCache, user: usize, engine: []const u8, keys: usm.Keys) *const usm.Keys { assert(engine.len <= 32); const slot = if (c.len < capacity) blk: { const i = c.len; c.len += 1; break :blk &c.entries[i]; } else blk: { const i = c.next; c.next = (c.next + 1) % capacity; break :blk &c.entries[i]; }; slot.* = .{ .user = user, .engine_len = engine.len, .keys = keys, .used = true }; @memcpy(slot.engine[0..engine.len], engine); return &slot.keys; } }; pub const BindError = Io.net.IpAddress.BindError || Allocator.Error; /// Binds a socket to listen on. Port 162 needs privilege; anything above 1024 /// does not. pub fn bind(io: Io, gpa: Allocator, address: Io.net.IpAddress, options: Options) BindError!Receiver { const socket = try address.bind(io, .{ .mode = .dgram, .protocol = .udp }); errdefer socket.close(io); // A v3 user with no engine ID of our own can receive traps but cannot // answer discovery, so an inform would time out with no explanation. // Saying so at bind time beats finding out in production. assert(options.users.len == 0 or options.engine_id.len != 0); for (options.users) |user| assert(user.isConsistent()); const buffer = try gpa.alloc(u8, Message.max_size); return .{ .io = io, .socket = socket, .options = options, .buffer = buffer, .started_at = Io.Timestamp.now(io, .awake).nanoseconds, }; } /// Seconds since this receiver started, which is what it reports as its /// `msgAuthoritativeEngineTime`. fn engineTime(r: *const Receiver) u32 { const elapsed = Io.Timestamp.now(r.io, .awake).nanoseconds - r.started_at; if (elapsed <= 0) return 0; return @intCast(@min( @as(i96, std.math.maxInt(u32)), @divTrunc(elapsed, std.time.ns_per_s), )); } /// The configured user of that name, and its index for the key cache. fn findUser(r: *const Receiver, name: []const u8) ?struct { usize, usm.User } { for (r.options.users, 0..) |user, i| { if (std.mem.eql(u8, user.name, name)) return .{ i, user }; } return null; } pub fn close(r: *Receiver, gpa: Allocator) void { r.socket.close(r.io); gpa.free(r.buffer); r.* = undefined; } /// The address actually bound, which is how a test finds the port when it /// asked for zero. `Socket.address` is filled in by `getsockname` after a /// bind, so this is *this* end. pub fn localAddress(r: *const Receiver) Io.net.IpAddress { return r.socket.address; } /// One notification, as it arrived. /// /// The bindings point into the receiver's buffer, so they are valid until the /// next call to `next` -- which is why anything worth keeping has to be copied /// before then. pub const Notification = struct { from: Io.net.IpAddress, version: Version, community: []const u8, kind: Kind, /// The request-id, needed to acknowledge an inform. A v1 trap has none, /// which is the deepest reason it cannot be acknowledged. request_id: ?i32, bindings: []const VarBind, /// Present only for a v1 trap, whose structure shares nothing with the /// others. v1: ?Pdu.TrapV1 = null, /// Which v3 user sent this, and at what level. Empty and /// `no_auth_no_priv` for v1 and v2c, where there is no such notion. user: []const u8 = "", level: usm.SecurityLevel = .no_auth_no_priv, /// The authoritative engine the message named: the *sender's* for a v3 /// trap, and *ours* for a v3 inform. engine_id: []const u8 = "", owned: []VarBind, /// Whatever the bindings point into, when the notification owns it -- a /// decrypted scoped PDU, or a copy of the datagram. Null for v1 and v2c, /// which borrow the receiver's buffer. backing: ?[]u8 = null, /// What an acknowledgement has to be authenticated with. Copied rather /// than borrowed, because the cache entry it came from may be evicted /// before the caller acknowledges. v3: ?V3Context = null, pub const Kind = enum { /// RFC 1157's `Trap-PDU`. trap_v1, /// RFC 3416's `SNMPv2-Trap-PDU`. trap_v2, /// An `InformRequest-PDU`, which **must be acknowledged** or the /// sender will send it again. inform, }; /// What `acknowledge` needs to answer a v3 inform. pub const V3Context = struct { msg_id: i32, request_id: i32, keys: usm.Keys, auth: usm.AuthProtocol, priv: usm.PrivProtocol, level: usm.SecurityLevel, context_engine_id: [32]u8, context_engine_len: usize, }; pub fn deinit(n: *Notification, gpa: Allocator) void { gpa.free(n.owned); if (n.backing) |b| gpa.free(b); n.* = undefined; } /// Whether the sender is waiting for a Response. pub fn needsAcknowledgement(n: Notification) bool { return n.kind == .inform; } /// `sysUpTime.0`, which an SNMPv2 notification carries as its first /// binding. Null for a v1 trap, whose timestamp is a field of its own -- /// `v1.?.time_stamp`. pub fn upTime(n: Notification) ?u32 { if (n.kind == .trap_v1) return null; if (n.bindings.len < 1) return null; const want = ObjectId.parse(sysUpTime) catch return null; if (!n.bindings[0].name.eql(want)) return null; return switch (n.bindings[0].value.data) { .timeticks => |t| t, else => null, }; } /// `snmpTrapOID.0`: *which* notification this is, which for an SNMPv2 /// trap is the whole of its identity. /// /// Null for a v1 trap, where the identity is the enterprise plus the /// generic and specific numbers instead. RFC 3584 §3.1 says how the two /// map onto each other, which this does not do: a receiver that wants /// both shapes should look at `kind` and read the right one. pub fn trapOid(n: Notification) ?ObjectId { if (n.kind == .trap_v1) return null; if (n.bindings.len < 2) return null; const want = ObjectId.parse(snmpTrapOID) catch return null; if (!n.bindings[1].name.eql(want)) return null; return switch (n.bindings[1].value.data) { .object_id => |o| o, else => null, }; } /// The bindings that are the notification's own payload, after the two /// RFC 3416 requires. A v1 trap's are all payload. pub fn payload(n: Notification) []const VarBind { if (n.kind == .trap_v1) return n.bindings; if (n.bindings.len < 2) return n.bindings[n.bindings.len..]; return n.bindings[2..]; } }; pub const ReceiveError = error{ /// Nothing arrived before the timeout. Timeout, } || Io.net.Socket.ReceiveTimeoutError || Allocator.Error; /// Waits for the next notification. /// /// Anything that is not one -- a request, a response, a malformed datagram, a /// version or community that was not asked for -- is **discarded silently** /// and the wait resumes. That is deliberate: a receiver on a real network is /// sent all sorts of things, and one that returned an error for each would /// spend its life reporting other people's misconfigurations. The deadline /// bounds the whole call, so a flood of rubbish cannot hold a caller for ever. pub fn next(r: *Receiver, gpa: Allocator, timeout: Io.Timeout) ReceiveError!Notification { const deadline = timeout.toDeadline(r.io); while (true) { const incoming = try r.socket.receiveTimeout(r.io, r.buffer, deadline); // A datagram larger than the buffer was truncated, and a truncated // BER message is not worth parsing. if (incoming.flags.trunc) continue; // Version 3 is a different wrapper entirely, so it is dispatched on // the version octet before `Message.decode` -- which only knows the // community-based one. if (peekVersion(incoming.data)) |v| { if (v == .v3) { if (r.options.users.len == 0) continue; if (try r.handleV3(gpa, incoming.from, incoming.data)) |n| return n; continue; } } var m = Message.decode(incoming.data, gpa) catch continue; var keep = false; defer if (!keep) m.deinit(gpa); const version = m.version(); switch (version) { .v1 => if (!r.options.accept_v1) continue, .v2c => if (!r.options.accept_v2c) continue, .v3 => unreachable, // handled before Message.decode, below. } const community = m.body.community.community; if (r.options.community) |expected| { if (!std.mem.eql(u8, community, expected)) continue; } const p = m.pdu(); const kind: Notification.Kind = switch (p.kind) { .trap_v1 => .trap_v1, .snmpv2_trap => .trap_v2, .inform_request => .inform, // A request or a response is somebody talking to the wrong port. else => continue, }; keep = true; return .{ .from = incoming.from, .version = version, .community = community, .kind = kind, .request_id = p.requestId(), .bindings = p.varBinds(), .v1 = switch (p.body) { .trap_v1 => |t| t, else => null, }, .owned = @constCast(p.varBinds()), }; } } /// The version octet, without decoding the rest. fn peekVersion(bytes: []const u8) ?Version { var outer: asn1.Decoder = .init(bytes); const el = outer.expect(.sequence) catch return null; var d = el.decoder(); return switch (d.integer(i32) catch return null) { 0 => .v1, 1 => .v2c, 3 => .v3, else => null, }; } /// Reads one v3 datagram, answering discovery and returning a notification /// when there is one. /// /// Returns null for anything that was handled without producing a /// notification -- a discovery request answered, a message that would not /// authenticate, a PDU that is not a notification -- because the caller's /// loop simply carries on. fn handleV3( r: *Receiver, gpa: Allocator, from: Io.net.IpAddress, datagram: []const u8, ) ReceiveError!?Notification { const m = V3.decode(datagram, gpa) catch return null; // A sender discovering us: unauthenticated, `reportable`, and naming no // engine. Answering is not optional -- an inform sender cannot proceed // without it, which is exactly why net-snmp's times out against a // receiver that stays quiet. if (m.header.flags.level() == .no_auth_no_priv) { if (m.header.flags.reportable) { r.sendDiscoveryReport(gpa, from, m) catch {}; } // An unauthenticated v3 notification is not one we can believe, and // believing it would make v3 weaker than v2c rather than stronger. if (m.scoped) |s| { var scoped = s; scoped.pdu.deinit(gpa); } return null; } const found = r.findUser(m.parameters.user_name) orelse { if (m.scoped) |s| { var scoped = s; scoped.pdu.deinit(gpa); } return null; }; const user_index, const user = found; // The level the message claims must be one the user is configured for. // A message asking for less than the user requires is somebody stripping // protection off. if (@intFromEnum(m.header.flags.level()) < @intFromEnum(user.level)) { if (m.scoped) |s| { var scoped = s; scoped.pdu.deinit(gpa); } return null; } // Which engine the keys are bound to: the message's authoritative engine. // For a trap that is the *sender's*, which arrives in the message; for an // inform it is *ours*, and a sender that named a different one has not // discovered us. const engine = m.parameters.engine_id; if (engine.len == 0 or engine.len > 32) { if (m.scoped) |s| { var scoped = s; scoped.pdu.deinit(gpa); } return null; } const keys = r.keys.find(user_index, engine) orelse r.keys.put(user_index, engine, usm.Keys.derive(user, engine)); // The digest, before anything else in the message is believed. Checked on // a copy because checking zeroes the field. { const scratch = try gpa.dupe(u8, datagram); defer gpa.free(scratch); if (!V3.checkAuth(scratch, user.auth, keys.authKey())) { if (m.scoped) |s| { var scoped = s; scoped.pdu.deinit(gpa); } return null; } } var plaintext: []u8 = &.{}; var plaintext_owned = true; defer if (plaintext_owned) gpa.free(plaintext); var scoped = if (m.scoped) |s| s else blk: { const salt = m.parameters.privacy_parameters; if (salt.len != usm.Salt.length) return null; plaintext = try gpa.alloc(u8, m.encrypted.len); const plain = switch (user.priv) { .none => return null, .des_cbc => usm.Des.decrypt( keys.privKey(), .{ .bytes = salt[0..usm.Salt.length].* }, m.encrypted, plaintext, ) catch return null, .des3_cbc => usm.Des3.decrypt( keys.privKey(), .{ .bytes = salt[0..usm.Salt.length].* }, m.encrypted, plaintext, ) catch return null, .aes_128_cfb, .aes_192_cfb, .aes_256_cfb => usm.Aes.decrypt( keys.privKey(), @intCast(m.parameters.engine_boots), @intCast(m.parameters.engine_time), .{ .bytes = salt[0..usm.Salt.length].* }, m.encrypted, plaintext, ), }; var d: asn1.Decoder = .init(plain); const el = d.next() catch return null; break :blk V3.ScopedPdu.decode(el, gpa) catch return null; }; var keep = false; defer if (!keep) scoped.pdu.deinit(gpa); const kind: Notification.Kind = switch (scoped.pdu.kind) { .snmpv2_trap => .trap_v2, .inform_request => .inform, // A v1 trap cannot appear in a v3 message, and a request or a // response is somebody talking to the wrong port. else => return null, }; // The bindings point into the plaintext or into the datagram, and the // datagram is the receiver's buffer -- reused on the next call. So a v3 // notification owns whichever buffer it came out of, the same way a v3 // response does in the client. const backing = if (plaintext.len != 0) blk: { plaintext_owned = false; break :blk plaintext; } else try gpa.dupe(u8, datagram); errdefer gpa.free(backing); // If the bindings came from the datagram rather than from decryption, // they point into the receiver's buffer and have to be re-decoded out of // the copy, or they dangle on the next receive. if (plaintext.len == 0) { scoped.pdu.deinit(gpa); var d: asn1.Decoder = .init(backing); const outer = d.expect(.sequence) catch return null; var inner = outer.decoder(); _ = inner.integer(i32) catch return null; _ = inner.expect(.sequence) catch return null; _ = inner.octetString() catch return null; const data = inner.next() catch return null; scoped = V3.ScopedPdu.decode(data, gpa) catch return null; } var context_engine: [32]u8 = @splat(0); const context_len = @min(scoped.context_engine_id.len, 32); @memcpy(context_engine[0..context_len], scoped.context_engine_id[0..context_len]); keep = true; return .{ .from = from, .version = .v3, .community = "", .kind = kind, .request_id = scoped.pdu.requestId(), .bindings = scoped.pdu.varBinds(), .user = user.name, .level = m.header.flags.level(), .engine_id = engine, .owned = @constCast(scoped.pdu.varBinds()), .backing = backing, .v3 = .{ .msg_id = m.header.id, .request_id = scoped.pdu.requestId() orelse 0, .keys = keys.*, .auth = user.auth, .priv = user.priv, .level = m.header.flags.level(), .context_engine_id = context_engine, .context_engine_len = context_len, }, }; } /// Answers a sender discovering us, with a Report carrying our engine ID, /// boots and time. /// /// RFC 3414 §3.2 has the report name `usmStatsUnknownEngineIDs`, which reads /// oddly -- the sender did not name a wrong engine, it named none -- but that /// is the counter the standard uses and what every sender expects. The report /// is unauthenticated, because there is nothing yet to authenticate it with. fn sendDiscoveryReport( r: *Receiver, gpa: Allocator, to: Io.net.IpAddress, request: V3.Message, ) !void { const counter = try ObjectId.parse("1.3.6.1.6.3.15.1.1.4.0"); const bindings = [_]VarBind{.{ .name = counter, .value = .{ .data = .{ .counter32 = 1 } }, }}; var e: asn1.Encoder = .init(gpa); defer e.deinit(); try V3.encode(&e, .{ .id = request.header.id, .max_size = @intCast(r.buffer.len), // Not reportable: a report about a report would not terminate. .flags = .fromLevel(.no_auth_no_priv, false), }, .{ .engine_id = r.options.engine_id, .engine_boots = @intCast(r.options.engine_boots), .engine_time = @intCast(r.engineTime()), }, .{ .plaintext = .{ .context_engine_id = r.options.engine_id, .pdu = .{ .kind = .report, .body = .{ .standard = .{ // Echoing the request's id if it had one, so a sender // matching on it recognises the answer. .request_id = if (request.scoped) |s| s.pdu.requestId() orelse 0 else 0, .bindings = &bindings, }, }, }, }, }); try r.socket.send(r.io, &to, e.buffered()); } pub const AcknowledgeError = error{ /// A trap cannot be acknowledged: there is nobody waiting and, for a v1 /// trap, no request-id to answer with. NotAnInform, } || Io.net.Socket.SendError || asn1.Encoder.Error || Allocator.Error; /// Answers an inform, which is what stops the sender retrying. /// /// RFC 3416 §4.2.7: the Response carries the same request-id and the same /// variable bindings back. Echoing the bindings is not decoration -- a sender /// may be matching on them -- and getting it wrong makes an inform look /// delivered while the sender keeps trying. pub fn acknowledge(r: *Receiver, gpa: Allocator, n: Notification) AcknowledgeError!void { if (n.kind != .inform) return error.NotAnInform; const request_id = n.request_id orelse return error.NotAnInform; if (n.version == .v3) return r.acknowledgeV3(gpa, n, request_id); const message = Message.init(n.version, n.community, .{ .kind = .response, .body = .{ .standard = .{ .request_id = request_id, .bindings = n.bindings, } }, }); const bytes = try message.encodeAlloc(gpa); defer gpa.free(bytes); try r.socket.send(r.io, &n.from, bytes); } /// Acknowledges a v3 inform, authenticated -- and encrypted if the inform /// was. /// /// The reply has to be at least as protected as the request. A sender that /// encrypted its inform and got a plaintext acknowledgement has no reason to /// believe the acknowledgement, so it would keep retrying; and an /// unauthenticated one it would reject outright. Matching the level is the /// rule, not a courtesy. fn acknowledgeV3( r: *Receiver, gpa: Allocator, n: Notification, request_id: i32, ) AcknowledgeError!void { const context = n.v3 orelse return error.NotAnInform; var keys = context.keys; const context_engine = context.context_engine_id[0..context.context_engine_len]; const response: Pdu = .{ .kind = .response, .body = .{ .standard = .{ .request_id = request_id, .bindings = n.bindings, } }, }; // We are the authoritative engine for an inform, so the reply carries // *our* boots and time -- which is also what lets the sender check its // own notion of our clock. const boots = r.options.engine_boots; const time = r.engineTime(); var scoped_encoder: asn1.Encoder = .init(gpa); defer scoped_encoder.deinit(); var salt: usm.Salt = .{ .bytes = @splat(0) }; var ciphertext: []u8 = &.{}; defer gpa.free(ciphertext); const body: V3.Body = if (context.level == .auth_priv) blk: { try (V3.ScopedPdu{ .context_engine_id = context_engine, .pdu = response, }).encode(&scoped_encoder); // A salt that must not repeat under one key. Seeded from the clock // and the message id, which together do not recur within a boot. r.salt_counter +%= 1; const nonce = @as(u64, @bitCast(@as(i64, @truncate(Io.Timestamp.now(r.io, .awake).nanoseconds)))) ^ r.salt_counter; switch (context.priv) { .none => return error.NotAnInform, .des_cbc => { salt = usm.Des.salt(boots, @truncate(nonce)); ciphertext = try gpa.alloc(u8, usm.Des.paddedLength(scoped_encoder.buffered().len)); break :blk .{ .encrypted = usm.Des.encrypt( keys.privKey(), salt, scoped_encoder.buffered(), ciphertext, ) }; }, .des3_cbc => { salt = usm.Des3.salt(boots, @truncate(nonce)); ciphertext = try gpa.alloc(u8, usm.Des.paddedLength(scoped_encoder.buffered().len)); break :blk .{ .encrypted = usm.Des3.encrypt( keys.privKey(), salt, scoped_encoder.buffered(), ciphertext, ) }; }, .aes_128_cfb, .aes_192_cfb, .aes_256_cfb => { salt = usm.Aes.salt(nonce); ciphertext = try gpa.alloc(u8, scoped_encoder.buffered().len); break :blk .{ .encrypted = usm.Aes.encrypt( keys.privKey(), boots, time, salt, scoped_encoder.buffered(), ciphertext, ) }; }, } } else .{ .plaintext = .{ .context_engine_id = context_engine, .pdu = response, } }; var e: asn1.Encoder = .init(gpa); defer e.deinit(); const zeros = [_]u8{0} ** usm.AuthProtocol.max_digest_length; try V3.encode(&e, .{ .id = context.msg_id, .max_size = @intCast(r.buffer.len), // Not reportable: this is an answer, and a report about it would not // terminate. .flags = .fromLevel(context.level, false), }, .{ .engine_id = r.options.engine_id, .engine_boots = @intCast(boots), .engine_time = @intCast(time), .user_name = n.user, .auth_parameters = zeros[0..context.auth.digestLength()], .privacy_parameters = if (context.level == .auth_priv) &salt.bytes else "", }, body); const bytes = try gpa.dupe(u8, e.buffered()); defer gpa.free(bytes); if (context.auth != .none) { V3.seal(bytes, context.auth, keys.authKey()) catch return error.NotAnInform; } try r.socket.send(r.io, &n.from, bytes); } // -- tests ------------------------------------------------------------------ fn oid(text: []const u8) ObjectId { return ObjectId.parse(text) catch unreachable; } /// Builds a notification the way a sender would, for driving the receiver /// over a loopback socket. fn notificationBytes( gpa: Allocator, version: Version, community: []const u8, kind: Pdu.Kind, request_id: i32, bindings: []const VarBind, ) ![]u8 { const message = Message.init(version, community, .{ .kind = kind, .body = .{ .standard = .{ .request_id = request_id, .bindings = bindings } }, }); return message.encodeAlloc(gpa); } const loopback: Io.net.IpAddress = .{ .ip4 = .{ .bytes = .{ 127, 0, 0, 1 }, .port = 0 } }; fn shortTimeout() Io.Timeout { return .{ .duration = .{ .raw = .fromMilliseconds(500), .clock = .awake } }; } test "an SNMPv2 trap, with the two bindings RFC 3416 requires" { const gpa = testing.allocator; var io_impl: Io.Threaded = .init(gpa, .{}); defer io_impl.deinit(); const io = io_impl.io(); var r = try Receiver.bind(io, gpa, loopback, .{ .community = "public" }); defer r.close(gpa); // Port zero, so the kernel picked one and `getsockname` is how we learn // it -- which is also the only way a test can avoid a fixed port. const where = r.localAddress(); try testing.expect(where.ip4.port != 0); const cold_start = oid("1.3.6.1.6.3.1.1.5.1"); const bindings = [_]VarBind{ .{ .name = oid(sysUpTime), .value = .{ .data = .{ .timeticks = 12345 } } }, .{ .name = oid(snmpTrapOID), .value = .{ .data = .{ .object_id = cold_start } } }, .{ .name = oid("1.3.6.1.2.1.1.1.0"), .value = .{ .data = .{ .octet_string = "something happened" } } }, }; const bytes = try notificationBytes(gpa, .v2c, "public", .snmpv2_trap, 7, &bindings); defer gpa.free(bytes); var sender = try loopback.bind(io, .{ .mode = .dgram, .protocol = .udp }); defer sender.close(io); try sender.send(io, &where, bytes); var n = try r.next(gpa, shortTimeout()); defer n.deinit(gpa); try testing.expectEqual(Notification.Kind.trap_v2, n.kind); try testing.expectEqual(Version.v2c, n.version); try testing.expectEqualStrings("public", n.community); try testing.expect(!n.needsAcknowledgement()); // The two required bindings, read through the accessors rather than by // index -- which is the point of having them. try testing.expectEqual(@as(?u32, 12345), n.upTime()); try testing.expect(cold_start.eql(n.trapOid().?)); // And the payload is what is left after those two. try testing.expectEqual(@as(usize, 1), n.payload().len); try testing.expectEqualStrings("something happened", n.payload()[0].value.data.octet_string); } test "an inform is acknowledged, and a trap cannot be" { const gpa = testing.allocator; var io_impl: Io.Threaded = .init(gpa, .{}); defer io_impl.deinit(); const io = io_impl.io(); var r = try Receiver.bind(io, gpa, loopback, .{}); defer r.close(gpa); const where = r.localAddress(); const bindings = [_]VarBind{ .{ .name = oid(sysUpTime), .value = .{ .data = .{ .timeticks = 1 } } }, .{ .name = oid(snmpTrapOID), .value = .{ .data = .{ .object_id = oid("1.3.6.1.6.3.1.1.5.2") } } }, }; const bytes = try notificationBytes(gpa, .v2c, "public", .inform_request, 4242, &bindings); defer gpa.free(bytes); var sender = try loopback.bind(io, .{ .mode = .dgram, .protocol = .udp }); defer sender.close(io); try sender.send(io, &where, bytes); var n = try r.next(gpa, shortTimeout()); defer n.deinit(gpa); try testing.expectEqual(Notification.Kind.inform, n.kind); try testing.expect(n.needsAcknowledgement()); try testing.expectEqual(@as(?i32, 4242), n.request_id); try r.acknowledge(gpa, n); // The acknowledgement is a Response echoing the request-id and the // bindings. A sender matches on the id, and getting it wrong makes the // inform look delivered while the sender keeps retrying. var reply_buffer: [Message.max_size]u8 = undefined; const incoming = try sender.receiveTimeout(io, &reply_buffer, shortTimeout()); var reply = try Message.decode(incoming.data, gpa); defer reply.deinit(gpa); try testing.expectEqual(Pdu.Kind.response, reply.pdu().kind); try testing.expectEqual(@as(?i32, 4242), reply.pdu().requestId()); try testing.expectEqual(@as(usize, 2), reply.pdu().varBinds().len); try testing.expect(oid(sysUpTime).eql(reply.pdu().varBinds()[0].name)); } test "a v1 trap, whose structure shares nothing with the others" { const gpa = testing.allocator; var io_impl: Io.Threaded = .init(gpa, .{}); defer io_impl.deinit(); const io = io_impl.io(); var r = try Receiver.bind(io, gpa, loopback, .{}); defer r.close(gpa); const where = r.localAddress(); const payload = [_]VarBind{ .{ .name = oid("1.3.6.1.2.1.2.2.1.1.1"), .value = .{ .data = .{ .integer = 1 } } }, }; const message = Message.init(.v1, "public", .{ .kind = .trap_v1, .body = .{ .trap_v1 = .{ .enterprise = oid("1.3.6.1.4.1.9"), .agent_addr = .{ 192, 168, 4, 64 }, .generic_trap = .link_down, .specific_trap = 0, .time_stamp = 28572867, .bindings = &payload, } }, }); const bytes = try message.encodeAlloc(gpa); defer gpa.free(bytes); var sender = try loopback.bind(io, .{ .mode = .dgram, .protocol = .udp }); defer sender.close(io); try sender.send(io, &where, bytes); var n = try r.next(gpa, shortTimeout()); defer n.deinit(gpa); try testing.expectEqual(Notification.Kind.trap_v1, n.kind); // No request-id, which is the deepest reason a v1 trap cannot be // acknowledged: there is nothing to answer with. try testing.expectEqual(@as(?i32, null), n.request_id); try testing.expect(!n.needsAcknowledgement()); try testing.expectError(error.NotAnInform, r.acknowledge(gpa, n)); // Its timestamp and identity are fields of their own rather than // bindings, so the v2 accessors have nothing to return. try testing.expectEqual(@as(?u32, null), n.upTime()); try testing.expectEqual(@as(?ObjectId, null), n.trapOid()); const v1 = n.v1.?; try testing.expectEqual(@as(u32, 28572867), v1.time_stamp); try testing.expectEqual(Pdu.TrapV1.GenericTrap.link_down, v1.generic_trap); try testing.expectEqualSlices(u8, &.{ 192, 168, 4, 64 }, &v1.agent_addr); // And every binding is payload. try testing.expectEqual(@as(usize, 1), n.payload().len); } test "what a receiver throws away" { const gpa = testing.allocator; var io_impl: Io.Threaded = .init(gpa, .{}); defer io_impl.deinit(); const io = io_impl.io(); var r = try Receiver.bind(io, gpa, loopback, .{ .community = "expected" }); defer r.close(gpa); const where = r.localAddress(); var sender = try loopback.bind(io, .{ .mode = .dgram, .protocol = .udp }); defer sender.close(io); const bindings = [_]VarBind{ .{ .name = oid(sysUpTime), .value = .{ .data = .{ .timeticks = 1 } } }, .{ .name = oid(snmpTrapOID), .value = .{ .data = .{ .object_id = oid("1.3.6.1.6.3.1.1.5.1") } } }, }; // Rubbish, a request sent to the wrong port, a response, and the wrong // community. A receiver on a real network is sent all of these, and one // that reported each as an error would spend its life describing other // people's misconfigurations. try sender.send(io, &where, "not BER at all"); try sender.send(io, &where, "\x30\x80"); { const b = try notificationBytes(gpa, .v2c, "expected", .get_request, 1, &bindings); defer gpa.free(b); try sender.send(io, &where, b); } { const b = try notificationBytes(gpa, .v2c, "expected", .response, 1, &bindings); defer gpa.free(b); try sender.send(io, &where, b); } { const b = try notificationBytes(gpa, .v2c, "not-expected", .snmpv2_trap, 1, &bindings); defer gpa.free(b); try sender.send(io, &where, b); } // None of the above is a notification, so nothing arrives and the // deadline bounds the call rather than a flood of rubbish holding it. try testing.expectError(error.Timeout, r.next(gpa, shortTimeout())); // And then a real one, which must still get through: the discards must // not have left the receiver confused. { const b = try notificationBytes(gpa, .v2c, "expected", .snmpv2_trap, 9, &bindings); defer gpa.free(b); try sender.send(io, &where, b); } var n = try r.next(gpa, shortTimeout()); defer n.deinit(gpa); try testing.expectEqual(Notification.Kind.trap_v2, n.kind); } test "a version the receiver was told not to accept" { const gpa = testing.allocator; var io_impl: Io.Threaded = .init(gpa, .{}); defer io_impl.deinit(); const io = io_impl.io(); var r = try Receiver.bind(io, gpa, loopback, .{ .accept_v1 = false }); defer r.close(gpa); const where = r.localAddress(); var sender = try loopback.bind(io, .{ .mode = .dgram, .protocol = .udp }); defer sender.close(io); const message = Message.init(.v1, "public", .{ .kind = .trap_v1, .body = .{ .trap_v1 = .{ .enterprise = oid("1.3.6.1.4.1.9"), .agent_addr = .{ 127, 0, 0, 1 }, .generic_trap = .cold_start, .specific_trap = 0, .time_stamp = 0, .bindings = &.{}, } }, }); const bytes = try message.encodeAlloc(gpa); defer gpa.free(bytes); try sender.send(io, &where, bytes); try testing.expectError(error.Timeout, r.next(gpa, shortTimeout())); } test "a notification whose required bindings are missing or the wrong type" { const gpa = testing.allocator; var io_impl: Io.Threaded = .init(gpa, .{}); defer io_impl.deinit(); const io = io_impl.io(); var r = try Receiver.bind(io, gpa, loopback, .{}); defer r.close(gpa); const where = r.localAddress(); var sender = try loopback.bind(io, .{ .mode = .dgram, .protocol = .udp }); defer sender.close(io); // RFC 3416 requires sysUpTime.0 and snmpTrapOID.0 first, and a sender // that omits them is malformed -- but a *receiver* that assumed they were // there would read whatever was, so the accessors return null rather than // the wrong thing. const wrong = [_]VarBind{ .{ .name = oid("1.3.6.1.2.1.1.1.0"), .value = .{ .data = .{ .octet_string = "hello" } } }, }; const bytes = try notificationBytes(gpa, .v2c, "public", .snmpv2_trap, 1, &wrong); defer gpa.free(bytes); try sender.send(io, &where, bytes); var n = try r.next(gpa, shortTimeout()); defer n.deinit(gpa); try testing.expectEqual(@as(?u32, null), n.upTime()); try testing.expectEqual(@as(?ObjectId, null), n.trapOid()); // One binding, so there is nothing after the two that should have been // there -- and `payload` must not slice past the end. try testing.expectEqual(@as(usize, 0), n.payload().len); // The right OIDs with the wrong types are also null rather than a // misreading. const mistyped = [_]VarBind{ .{ .name = oid(sysUpTime), .value = .{ .data = .{ .integer = 5 } } }, .{ .name = oid(snmpTrapOID), .value = .{ .data = .{ .octet_string = "not an oid" } } }, }; const bytes2 = try notificationBytes(gpa, .v2c, "public", .snmpv2_trap, 2, &mistyped); defer gpa.free(bytes2); try sender.send(io, &where, bytes2); var n2 = try r.next(gpa, shortTimeout()); defer n2.deinit(gpa); try testing.expectEqual(@as(?u32, null), n2.upTime()); try testing.expectEqual(@as(?ObjectId, null), n2.trapOid()); }