Something went wrong. Try again.
Sign git commits and tags with an OpenPGP key kept in Bitwarden.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The agent: the one process that ever holds the decrypted vault.//!//! It is started on demand by the first command that needs it and then//! lives on, detached, so that the master password is asked for once rather//! than at every commit. What it holds -- the user key, and the parsed//! OpenPGP keys -- lives in `secmem` memory and is wiped when the agent//! locks, which it does on request or after `lock_timeout_secs` without a//! request that used it.//!//! On Linux it can also be run by systemd, socket-activated: the//! `bwgpg-agent.socket` unit owns the socket and starts the agent on the//! first connection, handing it the listening descriptor. The agent then//! neither binds nor detaches, leaves the socket file to systemd when it//! stops, and exits once it locks after going unused, since systemd will//! start it again when it is next wanted.//!//! It also listens on an extra socket, `agent-extra.sock`, meant to be//! forwarded over SSH so that another machine can sign with the keys held//! here. A connection on it may only `describe` and `sign`; the environment//! it sends is ignored, since another machine's display and terminal mean//! nothing here; and each signature is confirmed on this machine unless//! `bwgpg remote allow` has been run for its SSH session. A session is the//! local `ssh` process carrying the forward, which `SO_PEERCRED` names.//!//! The secret keys never leave it. A client asks which key a selector means//! (`describe`), hashes its data itself, and sends only the digest to be//! signed (`sign`).
const std = @import("std");const Allocator = std.mem.Allocator;const Io = std.Io;const Environ = std.process.Environ;const log = std.log.scoped(.agent);
const protocol = @import("protocol.zig");const config_mod = @import("../config.zig");const Config = config_mod.Config;const secmem = @import("../secmem.zig");const platform = @import("../platform.zig");const pinentry = @import("../pinentry.zig");const api = @import("../bw/api.zig");const bw_crypto = @import("../bw/crypto.zig");const json = @import("../bw/json_util.zig");const Vault = @import("../bw/vault.zig").Vault;const sign = @import("../openpgp/sign.zig");const Sessions = @import("sessions.zig").Sessions;
/// Which socket a connection came in on.pub const Kind = enum { /// `agent.sock`, for this machine. main, /// `agent-extra.sock`, for another machine over SSH. remote,};
/// What the agent knows of a connection's other end.const Conn = struct { kind: Kind, /// The peer process: the local `ssh`, for a remote connection. pid: ?i32 = null, start_time: ?u64 = null, command: []const u8 = "?",};
/// Reads a process's start time from `/proc`, for pruning sessions.const ProcProber = struct { io: Io, pub fn startTime(p: ProcProber, pid: i32) ?u64 { return platform.processStartTime(p.io, pid); }};
pub const Agent = struct { gpa: Allocator, io: Io, env: *const Environ.Map, config: *const Config, socket_path: []const u8, extra_socket_path: []const u8, /// Started by systemd on a socket it owns. socket_activated: bool = false, sessions: Sessions = .{},
mutex: Io.Mutex = .init, user_key: ?*bw_crypto.SymmetricKey = null, vault: ?Vault = null, last_used: i64 = 0,
fn now(agent: *Agent) i64 { return Io.Timestamp.now(agent.io, .real).toSeconds(); }
/// Forgets everything, the allowed SSH sessions included. Called with /// the mutex held. fn lock(agent: *Agent) void { agent.sessions.clear(agent.gpa); if (agent.vault) |*v| v.deinit(secmem.allocator); agent.vault = null; if (agent.user_key) |k| { k.wipe(); secmem.allocator.destroy(k); } agent.user_key = null; }
fn endpoints(agent: *Agent) !api.Endpoints { const c = agent.config; if (!c.allow_insecure_http and !std.mem.startsWith(u8, c.base_url, "https://")) { return error.InsecureServer; } var e = try api.Endpoints.fromBase(agent.gpa, c.base_url); if (c.identity_url) |u| { agent.gpa.free(e.identity); e.identity = try agent.gpa.dupe(u8, u); } if (c.api_url) |u| { agent.gpa.free(e.api); e.api = try agent.gpa.dupe(u8, u); } return e; }
/// Fetches the vault and, if not already unlocked, asks for the master /// password to decrypt it. Called with the mutex held. fn syncVault(agent: *Agent, req_env: []const protocol.EnvVar, prompt: bool) !void { const gpa = agent.gpa; const e = try agent.endpoints(); defer e.deinit(gpa); var client = api.Client.init(gpa, agent.io, e); defer client.deinit();
const secret = try config_mod.clientSecret(gpa, agent.io, agent.config); defer { std.crypto.secureZero(u8, secret); gpa.free(secret); } const device_id = try config_mod.deviceId(gpa, agent.io, agent.env, agent.config); defer gpa.free(device_id); var token = try client.token(.{ .client_id = agent.config.client_id, .client_secret = secret, .device_id = device_id, }); defer token.deinit(gpa);
const sync = try client.sync(token.access_token); defer sync.deinit();
if (agent.user_key == null) { if (!prompt) return error.Locked; const protected = token.protected_key orelse json.getString(json.get(sync.value, "profile") orelse .null, "key") orelse return error.UnexpectedResponse; const kdf = token.kdf orelse try client.prelogin(agent.config.email); agent.user_key = try agent.askPassword(req_env, protected, kdf); }
const fresh = try Vault.load(secmem.allocator, sync.value, agent.user_key.?); if (agent.vault) |*old| old.deinit(secmem.allocator); agent.vault = fresh; for (fresh.problems.items) |p| { log.warn("note \"{s}\" looks like a key but cannot be read: {t}", .{ p.name, p.err }); } }
/// The environment pinentry runs in: the agent's, with the requester's /// display and terminal laid over it. The caller deinits it. fn pinentryEnv(agent: *Agent, req_env: []const protocol.EnvVar) !Environ.Map { var env: Environ.Map = .init(agent.gpa); errdefer env.deinit(); for (agent.env.keys(), agent.env.values()) |k, v| try env.put(k, v); // Meant for this process alone; a pinentry that saw them might think // it had been socket-activated too. for ([_][]const u8{ "LISTEN_PID", "LISTEN_FDS", "LISTEN_FDNAMES" }) |name| { _ = env.swapRemove(name); } for (req_env) |v| try env.put(v.name, v.value); return env; }
fn askPassword( agent: *Agent, req_env: []const protocol.EnvVar, protected: []const u8, kdf: bw_crypto.Kdf, ) !*bw_crypto.SymmetricKey { const gpa = agent.gpa; const io = agent.io;
var env = try agent.pinentryEnv(req_env); defer env.deinit();
const program = try agent.pinentryProgram(); defer gpa.free(program);
const description = try std.fmt.allocPrint( gpa, "Enter the master password for {s} on {s} to unlock your OpenPGP signing key.", .{ agent.config.email, agent.config.base_url }, ); defer gpa.free(description);
const key = try secmem.allocator.create(bw_crypto.SymmetricKey); errdefer secmem.allocator.destroy(key);
var error_text: ?[]const u8 = null; for (0..3) |_| { const password = try pinentry.getPin(secmem.allocator, io, program, &env, .{ .description = description, .error_text = error_text, .tty_name = env.get("GPG_TTY"), .tty_type = env.get("TERM"), }); defer secmem.allocator.free(password);
var master = try bw_crypto.masterKey(secmem.allocator, io, password, agent.config.email, kdf); defer std.crypto.secureZero(u8, &master); var stretched = bw_crypto.stretch(master); defer stretched.wipe();
key.* = bw_crypto.decryptKey(secmem.allocator, &stretched, protected) catch |err| switch (err) { error.MacMismatch => { error_text = "Wrong master password. Try again."; continue; }, else => return err, }; return key; } return error.WrongPassword; }
fn pinentryProgram(agent: *Agent) ![]u8 { return try platform.findPinentry(agent.gpa, agent.io, agent.env, agent.config.pinentry) orelse error.NoPinentry; }
fn ensureUnlocked(agent: *Agent, req: protocol.Request) !*Vault { if (agent.vault == null) try agent.syncVault(req.env, true); agent.last_used = agent.now(); return &agent.vault.?; }
fn keyList(agent: *Agent, arena: Allocator) ![]protocol.KeyInfo { const v = agent.vault orelse return &.{}; var list: std.ArrayList(protocol.KeyInfo) = .empty; for (v.items.items) |item| { const fpr = item.ring.primary().fingerprintHex(); try list.append(arena, .{ .fingerprint = try arena.dupe(u8, &fpr), .item = try arena.dupe(u8, item.name), .user_ids = try arena.dupe([]const u8, item.ring.user_ids), }); } return list.toOwnedSlice(arena); }
fn problemList(agent: *Agent, arena: Allocator) ![]const []const u8 { const v = agent.vault orelse return &.{}; var list: std.ArrayList([]const u8) = .empty; for (v.problems.items) |p| { try list.append(arena, try std.fmt.allocPrint(arena, "{s}: {t}", .{ p.name, p.err })); } return list.toOwnedSlice(arena); }
fn sessionList(agent: *Agent, arena: Allocator) ![]protocol.SessionInfo { agent.sessions.prune(agent.gpa, ProcProber{ .io = agent.io }); const list = try arena.alloc(protocol.SessionInfo, agent.sessions.list.items.len); for (agent.sessions.list.items, list) |session, *info| { info.* = .{ .pid = session.pid, .command = try arena.dupe(u8, session.command), .allowed = session.allowed, }; } return list; }
/// Asks on this machine whether a signature requested over SSH may be /// made. Called with the mutex held, so other requests wait for the /// answer, as they do for a password. fn confirmRemote(agent: *Agent, conn: Conn, found: Vault.Selected, summary: ?[]const u8) !bool { const gpa = agent.gpa; var env = try agent.pinentryEnv(&.{}); defer env.deinit(); const program = try agent.pinentryProgram(); defer gpa.free(program);
const uid = if (found.item.ring.user_ids.len > 0) found.item.ring.user_ids[0] else found.item.name; const fpr = found.key.fingerprintHex(); const description = try std.fmt.allocPrint(gpa, \\A signature was requested over SSH ({s}). \\ \\Key: {s} \\{s} \\ \\It says it is signing: {s} \\ \\To stop asking for this SSH session, run `bwgpg remote allow` on this machine. , .{ conn.command, uid, &fpr, summary orelse "(it did not say)" }); defer gpa.free(description);
return pinentry.confirm(gpa, agent.io, program, &env, .{ .title = "bwgpg: sign for another machine?", .description = description, }); }
/// Answers one request. Called with the mutex held. fn dispatch(agent: *Agent, arena: Allocator, conn: Conn, req_in: protocol.Request) !protocol.Response { const eql = std.mem.eql; var req = req_in; const op = req.op;
if (conn.kind == .remote) { // Another machine may sign and ask which key a selector means, // and nothing else; and its display and terminal mean nothing // here, so any prompt goes to this machine's own. if (!eql(u8, op, "ping") and !eql(u8, op, "describe") and !eql(u8, op, "sign")) { return error.NotPermittedRemotely; } req.env = &.{}; if (conn.pid) |pid| { agent.sessions.prune(agent.gpa, ProcProber{ .io = agent.io }); _ = try agent.sessions.touch(agent.gpa, pid, conn.start_time orelse 0, conn.command); } }
if (eql(u8, op, "ping")) return .{ .ok = true };
if (eql(u8, op, "remote_list")) return .{ .ok = true, .sessions = try agent.sessionList(arena) }; if (eql(u8, op, "remote_allow") or eql(u8, op, "remote_revoke")) { agent.sessions.prune(agent.gpa, ProcProber{ .io = agent.io }); _ = agent.sessions.setAllowed(req.pid, eql(u8, op, "remote_allow")); return .{ .ok = true, .sessions = try agent.sessionList(arena) }; }
if (eql(u8, op, "status")) return .{ .ok = true, .unlocked = agent.vault != null, .keys = try agent.keyList(arena), .problems = try agent.problemList(arena), };
if (eql(u8, op, "lock")) { agent.lock(); return .{ .ok = true }; }
if (eql(u8, op, "unlock") or eql(u8, op, "sync")) { if (eql(u8, op, "unlock") and agent.vault != null) { // Already open; nothing to ask for. } else { try agent.syncVault(req.env, true); } agent.last_used = agent.now(); return .{ .ok = true, .unlocked = true, .keys = try agent.keyList(arena), .problems = try agent.problemList(arena), }; }
if (eql(u8, op, "describe")) { const vault = try agent.ensureUnlocked(req); const selector = req.key orelse agent.config.default_key; const found = try vault.select(selector, config_mod.itemFor(agent.config, selector)); const fpr = found.key.fingerprintHex(); return .{ .ok = true, .fingerprint = try arena.dupe(u8, &fpr), .algorithm = @intFromEnum(found.key.algorithm), }; }
if (eql(u8, op, "sign")) { const vault = try agent.ensureUnlocked(req); var fpr: [20]u8 = undefined; const fpr_hex = req.fingerprint orelse return error.BadRequest; if (fpr_hex.len != 40) return error.BadRequest; _ = std.fmt.hexToBytes(&fpr, fpr_hex) catch return error.BadRequest; const found = vault.find(fpr) orelse return error.NoSigningKey; const key = found.key;
var digest: [sign.digest_length]u8 = undefined; const digest_b64 = req.digest orelse return error.BadRequest; const decoder = std.base64.standard.Decoder; if ((decoder.calcSizeForSlice(digest_b64) catch return error.BadRequest) != digest.len) { return error.BadRequest; } decoder.decode(&digest, digest_b64) catch return error.BadRequest;
if (conn.kind == .remote and agent.config.remote_confirm) { const allowed = if (conn.pid) |pid| for (agent.sessions.list.items) |session| { if (session.pid == pid and session.start_time == conn.start_time) break session.allowed; } else false else false; if (!allowed and !try agent.confirmRemote(conn, found, req.summary)) { log.info("refused a signature for {s}", .{conn.command}); return error.Denied; } }
var material_buf: [sign.max_material]u8 = undefined; const material = try sign.signDigest(key, digest, &material_buf); const encoded = try arena.alloc(u8, std.base64.standard.Encoder.calcSize(material.len)); return .{ .ok = true, .material = std.base64.standard.Encoder.encode(encoded, material) }; }
if (eql(u8, op, "stop")) return .{ .ok = true };
return error.BadRequest; }
fn handle(agent: *Agent, stream: Io.net.Stream, kind: Kind) void { const io = agent.io; defer stream.close(io);
if (!platform.peerIsSelf(stream)) { log.warn("refused a connection from another user", .{}); return; }
var arena_state: std.heap.ArenaAllocator = .init(agent.gpa); defer arena_state.deinit(); const arena = arena_state.allocator();
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);
const parsed = protocol.receive(protocol.Request, arena, &reader.interface) catch |err| { log.warn("unreadable request: {t}", .{err}); return; }; const req = parsed.value;
var conn: Conn = .{ .kind = kind }; if (kind == .remote) { if (platform.peerOf(stream)) |peer| { conn.pid = peer.pid; conn.start_time = platform.processStartTime(io, peer.pid); conn.command = platform.processCommand(arena, io, peer.pid) catch "?"; } }
const response = blk: { agent.mutex.lockUncancelable(io); defer agent.mutex.unlock(io); break :blk agent.dispatch(arena, conn, req) catch |err| errorResponse(err); };
protocol.send(arena, &writer.interface, response) catch |err| { log.warn("could not answer: {t}", .{err}); };
if (kind == .main and std.mem.eql(u8, req.op, "stop")) agent.shutdown(); }
fn shutdown(agent: *Agent) noreturn { agent.mutex.lockUncancelable(agent.io); agent.lock(); // systemd's socket stays, so that the next connection starts the // agent again. if (!agent.socket_activated) { Io.Dir.cwd().deleteFile(agent.io, agent.socket_path) catch {}; Io.Dir.cwd().deleteFile(agent.io, agent.extra_socket_path) catch {}; } log.info("stopped", .{}); std.process.exit(0); }
fn watchdog(agent: *Agent) void { const io = agent.io; const timeout: i64 = agent.config.lock_timeout_secs; while (true) { io.sleep(.fromSeconds(10), .awake) catch return; agent.mutex.lockUncancelable(io); defer agent.mutex.unlock(io); if (agent.vault != null and agent.now() - agent.last_used >= timeout) { agent.lock(); log.info("locked after {d} seconds unused", .{timeout}); // Locked, it holds nothing worth keeping a process for, and // systemd starts another on the next connection. if (agent.socket_activated) { log.info("exiting until the socket is next used", .{}); std.process.exit(0); } } } }};
fn errorResponse(err: anyerror) protocol.Response { const code: []const u8, const message: []const u8 = switch (err) { error.Cancelled => .{ "cancelled", "The password prompt was cancelled." }, error.WrongPassword => .{ "wrong_password", "The master password was wrong three times." }, error.NoPinentry => .{ "no_pinentry", "The agent found no pinentry on its PATH; set \"pinentry\" in the config, or BWGPG_PINENTRY in the agent's environment." }, error.BadCredentials => .{ "bad_credentials", "The server refused the API key; run `bwgpg login` again." }, error.InsecureServer => .{ "insecure_server", "The server URL is not https." }, error.NoClientSecret => .{ "no_client_secret", "The config has no client_secret, or client_secret_file cannot be read." }, error.InsecurePermissions => .{ "insecure_permissions", "The client_secret_file is readable by others; chmod 600 it." }, error.NoSigningKey => .{ "no_key", "No key in the vault matches, or none that matches can sign." }, error.AmbiguousKey => .{ "ambiguous", "The vault holds more than one key; say which with -u or default_key." }, error.Locked => .{ "locked", "The agent is locked." }, error.BadRequest => .{ "bad_request", "The request was not understood." }, error.NotPermittedRemotely => .{ "not_permitted_remotely", "The agent does not do that for another machine over SSH." }, error.Denied => .{ "denied", "The signature was refused on the machine holding the key." }, error.UnsupportedEncStringType => .{ "unsupported_encryption", "The account uses an encryption type bwgpg does not support." }, error.ConnectionRefused, error.NetworkUnreachable, error.HostUnreachable, error.UnknownHostName, error.NameServerFailure, error.TemporaryNameServerFailure, error.ConnectionTimedOut => .{ "unreachable", "The Bitwarden server could not be reached." }, else => .{ "failed", @errorName(err) }, }; return .{ .ok = false, .@"error" = code, .message = message };}
/// Runs the agent until it is told to stop. Returns only on failure to/// start./// Accepts connections on one socket, forever, each on a thread of its own:/// a client which connects and says nothing holds up only itself. Requests/// still take turns, and one waiting on a pinentry holds the others until it/// is answered.fn acceptLoop(agent: *Agent, server: *Io.net.Server, kind: Kind) void { const io = agent.io; while (true) { const stream = server.accept(io) catch |err| switch (err) { error.ConnectionAborted, error.WouldBlock, error.ProtocolFailure => continue, else => { log.err("cannot accept on the {t} socket: {t}", .{ kind, err }); std.process.exit(1); }, }; const thread = std.Thread.spawn(.{}, Agent.handle, .{ agent, stream, kind }) catch { agent.handle(stream, kind); continue; }; thread.detach(); }}
/// What `UnixAddress.listen` would have returned, for a socket that systemd/// bound instead.fn serverFromFd(fd: Io.net.Socket.Handle) Io.net.Server { return .{ .socket = .{ .handle = fd, .address = .{ .ip4 = .loopback(0) } }, .options = if (Io.net.Server.AcceptOptions != void) .{ .mode = .stream, .protocol = null } else {}, };}
fn bindFresh(io: Io, path: []const u8) !Io.net.Server { const address = try Io.net.UnixAddress.init(path); Io.Dir.cwd().deleteFile(io, path) catch {}; return address.listen(io, .{});}
/// Runs the agent until it is told to stop. Returns only on failure to/// start.pub fn run(gpa: Allocator, io: Io, env: *const Environ.Map, config: *const Config, foreground: bool) !void { secmem.hardenProcess();
const dir = try config_mod.runtimeDir(gpa, io, env); defer gpa.free(dir); const socket_path = try std.fs.path.join(gpa, &.{ dir, "agent.sock" }); defer gpa.free(socket_path); const extra_socket_path = try std.fs.path.join(gpa, &.{ dir, "agent-extra.sock" }); defer gpa.free(extra_socket_path);
var main_server: Io.net.Server = undefined; var extra_server: ?Io.net.Server = null;
const fds = try platform.systemdListenFds(env); // systemd hands sockets only on Linux; elsewhere this is never taken, // and is not compiled. if (platform.is_linux and fds.any()) { main_server = serverFromFd(fds.main orelse return error.NoMainSocket); if (fds.extra) |fd| extra_server = serverFromFd(fd); log.info("listening on socket from systemd ({s}{s})", .{ socket_path, if (fds.extra != null) ", and the extra socket for SSH" else "", }); } else { if (!foreground) platform.detach(); try config_mod.makePrivateDir(io, dir); // Another agent already answering is not an error: there should be // one, and there is. if ((try Io.net.UnixAddress.init(socket_path)).connect(io)) |stream| { stream.close(io); log.info("an agent is already running at {s}", .{socket_path}); return; } else |_| {} main_server = try bindFresh(io, socket_path); // The extra socket is for forwarding over SSH, which bwgpg supports // from Linux. if (platform.is_windows) { log.info("listening at {s}", .{socket_path}); } else if (bindFresh(io, extra_socket_path)) |extra| { extra_server = extra; log.info("listening at {s} and {s}", .{ socket_path, extra_socket_path }); } else |err| { // Signing over SSH is an extra; the agent works without it. log.warn("cannot listen at {s} ({t}); signing over SSH is not available", .{ extra_socket_path, err }); log.info("listening at {s}", .{socket_path}); } } defer main_server.deinit(io); defer if (extra_server) |*e| e.deinit(io);
var agent: Agent = .{ .gpa = gpa, .io = io, .env = env, .config = config, .socket_path = socket_path, .extra_socket_path = extra_socket_path, .socket_activated = fds.any(), };
const dog = try std.Thread.spawn(.{}, Agent.watchdog, .{&agent}); dog.detach();
if (extra_server) |*e| { const t = try std.Thread.spawn(.{}, acceptLoop, .{ &agent, e, Kind.remote }); t.detach(); } acceptLoop(&agent, &main_server, .main);}