// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Reading an OpenPGP transferable secret key, RFC 9580 sections 5.5 and 10.2. //! //! What `gpg --export-secret-keys` writes: a primary secret key packet, user //! IDs, secret subkeys, and the signatures binding them together. This reads //! version 4 keys whose secret material is stored unprotected (S2K usage 0), //! which is how a key with no passphrase is exported, for three algorithms: //! //! - **EdDSALegacy** (algorithm 22) with the Ed25519 curve, which is what //! GnuPG 2.2 through 2.4 generate for `ed25519`. //! - **Ed25519** (algorithm 27), RFC 9580's native encoding of the same thing. //! - **RSA** (algorithms 1 and 3), up to the 4096-bit ceiling of //! `std_crypto_ext.rsa`. //! //! Signature packets are read only for their key flags, which is how the //! signing key is chosen among the primary and its subkeys. They are not //! verified: the key came out of the user's own vault, and the question being //! answered is "which of these keys signs", not "should these be trusted". const std = @import("std"); const Allocator = std.mem.Allocator; const testing = std.testing; const Sha1 = std.crypto.hash.Sha1; const Ed25519 = std.crypto.sign.Ed25519; const rsa = @import("std_crypto_ext").rsa; const packet = @import("packet.zig"); pub const Error = packet.Error || error{ /// A key packet whose version is not 4. Version 6 keys (RFC 9580) and /// GnuPG's version 5 keys are not supported yet. UnsupportedKeyVersion, /// A public key algorithm other than RSA, EdDSALegacy or Ed25519, or /// EdDSALegacy over a curve other than Ed25519. UnsupportedAlgorithm, /// The secret material is encrypted with a passphrase. Export the key /// without one: Bitwarden's encryption is what protects it. ProtectedKey, /// The two-octet checksum over the secret material does not match. ChecksumMismatch, /// The secret and public halves of the key do not belong together. KeyMismatch, /// There is no secret key packet in the data. NoSecretKey, /// No component key matches the key selector, or none that matches can /// sign. NoSigningKey, }; /// Public key algorithm identifiers, RFC 9580 section 9.1. pub const Algorithm = enum(u8) { rsa = 1, rsa_sign = 3, eddsa_legacy = 22, ed25519 = 27, _, }; /// The OID of Ed25519 in EdDSALegacy keys, 1.3.6.1.4.1.11591.15.1. const oid_ed25519_legacy = [_]u8{ 0x2b, 0x06, 0x01, 0x04, 0x01, 0xda, 0x47, 0x0f, 0x01 }; pub const Secret = union(enum) { ed25519: struct { seed: [32]u8, public: [32]u8, }, /// Big-endian values pointing into `Key.bytes`. rsa: struct { n: []const u8, e: []const u8, d: []const u8, }, }; /// A primary key or subkey: RFC 9580's "component key". pub const ComponentKey = struct { algorithm: Algorithm, created: u32, fingerprint: [20]u8, secret: Secret, subkey: bool, /// From the key flags of the newest self-signature that carries them; /// null when no signature said. can_sign: ?bool = null, pub fn keyId(key: *const ComponentKey) [8]u8 { return key.fingerprint[12..20].*; } /// The fingerprint in upper-case hex, as GnuPG prints it. pub fn fingerprintHex(key: *const ComponentKey) [40]u8 { return std.fmt.bytesToHex(key.fingerprint, .upper); } }; /// Parses a key selector the way GnuPG takes `-u`: a fingerprint or key ID in /// hex with an optional `0x` and an optional trailing `!`, or otherwise text to /// find in a user ID. A full fingerprint may be split by spaces, as `gpg -K` /// prints it. Returns the hex upper-cased into `buf`, or null when it is not /// hex. fn selectorHex(buf: *[40]u8, selector: []const u8) ?[]const u8 { var s = std.mem.trim(u8, selector, " \t"); if (std.mem.endsWith(u8, s, "!")) s = s[0 .. s.len - 1]; if (std.mem.startsWith(u8, s, "0x") or std.mem.startsWith(u8, s, "0X")) s = s[2..]; var n: usize = 0; var spaced = false; for (s) |c| { if (c == ' ') { spaced = true; continue; } if (!std.ascii.isHex(c) or n == buf.len) return null; buf[n] = std.ascii.toUpper(c); n += 1; } // As GnuPG has it, only a whole fingerprint may have spaces in it. if (spaced and n != 40) return null; if (n != 8 and n != 16 and n != 40) return null; return buf[0..n]; } /// A transferable secret key: its component keys, the primary key first and /// then its subkeys, and its user IDs. pub const Key = struct { /// The binary the component keys were parsed from. Owned, and wiped by /// `deinit`, since RSA secrets point into it. bytes: []u8, components: []ComponentKey, user_ids: [][]const u8, /// Parses `bytes`, taking ownership of it; it must have come from `gpa`. pub fn parse(gpa: Allocator, bytes: []u8) (Error || Allocator.Error)!Key { errdefer { std.crypto.secureZero(u8, bytes); gpa.free(bytes); } var components: std.ArrayList(ComponentKey) = .empty; errdefer { std.crypto.secureZero(u8, std.mem.sliceAsBytes(components.items)); components.deinit(gpa); } var user_ids: std.ArrayList([]const u8) = .empty; errdefer user_ids.deinit(gpa); // The component key the signatures now being read belong to, if it is // one of ours; signatures after a public-only packet are skipped. var current: ?usize = null; var newest_flags_time: u32 = 0; var it: packet.Iterator = .{ .bytes = bytes }; while (try it.next()) |p| switch (p.tag) { .secret_key, .secret_subkey => { const subkey = p.tag == .secret_subkey; if (!subkey and components.items.len > 0) break; // a second key: stop at the first if (subkey and components.items.len == 0) return error.NoSecretKey; const component = parseSecretKey(p.body, subkey) catch |err| switch (err) { // A subkey bwgpg cannot sign with -- an encryption // subkey on an algorithm it does not implement, or one // whose secret is protected or held on a card -- is // passed over, with its binding signature. Only the // primary key has to be readable. error.UnsupportedAlgorithm, error.UnsupportedKeyVersion, error.ProtectedKey, => if (subkey) { current = null; continue; } else return err, else => return err, }; try components.append(gpa, component); current = components.items.len - 1; newest_flags_time = 0; }, .public_key, .public_subkey => { if (p.tag == .public_key and components.items.len > 0) break; current = null; }, .user_id => try user_ids.append(gpa, p.body), .signature => if (current) |i| { const flags = readKeyFlags(p.body) catch continue orelse continue; if (flags.created >= newest_flags_time) { newest_flags_time = flags.created; components.items[i].can_sign = flags.sign; } }, else => {}, }; if (components.items.len == 0) return error.NoSecretKey; return .{ .bytes = bytes, .components = try components.toOwnedSlice(gpa), .user_ids = try user_ids.toOwnedSlice(gpa), }; } pub fn deinit(key: *Key, gpa: Allocator) void { std.crypto.secureZero(u8, std.mem.sliceAsBytes(key.components)); gpa.free(key.components); gpa.free(key.user_ids); std.crypto.secureZero(u8, key.bytes); gpa.free(key.bytes); key.* = undefined; } pub fn primary(key: *const Key) *const ComponentKey { return &key.components[0]; } /// Whether `selector` names this key at all: by the fingerprint or key ID /// of any of its component keys, or as text in one of its user IDs. pub fn matches(key: *const Key, selector: []const u8) bool { return key.find(selector) != .none; } const Found = union(enum) { none, primary, subkey: usize }; fn find(key: *const Key, selector: []const u8) Found { var buf: [40]u8 = undefined; if (selectorHex(&buf, selector)) |hex| { for (key.components, 0..) |*component, i| { const fpr = component.fingerprintHex(); if (std.mem.endsWith(u8, &fpr, hex)) { return if (i == 0) .primary else .{ .subkey = i }; } } } const text = std.mem.trim(u8, selector, " \t<>"); if (text.len == 0) return .none; for (key.user_ids) |uid| { if (std.ascii.findIgnoreCase(uid, text) != null) return .primary; } return .none; } /// The signing key GnuPG would choose for `-u selector`. A key selector /// naming a subkey directly gets that subkey. One naming the primary key, /// or a user ID, gets the newest subkey whose flags allow signing, and /// failing that the primary key unless its flags say it cannot sign. pub fn signingKey(key: *const Key, selector: []const u8) Error!*const ComponentKey { switch (key.find(selector)) { .none => return error.NoSigningKey, .subkey => |i| { const component = &key.components[i]; if (component.can_sign == false) return error.NoSigningKey; return component; }, .primary => { var best: ?*const ComponentKey = null; for (key.components[1..]) |*component| { if (component.can_sign != true) continue; if (best == null or component.created >= best.?.created) best = component; } if (best) |component| return component; if (key.components[0].can_sign == false) return error.NoSigningKey; return &key.components[0]; }, } } }; fn parseSecretKey(body: []const u8, subkey: bool) Error!ComponentKey { var r: packet.Reader = .{ .bytes = body }; const version = try r.takeByte(); if (version != 4) return error.UnsupportedKeyVersion; const created = try r.takeInt(u32); const algorithm: Algorithm = @fromBackingInt(@intCast(try r.takeByte())); var ed_public: [32]u8 = undefined; var rsa_n: []const u8 = undefined; var rsa_e: []const u8 = undefined; switch (algorithm) { .rsa, .rsa_sign => { rsa_n = try r.takeMpi(); rsa_e = try r.takeMpi(); }, .eddsa_legacy => { const oid_len = try r.takeByte(); const oid = try r.take(oid_len); if (!std.mem.eql(u8, oid, &oid_ed25519_legacy)) return error.UnsupportedAlgorithm; // The point in the "native" compressed form: 0x40 then 32 octets. const point = try r.takeMpi(); if (point.len != 33 or point[0] != 0x40) return error.UnsupportedAlgorithm; ed_public = point[1..33].*; }, .ed25519 => ed_public = (try r.take(32))[0..32].*, else => return error.UnsupportedAlgorithm, } const public_len = r.index; var fingerprint: [20]u8 = undefined; var sha1 = Sha1.init(.{}); sha1.update(&.{0x99}); var len_bytes: [2]u8 = undefined; std.mem.writeInt(u16, &len_bytes, @intCast(public_len), .big); sha1.update(&len_bytes); sha1.update(body[0..public_len]); sha1.final(&fingerprint); if (try r.takeByte() != 0) return error.ProtectedKey; const secret_start = r.index; var secret: Secret = undefined; switch (algorithm) { .rsa, .rsa_sign => { const d = try r.takeMpi(); _ = try r.takeMpi(); // p _ = try r.takeMpi(); // q _ = try r.takeMpi(); // u secret = .{ .rsa = .{ .n = rsa_n, .e = rsa_e, .d = d } }; // Constructing the key checks that d < n and that e is usable, // which is better found out now than at the first signature. _ = rsa.SecretKey.fromComponents(rsa_n, rsa_e, d) catch return error.KeyMismatch; }, .eddsa_legacy => { // The seed as an MPI, so possibly missing its leading zeros. const value = try r.takeMpi(); if (value.len > 32) return error.KeyMismatch; var seed: [32]u8 = @splat(0); @memcpy(seed[32 - value.len ..], value); secret = .{ .ed25519 = .{ .seed = seed, .public = ed_public } }; }, .ed25519 => secret = .{ .ed25519 = .{ .seed = (try r.take(32))[0..32].*, .public = ed_public, } }, else => unreachable, } var sum: u16 = 0; for (body[secret_start..r.index]) |b| sum +%= b; if (try r.takeInt(u16) != sum) return error.ChecksumMismatch; if (secret == .ed25519) { const pair = Ed25519.KeyPair.generateDeterministic(secret.ed25519.seed) catch return error.KeyMismatch; if (!std.mem.eql(u8, &pair.public_key.toBytes(), &secret.ed25519.public)) { return error.KeyMismatch; } } return .{ .algorithm = algorithm, .created = created, .fingerprint = fingerprint, .secret = secret, .subkey = subkey, }; } const KeyFlags = struct { created: u32, sign: bool }; /// The key flags (subpacket 27) and creation time (subpacket 2) from the /// hashed area of a version 4 self-signature or subkey binding signature, or /// null when it is some other kind of signature or carries no flags. fn readKeyFlags(body: []const u8) packet.Error!?KeyFlags { var r: packet.Reader = .{ .bytes = body }; if (try r.takeByte() != 4) return null; const sig_type = try r.takeByte(); const self_sig = switch (sig_type) { 0x10...0x13, 0x18, 0x1f => true, else => false, }; if (!self_sig) return null; _ = try r.take(2); // public key and hash algorithms const hashed_len = try r.takeInt(u16); var sub: packet.Reader = .{ .bytes = try r.take(hashed_len) }; var created: u32 = 0; var sign: ?bool = null; while (!sub.atEnd()) { const first = try sub.takeByte(); const len: usize = if (first < 192) first else if (first < 255) ((@as(usize, first) - 192) << 8) + try sub.takeByte() + 192 else try sub.takeInt(u32); if (len == 0) return error.MalformedPacket; const data = try sub.take(len); switch (data[0] & 0x7f) { 2 => if (data.len == 5) { created = std.mem.readInt(u32, data[1..5], .big); }, 27 => if (data.len >= 2) { sign = data[1] & 0x02 != 0; }, else => {}, } } return .{ .created = created, .sign = sign orelse return null }; } // -- tests ------------------------------------------------------------------- pub const testing_keys = @import("testing_keys.zig"); test "an EdDSALegacy key exported by GnuPG" { const gpa = testing.allocator; const armor = @import("armor.zig"); const block = try armor.decode(gpa, testing_keys.ed25519_legacy.armored); var key = try Key.parse(gpa, block.data); defer key.deinit(gpa); const primary = key.primary(); try testing.expectEqual(Algorithm.eddsa_legacy, primary.algorithm); try testing.expectEqualStrings(testing_keys.ed25519_legacy.fingerprint, &primary.fingerprintHex()); try testing.expectEqual(@as(?bool, true), primary.can_sign); try testing.expectEqual(@as(usize, 1), key.user_ids.len); const fpr = testing_keys.ed25519_legacy.fingerprint; try testing.expectEqual(primary, try key.signingKey(fpr)); try testing.expectEqual(primary, try key.signingKey("0x" ++ fpr[24..])); try testing.expectEqual(primary, try key.signingKey(fpr[24..] ++ "!")); try testing.expectEqual(primary, try key.signingKey("Test Ed ")); try testing.expectEqual(primary, try key.signingKey("ED@EXAMPLE.ORG")); try testing.expectError(error.NoSigningKey, key.signingKey("someone@else.example")); try testing.expectError(error.NoSigningKey, key.signingKey("0123456789ABCDEF")); } test "a fingerprint split by spaces, as gpg -K prints it" { var buf: [40]u8 = undefined; const want = "536FCACF39ACEAB9D79316CB1BB9EB7EA602265B"; try testing.expectEqualStrings(want, selectorHex(&buf, "536F CACF 39AC EAB9 D793 16CB 1BB9 EB7E A602 265B").?); try testing.expectEqualStrings(want, selectorHex(&buf, "536f cacf 39ac eab9 d793 16cb 1bb9 eb7e a602 265b!").?); // A key ID may not be split; it is then text to find in a user ID. try testing.expectEqual(@as(?[]const u8, null), selectorHex(&buf, "1BB9 EB7E A602 265B")); try testing.expectEqual(@as(?[]const u8, null), selectorHex(&buf, "536F CACF 39AC EAB9 D793 16CB 1BB9 EB7E A602 265B 00")); } test "an RSA key exported by GnuPG" { const gpa = testing.allocator; const armor = @import("armor.zig"); const block = try armor.decode(gpa, testing_keys.rsa2048.armored); var key = try Key.parse(gpa, block.data); defer key.deinit(gpa); const primary = key.primary(); try testing.expectEqual(Algorithm.rsa, primary.algorithm); try testing.expectEqualStrings(testing_keys.rsa2048.fingerprint, &primary.fingerprintHex()); try testing.expectEqual(@as(usize, 256), primary.secret.rsa.n.len); } test "a native Ed25519 key, built by hand" { const gpa = testing.allocator; const bytes = try testing_keys.buildEd25519Native(gpa, testing_keys.native_seed, 1767225600); var key = try Key.parse(gpa, bytes); defer key.deinit(gpa); const primary = key.primary(); try testing.expectEqual(Algorithm.ed25519, primary.algorithm); try testing.expectEqualSlices(u8, &testing_keys.native_seed, &primary.secret.ed25519.seed); // No signature packet, so nothing said whether it signs; that is taken // as yes. try testing.expectEqual(@as(?bool, null), primary.can_sign); try testing.expectEqual(primary, try key.signingKey(&primary.fingerprintHex())); } test "a corrupted checksum, a protected key and a mismatched public half are refused" { const gpa = testing.allocator; const good = try testing_keys.buildEd25519Native(gpa, testing_keys.native_seed, 0); defer gpa.free(good); const bad_sum = try gpa.dupe(u8, good); bad_sum[bad_sum.len - 1] ^= 1; try testing.expectError(error.ChecksumMismatch, Key.parse(gpa, bad_sum)); // The S2K usage octet sits right after the 32-octet public key. const protected = try gpa.dupe(u8, good); protected[2 + 1 + 4 + 1 + 32] = 254; try testing.expectError(error.ProtectedKey, Key.parse(gpa, protected)); const mismatched = try gpa.dupe(u8, good); mismatched[2 + 1 + 4 + 1] ^= 1; try testing.expectError(error.KeyMismatch, Key.parse(gpa, mismatched)); } test "a subkey on an algorithm bwgpg does not implement is passed over" { const gpa = testing.allocator; const armor = @import("armor.zig"); const tk = testing_keys.ed25519_with_encryption_subkey; const block = try armor.decode(gpa, tk.armored); var key = try Key.parse(gpa, block.data); defer key.deinit(gpa); // The Curve25519 encryption subkey is dropped; the primary signs. try testing.expectEqual(@as(usize, 1), key.components.len); try testing.expectEqualStrings(tk.fingerprint, &key.primary().fingerprintHex()); try testing.expectEqual(key.primary(), try key.signingKey(tk.fingerprint)); } test "the signing subkey is preferred over a certify-only primary" { const gpa = testing.allocator; const armor = @import("armor.zig"); const block = try armor.decode(gpa, testing_keys.ed25519_with_subkey.armored); var key = try Key.parse(gpa, block.data); defer key.deinit(gpa); try testing.expectEqual(@as(usize, 2), key.components.len); try testing.expectEqual(@as(?bool, false), key.components[0].can_sign); try testing.expectEqual(@as(?bool, true), key.components[1].can_sign); const primary_fpr = testing_keys.ed25519_with_subkey.fingerprint; try testing.expectEqual(&key.components[1], try key.signingKey(primary_fpr)); try testing.expectEqual(&key.components[1], try key.signingKey(&key.components[1].fingerprintHex())); }