// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Talking to the agent, and starting it when it is not there. //! //! The agent is normally this machine's own. In an SSH session from a key //! machine, this machine is a remote machine and can sign with the key //! machine's agent instead, by one of two routes: the forward, which brings //! the agent's extra socket here as the forwarded socket (`RemoteForward`), //! or, when the session came over the tailnet and the two are paired, the //! tailnet, on which this machine dials the agent there (see `tailnet.zig`). //! The agent to talk to is, in order: //! //! 1. `BWGPG_AGENT_SOCKET`, when set, as with `SSH_AUTH_SOCK`. //! 2. The agent on the key machine this SSH session came from, over the //! tailnet, when `SSH_CONNECTION` begins with a tailnet address that //! `tailnet-agents.json` holds a pairing for. //! 3. `$XDG_RUNTIME_DIR/bwgpg-remote.sock`, the forwarded socket, when this //! is an SSH session (`SSH_CONNECTION` is set) and the socket is there. //! 4. This machine's agent socket. //! //! A key machine's agent is never replaced by a local one when it is //! missing -- the local one would have no keys -- and is sent none of this //! machine's environment, whose display and terminal mean nothing to the //! key machine. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const Environ = std.process.Environ; const protocol = @import("protocol.zig"); const tailnet = @import("tailnet.zig"); const config_mod = @import("../config.zig"); pub const Error = error{ /// No agent is running and none was to be started. AgentNotRunning, /// An agent was started and never began answering. AgentDidNotStart, /// The agent closed the connection without an answer. AgentFailed, /// This is an SSH session meant to use a key machine's agent, and /// nothing is listening on the forwarded socket: a socket file left /// behind by an SSH session that has ended. ForwardedSocketDead, /// The forwarded socket answers, but the agent at its other end does /// not: ssh accepted the connection and then closed it. ForwardedAgentGone, /// This SSH session came over the tailnet from a key machine this one /// is paired with, and nothing answered on the agent's port there. TailnetAgentUnreachable, /// The agent over the tailnet accepted the connection and closed it /// without an answer: it does not take this machine for a node of the /// tailnet. TailnetAgentGone, }; /// The name of the forwarded socket: what an SSH `RemoteForward` makes on /// this machine of a key machine's extra socket. pub const forwarded_socket_name = "bwgpg-remote.sock"; pub const Target = struct { /// The socket, or empty for an agent over the tailnet. path: []u8, /// A key machine's agent, for remote signing by either route; a socket /// named by `BWGPG_AGENT_SOCKET` is taken for one too. remote: bool, tailnet: ?Tailnet = null, /// An agent over the tailnet, and what it is to be shown. pub const Tailnet = struct { address: Io.net.IpAddress, /// The pairing token. Owned. token: []u8, /// This session's `SSH_CONNECTION`. Owned. ssh: []u8, }; pub fn deinit(t: Target, gpa: Allocator) void { gpa.free(t.path); if (t.tailnet) |tn| { std.crypto.secureZero(u8, tn.token); gpa.free(tn.token); gpa.free(tn.ssh); } } }; /// Which agent to use; see the top of this file. The caller deinits it. pub fn target(gpa: Allocator, io: Io, env: *const Environ.Map) !Target { if (env.get("BWGPG_AGENT_SOCKET")) |p| { if (p.len > 0) return .{ .path = try gpa.dupe(u8, p), .remote = true }; } const ssh_connection: []const u8 = env.get("SSH_CONNECTION") orelse ""; if (tailnet.parseSshConnection(ssh_connection)) |sc| if (tailnet.isTailnet(sc.client)) { if (try tailnetTarget(gpa, io, env, sc, ssh_connection)) |t| return t; }; if (ssh_connection.len > 0) { if (env.get("XDG_RUNTIME_DIR")) |dir| { const path = try std.fs.path.join(gpa, &.{ dir, forwarded_socket_name }); if (Io.Dir.cwd().access(io, path, .{})) { return .{ .path = path, .remote = true }; } else |_| gpa.free(path); } } return .{ .path = try config_mod.socketPath(gpa, io, env), .remote = false }; } /// The agent on the key machine an SSH session over the tailnet came from, /// if this machine is paired with it. fn tailnetTarget( gpa: Allocator, io: Io, env: *const Environ.Map, sc: tailnet.SshConnection, ssh_connection: []const u8, ) !?Target { var arena_state: std.heap.ArenaAllocator = .init(gpa); defer arena_state.deinit(); const arena = arena_state.allocator(); const path = try tailnet.keyMachinePairingsPath(arena, io, env); const list = try tailnet.load(tailnet.KeyMachinePairings, arena, io, path); const pairing = list.find(sc.client) orelse return null; var address = tailnet.unmap(sc.client); address.setPort(pairing.port); const token = try gpa.dupe(u8, pairing.token); errdefer gpa.free(token); const ssh = try gpa.dupe(u8, ssh_connection); errdefer gpa.free(ssh); return .{ .path = try gpa.dupe(u8, ""), .remote = true, .tailnet = .{ .address = address, .token = token, .ssh = ssh }, }; } /// Sends `req` and returns the agent's answer. With `autostart`, an agent /// that is not running is started first. /// /// The request's `env` is filled in from `env` here, so every request /// carries what a pinentry would need. pub fn call( gpa: Allocator, io: Io, env: *const Environ.Map, req: protocol.Request, autostart: bool, ) !std.json.Parsed(protocol.Response) { const t = try target(gpa, io, env); defer t.deinit(gpa); const stream = if (t.tailnet) |tn| tn.address.connect(io, .{ .mode = .stream }) catch |err| return switch (err) { error.Canceled => err, else => error.TailnetAgentUnreachable, } else try connectUnix(gpa, io, t, autostart); defer stream.close(io); var vars: std.ArrayList(protocol.EnvVar) = .empty; defer vars.deinit(gpa); if (!t.remote) for (protocol.pinentry_env) |name| { if (env.get(name)) |value| try vars.append(gpa, .{ .name = name, .value = value }); }; var full = req; full.env = vars.items; if (t.tailnet) |tn| { full.token = tn.token; full.ssh = tn.ssh; } var read_buf: [4096]u8 = undefined; var write_buf: [4096]u8 = undefined; var reader = stream.reader(io, &read_buf); var writer = stream.writer(io, &write_buf); // Over SSH, a forward whose other end is gone accepts the connection and // then closes it, which the request can meet as easily as the answer. // Over the tailnet, an agent that will not answer this machine at all // does the same. const gone: Error = if (t.tailnet != null) error.TailnetAgentGone else error.ForwardedAgentGone; protocol.send(gpa, &writer.interface, full) catch |err| switch (err) { error.WriteFailed => return if (t.remote) gone else err, else => return err, }; return protocol.receive(protocol.Response, gpa, &reader.interface) catch |err| switch (err) { error.EndOfStream, error.ReadFailed => if (t.remote) gone else error.AgentFailed, else => err, }; } /// Connects to the agent's socket at `t.path`, starting the agent first if /// it is this machine's, it is not running, and `autostart` says to. fn connectUnix(gpa: Allocator, io: Io, t: Target, autostart: bool) !Io.net.Stream { const address = try Io.net.UnixAddress.init(t.path); return address.connect(io) catch |err| blk: { // A socket file with no listener behind it is refused, and // whatever the reason, nothing is at the other end of this file. if (t.remote) return switch (err) { error.Canceled => err, else => error.ForwardedSocketDead, }; // Whatever the reason -- no socket file, or one left behind by an // agent that died -- the cure is the same: start one, which clears // away a stale socket before it listens. if (!autostart) return error.AgentNotRunning; try start(gpa, io); // It needs a moment to derive nothing and bind a socket; allow it // five seconds, which is far more than it takes. for (0..100) |_| { io.sleep(.fromMilliseconds(50), .awake) catch {}; break :blk address.connect(io) catch continue; } return error.AgentDidNotStart; }; } /// Starts `bwgpg agent` in the background. It detaches itself. fn start(gpa: Allocator, io: Io) !void { const self = try std.process.executablePathAlloc(io, gpa); defer gpa.free(self); // Not waited for: it outlives this process, and is reparented when this // one exits. _ = try std.process.spawn(io, .{ .argv = &.{ self, "agent" }, .stdin = .ignore, .stdout = .ignore, .stderr = .ignore, .create_no_window = true, }); } test "the socket to use: the variable, the forward, then the local agent" { const gpa = std.testing.allocator; const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const dir = try tmp.dir.realPathFileAlloc(io, ".", gpa); defer gpa.free(dir); var env: Environ.Map = .init(gpa); defer env.deinit(); try env.put("XDG_RUNTIME_DIR", dir); try env.put("BWGPG_RUNTIME_DIR", dir); // Not an SSH session: the local agent. const local = try target(gpa, io, &env); defer local.deinit(gpa); try std.testing.expect(!local.remote); // An SSH session with no forward: still the local agent. try env.put("SSH_CONNECTION", "192.0.2.1 50000 192.0.2.2 22"); const no_forward = try target(gpa, io, &env); defer no_forward.deinit(gpa); try std.testing.expect(!no_forward.remote); // With the forwarded socket there, that one. var f = try tmp.dir.createFile(io, forwarded_socket_name, .{}); f.close(io); const forwarded = try target(gpa, io, &env); defer forwarded.deinit(gpa); try std.testing.expect(forwarded.remote); try std.testing.expect(std.mem.endsWith(u8, forwarded.path, forwarded_socket_name)); // And the variable above both. try env.put("BWGPG_AGENT_SOCKET", "/somewhere/else.sock"); const explicit = try target(gpa, io, &env); defer explicit.deinit(gpa); try std.testing.expect(explicit.remote); try std.testing.expectEqualStrings("/somewhere/else.sock", explicit.path); } test "an SSH session over the tailnet, from a paired machine, uses its agent" { const gpa = std.testing.allocator; const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const dir = try tmp.dir.realPathFileAlloc(io, ".", gpa); defer gpa.free(dir); const config_path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); defer gpa.free(config_path); const agents_path = try std.fs.path.join(gpa, &.{ dir, "tailnet-agents.json" }); defer gpa.free(agents_path); var env: Environ.Map = .init(gpa); defer env.deinit(); try env.put("XDG_RUNTIME_DIR", dir); try env.put("BWGPG_RUNTIME_DIR", dir); try env.put("BWGPG_CONFIG", config_path); // The forwarded socket is there too, and loses. var f = try tmp.dir.createFile(io, forwarded_socket_name, .{}); f.close(io); // Over the tailnet, but not paired: the forward. try env.put("SSH_CONNECTION", "100.64.0.3 50022 100.64.0.7 22"); const unpaired = try target(gpa, io, &env); defer unpaired.deinit(gpa); try std.testing.expect(unpaired.tailnet == null); try std.testing.expect(unpaired.remote); try config_mod.savePrivate(gpa, io, agents_path, tailnet.KeyMachinePairings{ .agents = &.{.{ .node = "a", .addresses = &.{"100.64.0.3"}, .port = 7743, .token = "dG9rZW4=", }} }); const paired = try target(gpa, io, &env); defer paired.deinit(gpa); const tn = paired.tailnet.?; try std.testing.expect(paired.remote); try std.testing.expect(tailnet.sameHost(tn.address, try Io.net.IpAddress.parse("100.64.0.3", 0))); try std.testing.expectEqual(@as(u16, 7743), tn.address.getPort()); try std.testing.expectEqualStrings("dG9rZW4=", tn.token); try std.testing.expectEqualStrings("100.64.0.3 50022 100.64.0.7 22", tn.ssh); // A session from somewhere else: the forward again. try env.put("SSH_CONNECTION", "100.64.0.9 50022 100.64.0.7 22"); const elsewhere = try target(gpa, io, &env); defer elsewhere.deinit(gpa); try std.testing.expect(elsewhere.tailnet == null); // Not an SSH session: the token alone does nothing. _ = env.swapRemove("SSH_CONNECTION"); const local = try target(gpa, io, &env); defer local.deinit(gpa); try std.testing.expect(local.tailnet == null); try std.testing.expect(!local.remote); } /// An SSH session with the forwarded socket in `dir`, and the request /// `call` makes through it. fn callForwarded(gpa: Allocator, io: Io, dir: []const u8) !std.json.Parsed(protocol.Response) { var env: Environ.Map = .init(gpa); defer env.deinit(); try env.put("XDG_RUNTIME_DIR", dir); try env.put("BWGPG_RUNTIME_DIR", dir); try env.put("SSH_CONNECTION", "192.0.2.1 50000 192.0.2.2 22"); return call(gpa, io, &env, .{ .op = "status" }, true); } /// Listens on `path` for a test. Wine does not implement the AFD request /// that Zig's Windows `listen` names a Unix socket's path with, and answers /// `STATUS_INVALID_DEVICE_REQUEST`, which reaches here as `error.Unexpected`; /// a test that needs a listener is skipped there rather than failed. fn listenForTest(io: Io, path: []const u8) !Io.net.Server { const address = try Io.net.UnixAddress.init(path); return address.listen(io, .{}) catch |err| switch (err) { error.Unexpected => if (@import("builtin").os.tag == .windows) error.SkipZigTest else err, else => err, }; } test "a forwarded socket nothing is listening on" { const gpa = std.testing.allocator; const io = std.testing.io; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const dir = try tmp.dir.realPathFileAlloc(io, ".", gpa); defer gpa.free(dir); const path = try std.fs.path.join(gpa, &.{ dir, forwarded_socket_name }); defer gpa.free(path); // What an ended SSH session leaves: the file, with no listener. var server = try listenForTest(io, path); server.deinit(io); try std.testing.expectError(error.ForwardedSocketDead, callForwarded(gpa, io, dir)); } test "a forwarded socket whose far agent does not answer" { const gpa = std.testing.allocator; var threaded: Io.Threaded = .init(gpa, .{}); defer threaded.deinit(); const io = threaded.io(); var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const dir = try tmp.dir.realPathFileAlloc(io, ".", gpa); defer gpa.free(dir); const path = try std.fs.path.join(gpa, &.{ dir, forwarded_socket_name }); defer gpa.free(path); // What ssh does when the agent at the other end is not there: it // accepts, and closes. var server = try listenForTest(io, path); defer server.deinit(io); const Hangup = struct { fn run(s: *Io.net.Server, task_io: Io) void { const stream = s.accept(task_io) catch return; stream.close(task_io); } }; var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, Hangup.run, .{ &server, io }); try std.testing.expectError(error.ForwardedAgentGone, callForwarded(gpa, io, dir)); }