Something went wrong. Try again.
Sign git commits and tags with an OpenPGP key kept in Bitwarden.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! bwgpg signs git commits and tags with an OpenPGP key kept in Bitwarden.//!//! Set `git config --global gpg.program bwgpg` and it stands in for gpg://! detached signatures it makes itself, with a key read out of a Bitwarden//! Secure Note by a small agent that asks for the master password once;//! everything else, verification included, it hands to the real gpg.//!//! ```text//! bwgpg login set up the server, account and API key//! bwgpg git-setup configure git to sign with bwgpg, in this repository or --global//! bwgpg remote the SSH sessions signing with this machine's agent: list, allow, revoke;//! and pairing over the tailnet: pair, unpair, join//! bwgpg unlock ask for the master password now rather than at the next signature//! bwgpg status whether the agent is unlocked, and the keys it found//! bwgpg sync fetch the vault again//! bwgpg lock lock the agent: forget the keys//! bwgpg stop stop the agent//! bwgpg agent run the agent (started automatically; --foreground to watch it)//! bwgpg <gpg arguments>//! ```
const std = @import("std");const builtin = @import("builtin");const Allocator = std.mem.Allocator;const Io = std.Io;const Environ = std.process.Environ;
pub const openpgp = struct { pub const armor = @import("openpgp/armor.zig"); pub const packet = @import("openpgp/packet.zig"); pub const key = @import("openpgp/key.zig"); pub const sign = @import("openpgp/sign.zig");};pub const bw = struct { pub const crypto = @import("bw/crypto.zig"); pub const json_util = @import("bw/json_util.zig"); pub const api = @import("bw/api.zig"); pub const vault = @import("bw/vault.zig");};pub const agent = struct { pub const protocol = @import("agent/protocol.zig"); pub const client = @import("agent/client.zig"); pub const server = @import("agent/server.zig"); pub const sessions = @import("agent/sessions.zig"); pub const tailnet = @import("agent/tailnet.zig");};pub const config = @import("config.zig");pub const git_setup = @import("git_setup.zig");pub const git_summary = @import("git_summary.zig");pub const gpgargs = @import("gpgargs.zig");pub const pinentry = @import("pinentry.zig");pub const platform = @import("platform.zig");pub const secmem = @import("secmem.zig");pub const shim = @import("shim.zig");
const version = @import("build_options").version;
pub fn main(init: std.process.Init) !u8 { const gpa = init.gpa; const io = init.io; const env = init.environ_map; const args = try init.minimal.args.toSlice(init.arena.allocator()); const rest = args[1..];
if (rest.len > 0) { const cmd = rest[0]; const eql = std.mem.eql; if (eql(u8, cmd, "agent")) return runAgent(gpa, io, env, rest[1..]); if (eql(u8, cmd, "login")) return login(gpa, io, env, rest[1..]); if (eql(u8, cmd, "git-setup")) return git_setup.run(gpa, io, env, rest[1..]); if (eql(u8, cmd, "remote")) return remote(gpa, io, env, rest[1..]); if (eql(u8, cmd, "unlock") or eql(u8, cmd, "sync") or eql(u8, cmd, "status") or eql(u8, cmd, "lock") or eql(u8, cmd, "stop")) { return control(gpa, io, env, cmd); } // `--help` is gpg's, and goes to gpg. if (eql(u8, cmd, "help")) { try out(io, usage, .{}); return 0; } if (eql(u8, cmd, "--bwgpg-version")) { try out(io, "bwgpg {s}\n", .{version}); return 0; } } return shim.run(gpa, io, env, rest);}
const usage = \\usage: bwgpg <command> \\ bwgpg <gpg arguments> \\ \\ login [--server URL] [--email EMAIL] [--client-id ID] [--client-secret-stdin] \\ set up the server, account and personal API key \\ git-setup [--global | --repo DIR] [--key SELECTOR] [--no-sign-by-default] [--dry-run] \\ configure git to sign with bwgpg, here or globally \\ remote [list | allow [PID] | revoke [PID]] \\ the SSH sessions signing with this machine's agent; allow stops \\ confirming a session's signatures (all of them without a PID) \\ remote pair HOST [--print] | unpair HOST \\ let HOST sign with this machine's agent over the tailnet, during \\ an SSH session from here; pair runs `bwgpg remote join` there \\ over ssh, or with --print says what to run there by hand \\ unlock ask for the master password now \\ status whether the agent is unlocked, and the keys it found \\ sync fetch the vault again \\ lock lock the agent: forget the keys \\ stop stop the agent \\ agent [--foreground] \\ run the agent; it is started automatically when needed \\ \\Anything else is a gpg command line. Detached signatures (what git asks \\for) are made with a key from Bitwarden; the rest goes to the real gpg. \\;
fn out(io: Io, comptime fmt: []const u8, args: anytype) !void { var buf: [1024]u8 = undefined; var w = Io.File.stdout().writer(io, &buf); try w.interface.print(fmt, args); try w.interface.flush();}
fn err(io: Io, comptime fmt: []const u8, args: anytype) void { var buf: [1024]u8 = undefined; var w = Io.File.stderr().writer(io, &buf); w.interface.print("bwgpg: " ++ fmt ++ "\n", args) catch {}; w.interface.flush() catch {};}
fn loadConfig(gpa: Allocator, io: Io, env: *const Environ.Map) !std.json.Parsed(config.Config) { const path = try config.configPath(gpa, io, env); defer gpa.free(path); return config.load(gpa, io, path) catch |e| { switch (e) { error.NotConfigured => err(io, "no config at {s}; run `bwgpg login`", .{path}), error.InsecurePermissions => err(io, "{s} is readable by others; chmod 600 it", .{path}), error.InvalidConfig => err(io, "{s} is not a valid config", .{path}), else => {}, } return e; };}
fn runAgent(gpa: Allocator, io: Io, env: *const Environ.Map, args: []const []const u8) !u8 { var foreground = false; for (args) |a| { if (std.mem.eql(u8, a, "--foreground")) foreground = true; } const loaded = loadConfig(gpa, io, env) catch return 1; defer loaded.deinit(); agent.server.run(gpa, io, env, &loaded.value, foreground) catch |e| { err(io, "agent: {t}", .{e}); return 1; }; return 0;}
fn control(gpa: Allocator, io: Io, env: *const Environ.Map, cmd: []const u8) !u8 { const autostart = std.mem.eql(u8, cmd, "unlock") or std.mem.eql(u8, cmd, "sync"); const res = agent.client.call(gpa, io, env, .{ .op = cmd }, autostart) catch |e| switch (e) { error.AgentNotRunning => { try out(io, "the agent is not running\n", .{}); return if (std.mem.eql(u8, cmd, "status")) 1 else 0; }, else => { err(io, "{t}", .{e}); return 1; }, }; defer res.deinit(); const r = res.value; if (!r.ok) { err(io, "{s}", .{r.message orelse r.@"error" orelse "failed"}); return 1; } if (r.unlocked) |u| try out(io, "{s}\n", .{if (u) "unlocked" else "locked"}); if (r.keys) |keys| for (keys) |k| { try out(io, "{s} {s}\n", .{ k.fingerprint, k.item }); for (k.user_ids) |uid| try out(io, " {s}\n", .{uid}); }; if (r.problems) |problems| for (problems) |p| try out(io, "unreadable: {s}\n", .{p}); return 0;}
/// One line from standard input, without its line ending, copied into/// `arena`; `current` when the line is empty./// `bwgpg remote`: the SSH sessions remote signing goes through, by either/// route, and whether each is allowed or still confirmed.fn remote(gpa: Allocator, io: Io, env: *const Environ.Map, args: []const []const u8) !u8 { const sub = if (args.len > 0) args[0] else "list"; if (std.mem.eql(u8, sub, "pair")) return remotePair(gpa, io, env, args[1..]); if (std.mem.eql(u8, sub, "unpair")) return remoteUnpair(gpa, io, env, args[1..]); if (std.mem.eql(u8, sub, "join")) return remoteJoin(gpa, io, env); const op = if (std.mem.eql(u8, sub, "list")) "remote_list" else if (std.mem.eql(u8, sub, "allow")) "remote_allow" else if (std.mem.eql(u8, sub, "revoke")) "remote_revoke" else { err(io, "remote: list, allow [PID], revoke [PID], pair HOST or unpair HOST", .{}); return 2; }; const pid: ?i32 = if (args.len > 1) std.fmt.parseInt(i32, args[1], 10) catch { err(io, "remote: {s} is not a process ID", .{args[1]}); return 2; } else null;
const res = agent.client.call(gpa, io, env, .{ .op = op, .pid = pid }, false) catch |e| switch (e) { error.AgentNotRunning => { try out(io, "the agent is not running\n", .{}); return 1; }, else => { err(io, "{t}", .{e}); return 1; }, }; defer res.deinit(); const r = res.value; if (!r.ok) { err(io, "{s}", .{r.message orelse r.@"error" orelse "failed"}); return 1; } const sessions = r.sessions orelse &.{}; if (sessions.len == 0) try out(io, "no SSH sessions are signing through this agent\n", .{}); for (sessions) |s| { try out(io, "{d:>8} {s} {s}\n", .{ s.pid, if (s.allowed) "allowed" else "confirm", s.command }); } return 0;}
const tailnet = agent.tailnet;
/// `bwgpg remote pair HOST`, on the key machine: makes a pairing token for/// the remote machine HOST, hands it over ssh to `bwgpg remote join` there,/// and, once that has worked, keeps the key machine's half of the pairing.fn remotePair(gpa: Allocator, io: Io, env: *const Environ.Map, args: []const []const u8) !u8 { var arena_state: std.heap.ArenaAllocator = .init(gpa); defer arena_state.deinit(); const arena = arena_state.allocator();
var host: ?[]const u8 = null; var print = false; for (args) |a| { if (std.mem.eql(u8, a, "--print")) { print = true; } else if (host == null and !std.mem.startsWith(u8, a, "-")) { host = a; } else { err(io, "remote pair: HOST [--print]", .{}); return 2; } } const name = host orelse { err(io, "remote pair: which host?", .{}); return 2; };
// The port HOST is told: the config's, or the one the systemd unit // listens on. const parsed = loadConfig(gpa, io, env) catch |e| { err(io, "{t}", .{e}); return 1; }; defer parsed.deinit(); const port = parsed.value.tailnet_port orelse tailnet.default_port;
const status = tailnet.status(arena, io, tailnet.tailscaledSocket(env)) catch |e| { err(io, "cannot ask tailscaled about the tailnet: {t}", .{e}); return 1; }; const node = status.find(name) orelse { err(io, "{s} is not a machine on the tailnet", .{name}); return 1; };
const token = tailnet.newToken(io); const hash = tailnet.tokenHash(&token).?; const message = try std.json.Stringify.valueAlloc(arena, tailnet.KeyMachinePairing{ .node = status.self.dns_name, .addresses = status.self.address_texts, .port = port, .token = &token, }, .{});
if (print) { try out(io, "Run this on {s}; it holds the secret that lets it sign, so keep it to yourself:\n\n", .{node.name}); try out(io, " echo '{s}' | bwgpg remote join\n\n", .{message}); } else { var child = std.process.spawn(io, .{ .argv = &.{ "ssh", name, "bwgpg", "remote", "join" }, .stdin = .pipe, }) catch |e| { err(io, "cannot run ssh: {t}", .{e}); return 1; }; { var buf: [256]u8 = undefined; var w = child.stdin.?.writer(io, &buf); w.interface.print("{s}\n", .{message}) catch {}; w.interface.flush() catch {}; child.stdin.?.close(io); child.stdin = null; } const term = try child.wait(io); const ok = switch (term) { .exited => |code| code == 0, else => false, }; if (!ok) { err(io, "`bwgpg remote join` did not work on {s}; nothing was paired", .{name}); return 1; } }
// Kept only now, so that a failed hand-over leaves nothing behind. const path = try tailnet.remotePairingsPath(arena, io, env); const old = tailnet.load(tailnet.RemotePairings, arena, io, path) catch |e| { err(io, "{s}: {t}", .{ path, e }); return 1; }; var pairings: std.ArrayList(tailnet.RemotePairing) = .empty; for (old.peers) |p| if (!std.mem.eql(u8, p.stable_id, node.stable_id)) try pairings.append(arena, p); try pairings.append(arena, .{ .node = node.dns_name, .stable_id = node.stable_id, .token_sha256 = &hash }); try config.savePrivate(gpa, io, path, tailnet.RemotePairings{ .peers = pairings.items });
try out(io, "paired with {s}: during an SSH session from here over the tailnet, it signs with this agent\n", .{node.dns_name}); return 0;}
/// `bwgpg remote unpair HOST`, on the key machine: ends the pairing with the/// remote machine HOST, so that it can no longer sign over the tailnet.fn remoteUnpair(gpa: Allocator, io: Io, env: *const Environ.Map, args: []const []const u8) !u8 { var arena_state: std.heap.ArenaAllocator = .init(gpa); defer arena_state.deinit(); const arena = arena_state.allocator(); if (args.len != 1) { err(io, "remote unpair: HOST", .{}); return 2; } const name = args[0];
const path = try tailnet.remotePairingsPath(arena, io, env); const old = tailnet.load(tailnet.RemotePairings, arena, io, path) catch |e| { err(io, "{s}: {t}", .{ path, e }); return 1; }; // By the name it was paired under, or, when tailscaled knows it, by // whatever it is called now. const stable_id: ?[]const u8 = if (tailnet.status(arena, io, tailnet.tailscaledSocket(env))) |status| if (status.find(name)) |n| n.stable_id else null else |_| null; var pairings: std.ArrayList(tailnet.RemotePairing) = .empty; var removed: usize = 0; for (old.peers) |p| { const label = p.node[0 .. std.mem.findScalar(u8, p.node, '.') orelse p.node.len]; const named = std.ascii.eqlIgnoreCase(name, p.node) or std.ascii.eqlIgnoreCase(name, label) or (if (stable_id) |id| std.mem.eql(u8, id, p.stable_id) else false); if (named) removed += 1 else try pairings.append(arena, p); } if (removed == 0) { err(io, "{s} is not paired", .{name}); return 1; } try config.savePrivate(gpa, io, path, tailnet.RemotePairings{ .peers = pairings.items }); try out(io, "unpaired {s}\n", .{name}); return 0;}
/// `bwgpg remote join`, on the remote machine: reads what `bwgpg remote/// pair` sends on standard input and keeps it as the remote machine's half/// of the pairing, readable by its owner alone.fn remoteJoin(gpa: Allocator, io: Io, env: *const Environ.Map) !u8 { var arena_state: std.heap.ArenaAllocator = .init(gpa); defer arena_state.deinit(); const arena = arena_state.allocator();
var buf: [4096]u8 = undefined; var stdin = Io.File.stdin().readerStreaming(io, &buf); const line = try readLine(arena, &stdin.interface); const joined = std.json.parseFromSliceLeaky(tailnet.KeyMachinePairing, arena, line, .{ .ignore_unknown_fields = true, .allocate = .alloc_always, }) catch { err(io, "remote join: expected what `bwgpg remote pair --print` gives, on standard input", .{}); return 2; }; if (tailnet.tokenHash(joined.token) == null or joined.addresses.len == 0) { err(io, "remote join: that is not a pairing", .{}); return 2; }
const path = try tailnet.keyMachinePairingsPath(arena, io, env); const old = tailnet.load(tailnet.KeyMachinePairings, arena, io, path) catch |e| { err(io, "{s}: {t}", .{ path, e }); return 1; }; var pairings: std.ArrayList(tailnet.KeyMachinePairing) = .empty; for (old.agents) |p| if (!std.mem.eql(u8, p.node, joined.node)) try pairings.append(arena, p); try pairings.append(arena, joined); try config.savePrivate(gpa, io, path, tailnet.KeyMachinePairings{ .agents = pairings.items }); try out(io, "joined: during an SSH session from {s} over the tailnet, bwgpg here signs with the agent there\n", .{joined.node}); return 0;}
fn prompt(arena: Allocator, io: Io, reader: *Io.Reader, question: []const u8, current: ?[]const u8) ![]const u8 { var buf: [256]u8 = undefined; var w = Io.File.stderr().writer(io, &buf); if (current) |c| { try w.interface.print("{s} [{s}]: ", .{ question, c }); } else { try w.interface.print("{s}: ", .{question}); } try w.interface.flush(); const line = try readLine(arena, reader); if (line.len == 0) return current orelse error.Required; return line;}
fn readLine(arena: Allocator, reader: *Io.Reader) ![]const u8 { const raw = reader.takeDelimiterInclusive('\n') catch |e| switch (e) { error.EndOfStream => return "", else => return e, }; return arena.dupe(u8, std.mem.trim(u8, raw, " \t\r\n"));}
fn login(gpa: Allocator, io: Io, env: *const Environ.Map, args: []const []const u8) !u8 { var arena_state: std.heap.ArenaAllocator = .init(gpa); defer arena_state.deinit(); const arena = arena_state.allocator();
const path = try config.configPath(gpa, io, env); defer gpa.free(path);
// What is there already is the default for everything. var existing: ?std.json.Parsed(config.Config) = config.load(gpa, io, path) catch null; defer if (existing) |*e| e.deinit(); var cfg: config.Config = if (existing) |e| e.value else .{ .base_url = "", .email = "", .client_id = "", };
var server: ?[]const u8 = null; var email: ?[]const u8 = null; var client_id: ?[]const u8 = null; var secret_from_stdin = false; var i: usize = 0; while (i < args.len) : (i += 1) { const a = args[i]; const next = if (i + 1 < args.len) args[i + 1] else null; if (std.mem.eql(u8, a, "--server")) { server = next; i += 1; } else if (std.mem.eql(u8, a, "--email")) { email = next; i += 1; } else if (std.mem.eql(u8, a, "--client-id")) { client_id = next; i += 1; } else if (std.mem.eql(u8, a, "--client-secret-stdin")) { secret_from_stdin = true; } else { err(io, "login: unknown argument {s}", .{a}); return 2; } }
var in_buf: [1024]u8 = undefined; var stdin = Io.File.stdin().reader(io, &in_buf); const r = &stdin.interface; const or_null = struct { fn f(s: []const u8) ?[]const u8 { return if (s.len == 0) null else s; } }.f;
cfg.base_url = server orelse try prompt(arena, io, r, "Server URL (e.g. https://vault.bitwarden.com)", or_null(cfg.base_url)); cfg.base_url = std.mem.trimEnd(u8, cfg.base_url, "/"); cfg.email = email orelse try prompt(arena, io, r, "Account email", or_null(cfg.email)); cfg.client_id = client_id orelse try prompt(arena, io, r, "API key client_id (user.<uuid>)", or_null(cfg.client_id));
// The secret goes through pinentry, like the password does, so that it // is never echoed; --client-secret-stdin is for scripts. if (secret_from_stdin) { cfg.client_secret = try readLine(arena, r); } else { const program = try platform.findPinentry(arena, io, env, cfg.pinentry) orelse { err(io, "no pinentry found; set BWGPG_PINENTRY, or use --client-secret-stdin", .{}); return 1; }; const secret = pinentry.getPin(arena, io, program, env, .{ .description = "Enter the client_secret of your Bitwarden personal API key (Account settings, Security, Keys).", .prompt = "client_secret:", .tty_name = env.get("GPG_TTY"), .tty_type = env.get("TERM"), }) catch |e| { err(io, "could not read the client_secret: {t}", .{e}); return 1; }; cfg.client_secret = secret; } if (cfg.client_secret == null or cfg.client_secret.?.len == 0) { err(io, "the client_secret is required", .{}); return 1; }
// A secret given here replaces one kept in a file. cfg.client_secret_file = null; if (cfg.device_id == null) cfg.device_id = try config.newUuid(arena, io); if (std.mem.startsWith(u8, cfg.base_url, "http://")) cfg.allow_insecure_http = true;
// Check the key before keeping it. { const e = try bw.api.Endpoints.fromBase(gpa, cfg.base_url); defer e.deinit(gpa); var endpoints = e; if (cfg.identity_url) |u| endpoints.identity = u; if (cfg.api_url) |u| endpoints.api = u; var c = bw.api.Client.init(gpa, io, endpoints); defer c.deinit(); var token = c.token(.{ .client_id = cfg.client_id, .client_secret = cfg.client_secret.?, .device_id = cfg.device_id.?, }) catch |e2| { err(io, "the server refused the API key: {t}", .{e2}); return 1; }; token.deinit(gpa); }
config.save(gpa, io, path, cfg) catch |e| { // A config Home Manager wrote is a link into the read-only store. err(io, "cannot write {s}: {t}; if Home Manager manages it, set programs.bwgpg.settings there instead", .{ path, e }); return 1; }; try out(io, "saved {s}\n", .{path}); try out(io, "now: git config --global gpg.program bwgpg\n", .{});
// An agent running with the old config would keep using it. if (agent.client.call(gpa, io, env, .{ .op = "stop" }, false)) |res| res.deinit() else |_| {} return 0;}
test { std.testing.refAllDecls(openpgp); std.testing.refAllDecls(bw); std.testing.refAllDecls(agent); std.testing.refAllDecls(@This());}