Something went wrong. Try again.
Sign git commits and tags with an OpenPGP key kept in Bitwarden.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376// 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//! 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 forget everything//! 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 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) \\ unlock ask for the master password now \\ status whether the agent is unlocked, and the keys it found \\ sync fetch the vault again \\ lock forget the vault and 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 signing through the agent's extra/// socket, and whether each is still asked to confirm.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"; 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] or revoke [PID]", .{}); 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;}
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.…)", 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());}