// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Our client against net-snmp's agent. //! //! This is the tier that earns the most per minute, and it is an ordinary //! test rather than a virtual machine because of one convenient fact: `snmpd` //! needs no privilege to answer on a high port. Given //! `SNMP_PERSISTENT_DIR` pointed somewhere writable and an address with a //! port above 1024, it runs as whoever started it -- so the test spawns one, //! talks to it, and kills it, the same way `zig-ldap`'s end-to-end tests talk //! to a server of their own except that this server is the reference //! implementation. //! //! What that buys is worth being explicit about. The unit tests say our //! encoder produces the bytes we think it does, and the checked-in fixture //! says those bytes match one captured from net-snmp. Neither says that a //! real agent *accepts* them, answers them, and that we can read what comes //! back -- and the gap between "well-formed" and "understood" is where a //! protocol implementation actually fails. //! //! These tests skip rather than fail when `snmpd` is not on `PATH`, so a bare //! `zig build test` works for somebody who has not got net-snmp. `nix develop` //! puts it there, and so does the workflow. const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const testing = std.testing; const build_options = @import("build_options"); const snmp = @import("snmp"); const Client = snmp.Client; const ObjectId = snmp.ObjectId; const Value = snmp.Value; const VarBind = snmp.VarBind; /// A running `snmpd`, and everything that has to be cleaned up after it. const Agent = struct { child: std.process.Child, directory: std.testing.TmpDir, port: u16, gpa: Allocator, /// The community the configuration below grants read access to. const read_community = "oracle-ro"; /// And write access, for the Set tests. const write_community = "oracle-rw"; /// A port nothing is listening on, found by binding one ourselves and /// letting go of it. /// /// `snmpd` cannot be told to take whatever the kernel offers, because it /// has no way to report back which port it got --- so the port has to be /// chosen in advance, and the obvious way to choose one is to count up /// from an unlikely number. That was what this did, and it is wrong in a /// way that costs ten minutes every time it happens: if anything else on /// the machine already holds the port, `snmpd` fails to bind and exits, /// `spawn` still succeeds because spawning worked, and the failure /// arrives ten seconds later as `AgentNeverAnswered` with nothing said /// about why. It happened twice in one afternoon to a scratch `snmpd` /// left running in another terminal. /// /// Binding port zero and reading back what the kernel picked is /// better on both counts. It cannot collide with something already /// listening, and it needs no guess about which numbers are unpopular. /// There is still a window between letting go and `snmpd` binding, but /// it is a window rather than a standing conflict, and the kernel does /// not hand the same ephemeral port out twice in quick succession. fn freePort(io: Io) !u16 { const any: Io.net.IpAddress = .{ .ip4 = .{ .bytes = .{ 127, 0, 0, 1 }, .port = 0 } }; var socket = try any.bind(io, .{ .mode = .dgram, .protocol = .udp }); defer socket.close(io); // Filled in by `getsockname` after a bind, so this is *this* end. return socket.address.ip4.port; } /// What the agent is told to be. /// /// `sysDescr` is deliberately multi-line, because the Catalyst's is: its /// `sysDescr` is four lines of IOS banner, so one variable binding is not /// one line of output, and a renderer or a diff that assumes otherwise is /// wrong in a way only a real device would have shown. /// `sysLocation` is configured here and `sysContact` deliberately is /// not, and the difference is load bearing: net-snmp makes an object /// **read-only** once it has been given a value in the configuration /// file. So `sysLocation` is the one to test a refused write against and /// `sysContact` is the one to test an accepted write against, and the /// tests below assert both -- which pins a behaviour of the reference /// implementation rather than restating something about our own code. const config = \\rocommunity oracle-ro 127.0.0.1 \\rwcommunity oracle-rw 127.0.0.1 \\sysServices 72 \\sysLocation a test \\createUser md5des MD5 "authpassword" DES "privpassword" \\createUser shaaes SHA "authpassword" AES "privpassword" \\createUser md5only MD5 "authpassword" \\createUser shaonly SHA "authpassword" \\createUser sha256 SHA-256 "authpassword" AES "privpassword" \\createUser sha512 SHA-512 "authpassword" AES "privpassword" \\rouser md5des priv \\rouser shaaes priv \\rouser md5only auth \\rouser shaonly auth \\rouser sha256 priv \\rouser sha512 priv \\ ; /// The password every user above is created with, for both auth and /// privacy. A fixture, not a secret: it is in this file, in the agent's /// configuration, and nowhere near a real device. const v3_password = "authpassword"; const v3_priv_password = "privpassword"; fn start(io: Io, gpa: Allocator) !Agent { return startWith(io, gpa, ""); } /// As `start`, with extra lines appended to the configuration file. /// /// Used by the notification tests, which have to name the port their /// receiver is listening on --- and cannot know it until the receiver has /// bound, since it asks for port zero and reads back what the kernel /// gave it. So the receiver comes up first and the agent is configured /// around it, rather than the other way round. fn startWith(io: Io, gpa: Allocator, extra: []const u8) !Agent { // Resolved by `build.zig`, which can read the environment where a // test cannot. Absent means net-snmp is not installed, and these // tests are not something to fail over in that case. const snmpd = build_options.snmpd orelse return error.SkipZigTest; var directory = testing.tmpDir(.{}); errdefer directory.cleanup(); // `testing.tmpDir` puts its directory under `.zig-cache/tmp` and // gives back only the last component, so the path is assembled rather // than asked for. Relative is fine: the child inherits our working // directory. const path = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}", .{directory.sub_path}); defer gpa.free(path); const config_path = try std.fmt.allocPrint(gpa, "{s}/snmpd.conf", .{path}); defer gpa.free(config_path); const full = try std.fmt.allocPrint(gpa, "{s}{s}", .{ config, extra }); defer gpa.free(full); try directory.dir.writeFile(io, .{ .sub_path = "snmpd.conf", .data = full }); const listen_port = try freePort(io); const listen = try std.fmt.allocPrint(gpa, "127.0.0.1:{d}", .{listen_port}); defer gpa.free(listen); // A deliberately *minimal* environment, holding one variable. // // `snmpd` writes its own state -- and under v3 the users that // `createUser` derives keys for -- to a persistent directory that // defaults to /var/lib/net-snmp, which an ordinary user cannot write. // Pointing it at the temporary directory fixes that. // // Everything else being absent is the point rather than laziness. // With no `HOME` there is no `~/.snmp/snmpd.conf` to be read, and // with no `MIBDIRS` or `MIBS` there are no site MIBs either, so the // agent under test is configured by the file below and by nothing on // the machine it happens to be running on. A test that picked up a // developer's personal snmpd.conf would pass or fail for reasons // nobody could see. var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); try env.put("SNMP_PERSISTENT_DIR", path); const child = std.process.spawn(io, .{ .argv = &.{ snmpd, "-f", "-Lo", "-c", config_path, listen }, .environ_map = &env, .stdin = .ignore, .stdout = .ignore, .stderr = .ignore, }) catch |err| switch (err) { // No net-snmp: skip rather than fail, so that a bare `zig build // test` works for somebody who has not got it. // The `errdefer` above cleans the directory up; doing it here // as well was a double close, which `Io.Threaded` reports as an // operating system bug rather than as the caller's mistake. error.FileNotFound => return error.SkipZigTest, else => return err, }; return .{ .child = child, .directory = directory, .port = listen_port, .gpa = gpa }; } fn stop(a: *Agent, io: Io) void { a.child.kill(io); a.directory.cleanup(); } fn address(a: *const Agent) Io.net.IpAddress { return .{ .ip4 = .{ .bytes = .{ 127, 0, 0, 1 }, .port = a.port } }; } /// Waits until the agent answers, because spawning it is not the same as /// it being ready and a test that raced would be flaky in CI and nowhere /// else. /// /// This doubles as the first real assertion: if `snmpd` never answers /// anything we send, nothing below is worth running. fn waitUntilReady(a: *const Agent, io: Io, gpa: Allocator) !void { const sys_descr = try ObjectId.parse("1.3.6.1.2.1.1.1.0"); var attempt: usize = 0; while (attempt < 50) : (attempt += 1) { var probe = try Client.open(io, gpa, a.address(), .{ .version = .v2c, .community = read_community, .retries = 0, .timeout = .{ .duration = .{ .raw = .fromMilliseconds(200), .clock = .awake } }, }); defer probe.close(gpa); if (probe.get(gpa, &.{sys_descr})) |response| { var r = response; defer r.deinit(gpa); if (r.error_status == .no_error) return; } else |_| {} } // Ten seconds of silence, and the two reasons for it look identical // from here: the agent never started, or it started and something // else is answering on that port with a configuration of its own. Say // both, because the message is what somebody reads first. std.debug.print( "\n snmpd never answered on 127.0.0.1:{d}.\n" ++ " It either failed to start, or another agent holds that port.\n", .{a.port}, ); return error.AgentNeverAnswered; } }; /// Runs `body` against a freshly started agent. fn withAgent(comptime body: fn (Io, Allocator, *Agent) anyerror!void) !void { const gpa = testing.allocator; var io_impl: Io.Threaded = .init(gpa, .{}); defer io_impl.deinit(); const io = io_impl.io(); var agent = try Agent.start(io, gpa); defer agent.stop(io); try agent.waitUntilReady(io, gpa); try body(io, gpa, &agent); } fn client(io: Io, gpa: Allocator, agent: *Agent, version: snmp.Version, community: []const u8) !Client { return Client.open(io, gpa, agent.address(), .{ .version = version, .community = community, .retries = 2, .timeout = .{ .duration = .{ .raw = .fromMilliseconds(500), .clock = .awake } }, }); } test "a real agent answers a v2c Get" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { var c = try client(io, gpa, agent, .v2c, Agent.read_community); defer c.close(gpa); const sys_descr = try ObjectId.parse("1.3.6.1.2.1.1.1.0"); var r = try c.get(gpa, &.{sys_descr}); defer r.deinit(gpa); try r.expectOk(); try testing.expectEqual(@as(usize, 1), r.bindings.len); try testing.expect(sys_descr.eql(r.bindings[0].name)); // net-snmp reports itself, so the exact text is its business -- // but it is a string and it is not empty. const descr = r.bindings[0].value.data.octet_string; try testing.expect(descr.len > 0); } }.body); } test "a real agent answers v1 as well, with the same bytes but for the version" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { var c = try client(io, gpa, agent, .v1, Agent.read_community); defer c.close(gpa); var r = try c.get(gpa, &.{try ObjectId.parse("1.3.6.1.2.1.1.6.0")}); defer r.deinit(gpa); try r.expectOk(); try testing.expectEqualStrings("a test", r.bindings[0].value.data.octet_string); } }.body); } test "the types a real agent actually sends" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { var c = try client(io, gpa, agent, .v2c, Agent.read_community); defer c.close(gpa); // sysUpTime is TimeTicks, sysObjectID is an OID, sysServices an // INTEGER -- three different tags in one reply, which is the // point: a decoder that only ever saw OCTET STRINGs would pass // every other test in this file. var r = try c.get(gpa, &.{ try ObjectId.parse("1.3.6.1.2.1.1.3.0"), try ObjectId.parse("1.3.6.1.2.1.1.2.0"), try ObjectId.parse("1.3.6.1.2.1.1.7.0"), }); defer r.deinit(gpa); try r.expectOk(); try testing.expectEqual(@as(usize, 3), r.bindings.len); try testing.expectEqual( std.meta.Tag(Value.Data).timeticks, std.meta.activeTag(r.bindings[0].value.data), ); try testing.expectEqual( std.meta.Tag(Value.Data).object_id, std.meta.activeTag(r.bindings[1].value.data), ); try testing.expectEqual(@as(i32, 72), r.bindings[2].value.data.integer); } }.body); } test "GetNext walks, and the order it walks in is the OID order" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { var c = try client(io, gpa, agent, .v2c, Agent.read_community); defer c.close(gpa); const root = try ObjectId.parse("1.3.6.1.2.1.1"); var at = root; var seen: usize = 0; while (seen < 32) : (seen += 1) { var r = try c.getNext(gpa, &.{at}); defer r.deinit(gpa); try r.expectOk(); const next = r.bindings[0].name; // Left the subtree, which is how a walk ends. if (!next.startsWith(root)) break; // And every step must move strictly forwards, or a walk that // trusted the agent would spin for ever. This is the // assertion worth having: it is a claim about the agent as // much as about us. try testing.expectEqual(std.math.Order.lt, at.order(next)); at = next; } // The system group has rather more than a couple of objects, so a // walk that stopped immediately did not walk. try testing.expect(seen > 3); } }.body); } test "GetBulk returns as many as asked, and honours non-repeaters" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { var c = try client(io, gpa, agent, .v2c, Agent.read_community); defer c.close(gpa); const root = try ObjectId.parse("1.3.6.1.2.1.1"); var r = try c.getBulk(gpa, &.{root}, 0, 5); defer r.deinit(gpa); try r.expectOk(); // An agent may return fewer than asked, so this is `<=` on // purpose -- but it must return more than one, or GetBulk is // doing nothing a GetNext would not. try testing.expect(r.bindings.len > 1); try testing.expect(r.bindings.len <= 5); // Every binding must be strictly after the last, which is the // property that makes a bulk walk terminate. for (r.bindings[1..], r.bindings[0 .. r.bindings.len - 1]) |next, previous| { try testing.expectEqual(std.math.Order.lt, previous.name.order(next.name)); } // With one non-repeater and one repeater, the first binding is // answered once and the second up to max-repetitions times. var r2 = try c.getBulk(gpa, &.{ try ObjectId.parse("1.3.6.1.2.1.1.1.0"), root, }, 1, 3); defer r2.deinit(gpa); try r2.expectOk(); try testing.expect(r2.bindings.len > 1); try testing.expect(r2.bindings.len <= 1 + 3); } }.body); } test "v1 says noSuchName where v2c puts a marker in the varbind" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { // The same question, asked twice, answered in two different // shapes by the same agent. This is the distinction the Catalyst // showed with a Counter64 and it is not something either RFC // states as plainly as an agent demonstrates it. const missing = try ObjectId.parse("1.3.6.1.2.1.1.99.0"); { var c = try client(io, gpa, agent, .v1, Agent.read_community); defer c.close(gpa); var r = try c.get(gpa, &.{missing}); defer r.deinit(gpa); // The error is in the PDU, and the index names the binding. try testing.expectEqual(snmp.Pdu.ErrorStatus.no_such_name, r.error_status); try testing.expectEqual(@as(i32, 1), r.error_index); try testing.expect(r.failedBinding() != null); } { var c = try client(io, gpa, agent, .v2c, Agent.read_community); defer c.close(gpa); var r = try c.get(gpa, &.{missing}); defer r.deinit(gpa); // No error at all: the answer is the marker in the value. try r.expectOk(); try testing.expectEqual( std.meta.Tag(Value.Data).no_such_object, std.meta.activeTag(r.bindings[0].value.data), ); } } }.body); } test "a wrong community is not answered at all" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { var c = try Client.open(io, gpa, agent.address(), .{ .version = .v2c, .community = "not-the-community", .retries = 0, .timeout = .{ .duration = .{ .raw = .fromMilliseconds(300), .clock = .awake } }, }); defer c.close(gpa); // SNMPv1 and v2c have no way to say "wrong community" -- an agent // that answered would be telling an unauthenticated stranger that // it exists, so it says nothing and the request times out. That // silence is the whole of the security model, and it is why v3 // exists. try testing.expectError( error.Timeout, c.get(gpa, &.{try ObjectId.parse("1.3.6.1.2.1.1.1.0")}), ); } }.body); } test "a Set that is accepted, and read back" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { var c = try client(io, gpa, agent, .v2c, Agent.write_community); defer c.close(gpa); // sysContact, which the configuration deliberately leaves unset // and which is therefore writable. const sys_contact = try ObjectId.parse("1.3.6.1.2.1.1.4.0"); const bindings = [_]VarBind{.{ .name = sys_contact, .value = .{ .data = .{ .octet_string = "somebody@example.com" } }, }}; var r = try c.set(gpa, &bindings); defer r.deinit(gpa); try r.expectOk(); // And it took. Reading it back is the only way to know the Set // did anything rather than merely being acknowledged. var read = try c.get(gpa, &.{sys_contact}); defer read.deinit(gpa); try read.expectOk(); try testing.expectEqualStrings( "somebody@example.com", read.bindings[0].value.data.octet_string, ); } }.body); } test "an object configured in the file is not writable" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { var c = try client(io, gpa, agent, .v2c, Agent.write_community); defer c.close(gpa); // sysLocation *is* in the configuration, and net-snmp makes such // an object read-only -- the file wins over the wire. Asserting // it pins a behaviour of the reference implementation, and it is // also the only easy way to get a `notWritable` out of an agent // that is otherwise entirely cooperative. const bindings = [_]VarBind{.{ .name = try ObjectId.parse("1.3.6.1.2.1.1.6.0"), .value = .{ .data = .{ .octet_string = "somewhere else" } }, }}; var r = try c.set(gpa, &bindings); defer r.deinit(gpa); try testing.expectEqual(snmp.Pdu.ErrorStatus.not_writable, r.error_status); try testing.expectEqual(@as(i32, 1), r.error_index); try testing.expect(r.failedBinding() != null); } }.body); } test "the read-only community may not write, and is not told why" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { var c = try client(io, gpa, agent, .v2c, Agent.read_community); defer c.close(gpa); const bindings = [_]VarBind{.{ .name = try ObjectId.parse("1.3.6.1.2.1.1.4.0"), .value = .{ .data = .{ .octet_string = "not allowed" } }, }}; // Silence, for the same reason a wrong community gets silence: // the request is not authorised, so there is nobody to report to. // If it does answer, it must be a refusal rather than a success. if (c.set(gpa, &bindings)) |response| { var r = response; defer r.deinit(gpa); try testing.expect(r.error_status != .no_error); } else |err| { try testing.expectEqual(error.Timeout, err); } } }.body); } test "a Set of the wrong type is refused rather than coerced" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { var c = try client(io, gpa, agent, .v2c, Agent.write_community); defer c.close(gpa); // sysLocation is an OCTET STRING, so an INTEGER is the wrong // type. A v2c agent has a code for exactly this, which a v1 // agent does not -- it would say badValue. const bindings = [_]VarBind{.{ .name = try ObjectId.parse("1.3.6.1.2.1.1.6.0"), .value = .{ .data = .{ .integer = 42 } }, }}; var r = try c.set(gpa, &bindings); defer r.deinit(gpa); try testing.expect(r.error_status != .no_error); try testing.expectEqual(@as(i32, 1), r.error_index); } }.body); } test "walking the whole system group, both ways round" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { const root = try ObjectId.parse("1.3.6.1.2.1.1"); // GetNext and GetBulk must walk the *same* subtree and return the // same objects in the same order -- one round trip per object // against one per batch. If they disagree, one of them is wrong, // and a test of either alone could not tell which. var plain: Io.Writer.Allocating = .init(gpa); defer plain.deinit(); var bulk: Io.Writer.Allocating = .init(gpa); defer bulk.deinit(); for ([_]bool{ false, true }) |use_bulk| { var c = try client(io, gpa, agent, .v2c, Agent.read_community); defer c.close(gpa); var w = c.walk(root, .{ .bulk = use_bulk, .max_repetitions = 4 }); defer w.deinit(gpa); const out = if (use_bulk) &bulk else &plain; var count: usize = 0; while (try w.next(gpa)) |binding| { count += 1; // Only the name, because sysUpTime changes between the // two walks and would be a false difference. try out.writer.print("{f}\n", .{binding.name}); } try testing.expect(count > 3); } try testing.expectEqualStrings(plain.written(), bulk.written()); } }.body); } test "a walk of a subtree stops at its edge" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { var c = try client(io, gpa, agent, .v2c, Agent.read_community); defer c.close(gpa); // sysDescr has exactly one instance, so a walk rooted at the // object rather than the group yields exactly one binding and // then notices it has left. That is the boundary check doing the // work: the agent happily carries on into sysObjectID and the // walk is what stops. const sys_descr = try ObjectId.parse("1.3.6.1.2.1.1.1"); var w = c.walk(sys_descr, .{}); defer w.deinit(gpa); const first = (try w.next(gpa)).?; try testing.expect(first.name.startsWith(sys_descr)); try testing.expectEqual(@as(?VarBind, null), try w.next(gpa)); } }.body); } test "a walk under v1 ends on noSuchName" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { var c = try client(io, gpa, agent, .v1, Agent.read_community); defer c.close(gpa); // Version 1 has no endOfMibView marker, so an agent that has run // out says noSuchName in the PDU instead. Walking past the end of // everything is how that path is reached -- and it is an ending // rather than a failure, which a walk that treated every // error-status alike would get wrong. var w = c.walk(try ObjectId.parse("1.3.6.1.2.1.1.1"), .{}); defer w.deinit(gpa); var count: usize = 0; while (try w.next(gpa)) |_| count += 1; try testing.expectEqual(@as(usize, 1), count); } }.body); } // -- version 3 --------------------------------------------------------------- fn v3Client(io: Io, gpa: Allocator, agent: *Agent, user: snmp.usm.User) !Client { return Client.open(io, gpa, agent.address(), .{ .version = .v3, .user = user, .retries = 2, .timeout = .{ .duration = .{ .raw = .fromMilliseconds(2000), .clock = .awake } }, }); } test "engine discovery learns the agent's identity" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { var c = try v3Client(io, gpa, agent, .{ .name = "md5only" }); defer c.close(gpa); // Nothing is known before the first request. try testing.expect(!c.engine.known); try c.discover(gpa); try testing.expect(c.engine.known); // net-snmp builds an engine ID beginning 0x80 -- the // "enterprise-specific" format of RFC 3411 §5 -- and it is never // empty, because an agent with no engine ID could not be // authenticated to at all. const id = c.engine.engineId(); try testing.expect(id.len > 0); try testing.expect(id.len <= Client.max_engine_id); try testing.expectEqual(@as(u8, 0x80), id[0] & 0x80); // Boots is at least one: the agent has started. try testing.expect(c.engine.boots >= 1); } }.body); } test "every authentication protocol authenticates" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { // The truncation lengths differ per protocol -- 12, 12, 24 and 48 // octets here -- and getting one wrong authenticates against // nothing, with net-snmp reporting only "Authentication failure" // and no hint which. So each is its own case. const cases = [_]struct { []const u8, snmp.usm.AuthProtocol }{ .{ "md5only", .hmac_md5_96 }, .{ "shaonly", .hmac_sha1_96 }, }; for (cases) |case| { var c = try v3Client(io, gpa, agent, .{ .name = case[0], .level = .auth_no_priv, .auth = case[1], .auth_password = Agent.v3_password, }); defer c.close(gpa); var r = try c.get(gpa, &.{try ObjectId.parse("1.3.6.1.2.1.1.6.0")}); defer r.deinit(gpa); try r.expectOk(); try testing.expectEqualStrings("a test", r.bindings[0].value.data.octet_string); } } }.body); } test "the SHA-2 protocols, which RFC 7860 added and publishes no vectors for" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { // The key derivation for these was checked against an independent // implementation, but only a real agent says whether the // *truncation* lengths are right -- 24 octets for SHA-256 and 48 // for SHA-512 -- since nothing in the unit tests would notice a // digest of the wrong width. const cases = [_]struct { []const u8, snmp.usm.AuthProtocol }{ .{ "sha256", .hmac_sha256_192 }, .{ "sha512", .hmac_sha512_384 }, }; for (cases) |case| { var c = try v3Client(io, gpa, agent, .{ .name = case[0], .level = .auth_priv, .auth = case[1], .priv = .aes_128_cfb, .auth_password = Agent.v3_password, .priv_password = Agent.v3_priv_password, }); defer c.close(gpa); var r = try c.get(gpa, &.{try ObjectId.parse("1.3.6.1.2.1.1.6.0")}); defer r.deinit(gpa); try r.expectOk(); try testing.expectEqualStrings("a test", r.bindings[0].value.data.octet_string); } } }.body); } test "both privacy protocols encrypt and decrypt" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { const cases = [_]struct { []const u8, snmp.usm.AuthProtocol, snmp.usm.PrivProtocol }{ .{ "md5des", .hmac_md5_96, .des_cbc }, .{ "shaaes", .hmac_sha1_96, .aes_128_cfb }, }; for (cases) |case| { var c = try v3Client(io, gpa, agent, .{ .name = case[0], .level = .auth_priv, .auth = case[1], .priv = case[2], .auth_password = Agent.v3_password, .priv_password = Agent.v3_priv_password, }); defer c.close(gpa); // Several values of different types, because a decryption // that half worked could still return one plausible string. var r = try c.get(gpa, &.{ try ObjectId.parse("1.3.6.1.2.1.1.6.0"), try ObjectId.parse("1.3.6.1.2.1.1.7.0"), try ObjectId.parse("1.3.6.1.2.1.1.3.0"), }); defer r.deinit(gpa); try r.expectOk(); try testing.expectEqual(@as(usize, 3), r.bindings.len); try testing.expectEqualStrings("a test", r.bindings[0].value.data.octet_string); try testing.expectEqual(@as(i32, 72), r.bindings[1].value.data.integer); try testing.expectEqual( std.meta.Tag(Value.Data).timeticks, std.meta.activeTag(r.bindings[2].value.data), ); } } }.body); } test "a wrong password is reported as a wrong digest, not a timeout" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { var c = try v3Client(io, gpa, agent, .{ .name = "md5only", .level = .auth_no_priv, .auth = .hmac_md5_96, .auth_password = "the wrong password entirely", }); defer c.close(gpa); // This is what v3 buys over v2c diagnostically: a community // string that is wrong gets silence, but a USM failure gets a // Report PDU naming the counter. The agent can say so because // the message identified a user it knows. try testing.expectError( error.WrongDigest, c.get(gpa, &.{try ObjectId.parse("1.3.6.1.2.1.1.6.0")}), ); } }.body); } test "a user the agent does not know is named as such" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { var c = try v3Client(io, gpa, agent, .{ .name = "nobody-by-that-name", .level = .auth_no_priv, .auth = .hmac_md5_96, .auth_password = Agent.v3_password, }); defer c.close(gpa); try testing.expectError( error.UnknownUserName, c.get(gpa, &.{try ObjectId.parse("1.3.6.1.2.1.1.6.0")}), ); } }.body); } test "a wrong privacy password gets silence, and that is correct" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { var c = try v3Client(io, gpa, agent, .{ .name = "shaaes", .level = .auth_priv, .auth = .hmac_sha1_96, .priv = .aes_128_cfb, // Right authentication, wrong privacy. The message // authenticates, so the agent accepts it and *then* cannot // make sense of the ciphertext. .auth_password = Agent.v3_password, .priv_password = "the wrong privacy password", }); defer c.close(gpa); // A timeout, not a report -- and this is the answer net-snmp's // *own* client gets against the same agent, which is how it was // settled. The agent logs "security service 3 error parsing // ScopedPDU" and says nothing at all. // // The reasoning is sound rather than a gap: RFC 3414 §3.2 has the // agent report a decryption error only when it can attribute the // message, and it cannot attribute garbage it could not decrypt. // Answering would tell an attacker which of two passwords was // wrong. // // So this test pins the *absence* of a diagnostic, which is worth // asserting precisely because it looks like a missing feature. try testing.expectError( error.Timeout, c.get(gpa, &.{try ObjectId.parse("1.3.6.1.2.1.1.6.0")}), ); } }.body); } test "a v3 walk, which is discovery plus a loop" { try withAgent(struct { fn body(io: Io, gpa: Allocator, agent: *Agent) anyerror!void { var c = try v3Client(io, gpa, agent, .{ .name = "shaaes", .level = .auth_priv, .auth = .hmac_sha1_96, .priv = .aes_128_cfb, .auth_password = Agent.v3_password, .priv_password = Agent.v3_priv_password, }); defer c.close(gpa); // Every step is authenticated and encrypted, and the keys are // derived once -- a walk that re-derived per request would spend // a megabyte of hashing per object. var w = c.walk(try ObjectId.parse("1.3.6.1.2.1.1"), .{ .bulk = true, .max_repetitions = 4 }); defer w.deinit(gpa); var count: usize = 0; while (try w.next(gpa)) |_| count += 1; try testing.expect(count > 3); } }.body); } // -- the other direction: net-snmp sending at our receiver -------------------- const Receiver = snmp.Receiver; /// Runs one of net-snmp's notification senders and waits for it to finish. /// /// This is the only tier that tests our *decoder* against net-snmp's /// *encoder*. Everywhere else we encode and net-snmp decodes; a trap goes the /// other way, so a disagreement neither side had noticed shows up here and /// nowhere else. fn runSender(io: Io, gpa: Allocator, argv: []const []const u8) !void { var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); var child = std.process.spawn(io, .{ .argv = argv, .environ_map = &env, .stdin = .ignore, .stdout = .ignore, .stderr = .ignore, }) catch |err| switch (err) { error.FileNotFound => return error.SkipZigTest, else => return err, }; _ = child.wait(io) catch {}; } fn withReceiver(comptime body: fn (Io, Allocator, *Receiver, []const u8) anyerror!void) !void { return withConfiguredReceiver(.{ .community = "trapcommunity" }, body); } /// This receiver's own engine ID, which a v3 inform is authenticated against /// and which a sender discovers. /// /// Enterprise zero on purpose: it is not anybody's, which is the honest thing /// for a test fixture. A real receiver supplies its owner's number, because /// an engine ID identifies whoever is running it -- 8072 would be claiming to /// be net-snmp. const receiver_engine_octets = [_]u8{ 0x01, 0x02, 0x03, 0x04 }; fn withConfiguredReceiver( options: Receiver.Options, comptime body: fn (Io, Allocator, *Receiver, []const u8) anyerror!void, ) !void { const gpa = testing.allocator; var io_impl: Io.Threaded = .init(gpa, .{}); defer io_impl.deinit(); const io = io_impl.io(); // Port zero: the kernel picks, and `getsockname` reports it -- so this // needs no privilege and cannot collide with anything. Port 162 is what // the NixOS test is for. var r = try Receiver.bind(io, gpa, .{ .ip4 = .{ .bytes = .{ 127, 0, 0, 1 }, .port = 0 }, }, options); defer r.close(gpa); const where = try std.fmt.allocPrint(gpa, "127.0.0.1:{d}", .{r.localAddress().ip4.port}); defer gpa.free(where); try body(io, gpa, &r, where); } test "an SNMPv2 trap sent by net-snmp's snmptrap" { try withReceiver(struct { fn body(io: Io, gpa: Allocator, r: *Receiver, where: []const u8) anyerror!void { const snmptrap = build_options.snmptrap orelse return error.SkipZigTest; // `snmptrap -v 2c` takes the uptime, the trap OID, and then // OID/type/value triples. An empty uptime means "now". try runSender(io, gpa, &.{ snmptrap, "-v", "2c", "-c", "trapcommunity", where, "", "1.3.6.1.6.3.1.1.5.1", "1.3.6.1.2.1.1.1.0", "s", "something happened", }); var n = try r.next(gpa, .{ .duration = .{ .raw = .fromSeconds(5), .clock = .awake } }); defer n.deinit(gpa); try testing.expectEqual(Receiver.Notification.Kind.trap_v2, n.kind); try testing.expectEqual(snmp.Version.v2c, n.version); try testing.expectEqualStrings("trapcommunity", n.community); // net-snmp fills in the two bindings RFC 3416 requires, which is // the thing worth checking: we did not construct this message, so // this is net-snmp's idea of a notification being read by ours. try testing.expect(n.upTime() != null); const cold_start = try ObjectId.parse("1.3.6.1.6.3.1.1.5.1"); try testing.expect(cold_start.eql(n.trapOid().?)); try testing.expectEqual(@as(usize, 1), n.payload().len); try testing.expectEqualStrings( "something happened", n.payload()[0].value.data.octet_string, ); } }.body); } test "an inform sent by net-snmp, which retries until acknowledged" { try withReceiver(struct { fn body(io: Io, gpa: Allocator, r: *Receiver, where: []const u8) anyerror!void { // `snmptrap -Ci` rather than the `snmpinform` symlink. // // net-snmp installs `snmpinform` as a symlink to `snmptrap` and // dispatches on argv[0] -- the same trick this library's own // tools use -- and that dispatch did not survive being spawned // with a full path here: it sent a trap, and the test caught a // trap_v2 where it wanted an inform. The documented flag does not // depend on the name at all. const snmptrap = build_options.snmptrap orelse return error.SkipZigTest; // Sent in the background, because an inform sender does not exit // until it is acknowledged or gives up -- which is precisely the // difference from a trap, and waiting for it first would // deadlock. var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); var child = std.process.spawn(io, .{ .argv = &.{ snmptrap, "-v", "2c", "-c", "trapcommunity", "-Ci", "-r", "3", "-t", "2", where, "", "1.3.6.1.6.3.1.1.5.2", "1.3.6.1.2.1.1.1.0", "s", "please confirm", }, .environ_map = &env, .stdin = .ignore, .stdout = .ignore, .stderr = .ignore, }) catch |err| switch (err) { error.FileNotFound => return error.SkipZigTest, else => return err, }; // Killed only if this test fails before acknowledging; the // success path waits for it below. `wait` clears `child.id`, so // waiting twice asserts -- which is what a `defer wait` beside // the explicit one did. var reaped = false; errdefer if (!reaped) child.kill(io); var n = try r.next(gpa, .{ .duration = .{ .raw = .fromSeconds(5), .clock = .awake } }); defer n.deinit(gpa); try testing.expectEqual(Receiver.Notification.Kind.inform, n.kind); try testing.expect(n.needsAcknowledgement()); try testing.expect(n.request_id != null); try testing.expectEqualStrings("please confirm", n.payload()[0].value.data.octet_string); // Acknowledging is what lets the sender exit. Without it // `snmpinform` would retry three times and then fail -- which is // how forgetting to acknowledge presents in production: duplicate // notifications and a working system everywhere else. try r.acknowledge(gpa, n); const term = try child.wait(io); reaped = true; try testing.expectEqual(@as(u8, 0), switch (term) { .exited => |code| code, else => 1, }); } }.body); } test "a v1 trap sent by net-snmp, whose shape is entirely different" { try withReceiver(struct { fn body(io: Io, gpa: Allocator, r: *Receiver, where: []const u8) anyerror!void { const snmptrap = build_options.snmptrap orelse return error.SkipZigTest; // `snmptrap -v 1` takes the enterprise, the agent address, the // generic and specific trap numbers, and the uptime -- all of // which are *fields* rather than bindings, which is why v1 and v2 // traps share no structure at all. try runSender(io, gpa, &.{ snmptrap, "-v", "1", "-c", "trapcommunity", where, "1.3.6.1.4.1.9", "192.168.4.64", "2", "0", "28572867", "1.3.6.1.2.1.2.2.1.1.1", "i", "1", }); var n = try r.next(gpa, .{ .duration = .{ .raw = .fromSeconds(5), .clock = .awake } }); defer n.deinit(gpa); try testing.expectEqual(Receiver.Notification.Kind.trap_v1, n.kind); try testing.expectEqual(snmp.Version.v1, n.version); // No request-id, so nothing to acknowledge with. try testing.expectEqual(@as(?i32, null), n.request_id); try testing.expectError(error.NotAnInform, r.acknowledge(gpa, n)); const v1 = n.v1.?; try testing.expect((try ObjectId.parse("1.3.6.1.4.1.9")).eql(v1.enterprise)); try testing.expectEqualSlices(u8, &.{ 192, 168, 4, 64 }, &v1.agent_addr); try testing.expectEqual(snmp.Pdu.TrapV1.GenericTrap.link_down, v1.generic_trap); try testing.expectEqual(@as(u32, 28572867), v1.time_stamp); // The v2 accessors have nothing to say about a v1 trap. try testing.expectEqual(@as(?u32, null), n.upTime()); try testing.expectEqual(@as(?ObjectId, null), n.trapOid()); try testing.expectEqual(@as(usize, 1), n.payload().len); try testing.expectEqual(@as(i32, 1), n.payload()[0].value.data.integer); } }.body); } // -- v3 notifications, sent by net-snmp -------------------------------------- /// The engine ID the receiver below reports to a sender discovering it. var receiver_engine_storage: [32]u8 = undefined; fn receiverEngineId() []const u8 { receiver_engine_storage = Receiver.engineId(0, &receiver_engine_octets) catch unreachable; return receiver_engine_storage[0..Receiver.engineIdLength(receiver_engine_octets.len)]; } /// The sender's own engine ID, which a v3 *trap* is authenticated against /// because the sender is the authoritative engine for one. const sender_engine_hex = "0x80001f8880010203"; const v3_trap_user: snmp.usm.User = .{ .name = "trapuser", .level = .auth_priv, .auth = .hmac_sha1_96, .priv = .aes_128_cfb, .auth_password = "authpassword", .priv_password = "privpassword", }; test "a v3 trap, authenticated against the sender's engine" { try withConfiguredReceiver(.{ .users = &.{v3_trap_user}, .engine_id = receiverEngineId(), }, struct { fn body(io: Io, gpa: Allocator, r: *Receiver, where: []const u8) anyerror!void { const snmptrap = build_options.snmptrap orelse return error.SkipZigTest; // `-e` names the sender's engine. A trap is self-contained: the // sender is authoritative, so there is no exchange beforehand and // the receiver derives keys against the engine ID in the message. try runSender(io, gpa, &.{ snmptrap, "-v3", "-e", sender_engine_hex, "-u", v3_trap_user.name, "-a", "SHA", "-A", v3_trap_user.auth_password, "-x", "AES", "-X", v3_trap_user.priv_password, "-l", "authPriv", where, "", "1.3.6.1.6.3.1.1.5.1", "1.3.6.1.2.1.1.1.0", "s", "an encrypted v3 trap", }); var n = try r.next(gpa, .{ .duration = .{ .raw = .fromSeconds(5), .clock = .awake } }); defer n.deinit(gpa); try testing.expectEqual(Receiver.Notification.Kind.trap_v2, n.kind); try testing.expectEqual(snmp.Version.v3, n.version); try testing.expectEqualStrings(v3_trap_user.name, n.user); try testing.expectEqual(snmp.usm.SecurityLevel.auth_priv, n.level); // The authoritative engine is the *sender's*, not ours -- which // is the whole difference from an inform. try testing.expect(!std.mem.eql(u8, receiverEngineId(), n.engine_id)); try testing.expectEqual(@as(u8, 0x80), n.engine_id[0] & 0x80); // A trap needs no answer, so there is nothing to acknowledge. try testing.expect(!n.needsAcknowledgement()); try testing.expectError(error.NotAnInform, r.acknowledge(gpa, n)); // And the payload came through the encryption intact. try testing.expectEqualStrings( "an encrypted v3 trap", n.payload()[0].value.data.octet_string, ); } }.body); } test "a v3 inform, which cannot be sent until we answer discovery" { try withConfiguredReceiver(.{ .users = &.{v3_trap_user}, .engine_id = receiverEngineId(), }, struct { fn body(io: Io, gpa: Allocator, r: *Receiver, where: []const u8) anyerror!void { const snmptrap = build_options.snmptrap orelse return error.SkipZigTest; // No `-e` this time, and that is the point: for an inform the // *receiver* is authoritative, so the sender begins by // discovering us -- an unauthenticated reportable message with // everything empty -- and cannot send the inform at all until // that is answered. net-snmp's sender times out against a // receiver that stays quiet, which is how this was found. var env: std.process.Environ.Map = .init(gpa); defer env.deinit(); var child = std.process.spawn(io, .{ .argv = &.{ snmptrap, "-v3", "-Ci", "-u", v3_trap_user.name, "-a", "SHA", "-A", v3_trap_user.auth_password, "-x", "AES", "-X", v3_trap_user.priv_password, "-l", "authPriv", "-r", "3", "-t", "3", where, "", "1.3.6.1.6.3.1.1.5.2", "1.3.6.1.2.1.1.1.0", "s", "an encrypted v3 inform", }, .environ_map = &env, .stdin = .ignore, .stdout = .ignore, .stderr = .ignore, }) catch |err| switch (err) { error.FileNotFound => return error.SkipZigTest, else => return err, }; var reaped = false; errdefer if (!reaped) child.kill(io); // `next` answers the discovery itself and then returns the inform // that follows, so the caller never sees the exchange. var n = try r.next(gpa, .{ .duration = .{ .raw = .fromSeconds(10), .clock = .awake } }); defer n.deinit(gpa); try testing.expectEqual(Receiver.Notification.Kind.inform, n.kind); try testing.expectEqual(snmp.Version.v3, n.version); try testing.expect(n.needsAcknowledgement()); // *Our* engine, because we are authoritative for an inform. try testing.expectEqualSlices(u8, receiverEngineId(), n.engine_id); try testing.expectEqualStrings( "an encrypted v3 inform", n.payload()[0].value.data.octet_string, ); // The acknowledgement has to be authenticated *and encrypted*, // because the inform was: a sender that encrypted its inform has // no reason to believe a plaintext answer, and would keep // retrying. `snmptrap -Ci` exits zero only when it accepted the // answer, so its exit code is the assertion. try r.acknowledge(gpa, n); const term = try child.wait(io); reaped = true; try testing.expectEqual(@as(u8, 0), switch (term) { .exited => |code| code, else => 1, }); } }.body); } test "a v3 notification from a user we do not know is ignored" { try withConfiguredReceiver(.{ .users = &.{v3_trap_user}, .engine_id = receiverEngineId(), }, struct { fn body(io: Io, gpa: Allocator, r: *Receiver, where: []const u8) anyerror!void { const snmptrap = build_options.snmptrap orelse return error.SkipZigTest; // Right protocols, wrong user. A receiver that accepted this // would be accepting anything, since the user name is what // selects the key. try runSender(io, gpa, &.{ snmptrap, "-v3", "-e", sender_engine_hex, "-u", "somebody-else", "-a", "SHA", "-A", "authpassword", "-l", "authNoPriv", where, "", "1.3.6.1.6.3.1.1.5.1", }); try testing.expectError( error.Timeout, r.next(gpa, .{ .duration = .{ .raw = .fromSeconds(2), .clock = .awake } }), ); } }.body); } test "a v3 notification with the wrong password is ignored" { try withConfiguredReceiver(.{ .users = &.{v3_trap_user}, .engine_id = receiverEngineId(), }, struct { fn body(io: Io, gpa: Allocator, r: *Receiver, where: []const u8) anyerror!void { const snmptrap = build_options.snmptrap orelse return error.SkipZigTest; // The right user with the wrong key. This is the assertion that // makes all the others mean something: a receiver that never // checked a digest would pass every test above. try runSender(io, gpa, &.{ snmptrap, "-v3", "-e", sender_engine_hex, "-u", v3_trap_user.name, "-a", "SHA", "-A", "the wrong password entirely", "-x", "AES", "-X", v3_trap_user.priv_password, "-l", "authPriv", where, "", "1.3.6.1.6.3.1.1.5.1", }); try testing.expectError( error.Timeout, r.next(gpa, .{ .duration = .{ .raw = .fromSeconds(2), .clock = .awake } }), ); } }.body); } test "an unauthenticated v3 notification is not believed" { try withConfiguredReceiver(.{ .users = &.{.{ .name = "noauthuser", .level = .no_auth_no_priv, }}, .engine_id = receiverEngineId(), }, struct { fn body(io: Io, gpa: Allocator, r: *Receiver, where: []const u8) anyerror!void { const snmptrap = build_options.snmptrap orelse return error.SkipZigTest; // noAuthNoPriv is a real security level and a sender may use it, // but a notification at that level carries no evidence of who // sent it -- so believing one would make v3 *weaker* than v2c, // which at least has a community string. It is dropped, and the // discovery half of the same path still works. try runSender(io, gpa, &.{ snmptrap, "-v3", "-e", sender_engine_hex, "-u", "noauthuser", "-l", "noAuthNoPriv", where, "", "1.3.6.1.6.3.1.1.5.1", }); try testing.expectError( error.Timeout, r.next(gpa, .{ .duration = .{ .raw = .fromSeconds(2), .clock = .awake } }), ); } }.body); } test "a v3 trap under each authentication and privacy protocol" { // DES and MD5 as well as AES and SHA, because the two privacy protocols // build their IV differently -- DES from the key's second half XORed with // the salt, AES from boots, time and salt -- and a receiver that got one // right could have the other wrong. const combinations = [_]struct { []const u8, []const u8, snmp.usm.AuthProtocol, snmp.usm.PrivProtocol, }{ .{ "MD5", "DES", .hmac_md5_96, .des_cbc }, .{ "SHA", "AES", .hmac_sha1_96, .aes_128_cfb }, .{ "SHA-256", "AES", .hmac_sha256_192, .aes_128_cfb }, }; inline for (combinations) |combo| { try withConfiguredReceiver(.{ .users = &.{.{ .name = "multiuser", .level = .auth_priv, .auth = combo[2], .priv = combo[3], .auth_password = "authpassword", .priv_password = "privpassword", }}, .engine_id = receiverEngineId(), }, struct { fn body(io: Io, gpa: Allocator, r: *Receiver, where: []const u8) anyerror!void { const snmptrap = build_options.snmptrap orelse return error.SkipZigTest; try runSender(io, gpa, &.{ snmptrap, "-v3", "-e", sender_engine_hex, "-u", "multiuser", "-a", combo[0], "-A", "authpassword", "-x", combo[1], "-X", "privpassword", "-l", "authPriv", where, "", "1.3.6.1.6.3.1.1.5.1", "1.3.6.1.2.1.1.1.0", "s", "one of several", }); var n = try r.next(gpa, .{ .duration = .{ .raw = .fromSeconds(5), .clock = .awake } }); defer n.deinit(gpa); try testing.expectEqual(Receiver.Notification.Kind.trap_v2, n.kind); try testing.expectEqualStrings( "one of several", n.payload()[0].value.data.octet_string, ); } }.body); } } // -- a notification the agent decided to send ------------------------------- /// `authenticationFailure`, from SNMPv2-MIB's `snmpTraps` group. const authentication_failure = "1.3.6.1.6.3.1.1.5.5"; /// An agent that sends its own notifications, and a receiver to catch them. /// /// Every other notification test here runs net-snmp's `snmptrap`, which is a /// program whose whole job is to send one. This is the other shape and the /// one that happens in the field: an *agent*, going about its business, /// deciding on its own that something has happened and telling somebody. The /// difference is not cosmetic --- the agent builds the varbind list itself, /// picks its own request-id, and retries an inform on its own schedule --- /// and it is the shape `tests/device.zig` uses against a real switch, which /// is the other reason to have it covered here where it runs in CI. /// /// The provocation is the interesting part. A well-behaved agent sends /// nothing for days, so a test has to make something happen, and the cheapest /// something is a request with a community the agent does not know: /// `authtrapenable 1` turns that into an `authenticationFailure` notification /// and nothing else about the agent is disturbed. No write, no interface /// bounced, and repeatable a second later. fn withNotifyingAgent( comptime sink: []const u8, comptime body: fn (Io, Allocator, *Agent, *Receiver) anyerror!void, ) !void { const gpa = testing.allocator; var io_impl: Io.Threaded = .init(gpa, .{}); defer io_impl.deinit(); const io = io_impl.io(); // The receiver first, because the agent's configuration has to name its // port and port zero means the kernel has not chosen one yet. var r = try Receiver.bind(io, gpa, .{ .ip4 = .{ .bytes = .{ 127, 0, 0, 1 }, .port = 0 }, }, .{ .community = "trapcommunity" }); defer r.close(gpa); const extra = try std.fmt.allocPrint(gpa, \\authtrapenable 1 \\{s} 127.0.0.1:{d} trapcommunity \\ , .{ sink, r.localAddress().ip4.port }); defer gpa.free(extra); var agent = try Agent.startWith(io, gpa, extra); defer agent.stop(io); try agent.waitUntilReady(io, gpa); try body(io, gpa, &agent, &r); } /// Asks the agent a question with a community it does not know. /// /// The agent does not answer --- refusing to answer is the whole of what it /// is being asked to demonstrate --- so the timeout is the expected result /// and an *answer* would be the failure. fn provoke(io: Io, gpa: Allocator, agent: *Agent) !void { var c = try Client.open(io, gpa, agent.address(), .{ .version = .v2c, .community = "oracle-deliberately-wrong", .retries = 0, .timeout = .{ .duration = .{ .raw = .fromMilliseconds(300), .clock = .awake } }, }); defer c.close(gpa); const sys_descr = try ObjectId.parse("1.3.6.1.2.1.1.1.0"); if (c.get(gpa, &.{sys_descr})) |response| { var got = response; got.deinit(gpa); return error.AgentAcceptedAnyCommunity; } else |_| {} } /// Provokes until a notification carrying `want` arrives. fn awaitProvoked( io: Io, gpa: Allocator, agent: *Agent, r: *Receiver, want: []const u8, ) !Receiver.Notification { const wanted = try ObjectId.parse(want); var attempt: usize = 0; while (attempt < 10) : (attempt += 1) { try provoke(io, gpa, agent); var n = r.next(gpa, .{ .duration = .{ .raw = .fromMilliseconds(1000), .clock = .awake, } }) catch continue; if (n.trapOid()) |got| { if (got.eql(wanted)) return n; } n.deinit(gpa); } return error.NoNotificationArrived; } test "a trap the agent sent on its own, because we asked it a question wrongly" { try withNotifyingAgent("trap2sink", struct { fn body(io: Io, gpa: Allocator, agent: *Agent, r: *Receiver) anyerror!void { var n = try awaitProvoked(io, gpa, agent, r, authentication_failure); defer n.deinit(gpa); try testing.expectEqual(Receiver.Notification.Kind.trap_v2, n.kind); try testing.expectEqual(snmp.Version.v2c, n.version); try testing.expectEqualStrings("trapcommunity", n.community); // RFC 3416 §4.2.6: `sysUpTime.0` then `snmpTrapOID.0`, in that // order, and everything after is what the notification is about. // Asserted positionally rather than by search, because that is // the claim -- a receiver that looked them up by OID would agree // with a sender that puts them first and quietly disagree with // one that does not. try testing.expect(n.bindings.len >= 2); try testing.expect(n.bindings[0].name.eql(try ObjectId.parse(Receiver.sysUpTime))); try testing.expect(n.bindings[1].name.eql(try ObjectId.parse(Receiver.snmpTrapOID))); try testing.expect(n.upTime() != null); // Fire and forget: no request-id, so nothing to answer with. try testing.expect(!n.needsAcknowledgement()); } }.body); } test "an inform the agent sent on its own, and stopped resending once answered" { try withNotifyingAgent("informsink", struct { fn body(io: Io, gpa: Allocator, agent: *Agent, r: *Receiver) anyerror!void { var n = try awaitProvoked(io, gpa, agent, r, authentication_failure); defer n.deinit(gpa); try testing.expectEqual(Receiver.Notification.Kind.inform, n.kind); try testing.expect(n.needsAcknowledgement()); try testing.expect(n.request_id != null); try r.acknowledge(gpa, n); // The whole difference from a trap: an inform is resent until the // sender hears its own request-id back. Seeing that id again // would mean the acknowledgement did not satisfy it. var quiet: usize = 0; while (quiet < 4) : (quiet += 1) { var again = r.next(gpa, .{ .duration = .{ .raw = .fromMilliseconds(700), .clock = .awake, } }) catch break; defer again.deinit(gpa); if (again.request_id) |id| try testing.expect(id != n.request_id.?); } } }.body); }