Something went wrong. Try again.
An SNMP manager library and command line tools for Zig, covering versions 1, 2c and 3.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A manager: a socket, a request-id, and the operations carried out over one.//!//! This is the only file in the library that does any I/O, and it takes its//! `Io` as a parameter rather than naming an implementation -- so the whole//! layer below it is testable with no socket, and this layer is testable on//! `std.Io.failing`, whose network calls all return errors the code has to//! handle anyway.//!//! ## Why UDP makes this more than a function call//!//! SNMP is request/response over a datagram, which means there is no//! connection, no acknowledgement and no ordering. Three consequences shape//! everything here://!//! * **A lost request is indistinguishable from a slow agent**, so the only//! answer is to ask again and give up eventually. `retries` and `timeout`//! default to net-snmp's own (`-r 5`, `-t 1`), because the point of matching//! them is that the same arguments to both programs mean the same thing.//!//! * **A late reply arrives anyway.** A response to an attempt that already//! timed out can land during the next attempt, and it is a *valid* message//! from the right peer -- so the request-id is the only thing that//! distinguishes it, and a mismatch means keep waiting rather than answer//! the caller with the previous question's answer. Getting this wrong//! produces a client that works perfectly until the network is busy and//! then silently returns stale values.//!//! * **Anyone can send us a datagram.** A reply from an address we did not//! ask is discarded before it is parsed, which is cheap and rules out the//! easiest spoof. It is not a security control -- a source address is//! forgeable, which is what SNMPv3's authentication is actually for -- but//! there is no reason to parse what we know we did not ask for.
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 z46 = @import("z46");
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 Client = @This();
pub const default_port = 161;/// Where a trap or an inform is sent.pub const default_trap_port = 162;
io: Io,socket: Io.net.Socket,peer: Io.net.IpAddress,options: Options,/// Incremented for every request. Starts somewhere unpredictable so that a/// late reply to a *previous run* of the same program cannot be mistaken for/// an answer to this one -- the socket is likely to get the same ephemeral/// port back.next_request_id: i32,/// Where a received datagram lands. One message at a time, and sized for the/// largest a datagram can be, so a peer cannot make us truncate a reply we/// would otherwise have understood.receive_buffer: []u8,/// What has been learned about the agent's engine, and the keys derived for/// it. Empty until the first v3 request runs discovery.engine: Engine = .{},/// Where a privacy salt comes from. It must never repeat under one key, so it/// starts unpredictably rather than at zero: two runs of the same program/// against the same agent would otherwise reuse salts, and for AES-CFB a/// repeated salt with a repeated boots and time is a repeated keystream.privacy_counter: u64 = 0,
pub const Options = struct { version: Version = .v2c, /// Sent in the clear, and the whole of v1 and v2c security. community: []const u8 = "public", /// Who we are under SNMPv3. Required for `.v3` and ignored otherwise. user: usm.User = .{ .name = "" }, /// How many times to *re*send before giving up, so the total number of /// attempts is one more than this. net-snmp's `-r`, and its default. retries: u8 = 5, /// How long to wait for each attempt. net-snmp's `-t`, and its default. timeout: Io.Timeout = .{ .duration = .{ .raw = .fromSeconds(1), .clock = .awake } }, /// Discard a datagram that came from an address other than the one asked. check_source: bool = true,};
pub const OpenError = Io.net.IpAddress.BindError || Allocator.Error;
/// Binds a socket and points it at `peer`. Nothing is sent, because there is/// nothing to connect: the first datagram is the first request.pub fn open(io: Io, gpa: Allocator, peer: Io.net.IpAddress, options: Options) OpenError!Client { // A v3 user whose level asks for more than its protocols provide would // otherwise fail as an unexplained rejection from the agent. assert(options.version != .v3 or options.user.isConsistent());
// Bind to the unspecified address of the peer's family on a port the // kernel picks, which is what a client wants: a source address chosen by // the routing table rather than by us. const local: Io.net.IpAddress = switch (peer) { .ip4 => .{ .ip4 = .{ .bytes = .{ 0, 0, 0, 0 }, .port = 0 } }, .ip6 => .{ .ip6 = .{ .bytes = @splat(0), .port = 0 } }, }; const socket = try local.bind(io, .{ .mode = .dgram, .protocol = .udp }); errdefer socket.close(io);
const buffer = try gpa.alloc(u8, Message.max_size); errdefer gpa.free(buffer);
return .{ .io = io, .socket = socket, .peer = peer, .options = options, // The awake clock -- CLOCK_MONOTONIC -- has no epoch worth speaking of, // but it does differ between runs, which is all this needs. Masked to // 31 bits because `msgID` must not be negative. .next_request_id = @truncate(Io.Timestamp.now(io, .awake).nanoseconds & std.math.maxInt(i32)), .receive_buffer = buffer, .privacy_counter = @bitCast(@as(i64, @truncate(Io.Timestamp.now(io, .awake).nanoseconds))), };}
pub fn close(c: *Client, gpa: Allocator) void { c.socket.close(c.io); gpa.free(c.receive_buffer); c.* = undefined;}
/// The local address the socket ended up on, which is the port the kernel/// picked. `Socket.address` is filled in by `getsockname` after a bind, so/// this is *this* end rather than the peer.pub fn localAddress(c: *const Client) Io.net.IpAddress { return c.socket.address;}
/// The next identifier, always non-negative.////// That is not tidiness: RFC 3412 declares `msgID` as/// `INTEGER (0..2147483647)`, so a negative one is out of range and an agent/// drops the message without answering -- which presents as a timeout with/// no diagnostic anywhere. Since the counter is seeded from the clock, whether/// that happened depended on the sign of a truncated timestamp, so it worked/// about half the time. The PDU's request-id may legitimately be negative,/// but there is no reason to spend one.fn takeRequestId(c: *Client) i32 { const id = c.next_request_id & std.math.maxInt(i32); c.next_request_id = (c.next_request_id +% 1) & std.math.maxInt(i32); return id;}
pub const RequestError = error{ /// Every attempt went unanswered. Timeout, /// The agent said something that is not a response. UnexpectedPdu, /// The reply did not decode. MalformedResponse, /// The agent reported an error in the PDU's error-status. AgentError,} || Io.net.Socket.SendError || Io.net.Socket.ReceiveTimeoutError || Message.DecodeError || asn1.Encoder.Error || Allocator.Error;
/// What came back. The bindings point into the client's receive buffer, so/// they are valid until the next request -- which is why this is a borrowed/// view and not a value to keep.pub const Response = struct { request_id: i32, error_status: Pdu.ErrorStatus, /// Which binding the error is about, counting from one. error_index: i32, bindings: []const VarBind, /// The allocation behind `bindings`. owned: []VarBind, /// The bytes the bindings' values point *into*, when the response owns /// them. /// /// Under v1 and v2c they point into the client's receive buffer and this /// is null: the caller has them until the next request, which is what /// makes a walk cheap. Under v3 there is no datagram left to borrow from /// -- the plaintext was decrypted into a buffer of its own, and even an /// unencrypted v3 reply was copied out of the receive buffer so that /// `exchange` could hand it over -- so the response carries it. /// /// Leaving this out is a use-after-free that shows up as a segfault on /// the first v3 response with a string in it, which is exactly how it was /// found. backing: ?[]u8 = null,
pub fn deinit(r: *Response, gpa: Allocator) void { gpa.free(r.owned); if (r.backing) |b| gpa.free(b); r.* = undefined; }
/// The binding the error-status refers to, if there is one and the index /// makes sense. RFC 3416 numbers from one, and zero means "no particular /// binding". pub fn failedBinding(r: Response) ?VarBind { if (r.error_status == .no_error) return null; if (r.error_index < 1) return null; const i: usize = @intCast(r.error_index - 1); if (i >= r.bindings.len) return null; return r.bindings[i]; }
/// Fails if the agent reported an error, which is what a caller that just /// wants the value wants. pub fn expectOk(r: Response) error{AgentError}!void { if (r.error_status != .no_error) return error.AgentError; }};
/// Sends `pdu` and waits for the response to it, resending on timeout.////// The PDU is encoded once and the same bytes are sent on every attempt,/// request-id included -- which is the point. An agent that answers the second/// attempt is answering the same question, and a reply to the first is still/// recognisable when it arrives late.pub fn request(c: *Client, gpa: Allocator, pdu: Pdu) V3Error!Response { if (c.options.version == .v3) return c.requestV3(gpa, pdu);
const message = Message.init(c.options.version, c.options.community, pdu); const bytes = try message.encodeAlloc(gpa); defer gpa.free(bytes);
const want = pdu.requestId().?;
var attempt: usize = 0; while (true) : (attempt += 1) { try c.socket.send(c.io, &c.peer, bytes);
// The timeout is converted to a *deadline* once, before the loop. // Passing the duration itself would restart the clock on every // datagram, so a peer sending a steady trickle of rubbish -- or a // stream of late replies to earlier attempts -- would keep a caller // waiting for ever without ever answering. const deadline = c.options.timeout.toDeadline(c.io); while (true) { const incoming = c.socket.receiveTimeout(c.io, c.receive_buffer, deadline) catch |err| switch (err) { error.Timeout => break, else => |e| return e, };
if (c.options.check_source and !sameAddress(incoming.from, c.peer)) continue;
// A datagram larger than the buffer was truncated, and a // truncated BER message is not worth parsing. if (incoming.flags.trunc) continue;
var reply = Message.decode(incoming.data, gpa) catch continue; var keep = false; defer if (!keep) reply.deinit(gpa);
const p = reply.pdu(); // The whole reason this loop exists: a valid response from the // right peer to a *different* request is a late reply to an // earlier attempt, and answering the caller with it would return // the previous question's answer. if (p.requestId() != want) continue; if (p.kind != .response) continue;
const s = p.body.standard; keep = true; return .{ .request_id = s.request_id, .error_status = s.error_status, .error_index = s.error_index, .bindings = s.bindings, .owned = @constCast(s.bindings), }; }
if (attempt >= c.options.retries) return error.Timeout; }}
/// Whether two addresses are the same host and port. `std.Io.net.IpAddress`/// is a union, so a v4 and a v6 address are never equal here even when one is/// the mapped form of the other -- which is right for this purpose: a reply/// should come back the way the request went out.fn sameAddress(a: Io.net.IpAddress, b: Io.net.IpAddress) bool { return switch (a) { .ip4 => |x| switch (b) { .ip4 => |y| x.port == y.port and std.mem.eql(u8, &x.bytes, &y.bytes), .ip6 => false, }, .ip6 => |x| switch (b) { .ip6 => |y| x.port == y.port and std.mem.eql(u8, &x.bytes, &y.bytes), .ip4 => false, }, };}
/// `Get`: the value of each named object, or an error saying which one could/// not be had.pub fn get(c: *Client, gpa: Allocator, names: []const ObjectId) V3Error!Response { const bindings = try gpa.alloc(VarBind, names.len); defer gpa.free(bindings); for (bindings, names) |*vb, name| vb.* = .request(name); return c.request(gpa, Pdu.get(c.takeRequestId(), bindings));}
/// `GetNext`: the object *after* each of these in the agent's view, which is/// what walking a MIB is made of.pub fn getNext(c: *Client, gpa: Allocator, names: []const ObjectId) V3Error!Response { const bindings = try gpa.alloc(VarBind, names.len); defer gpa.free(bindings); for (bindings, names) |*vb, name| vb.* = .request(name); return c.request(gpa, Pdu.getNext(c.takeRequestId(), bindings));}
/// `GetBulk`: up to `max_repetitions` successive objects for each of the/// bindings after the first `non_repeaters`.////// An agent may return fewer than asked -- the reply has to fit in a datagram/// -- so this is a request and not a promise, and a caller walking a table has/// to be prepared to ask again from where it got to.pub fn getBulk( c: *Client, gpa: Allocator, names: []const ObjectId, non_repeaters: u32, max_repetitions: u32,) V3Error!Response { assert(c.options.version.hasBulkAndInform()); const bindings = try gpa.alloc(VarBind, names.len); defer gpa.free(bindings); for (bindings, names) |*vb, name| vb.* = .request(name); return c.request(gpa, Pdu.getBulk(c.takeRequestId(), non_repeaters, max_repetitions, bindings));}
/// `Set`: write each binding.pub fn set(c: *Client, gpa: Allocator, bindings: []const VarBind) V3Error!Response { return c.request(gpa, Pdu.set(c.takeRequestId(), bindings));}
pub const WalkError = V3Error || error{ /// The agent answered with an OID that is not after the one asked for. /// /// A walk is a loop whose only termination argument is that each step /// moves strictly forwards, so an agent that repeats itself -- or goes /// backwards -- would spin for ever. This is not a theoretical worry: a /// buggy agent, or a table whose implementation loses track, is exactly /// how it happens, and a manager that hung would be blamed for it. AgentDidNotAdvance,};
pub const WalkOptions = struct { /// Use `GetBulk` rather than `GetNext`, which is one round trip per /// `max_repetitions` objects instead of one per object. Not available in /// version 1. bulk: bool = false, max_repetitions: u32 = 10,};
/// Walks the subtree under `root`, yielding one binding at a time.////// ```/// var walk = client.walk(root, .{ .bulk = true });/// defer walk.deinit(gpa);/// while (try walk.next(gpa)) |binding| {/// std.debug.print("{f}\n", .{binding});/// }/// ```////// **The yielded binding borrows.** Its value points into the client's/// receive buffer, which the next call to `next` may overwrite, so anything/// worth keeping has to be copied before then. The *name* is a value and is/// safe to keep.pub fn walk(c: *Client, root: ObjectId, options: WalkOptions) Walk { assert(!options.bulk or c.options.version.hasBulkAndInform()); return .{ .client = c, .root = root, .at = root, .options = options, .batch = null, .index = 0, .finished = false, };}
pub const Walk = struct { client: *Client, root: ObjectId, /// The OID to ask after next. at: ObjectId, options: WalkOptions, /// The reply being handed out, one binding at a time. batch: ?Response, index: usize, finished: bool,
pub fn deinit(w: *Walk, gpa: Allocator) void { if (w.batch) |*b| b.deinit(gpa); w.* = undefined; }
/// The next binding in the subtree, or null at the end of it. pub fn next(w: *Walk, gpa: Allocator) WalkError!?VarBind { while (true) { if (w.batch) |*b| { if (w.index < b.bindings.len) { const binding = b.bindings[w.index]; w.index += 1;
// Three ways a walk ends, and all three have to be // checked on every binding rather than once per reply. // // The agent says so explicitly. if (binding.value.data == .end_of_mib_view) { w.finished = true; continue; } // Or the answer has left the subtree that was asked for, // which is how a walk of a table ends: the agent has no // notion of the boundary and simply carries on into // whatever is next. if (!binding.name.startsWith(w.root)) { w.finished = true; continue; } // Or the agent did not move, which is not an ending but a // fault -- and the only thing standing between a caller // and an infinite loop. if (binding.name.order(w.at) != .gt) return error.AgentDidNotAdvance;
w.at = binding.name; return binding; } // The batch is spent. A GetBulk reply shorter than asked for // means the agent has run out, but a reply of exactly the // length asked for does not, so the only safe reading is to // ask again from where we got to. const was_short = b.bindings.len < w.batchSize(); b.deinit(gpa); w.batch = null; w.index = 0; if (was_short) w.finished = true; }
if (w.finished) return null;
var reply = if (w.options.bulk) try w.client.getBulk(gpa, &.{w.at}, 0, w.options.max_repetitions) else try w.client.getNext(gpa, &.{w.at}); errdefer reply.deinit(gpa);
// A v1 agent reports the end of the MIB as `noSuchName` rather // than with a marker, because it has no marker to use. That is an // ending and not a failure. if (reply.error_status == .no_such_name) { reply.deinit(gpa); return null; } if (reply.error_status != .no_error) { reply.deinit(gpa); return error.AgentError; } // An empty reply would leave the loop with nothing to do and // nothing to ask, so it ends the walk rather than repeating the // request for ever. if (reply.bindings.len == 0) { reply.deinit(gpa); return null; }
w.batch = reply; w.index = 0; } }
fn batchSize(w: *const Walk) usize { return if (w.options.bulk) w.options.max_repetitions else 1; }};
// -- tests ------------------------------------------------------------------
test "the request-id is per-request and wraps rather than overflowing" { var c: Client = .{ .io = .failing, .socket = .{ .handle = -1, .address = .{ .ip4 = .{ .bytes = .{ 0, 0, 0, 0 }, .port = 0 } } }, .peer = .{ .ip4 = .{ .bytes = .{ 127, 0, 0, 1 }, .port = 161 } }, .options = .{}, .next_request_id = std.math.maxInt(i32) - 1, .receive_buffer = &.{}, }; try testing.expectEqual(@as(i32, std.math.maxInt(i32) - 1), c.takeRequestId()); try testing.expectEqual(@as(i32, std.math.maxInt(i32)), c.takeRequestId()); // Wrapping to zero rather than to the bottom of i32: a client that has // made two billion requests must keep working, and it must not start // sending a negative `msgID`, which an agent drops without answering. try testing.expectEqual(@as(i32, 0), c.takeRequestId()); try testing.expectEqual(@as(i32, 1), c.takeRequestId());}
test "a reply from somewhere else is not a reply" { const a: Io.net.IpAddress = .{ .ip4 = .{ .bytes = .{ 127, 0, 0, 1 }, .port = 161 } }; const same: Io.net.IpAddress = .{ .ip4 = .{ .bytes = .{ 127, 0, 0, 1 }, .port = 161 } }; const other_port: Io.net.IpAddress = .{ .ip4 = .{ .bytes = .{ 127, 0, 0, 1 }, .port = 162 } }; const other_host: Io.net.IpAddress = .{ .ip4 = .{ .bytes = .{ 127, 0, 0, 2 }, .port = 161 } }; const v6: Io.net.IpAddress = .{ .ip6 = .{ .bytes = @splat(0), .port = 161 } };
try testing.expect(sameAddress(a, same)); try testing.expect(!sameAddress(a, other_port)); try testing.expect(!sameAddress(a, other_host)); // A v4 address and a v6 one are never the same here, even when one is the // mapped form of the other: a reply should come back the way the request // went out. try testing.expect(!sameAddress(a, v6)); try testing.expect(!sameAddress(v6, a)); try testing.expect(sameAddress(v6, v6));}
test "a client on a failing Io reports the failure rather than hanging" { // `std.Io.failing` answers every network call with an error, which is // exactly the shape the code has to handle anyway -- so a whole request // can be driven with no socket in sight. var buffer: [Message.max_size]u8 = undefined; var c: Client = .{ .io = .failing, .socket = .{ .handle = -1, .address = .{ .ip4 = .{ .bytes = .{ 0, 0, 0, 0 }, .port = 0 } } }, .peer = .{ .ip4 = .{ .bytes = .{ 127, 0, 0, 1 }, .port = 161 } }, .options = .{ .retries = 0 }, .next_request_id = 1, .receive_buffer = &buffer, }; const names = [_]ObjectId{try ObjectId.parse("1.3.6.1.2.1.1.1.0")}; // Which error it is, is `failing`'s business -- today it says // `NetworkDown` for a send. What matters is that the request returns one // rather than blocking, and that nothing leaks on the way out, which the // testing allocator checks. if (c.get(testing.allocator, &names)) |_| { return error.TestUnexpectedResult; } else |_| {}}
test "which binding an error refers to" { const bindings = [_]VarBind{ .request(try ObjectId.parse("1.3.6.1.2.1.1.1.0")), .request(try ObjectId.parse("1.3.6.1.2.1.31.1.1.1.6.1")), }; // RFC 3416 numbers from one, which is the off-by-one worth a test: a v1 // agent reporting noSuchName on the second binding says index 2. var r: Response = .{ .request_id = 1, .error_status = .no_such_name, .error_index = 2, .bindings = &bindings, .owned = @constCast(&bindings), }; try testing.expect(r.failedBinding().?.name.eql(bindings[1].name)); try testing.expectError(error.AgentError, r.expectOk());
// Zero means "no particular binding", and an index past the end is a // malformed agent rather than a panic. r.error_index = 0; try testing.expectEqual(@as(?VarBind, null), r.failedBinding()); r.error_index = 99; try testing.expectEqual(@as(?VarBind, null), r.failedBinding()); r.error_index = -1; try testing.expectEqual(@as(?VarBind, null), r.failedBinding());
// And no error means no failed binding, whatever the index says. r.error_status = .no_error; r.error_index = 1; try testing.expectEqual(@as(?VarBind, null), r.failedBinding()); try r.expectOk();}
// -- version 3 ---------------------------------------------------------------
/// The longest `snmpEngineID` RFC 3411 allows.pub const max_engine_id = 32;
/// What has been learned about the agent's engine, and the keys bound to it.////// A v3 client cannot say anything authenticated until it knows this: the keys/// are derived from the password *and* the engine ID, so there is nothing to/// sign with beforehand. That is what engine discovery is for, and it is why/// the first v3 request always costs two round trips.pub const Engine = struct { id: [max_engine_id]u8 = @splat(0), id_len: usize = 0, /// How many times the agent has restarted. Part of the replay defence: /// a message from before a restart is rejected on this alone. boots: u32 = 0, /// The agent's clock, as last reported. time: u32 = 0, /// Our own clock when `time` was learned, so that what we send is the /// agent's time advanced by however long ago that was rather than a stale /// reading. RFC 3414 §3.2 requires the estimate to track. learned_at: i96 = 0, keys: usm.Keys = .{}, known: bool = false,
pub fn engineId(e: *const Engine) []const u8 { return e.id[0..e.id_len]; }
/// The agent's time as it is now, by our reckoning. /// /// The time window is 150 seconds either side, so an estimate that did not /// advance would fall outside it after two and a half minutes of idling /// and every request after that would draw a /// `usmStatsNotInTimeWindows` report. pub fn timeNow(e: *const Engine, io: Io) u32 { if (!e.known) return 0; const elapsed_ns = Io.Timestamp.now(io, .awake).nanoseconds - e.learned_at; if (elapsed_ns <= 0) return e.time; const elapsed_s: u32 = @intCast(@min( @as(i96, std.math.maxInt(u32)), @divTrunc(elapsed_ns, std.time.ns_per_s), )); // Saturating, because the agent's clock is a u32 of seconds and a // client left running for 136 years should not wrap into the past. return e.time +| elapsed_s; }};
/// The OIDs an agent reports a USM failure with. RFC 3414 §5 defines them as/// counters, and a Report PDU naming one is how the agent says what went/// wrong -- there is no error-status for "your password is wrong".pub const usm_stats = struct { pub const unsupported_sec_level = "1.3.6.1.6.3.15.1.1.1.0"; pub const not_in_time_window = "1.3.6.1.6.3.15.1.1.2.0"; pub const unknown_user_name = "1.3.6.1.6.3.15.1.1.3.0"; pub const unknown_engine_id = "1.3.6.1.6.3.15.1.1.4.0"; pub const wrong_digest = "1.3.6.1.6.3.15.1.1.5.0"; pub const decryption_error = "1.3.6.1.6.3.15.1.1.6.0";};
pub const UsmError = error{ /// The agent does not know the user we claimed to be. UnknownUserName, /// The digest did not check out at the agent, which in practice means the /// authentication password is wrong. WrongDigest, /// Our notion of the agent's clock was outside the 150-second window and /// resynchronising did not help. NotInTimeWindow, /// The agent could not decrypt, which means the privacy password is /// wrong. DecryptionError, /// The agent will not accept the security level asked for. UnsupportedSecurityLevel, /// A Report naming a counter this does not recognise. UnexpectedReport, /// The reply's digest did not check out here, so it was not sent by /// somebody holding the key. AuthenticationFailed, /// The reply would not decrypt. DecryptionFailed, /// Discovery produced no engine ID. NoEngineId, /// An engine ID longer than RFC 3411 allows. EngineIdTooLong,};
fn reportToError(name: ObjectId) UsmError { const table = .{ .{ usm_stats.unsupported_sec_level, UsmError.UnsupportedSecurityLevel }, .{ usm_stats.not_in_time_window, UsmError.NotInTimeWindow }, .{ usm_stats.unknown_user_name, UsmError.UnknownUserName }, .{ usm_stats.unknown_engine_id, UsmError.NotInTimeWindow }, .{ usm_stats.wrong_digest, UsmError.WrongDigest }, .{ usm_stats.decryption_error, UsmError.DecryptionError }, }; inline for (table) |entry| { const oid = ObjectId.parse(entry[0]) catch unreachable; if (name.eql(oid)) return entry[1]; } return error.UnexpectedReport;}
pub const V3Error = RequestError || UsmError || error{ /// The message could not be built, which for v3 means there was no room /// for the digest. NoAuthField,};
/// Learns the agent's engine ID, boots and time.////// The request is deliberately empty and unauthenticated: no engine ID, no/// user name, no digest, and the `reportable` flag set. The agent cannot/// process it -- it does not know who we are -- so it answers with a Report/// PDU carrying its own engine parameters, which is exactly what was wanted./// Asking politely would not work, because there is no key to ask with until/// this has happened.pub fn discover(c: *Client, gpa: Allocator) V3Error!void { const msg_id = c.takeRequestId(); var e: asn1.Encoder = .init(gpa); defer e.deinit(); try V3.encode(&e, .{ .id = msg_id, .max_size = @intCast(c.receive_buffer.len), .flags = .fromLevel(.no_auth_no_priv, true), }, .{}, .{ .plaintext = .{ .pdu = Pdu.get(c.takeRequestId(), &.{}) } });
const bytes = try gpa.dupe(u8, e.buffered()); defer gpa.free(bytes);
const reply = try c.exchange(gpa, bytes, msg_id); defer gpa.free(reply);
const m = V3.decode(reply, gpa) catch return error.MalformedResponse; var scoped = m.scoped orelse return error.MalformedResponse; defer scoped.pdu.deinit(gpa);
if (m.parameters.engine_id.len == 0) return error.NoEngineId; if (m.parameters.engine_id.len > max_engine_id) return error.EngineIdTooLong;
c.engine.id_len = m.parameters.engine_id.len; @memcpy(c.engine.id[0..c.engine.id_len], m.parameters.engine_id); c.engine.boots = @intCast(m.parameters.engine_boots); c.engine.time = @intCast(m.parameters.engine_time); c.engine.learned_at = Io.Timestamp.now(c.io, .awake).nanoseconds; c.engine.known = true;
// Deriving the keys is a megabyte of hashing per key, so it happens here // -- once, when the engine ID becomes known -- rather than per request. if (c.options.user.auth != .none) { c.engine.keys = usm.Keys.derive(c.options.user, c.engine.engineId()); }}
/// Sends a v3 request and returns the response, running discovery first if/// needed and resynchronising once if the agent says our clock is wrong.fn requestV3(c: *Client, gpa: Allocator, pdu: Pdu) V3Error!Response { if (!c.engine.known) try c.discover(gpa);
var resynchronised = false; while (true) { if (c.sendV3(gpa, pdu)) |response| { return response; } else |err| switch (err) { // The window is 150 seconds either side and our estimate can be // wrong after a suspend, after an agent restart, or simply // because this is the first request in a long while. The agent's // Report carries its *current* boots and time, and `sendV3` has // already taken them, so one retry is all this needs -- and only // one, or a genuinely broken clock would loop. error.NotInTimeWindow => { if (resynchronised) return err; resynchronised = true; continue; }, else => return err, } }}
fn sendV3(c: *Client, gpa: Allocator, pdu: Pdu) V3Error!Response { const user = c.options.user; const level = user.level; const msg_id = c.takeRequestId();
// When privacy is on it is the *ciphertext* that goes in the message, so // the scoped PDU has to be encoded on its own first and the message built // around the result. Without privacy it is nested directly and this is // never used. var scoped_encoder: asn1.Encoder = .init(gpa); defer scoped_encoder.deinit(); if (level == .auth_priv) { try (V3.ScopedPdu{ .context_engine_id = c.engine.engineId(), .pdu = pdu, }).encode(&scoped_encoder); }
const boots = c.engine.boots; const time = c.engine.timeNow(c.io);
var salt: usm.Salt = .{ .bytes = @splat(0) }; var ciphertext: []u8 = &.{}; defer gpa.free(ciphertext);
const body: V3.Body = if (level == .auth_priv) blk: { c.privacy_counter +%= 1; switch (user.priv) { .none => unreachable, .des_cbc => { salt = usm.Des.salt(boots, @truncate(c.privacy_counter)); const room = usm.Des.paddedLength(scoped_encoder.buffered().len); ciphertext = try gpa.alloc(u8, room); break :blk .{ .encrypted = usm.Des.encrypt( c.engine.keys.privKey(), salt, scoped_encoder.buffered(), ciphertext, ) }; }, .des3_cbc => { salt = usm.Des3.salt(boots, @truncate(c.privacy_counter)); const room = usm.Des.paddedLength(scoped_encoder.buffered().len); ciphertext = try gpa.alloc(u8, room); break :blk .{ .encrypted = usm.Des3.encrypt( c.engine.keys.privKey(), salt, scoped_encoder.buffered(), ciphertext, ) }; }, .aes_128_cfb, .aes_192_cfb, .aes_256_cfb => { salt = usm.Aes.salt(c.privacy_counter); ciphertext = try gpa.alloc(u8, scoped_encoder.buffered().len); break :blk .{ .encrypted = usm.Aes.encrypt( c.engine.keys.privKey(), boots, time, salt, scoped_encoder.buffered(), ciphertext, ) }; }, } } else .{ .plaintext = .{ .context_engine_id = c.engine.engineId(), .pdu = pdu, } };
var e: asn1.Encoder = .init(gpa); defer e.deinit(); const zeros = [_]u8{0} ** usm.AuthProtocol.max_digest_length; try V3.encode(&e, .{ .id = msg_id, .max_size = @intCast(c.receive_buffer.len), .flags = .fromLevel(level, true), }, .{ .engine_id = c.engine.engineId(), .engine_boots = @intCast(boots), .engine_time = @intCast(time), .user_name = user.name, .auth_parameters = zeros[0..user.auth.digestLength()], .privacy_parameters = if (level == .auth_priv) &salt.bytes else "", }, body);
const bytes = try gpa.dupe(u8, e.buffered()); defer gpa.free(bytes); if (user.auth != .none) try V3.seal(bytes, user.auth, c.engine.keys.authKey());
const reply = try c.exchange(gpa, bytes, msg_id); var reply_owned = true; defer if (reply_owned) gpa.free(reply);
// Check the digest before believing anything else in the message. An // unauthenticated reply to an authenticated request is somebody else // talking, and acting on its contents first would defeat the point. if (user.auth != .none) { const scratch = try gpa.dupe(u8, reply); defer gpa.free(scratch); if (!V3.checkAuth(scratch, user.auth, c.engine.keys.authKey())) { // A Report can legitimately arrive unauthenticated -- the agent // may not have been able to authenticate it either -- so it is // inspected before giving up, which is how a wrong password gets // a useful message instead of a bare failure. return c.reportOrFail(gpa, reply) orelse error.AuthenticationFailed; } }
const m = V3.decode(reply, gpa) catch return error.MalformedResponse;
// Whatever the agent reports, take its clock: the Report carrying // notInTimeWindow is also the thing that tells us what the window is. if (m.parameters.engine_id.len != 0 and std.mem.eql(u8, m.parameters.engine_id, c.engine.engineId())) { c.engine.boots = @intCast(m.parameters.engine_boots); c.engine.time = @intCast(m.parameters.engine_time); c.engine.learned_at = Io.Timestamp.now(c.io, .awake).nanoseconds; }
var plaintext: []u8 = &.{}; var plaintext_owned = true; defer if (plaintext_owned) gpa.free(plaintext);
var scoped = if (m.scoped) |s| s else blk: { plaintext = try gpa.alloc(u8, m.encrypted.len); // Both protocols put exactly eight octets in msgPrivacyParameters, so // anything else is malformed rather than something to pad out -- and // padding it would mean decrypting with an IV the sender never used, // producing rubbish instead of an error. const received_salt = saltFrom(m.parameters.privacy_parameters) orelse return error.DecryptionFailed; const plain = switch (user.priv) { .none => return error.DecryptionFailed, .des_cbc => usm.Des.decrypt( c.engine.keys.privKey(), received_salt, m.encrypted, plaintext, ) catch return error.DecryptionFailed, .des3_cbc => usm.Des3.decrypt( c.engine.keys.privKey(), received_salt, m.encrypted, plaintext, ) catch return error.DecryptionFailed, .aes_128_cfb, .aes_192_cfb, .aes_256_cfb => usm.Aes.decrypt( c.engine.keys.privKey(), @intCast(m.parameters.engine_boots), @intCast(m.parameters.engine_time), received_salt, m.encrypted, plaintext, ), }; var d: asn1.Decoder = .init(plain); const el = d.next() catch return error.DecryptionFailed; break :blk V3.ScopedPdu.decode(el, gpa) catch return error.DecryptionFailed; }; var keep = false; defer if (!keep) scoped.pdu.deinit(gpa);
if (scoped.pdu.kind == .report) { if (scoped.pdu.varBinds().len == 0) return error.UnexpectedReport; return reportToError(scoped.pdu.varBinds()[0].name); } if (scoped.pdu.kind != .response) return error.UnexpectedPdu;
// The bindings' values point into whichever buffer they were decoded // from -- the decrypted plaintext, or the copy of the reply -- and both // are local to this function, so the response takes ownership of the one // that matters. Freeing it here instead is a use-after-free. const s = scoped.pdu.body.standard; keep = true; const backing = if (plaintext.len != 0) blk: { plaintext_owned = false; break :blk plaintext; } else blk: { reply_owned = false; break :blk reply; }; return .{ .request_id = s.request_id, .error_status = s.error_status, .error_index = s.error_index, .bindings = s.bindings, .owned = @constCast(s.bindings), .backing = backing, };}
/// If `reply` is a Report, the error it names; otherwise null.fn reportOrFail(c: *Client, gpa: Allocator, reply: []const u8) ?V3Error { _ = c; const m = V3.decode(reply, gpa) catch return null; var scoped = m.scoped orelse return null; defer scoped.pdu.deinit(gpa); if (scoped.pdu.kind != .report) return null; if (scoped.pdu.varBinds().len == 0) return null; return reportToError(scoped.pdu.varBinds()[0].name);}
/// Sends `bytes` and returns the reply whose `msgID` matches, retrying on/// timeout. The reply is a fresh allocation, because a v3 reply has to/// outlive the receive buffer once it has been decrypted.fn exchange(c: *Client, gpa: Allocator, bytes: []const u8, msg_id: i32) RequestError![]u8 { var attempt: usize = 0; while (true) : (attempt += 1) { try c.socket.send(c.io, &c.peer, bytes); const deadline = c.options.timeout.toDeadline(c.io); while (true) { const incoming = c.socket.receiveTimeout(c.io, c.receive_buffer, deadline) catch |err| switch (err) { error.Timeout => break, else => |e| return e, }; if (c.options.check_source and !sameAddress(incoming.from, c.peer)) continue; if (incoming.flags.trunc) continue;
// Matched on `msgID` rather than on the PDU's request-id, because // the PDU may still be encrypted at this point -- which is the // whole reason RFC 3412 put an identifier in the header. const id = peekMsgId(incoming.data) orelse continue; if (id != msg_id) continue; return gpa.dupe(u8, incoming.data); } if (attempt >= c.options.retries) return error.Timeout; }}
/// The salt a message carried, or null if it is not the eight octets both/// privacy protocols use.fn saltFrom(bytes: []const u8) ?usm.Salt { if (bytes.len != usm.Salt.length) return null; return .{ .bytes = bytes[0..usm.Salt.length].* };}
/// `msgID` out of a v3 message, without decoding the rest of it.fn peekMsgId(bytes: []const u8) ?i32 { var outer: asn1.Decoder = .init(bytes); const el = outer.expect(.sequence) catch return null; var d = el.decoder(); const version = d.integer(i32) catch return null; if (version != @intFromEnum(Version.v3)) return null; const header = d.expect(.sequence) catch return null; var h = header.decoder(); return h.integer(i32) catch null;}