// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Against a real switch, opt-in, and never in CI. //! //! Every other tier in this repository tests against net-snmp, which is one //! implementation wearing two hats: `snmpd` is the agent and `snmpget` is the //! client, and they were written by the same people from the same reading of //! the same RFCs. This tier is the only one that talks to somebody else's //! implementation, and it has already earned its place by showing three //! things `snmpd` never will: //! //! * **A `sysDescr` containing newlines.** A Catalyst answers with four lines //! of IOS banner, so one variable binding is not one line of output -- which //! breaks a line-oriented diff and any renderer that assumed otherwise. //! * **Sparse table indices.** `ifDescr` runs 1, then 10101 upwards. A walk //! cannot assume indices are contiguous, small, or ordered the way a //! for-loop would produce them. //! * **A type that exists in one version and not another.** `ifHCInOctets` is //! a `Counter64` over v2c and `noSuchName` over v1, from the same agent at //! the same OID, because SNMPv1 has no type that could hold the reply. //! //! ## Why it can never be in CI //! //! It is one piece of physical hardware on a private network. A job that //! depended on it would fail for anybody else, fail whenever the switch was //! rebooted or readdressed, and put synthetic load on equipment that is doing //! a real job. So everything here is **gated on the environment** and skips //! when it is not set: //! //! ```console //! $ export ZIG_SNMP_DEVICE=192.168.4.64 ZIG_SNMP_COMMUNITY=... //! $ nix develop -c zig build test --summary all //! ``` //! //! No credential is committed, and none is passed through a build option //! either -- a build option would be written into `.zig-cache`, which is the //! wrong place for a community string that opens live network equipment. The //! environment is read directly instead, out of `/proc/self/environ`, because //! Zig 0.16 hands a test no `std.process.Init` and so no other way to see it. //! That makes this file Linux-only, which is an acceptable price for a test //! that is opt-in anyway. //! //! ## Configuring the device //! //! `tests/device-cisco.md` has paste-ready IOS commands for creating the //! users and the community these tests need, and -- just as importantly -- //! for removing them again. IOS does not list `snmp-server user` lines in //! `show running-config`, so a user created for a test and then forgotten is //! invisible to a configuration diff; `show snmp user` is the only place it //! appears. //! //! ## Read-only, deliberately //! //! `Get`, `GetNext` and `GetBulk` and nothing else. A `Set` against //! production switchgear is not something to do because a test suite felt //! like it. //! //! The receiving tests below stretch that rule in one direction and not the //! other. They need the device *configured* to send notifications, which is a //! change to live equipment and is why those commands are in a document with //! a removal section rather than issued from here. But nothing in this file //! writes to the device at run time: the only thing it sends is a request //! carrying a community the device does not know, which the device refuses //! and reports. No object is written, no interface is bounced, and the //! provocation costs the device one refused packet and one notification. //! //! ## What the receiving tests are for //! //! Every other notification test in this repository runs net-snmp's //! `snmptrap`, a program whose entire job is to send one. That is the easy //! shape. The shape that happens in the field is an *agent* deciding on its //! own that something has happened -- building the varbind list itself, //! choosing its own request-id, and retrying an inform on its own schedule -- //! and a Catalyst doing that is a second vendor's notification encoder, which //! is the only place the receiver here is checked against one. //! //! The same two community-based tests exist against `snmpd` in //! `tests/oracle.zig`, where they run in CI. These are the ones that say //! whether real firmware agrees. //! //! ### What has been run, and what has not //! //! The mechanism is verified; the device is not. These three tests were run //! against a net-snmp `snmpd` configured the same way a switch would be -- //! `authtrapenable 1` plus a `trap2sink`, an `informsink` and a v3 //! `trapsess -Ci` -- by pointing `ZIG_SNMP_DEVICE` at it. All three pass //! there, each gated independently on its own port variable, and every other //! test in the suite still skips when those variables are unset. //! //! What that does *not* establish is that IOS behaves the same way: that its //! `snmp-server enable traps snmp authentication` fires on a bad community, //! that its `udp-port` keyword sits where `tests/device-cisco.md` says, and //! that it puts `sysUpTime.0` and `snmpTrapOID.0` first. Those are the claims //! these tests exist to check, and they have not been checked yet -- the //! switch was not configured for notifications when they were written. const builtin = @import("builtin"); const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const testing = std.testing; const snmp = @import("snmp"); const Client = snmp.Client; const ObjectId = snmp.ObjectId; const Value = snmp.Value; const VarBind = snmp.VarBind; const Receiver = snmp.Receiver; /// What the environment has to say for these tests to run. /// /// The v1/v2c group and the v3 group are checked independently, so the /// community tests run when only `ZIG_SNMP_COMMUNITY` is set. const Settings = struct { device: []const u8, community: ?[]const u8, user: ?[]const u8 = null, auth: ?[]const u8 = null, auth_password: ?[]const u8 = null, priv: ?[]const u8 = null, priv_password: ?[]const u8 = null, /// The UDP port the device is configured to send *traps* to, which the /// receiving tests bind. There is no default: a port only works if the /// switch was told the same number, so an unset variable means the device /// has not been configured for this and the test skips. trap_port: ?[]const u8 = null, /// And the port for *informs*, which has to be a second one: an IOS /// `snmp-server host` line is either a trap destination or an inform /// destination, never both, so testing both means two lines and two /// ports. inform_port: ?[]const u8 = null, /// The port for v3 informs, if a third `snmp-server host` line was /// configured for a v3 user. inform_port_v3: ?[]const u8 = null, /// The community the device puts in a notification, which is whatever the /// `snmp-server host` line names and need not be the read community. /// Falls back to `ZIG_SNMP_COMMUNITY`. trap_community: ?[]const u8 = null, fn read(gpa: Allocator) !Settings { if (builtin.os.tag != .linux) return error.SkipZigTest; const device = (try getenv(gpa, "ZIG_SNMP_DEVICE")) orelse return error.SkipZigTest; errdefer gpa.free(device); return .{ .device = device, .community = try getenv(gpa, "ZIG_SNMP_COMMUNITY"), .user = try getenv(gpa, "ZIG_SNMP_USER"), .auth = try getenv(gpa, "ZIG_SNMP_AUTH_PROTO"), .auth_password = try getenv(gpa, "ZIG_SNMP_AUTH_PASS"), .priv = try getenv(gpa, "ZIG_SNMP_PRIV_PROTO"), .priv_password = try getenv(gpa, "ZIG_SNMP_PRIV_PASS"), .trap_port = try getenv(gpa, "ZIG_SNMP_TRAP_PORT"), .inform_port = try getenv(gpa, "ZIG_SNMP_INFORM_PORT"), .inform_port_v3 = try getenv(gpa, "ZIG_SNMP_INFORM_PORT_V3"), .trap_community = try getenv(gpa, "ZIG_SNMP_TRAP_COMMUNITY"), }; } fn free(settings: Settings, gpa: Allocator) void { gpa.free(settings.device); inline for (.{ settings.community, settings.user, settings.auth, settings.auth_password, settings.priv, settings.priv_password, settings.trap_port, settings.inform_port, settings.inform_port_v3, settings.trap_community, }) |maybe| if (maybe) |value| gpa.free(value); } /// The community string, or a skip: a test that needs one and has none is /// not a failure. fn requireCommunity(settings: Settings) ![]const u8 { return settings.community orelse error.SkipZigTest; } /// The community the device will put in a notification. fn notifyCommunity(settings: Settings) ![]const u8 { return settings.trap_community orelse settings.community orelse error.SkipZigTest; } /// One of the notification ports, parsed, or a skip. fn requirePort(text: ?[]const u8) !u16 { return std.fmt.parseInt(u16, text orelse return error.SkipZigTest, 10) catch error.SkipZigTest; } /// The v3 user, assembled from the environment, or a skip. fn requireUser(settings: Settings) !snmp.usm.User { const name = settings.user orelse return error.SkipZigTest; const auth_password = settings.auth_password orelse return error.SkipZigTest; const auth = snmp.usm.AuthProtocol.parse( settings.auth orelse return error.SkipZigTest, ) orelse return error.SkipZigTest; // Privacy is optional: a user may be authNoPriv. if (settings.priv) |priv_text| { const priv = snmp.usm.PrivProtocol.parse(priv_text) orelse // A protocol this library does not implement -- 3DES and // AES-192/256 are the ones a Cisco offers and neither RFC 3826 // nor net-snmp 5.9 has -- is a skip rather than a failure. return error.SkipZigTest; return .{ .name = name, .level = .auth_priv, .auth = auth, .priv = priv, .auth_password = auth_password, .priv_password = settings.priv_password orelse return error.SkipZigTest, }; } return .{ .name = name, .level = .auth_no_priv, .auth = auth, .auth_password = auth_password, }; } }; /// One variable out of `/proc/self/environ`, which is NUL-separated /// `KEY=VALUE` records. /// /// A test cannot be handed `std.process.Init`, so this is the only way to see /// the environment without baking it into the build -- and baking a /// credential into `.zig-cache` is exactly what is being avoided. fn getenv(gpa: Allocator, key: []const u8) !?[]const u8 { const io = std.testing.io; var file = Io.Dir.cwd().openFile(io, "/proc/self/environ", .{}) catch return null; defer file.close(io); // `readerStreaming`, not `reader`: the latter asks the file how big it is // and a `/proc` file answers zero, so `allocRemaining` reads nothing at // all and every one of these tests skips for no visible reason. That cost // a confusing half hour. var buffer: [4096]u8 = undefined; var reader = file.readerStreaming(io, &buffer); const contents = reader.interface.allocRemaining(gpa, .unlimited) catch return null; defer gpa.free(contents); var it = std.mem.splitScalar(u8, contents, 0); while (it.next()) |record| { const equals = std.mem.indexOfScalar(u8, record, '=') orelse continue; if (std.mem.eql(u8, record[0..equals], key)) { // A variable that is set and empty is not a usable answer, and // treating it as one would produce a puzzling timeout instead of // a skip. const value = record[equals + 1 ..]; if (value.len == 0) return null; // Owned, because `contents` goes away with this function -- the // caller frees what it is given. return try gpa.dupe(u8, value); } } return null; } fn peerAddress(settings: Settings) !Io.net.IpAddress { var host = settings.device; var port: u16 = Client.default_port; if (std.mem.indexOfScalar(u8, host, ':')) |colon| { port = try std.fmt.parseInt(u16, host[colon + 1 ..], 10); host = host[0..colon]; } const address = try snmp.z46.Ipv4Address.parse(host); return .{ .ip4 = .{ .bytes = address.octets, .port = port } }; } fn connect(io: Io, gpa: Allocator, settings: Settings, version: snmp.Version) !Client { return Client.open(io, gpa, try peerAddress(settings), .{ .version = version, .community = try settings.requireCommunity(), // A switch on a LAN answers quickly or is not there; a long retry // schedule would only make a failing test slow. .retries = 2, .timeout = .{ .duration = .{ .raw = .fromSeconds(2), .clock = .awake } }, }); } fn connectV3(io: Io, gpa: Allocator, settings: Settings) !Client { return Client.open(io, gpa, try peerAddress(settings), .{ .version = .v3, .user = try settings.requireUser(), .retries = 2, .timeout = .{ .duration = .{ .raw = .fromSeconds(3), .clock = .awake } }, }); } /// Runs `body` against the device, or skips. fn withDevice(comptime body: fn (Io, Allocator, Settings) anyerror!void) !void { const gpa = testing.allocator; const settings = try Settings.read(gpa); defer settings.free(gpa); var io_impl: Io.Threaded = .init(gpa, .{}); defer io_impl.deinit(); try body(io_impl.io(), gpa, settings); } test "it is the vendor we think it is" { try withDevice(struct { fn body(io: Io, gpa: Allocator, settings: Settings) anyerror!void { var c = try connect(io, gpa, settings, .v2c); defer c.close(gpa); var r = try c.get(gpa, &.{try ObjectId.parse("1.3.6.1.2.1.1.2.0")}); defer r.deinit(gpa); try r.expectOk(); // sysObjectID under the Cisco enterprise arc. If this ever fails, // the device at that address has been replaced and the // assumptions in the rest of this file want rereading rather than // the test want relaxing. const cisco = try ObjectId.parse("1.3.6.1.4.1.9"); try testing.expect(r.bindings[0].value.data.object_id.startsWith(cisco)); } }.body); } test "a value containing newlines survives the round trip" { try withDevice(struct { fn body(io: Io, gpa: Allocator, settings: Settings) anyerror!void { var c = try connect(io, gpa, settings, .v2c); defer c.close(gpa); var r = try c.get(gpa, &.{try ObjectId.parse("1.3.6.1.2.1.1.1.0")}); defer r.deinit(gpa); try r.expectOk(); const descr = r.bindings[0].value.data.octet_string; // The IOS banner. This is the assertion that pins what this // device brings: net-snmp's own agent will never send a // multi-line sysDescr, so without a real one nothing checks that // a value is not a line. try testing.expect(std.mem.indexOfScalar(u8, descr, '\n') != null); try testing.expect(descr.len > 64); // And it renders as several lines rather than being mangled into // one or truncated at the newline. var out: Io.Writer.Allocating = .init(gpa); defer out.deinit(); try out.writer.print("{f}", .{r.bindings[0]}); try testing.expect(std.mem.count(u8, out.written(), "\n") > 0); try testing.expect(std.mem.endsWith(u8, out.written(), descr[descr.len - 8 ..])); } }.body); } test "a table with sparse indices walks correctly" { try withDevice(struct { fn body(io: Io, gpa: Allocator, settings: Settings) anyerror!void { var c = try connect(io, gpa, settings, .v2c); defer c.close(gpa); const if_descr = try ObjectId.parse("1.3.6.1.2.1.2.2.1.2"); var w = c.walk(if_descr, .{}); defer w.deinit(gpa); var indices: std.ArrayList(u32) = .empty; defer indices.deinit(gpa); while (try w.next(gpa)) |binding| { try testing.expect(binding.name.startsWith(if_descr)); const sub = binding.name.slice(); try indices.append(gpa, sub[sub.len - 1]); } // More than one interface, and the indices are *not* 1..n -- // a Catalyst numbers them 1 then 10101 upwards. A walk that // assumed contiguity would work against snmpd and fail here. try testing.expect(indices.items.len > 2); var contiguous = true; for (indices.items, 1..) |index, expected| { if (index != expected) contiguous = false; } try testing.expect(!contiguous); // And strictly increasing, which is what makes the walk // terminate. for (indices.items[1..], indices.items[0 .. indices.items.len - 1]) |next, previous| { try testing.expect(next > previous); } } }.body); } test "GetNext and GetBulk agree on a real table" { try withDevice(struct { fn body(io: Io, gpa: Allocator, settings: Settings) anyerror!void { const if_descr = try ObjectId.parse("1.3.6.1.2.1.2.2.1.2"); 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 connect(io, gpa, settings, .v2c); defer c.close(gpa); var w = c.walk(if_descr, .{ .bulk = use_bulk, .max_repetitions = 4 }); defer w.deinit(gpa); const out = if (use_bulk) &bulk else &plain; while (try w.next(gpa)) |binding| { try out.writer.print("{f}\n", .{binding}); } } // Interface descriptions do not change between two walks a second // apart, so these can be compared in full -- values included, // which the snmpd version of this test cannot do because // sysUpTime moves. try testing.expectEqualStrings(plain.written(), bulk.written()); } }.body); } test "a Counter64 over v2c is noSuchName over v1" { try withDevice(struct { fn body(io: Io, gpa: Allocator, settings: Settings) anyerror!void { // ifHCInOctets.1, the 64-bit byte counter. This is the cleanest // demonstration of the version split there is: one agent, one // OID, two answers, and asserted in *both* directions so that it // keeps covering the split rather than quietly passing if either // side changes. const counter = try ObjectId.parse("1.3.6.1.2.1.31.1.1.1.6.1"); { var c = try connect(io, gpa, settings, .v2c); defer c.close(gpa); var r = try c.get(gpa, &.{counter}); defer r.deinit(gpa); try r.expectOk(); try testing.expectEqual( std.meta.Tag(Value.Data).counter64, std.meta.activeTag(r.bindings[0].value.data), ); } { var c = try connect(io, gpa, settings, .v1); defer c.close(gpa); var r = try c.get(gpa, &.{counter}); defer r.deinit(gpa); // Not an exception marker in the varbind -- v1 has none -- // but the error in the PDU, naming the binding. try testing.expectEqual(snmp.Pdu.ErrorStatus.no_such_name, r.error_status); try testing.expectEqual(@as(i32, 1), r.error_index); } } }.body); } test "GetBulk returns what it was asked for, from real firmware" { try withDevice(struct { fn body(io: Io, gpa: Allocator, settings: Settings) anyerror!void { var c = try connect(io, gpa, settings, .v2c); defer c.close(gpa); // The interface table is big enough on a switch that ten // repetitions is a real request rather than one the agent // trivially satisfies. var r = try c.getBulk(gpa, &.{try ObjectId.parse("1.3.6.1.2.1.2.2.1.2")}, 0, 10); defer r.deinit(gpa); try r.expectOk(); try testing.expectEqual(@as(usize, 10), r.bindings.len); 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)); } } }.body); } // -- version 3, against real firmware ---------------------------------------- test "SNMPv3 against the device's own USM implementation" { try withDevice(struct { fn body(io: Io, gpa: Allocator, settings: Settings) anyerror!void { var c = try connectV3(io, gpa, settings); 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(); // This is the strongest evidence in the whole repository. IOS and // net-snmp wrote their key derivation, their HMAC truncation and // their CFB salt construction separately from each other and from // this, so a client all three accept has read RFC 3414 correctly // rather than learned one implementation's habits. try testing.expect(r.bindings[0].value.data.octet_string.len > 0); } }.body); } test "the device's engine ID is its own, and discovery finds it" { try withDevice(struct { fn body(io: Io, gpa: Allocator, settings: Settings) anyerror!void { var c = try connectV3(io, gpa, settings); defer c.close(gpa); try c.discover(gpa); const id = c.engine.engineId(); // RFC 3411 §5's enterprise format: the top bit set, then the // vendor's enterprise number. A Cisco's begins with 0x80 and // 0x00000009. try testing.expect(id.len >= 5); try testing.expectEqual(@as(u8, 0x80), id[0] & 0x80); try testing.expect(c.engine.boots >= 1); // A real device has been up for a while, unlike a freshly spawned // snmpd -- so its clock is a number worth having rather than // nearly zero. try testing.expect(c.engine.time > 0); } }.body); } test "a v3 walk of a real table, authenticated and encrypted throughout" { try withDevice(struct { fn body(io: Io, gpa: Allocator, settings: Settings) anyerror!void { const if_descr = try ObjectId.parse("1.3.6.1.2.1.2.2.1.2"); var over_v3: Io.Writer.Allocating = .init(gpa); defer over_v3.deinit(); { var c = try connectV3(io, gpa, settings); defer c.close(gpa); var w = c.walk(if_descr, .{ .bulk = true, .max_repetitions = 4 }); defer w.deinit(gpa); while (try w.next(gpa)) |binding| { try over_v3.writer.print("{f}\n", .{binding}); } } // And the same table over v2c, which must agree exactly. The two // paths share nothing below the PDU -- different message wrapper, // different security, and under authPriv the whole scoped PDU // went through AES -- so agreement is a real check rather than a // tautology. var over_v2c: Io.Writer.Allocating = .init(gpa); defer over_v2c.deinit(); { var c = connect(io, gpa, settings, .v2c) catch |err| switch (err) { // No community configured: the v3 half still ran. error.SkipZigTest => return, else => return err, }; defer c.close(gpa); var w = c.walk(if_descr, .{ .bulk = true, .max_repetitions = 4 }); defer w.deinit(gpa); while (try w.next(gpa)) |binding| { try over_v2c.writer.print("{f}\n", .{binding}); } } try testing.expect(over_v3.written().len > 0); try testing.expectEqualStrings(over_v2c.written(), over_v3.written()); } }.body); } test "a wrong v3 password is refused by real firmware" { try withDevice(struct { fn body(io: Io, gpa: Allocator, settings: Settings) anyerror!void { var user = try settings.requireUser(); user.auth_password = "definitely not the right password"; var c = try Client.open(io, gpa, try peerAddress(settings), .{ .version = .v3, .user = user, .retries = 1, .timeout = .{ .duration = .{ .raw = .fromSeconds(2), .clock = .awake } }, }); defer c.close(gpa); // Asserting the refusal as well as the acceptance: a USM // implementation that accepted everything would pass every other // test in this file. const result = c.get(gpa, &.{try ObjectId.parse("1.3.6.1.2.1.1.6.0")}); if (result) |response| { var r = response; defer r.deinit(gpa); return error.TestUnexpectedResult; } else |err| { // IOS answers a bad digest with a report; some firmware says // nothing, which is also a refusal. try testing.expect(err == error.WrongDigest or err == error.Timeout or err == error.AuthenticationFailed); } } }.body); } test "a privacy key longer than the hash that derived it" { try withDevice(struct { fn body(io: Io, gpa: Allocator, settings: Settings) anyerror!void { const user = try settings.requireUser(); // Only meaningful for a protocol whose key exceeds the hash // output: AES-192 and AES-256 always, 3DES when the hash is MD5. // With AES-128 there is no extension to exercise. const needed = user.priv.keyLength(); if (needed <= user.auth.keyLength()) return error.SkipZigTest; var c = try connectV3(io, gpa, settings); defer c.close(gpa); try c.discover(gpa); // More privacy key than the hash produced, so the chained // extension must have run. This is the only place in the // repository where a *non-standard* algorithm is checked: the // drafts defining 3DES and the wider AES key sizes both expired, // and net-snmp's command line refuses all three even though its // library implements the extension -- so real Cisco firmware is // the only oracle there is for them. try testing.expectEqual(needed, c.engine.keys.privKey().len); try testing.expectEqual(user.auth.keyLength(), c.engine.keys.authKey().len); try testing.expect(c.engine.keys.privKey().len > c.engine.keys.authKey().len); 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.expect(r.bindings[0].value.data.octet_string.len > 0); } }.body); } test "a shorter privacy key is not the right key" { try withDevice(struct { fn body(io: Io, gpa: Allocator, settings: Settings) anyerror!void { var user = try settings.requireUser(); if (user.priv != .aes_256_cfb) return error.SkipZigTest; // The same passwords with the *shorter* protocol, which derives // 16 octets of key where the agent expects 32. This is what makes // the test above mean something: without it, an extension that // produced anything at all would appear to work, because the // agent would be decrypting with a key we never proved was the // one it wanted. user.priv = .aes_128_cfb; var c = try Client.open(io, gpa, try peerAddress(settings), .{ .version = .v3, .user = user, .retries = 1, .timeout = .{ .duration = .{ .raw = .fromSeconds(2), .clock = .awake } }, }); defer c.close(gpa); const result = c.get(gpa, &.{try ObjectId.parse("1.3.6.1.2.1.1.6.0")}); if (result) |response| { var r = response; defer r.deinit(gpa); return error.TestUnexpectedResult; } else |err| { // The agent authenticates the message -- the auth key is // unchanged -- and then cannot decrypt it, which it answers // with silence for the same reason net-snmp does. try testing.expect(err == error.Timeout or err == error.DecryptionError or err == error.DecryptionFailed); } } }.body); } // -- notifications the device sends us -------------------------------------- /// `authenticationFailure`, from SNMPv2-MIB's `snmpTraps` group. const authentication_failure = "1.3.6.1.6.3.1.1.5.5"; /// Provokes the device into sending a notification, repeatably and without /// touching its configuration or its traffic. /// /// This is the part that makes a receiving test possible at all. A device /// emits notifications when something happens to it, and "something happens" /// is not a thing a test can wait for: a switch that is behaving itself sends /// nothing for days. The usual answer is to bounce an interface for a /// `linkDown`, which means write access and means taking a port down on live /// equipment to satisfy a test. /// /// `authenticationFailure` is the better lever. Sending any request with a /// community the device does not know makes it emit one, and that costs /// nothing: no write access, no configuration change at trigger time, no /// traffic interrupted, and it can be done again a second later. The device /// does not answer the request -- it drops a request it cannot authenticate, /// which is the whole point -- so the timeout here is the expected outcome /// and not a failure. /// /// It does need `snmp-server enable traps snmp authentication` on the device; /// see `tests/device-cisco.md`. fn provoke(io: Io, gpa: Allocator, settings: Settings) !void { var client = Client.open(io, gpa, try peerAddress(settings), .{ .version = .v2c, // Not a credential and not a guess at one: a string chosen to be // wrong, so that the device refuses it and says so. Anything it // accepted would defeat the purpose. .community = "zig-snmp-deliberately-wrong", .retries = 0, .timeout = .{ .duration = .{ .raw = .fromMilliseconds(400), .clock = .awake } }, }) catch return; defer client.close(gpa); const sys_descr = try ObjectId.parse("1.3.6.1.2.1.1.1.0"); if (client.get(gpa, &.{sys_descr})) |response| { var r = response; r.deinit(gpa); // An answer means the device accepted that community, which would be // alarming and is certainly not the state this test wants to run in. return error.DeviceAcceptedAnyCommunity; } else |_| { // The expected outcome: no reply, and a trap on its way elsewhere. } } /// Waits for a notification carrying `want`, provoking the device until one /// arrives or the attempts run out. /// /// Two things make this a loop rather than a single receive. A switch on a /// real network sends notifications nobody asked for --- a port came up, a /// neighbour appeared --- so the first thing to arrive is often not the thing /// under test and has to be discarded rather than asserted about. And IOS /// rate-limits notifications of the same kind, so one provocation may produce /// nothing at all and the right response is to wait and ask again. fn awaitNotification( io: Io, gpa: Allocator, r: *Receiver, settings: Settings, want: []const u8, ) !Receiver.Notification { const wanted = try ObjectId.parse(want); var attempt: usize = 0; while (attempt < 6) : (attempt += 1) { try provoke(io, gpa, settings); var waited: usize = 0; while (waited < 10) : (waited += 1) { var n = r.next(gpa, .{ .duration = .{ .raw = .fromMilliseconds(500), .clock = .awake, } }) catch |err| switch (err) { error.Timeout => break, // A malformed or unauthenticated datagram from somewhere else // on the network is not this test's business. else => continue, }; if (n.trapOid()) |got| { if (got.eql(wanted)) return n; } n.deinit(gpa); } } return error.NoNotificationArrived; } /// Which `snmp-server host` line a test is exercising. const Destination = enum { trap, inform, inform_v3 }; /// This receiver's own engine ID, which a v3 inform is authenticated against /// and which the device discovers by asking. /// /// Enterprise zero on purpose: it is nobody's, which is the honest thing for /// a test fixture. A real receiver supplies its owner's number, because an /// engine ID says who is running it, and claiming somebody else's is how two /// engines end up sharing one identity. const receiver_engine_octets = [_]u8{ 0x7a, 0x69, 0x67, 0x00 }; const receiver_engine_storage = Receiver.engineId(0, &receiver_engine_octets) catch unreachable; const receiver_engine = receiver_engine_storage[0..Receiver.engineIdLength(receiver_engine_octets.len)]; /// Binds a receiver on the port that destination was configured with, and /// runs `body` against it. /// /// The receiver is given the device's notification community, and for the v3 /// destination a user and an engine ID as well --- an inform is acknowledged, /// and a v3 acknowledgement has to be authenticated as the *receiver's* /// engine, which means having one. fn withDeviceReceiver( destination: Destination, comptime body: fn (Io, Allocator, *Receiver, Settings) anyerror!void, ) !void { const gpa = testing.allocator; var settings = try Settings.read(gpa); defer settings.free(gpa); const listen = try Settings.requirePort(switch (destination) { .trap => settings.trap_port, .inform => settings.inform_port, .inform_v3 => settings.inform_port_v3, }); var users: [1]snmp.usm.User = undefined; var user_slice: []const snmp.usm.User = &.{}; var engine: []const u8 = ""; if (destination == .inform_v3) { users[0] = try settings.requireUser(); user_slice = users[0..1]; engine = receiver_engine; } var io_impl: Io.Threaded = .init(gpa, .{}); defer io_impl.deinit(); const io = io_impl.io(); // The unspecified address, because the device sends to whichever of this // machine's addresses it was configured with and a test has no way to // know which one that is. var r = try Receiver.bind(io, gpa, .{ .ip4 = .{ .bytes = .{ 0, 0, 0, 0 }, .port = listen }, }, .{ .community = try settings.notifyCommunity(), .users = user_slice, .engine_id = engine, }); defer r.close(gpa); try body(io, gpa, &r, settings); } /// That a notification came from the device rather than from something else /// on the network that happens to send traps. fn expectFromDevice(n: Receiver.Notification, settings: Settings) !void { const expected = try peerAddress(settings); try testing.expectEqualSlices(u8, &expected.ip4.bytes, &n.from.ip4.bytes); } /// That the first two bindings are the ones RFC 3416 §4.2.6 requires. /// /// An SNMPv2 notification begins with `sysUpTime.0` and `snmpTrapOID.0`, in /// that order, and everything after them is what the notification is about. /// Real firmware is where that ordering is worth checking: a receiver that /// looked for them by OID rather than taking them positionally would agree /// with a sender that puts them first and quietly disagree with one that does /// not. fn expectV2Preamble(n: Receiver.Notification) !void { 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); } test "a v2c trap, sent because we asked the device a question wrongly" { try withDeviceReceiver(.trap, struct { fn body(io: Io, gpa: Allocator, r: *Receiver, settings: Settings) anyerror!void { var n = try awaitNotification(io, gpa, r, settings, authentication_failure); defer n.deinit(gpa); try expectFromDevice(n, settings); try testing.expectEqual(Receiver.Notification.Kind.trap_v2, n.kind); try testing.expectEqual(snmp.Version.v2c, n.version); try testing.expectEqualStrings(try settings.notifyCommunity(), n.community); try expectV2Preamble(n); // A trap is fire and forget: it carries no request-id, so there // is nothing to answer with and nothing owed to the sender. try testing.expect(!n.needsAcknowledgement()); } }.body); } test "a v2c inform, which the device retries until we acknowledge it" { try withDeviceReceiver(.inform, struct { fn body(io: Io, gpa: Allocator, r: *Receiver, settings: Settings) anyerror!void { var n = try awaitNotification(io, gpa, r, settings, authentication_failure); defer n.deinit(gpa); try expectFromDevice(n, settings); try testing.expectEqual(Receiver.Notification.Kind.inform, n.kind); try expectV2Preamble(n); // The whole difference from a trap, and the reason this test is // worth having against real firmware rather than only against // net-snmp: an inform has a request-id, and IOS keeps resending // it until that id comes back. Acknowledging is not politeness, // it is what stops the device retrying. try testing.expect(n.needsAcknowledgement()); try testing.expect(n.request_id != null); try r.acknowledge(gpa, n); // And having acknowledged, the same notification should stop // arriving. A duplicate here would mean the response did not // satisfy the sender -- a wrong request-id, or a community the // device did not accept back. var quiet: usize = 0; while (quiet < 6) : (quiet += 1) { var again = r.next(gpa, .{ .duration = .{ .raw = .fromMilliseconds(500), .clock = .awake, } }) catch break; defer again.deinit(gpa); if (again.request_id) |id| { try testing.expect(id != n.request_id.?); } } } }.body); } test "a v3 inform from the device, authenticated against our engine" { // v3 *informs* rather than v3 traps, and the difference is not a // preference. A v3 trap is authenticated as the sender's engine, so the // receiver has to have been told that engine's ID in advance --- on IOS, // an `snmp-server engineID remote` line naming us. An inform is // authenticated as the *receiver's* engine, which the sender discovers by // asking, so it needs no such line and works against a receiver it has // never met. That makes it the one a test can set up from one end. try withDeviceReceiver(.inform_v3, struct { fn body(io: Io, gpa: Allocator, r: *Receiver, settings: Settings) anyerror!void { var n = try awaitNotification(io, gpa, r, settings, authentication_failure); defer n.deinit(gpa); try expectFromDevice(n, settings); try testing.expectEqual(Receiver.Notification.Kind.inform, n.kind); try testing.expectEqual(snmp.Version.v3, n.version); try expectV2Preamble(n); // The user the device was configured with, and a level that is at // least authenticated -- an unauthenticated v3 notification tells // us nothing that a forged datagram could not. const user = try settings.requireUser(); try testing.expectEqualStrings(user.name, n.user); try testing.expect(n.level != .no_auth_no_priv); try testing.expectEqual(user.level, n.level); // The engine the message names is ours, because that is what an // inform is authenticated against. try testing.expectEqualSlices(u8, receiver_engine, n.engine_id); try testing.expect(n.needsAcknowledgement()); try r.acknowledge(gpa, n); } }.body); }