// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! bwgpg standing in for gpg. //! //! Given a gpg command line, it either makes a detached signature itself, //! with a key the agent holds, or runs the real gpg with the same arguments //! and passes its exit status back. To git the two are indistinguishable, //! which is the point: `gpg.program = bwgpg` and nothing else changes. //! //! A signature is made the way gpg makes one, and reported the way gpg //! reports it: the signature on standard output (or `-o`), and on the //! status descriptor the `KEY_CONSIDERED`, `BEGIN_SIGNING` and `SIG_CREATED` //! lines. git looks for the last of those and refuses a signature without //! it. const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; const Environ = std.process.Environ; const gpgargs = @import("gpgargs.zig"); const platform = @import("platform.zig"); const config_mod = @import("config.zig"); const client = @import("agent/client.zig"); const armor = @import("openpgp/armor.zig"); const sign = @import("openpgp/sign.zig"); const Algorithm = @import("openpgp/key.zig").Algorithm; const git_summary = @import("git_summary.zig"); /// Runs one gpg command line and returns the exit status to leave with. pub fn run(gpa: Allocator, io: Io, env: *const Environ.Map, args: []const []const u8) !u8 { const parsed = gpgargs.parse(args); switch (parsed.mode) { .passthrough => return passthrough(gpa, io, env, args), .unsupported_sign => { complain(io, "bwgpg makes detached signatures only (-b), without --textmode or encryption", .{}); return 2; }, .detach_sign => return detachSign(gpa, io, env, parsed) catch |err| { // A refusal has already been explained, in the agent's words. switch (err) { error.AgentRefused => {}, error.ForwardedSocketDead => complain(io, "this SSH session is set up to sign with the key machine's agent, and nothing is listening on {s}: it was left behind by an SSH session that has ended, often a second session to this host that took the socket over. Log in again; sshd here wants StreamLocalBindUnlink yes", .{client.forwarded_socket_name}), error.ForwardedAgentGone => complain(io, "this SSH session is set up to sign with the key machine's agent, and the forward reached the key machine but no agent answered there: is bwgpg-agent-extra.socket running on it?", .{}), error.TailnetAgentUnreachable => complain(io, "this SSH session came over the tailnet from a machine this one is paired with, and nothing answered on its agent's port: is bwgpg-agent-tailnet.socket running there, or tailnet_port set?", .{}), error.TailnetAgentGone => complain(io, "this SSH session came over the tailnet from a machine this one is paired with, and its agent hung up without an answer: it did not take this machine for a node of the tailnet", .{}), else => complain(io, "signing failed: {t}", .{err}), } return 2; }, } } fn complain(io: Io, comptime fmt: []const u8, args: anytype) void { var buf: [512]u8 = undefined; var w = Io.File.stderr().writer(io, &buf); w.interface.print("bwgpg: " ++ fmt ++ "\n", args) catch {}; w.interface.flush() catch {}; } fn agentCall(gpa: Allocator, io: Io, env: *const Environ.Map, req: @import("agent/protocol.zig").Request) !std.json.Parsed(@import("agent/protocol.zig").Response) { const res = try client.call(gpa, io, env, req, true); if (!res.value.ok) { defer res.deinit(); complain(io, "{s}", .{res.value.message orelse res.value.@"error" orelse "the agent refused"}); return error.AgentRefused; } return res; } fn detachSign(gpa: Allocator, io: Io, env: *const Environ.Map, parsed: gpgargs.Parsed) !u8 { if (parsed.extra_inputs) { complain(io, "a detached signature covers one file", .{}); return 2; } const described = try agentCall(gpa, io, env, .{ .op = "describe", .key = parsed.key_selector }); defer described.deinit(); var fingerprint: [20]u8 = undefined; _ = try std.fmt.hexToBytes(&fingerprint, described.value.fingerprint orelse return error.AgentFailed); const algorithm: Algorithm = @fromBackingInt(@intCast(described.value.algorithm orelse return error.AgentFailed)); const fpr_hex = std.fmt.bytesToHex(fingerprint, .upper); const params: sign.Params = .{ .created = @intCast(Io.Timestamp.now(io, .real).toSeconds()), .algorithm = algorithm, .fingerprint = fingerprint, }; // Hash the data where it is, however long it is, keeping its start for // the summary a remote agent shows when it asks to confirm. var hasher: sign.Hasher = .init(); var head_buf: [4096]u8 = undefined; var head_len: usize = 0; { const input: Io.File = if (parsed.input) |path| try Io.Dir.cwd().openFile(io, path, .{}) else .stdin(); defer if (parsed.input != null) input.close(io); var buf: [64 * 1024]u8 = undefined; var reader = input.reader(io, &buf); while (true) { const chunk = reader.interface.peekGreedy(1) catch |err| switch (err) { error.EndOfStream => break, else => return err, }; hasher.update(chunk); const keep = @min(chunk.len, head_buf.len - head_len); @memcpy(head_buf[head_len..][0..keep], chunk[0..keep]); head_len += keep; reader.interface.toss(chunk.len); } } const digest = hasher.final(params); var summary_buf: [git_summary.max_len]u8 = undefined; var digest_b64: [std.base64.standard.Encoder.calcSize(sign.digest_length)]u8 = undefined; const signed = try agentCall(gpa, io, env, .{ .op = "sign", .fingerprint = &fpr_hex, .digest = std.base64.standard.Encoder.encode(&digest_b64, &digest), .summary = git_summary.summarize(head_buf[0..head_len], &summary_buf), }); defer signed.deinit(); const material_b64 = signed.value.material orelse return error.AgentFailed; var material_buf: [sign.max_material]u8 = undefined; const decoder = std.base64.standard.Decoder; const material_len = decoder.calcSizeForSlice(material_b64) catch return error.AgentFailed; if (material_len > material_buf.len) return error.AgentFailed; decoder.decode(material_buf[0..material_len], material_b64) catch return error.AgentFailed; var packet: Io.Writer.Allocating = .init(gpa); defer packet.deinit(); try sign.writePacket(&packet.writer, params, digest, material_buf[0..material_len]); { const output: Io.File = if (parsed.output) |path| if (std.mem.eql(u8, path, "-")) .stdout() else try Io.Dir.cwd().createFile(io, path, .{}) else .stdout(); defer if (parsed.output != null and !std.mem.eql(u8, parsed.output.?, "-")) output.close(io); var buf: [4096]u8 = undefined; var w = output.writer(io, &buf); if (parsed.armor) { try armor.encode(&w.interface, "SIGNATURE", packet.written()); } else { try w.interface.writeAll(packet.written()); } try w.interface.flush(); } if (parsed.status_fd) |fd| { var status_buf: [512]u8 = undefined; const status = try std.fmt.bufPrint(&status_buf, \\[GNUPG:] KEY_CONSIDERED {s} 0 \\[GNUPG:] BEGIN_SIGNING H{d} \\[GNUPG:] SIG_CREATED D {d} {d} 00 {d} {s} \\ , .{ fpr_hex, sign.hash_algorithm_sha512, @backingInt(algorithm), sign.hash_algorithm_sha512, params.created, fpr_hex, }); platform.writeFd(io, fd, status); } return 0; } /// Runs the real gpg with the same arguments. fn passthrough(gpa: Allocator, io: Io, env: *const Environ.Map, args: []const []const u8) !u8 { const gpg = findGpg(gpa, io, env) catch |err| { complain(io, "cannot find the real gpg to pass this to ({t}); set \"gpg\" in the config", .{err}); return 2; }; defer gpa.free(gpg); const argv = try gpa.alloc([]const u8, args.len + 1); defer gpa.free(argv); argv[0] = gpg; @memcpy(argv[1..], args); var child = try std.process.spawn(io, .{ .argv = argv }); const term = try child.wait(io); return switch (term) { .exited => |code| code, .signal => |sig| 128 +| @as(u8, @truncate(@backingInt(sig))), else => 2, }; } /// The real gpg: the one the config names, or the first on PATH that is not /// bwgpg itself, which it would be if bwgpg had been installed as `gpg`. fn findGpg(gpa: Allocator, io: Io, env: *const Environ.Map) ![]u8 { if (config_mod.configPath(gpa, io, env)) |path| { defer gpa.free(path); if (config_mod.load(gpa, io, path)) |loaded| { defer loaded.deinit(); if (loaded.value.gpg) |g| return gpa.dupe(u8, g); } else |_| {} } else |_| {} const self = try std.process.executablePathAlloc(io, gpa); defer gpa.free(self); const candidates = try platform.gpgCandidates(gpa, env); defer { for (candidates) |c| gpa.free(c); gpa.free(candidates); } for (candidates) |c| { const found = try platform.findProgram(gpa, io, env, c) orelse continue; const real = Io.Dir.cwd().realPathFileAlloc(io, found, gpa) catch { gpa.free(found); continue; }; defer gpa.free(real); if (std.mem.eql(u8, real, self)) { gpa.free(found); continue; } return found; } return error.FileNotFound; }