Something went wrong. Try again.
Sign git commits and tags with an OpenPGP key kept in Bitwarden.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Finding the OpenPGP keys in a synced vault.//!//! A key is kept as a Secure Note whose notes hold the output of `gpg//! --armor --export-secret-keys`. Rather than being told which notes those//! are, bwgpg looks: every personal Secure Note is decrypted, and those whose//! notes contain an armored private key block are parsed and kept. A note//! that fails to parse is reported by name rather than stopping the others.//!//! Only personal Secure Notes are read. One belonging to an organization is//! encrypted under the organization's key, which is wrapped with RSA-OAEP,//! and bwgpg does not do RSA decryption.
const std = @import("std");const Allocator = std.mem.Allocator;const Value = std.json.Value;const testing = std.testing;
const json = @import("json_util.zig");const crypto = @import("crypto.zig");const armor = @import("../openpgp/armor.zig");const key_mod = @import("../openpgp/key.zig");
const armor_marker = "-----BEGIN PGP PRIVATE KEY BLOCK-----";
/// Cipher type 2 is a Secure Note.const cipher_type_secure_note = 2;
/// A Secure Note holding a key.pub const SecureNote = struct { id: []u8, name: []u8, key: key_mod.Key,};
/// A Secure Note that looked like it held a key and could not be read as one.pub const UnreadableNote = struct { name: []u8, err: anyerror,};
/// The keys found in the vault, which is what the agent holds while it is/// unlocked.pub const Keys = struct { notes: std.ArrayList(SecureNote) = .empty, unreadable: std.ArrayList(UnreadableNote) = .empty,
/// Decrypts every personal Secure Note in `sync` with `user_key` and /// keeps the ones holding a key. /// /// `secure` holds everything that is or was plaintext; `gpa` is for the /// rest. pub fn load(secure: Allocator, sync: Value, user_key: *const crypto.SymmetricKey) Allocator.Error!Keys { var keys: Keys = .{}; errdefer keys.deinit(secure);
const ciphers = json.getArray(sync, "ciphers") orelse return keys; for (ciphers) |cipher| { if (json.getInt(cipher, "type") != cipher_type_secure_note) continue; if (json.get(cipher, "organizationId") != null) continue; if (json.get(cipher, "deletedDate") != null) continue; const notes_enc = json.getString(cipher, "notes") orelse continue;
keys.loadOne(secure, cipher, notes_enc, user_key) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => {}, }; } return keys; }
fn loadOne( keys: *Keys, secure: Allocator, cipher: Value, notes_enc: []const u8, user_key: *const crypto.SymmetricKey, ) !void { // A Secure Note may have an item key of its own, wrapped with the // user key. var item_key: crypto.SymmetricKey = if (json.getString(cipher, "key")) |k| try crypto.decryptKey(secure, user_key, k) else user_key.*; defer item_key.wipe();
const name = if (json.getString(cipher, "name")) |n| try crypto.decrypt(secure, &item_key, n) else try secure.dupe(u8, "(unnamed)"); errdefer secure.free(name);
const notes = try crypto.decrypt(secure, &item_key, notes_enc); defer { std.crypto.secureZero(u8, notes); secure.free(notes); } if (std.mem.find(u8, notes, armor_marker) == null) { secure.free(name); return; }
var key = blk: { const block = armor.decode(secure, notes) catch |err| break :blk err; break :blk key_mod.Key.parse(secure, block.data); } catch |err| { if (err == error.OutOfMemory) return error.OutOfMemory; try keys.unreadable.append(secure, .{ .name = name, .err = err }); return; }; errdefer key.deinit(secure);
const id = try secure.dupe(u8, json.getString(cipher, "id") orelse ""); errdefer secure.free(id); try keys.notes.append(secure, .{ .id = id, .name = name, .key = key }); }
pub fn deinit(keys: *Keys, secure: Allocator) void { for (keys.notes.items) |*note| { note.key.deinit(secure); secure.free(note.id); secure.free(note.name); } keys.notes.deinit(secure); for (keys.unreadable.items) |u| secure.free(u.name); keys.unreadable.deinit(secure); keys.* = undefined; }
pub const Selected = struct { note: *const SecureNote, /// The signing key: the primary key or one of its subkeys. key: *const key_mod.ComponentKey, };
pub const SelectError = error{ /// No key matches. NoSigningKey, /// No key selector was given and there is more than one key. AmbiguousKey, };
/// The signing key for `selector`, as `gpg -u` would choose it. /// /// `only_note` restricts the search to one Secure Note, by name or ID; /// that is how the config's `keys` mapping pins a key selector to a note. /// With no key selector at all, holding exactly one key means using it. pub fn select(keys: *const Keys, selector: ?[]const u8, only_note: ?[]const u8) SelectError!Selected { var candidates: usize = 0; var sole: ?*const SecureNote = null; for (keys.notes.items) |*note| { if (only_note) |only| { if (!std.mem.eql(u8, note.name, only) and !std.mem.eql(u8, note.id, only)) continue; } candidates += 1; sole = note; const sel = selector orelse continue; const key = note.key.signingKey(sel) catch continue; return .{ .note = note, .key = key }; } if (selector == null) { if (candidates == 1) { const note = sole.?; const key = note.key.signingKey(¬e.key.primary().fingerprintHex()) catch return error.NoSigningKey; return .{ .note = note, .key = key }; } return if (candidates == 0) error.NoSigningKey else error.AmbiguousKey; } return error.NoSigningKey; }
/// The component key with this exact fingerprint, primary or subkey. pub fn byFingerprint(keys: *const Keys, fingerprint: [20]u8) ?*const key_mod.ComponentKey { return (keys.find(fingerprint) orelse return null).key; }
/// The component key with this exact fingerprint, and the Secure Note it /// came from. pub fn find(keys: *const Keys, fingerprint: [20]u8) ?Selected { for (keys.notes.items) |*note| { for (note.key.components) |*component| { if (std.mem.eql(u8, &component.fingerprint, &fingerprint)) return .{ .note = note, .key = component }; } } return null; }};
/// Builds a sync response holding the given notes, encrypted as the server/// would hold them. For the tests here and for the Vaultwarden fixture.pub fn encryptNoteForTest( gpa: Allocator, user_key: *const crypto.SymmetricKey, name: []const u8, notes: []const u8,) ![2][]u8 { return .{ try crypto.encrypt(gpa, user_key, @splat(1), name), try crypto.encrypt(gpa, user_key, @splat(2), notes), };}
test "keys are found among other notes, and an unreadable one is reported" { const gpa = testing.allocator; const testing_keys = @import("../openpgp/testing_keys.zig"); const user_key: crypto.SymmetricKey = .{ .enc = @splat(5), .mac = @splat(6) };
// One note holding a key, one ordinary note, one key with a corrupted // checksum line, one belonging to an organization, and one in the trash. const good = try encryptNoteForTest(gpa, &user_key, "signing key", testing_keys.ed25519_legacy.armored); const plain = try encryptNoteForTest(gpa, &user_key, "wifi", "hunter2"); var broken_text = try gpa.dupe(u8, testing_keys.rsa2048.armored); defer gpa.free(broken_text); const eq = std.mem.findScalarLast(u8, broken_text, '=').?; broken_text[eq + 1] = if (broken_text[eq + 1] == 'A') 'B' else 'A'; const broken = try encryptNoteForTest(gpa, &user_key, "broken", broken_text); var all: [3][2][]u8 = .{ good, plain, broken }; defer for (&all) |*pair| { gpa.free(pair[0]); gpa.free(pair[1]); };
const text = try std.fmt.allocPrint(gpa, \\{{"ciphers":[ \\ {{"id":"1","type":2,"organizationId":null,"deletedDate":null,"name":"{s}","notes":"{s}"}}, \\ {{"id":"2","type":2,"name":"{s}","notes":"{s}"}}, \\ {{"id":"3","type":2,"name":"{s}","notes":"{s}"}}, \\ {{"id":"4","type":2,"organizationId":"org","name":"{s}","notes":"{s}"}}, \\ {{"id":"5","type":2,"deletedDate":"2026-01-01","name":"{s}","notes":"{s}"}}, \\ {{"id":"6","type":1,"name":"{s}","notes":"{s}"}} \\]}} , .{ good[0], good[1], plain[0], plain[1], broken[0], broken[1], good[0], good[1], good[0], good[1], good[0], good[1] }); defer gpa.free(text); const parsed = try std.json.parseFromSlice(Value, gpa, text, .{}); defer parsed.deinit();
var keys = try Keys.load(gpa, parsed.value, &user_key); defer keys.deinit(gpa);
try testing.expectEqual(@as(usize, 1), keys.notes.items.len); try testing.expectEqualStrings("signing key", keys.notes.items[0].name); try testing.expectEqual(@as(usize, 1), keys.unreadable.items.len); try testing.expectEqualStrings("broken", keys.unreadable.items[0].name);
const fpr = testing_keys.ed25519_legacy.fingerprint; const sel = try keys.select(fpr, null); try testing.expectEqualStrings(fpr, &sel.key.fingerprintHex()); _ = try keys.select(null, null); _ = try keys.select("ed@example.org", "signing key"); try testing.expectError(error.NoSigningKey, keys.select("ed@example.org", "wifi")); try testing.expectError(error.NoSigningKey, keys.select("nobody@example.org", null)); try testing.expect(keys.byFingerprint(sel.key.fingerprint) != null);}