// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Bitwarden's client-side encryption: turning a master password into the key //! that unwraps the account's user key, and decrypting the `EncString`s every //! item field is stored as. //! //! The chain, as the Bitwarden security whitepaper describes it: //! //! 1. **Master key**: PBKDF2-HMAC-SHA256 of the password, salted with the //! lower-cased email; or Argon2id, salted with SHA-256 of that email. //! 2. **Stretched master key**: HKDF-Expand-SHA256 of the master key (used //! directly as the PRK, with no Extract step), once with the info string //! `enc` and once with `mac`, 32 octets each. //! 3. **User key**: the account's `Key`, an EncString decrypted with the //! stretched master key, 64 octets: an encryption key then a MAC key. //! 4. **Item fields**: EncStrings decrypted with the user key, or with the //! item's own key when it has one, which is itself an EncString under the //! user key. //! //! Only EncString type 2, AES-256-CBC with HMAC-SHA256, is accepted. Type 0 //! has no MAC and is refused rather than decrypted; the RSA types belong to //! organizations, which this program does not support. const std = @import("std"); const Allocator = std.mem.Allocator; const testing = std.testing; const crypto = std.crypto; const Aes256 = crypto.core.aes.Aes256; const HmacSha256 = crypto.auth.hmac.sha2.HmacSha256; const HkdfSha256 = crypto.kdf.hkdf.HkdfSha256; const Sha256 = crypto.hash.sha2.Sha256; const modes = @import("std_crypto_ext").modes; pub const Error = error{ /// Not of the form `.||`, or a part that is /// not base64 or not the right length. MalformedEncString, /// An EncString of a type other than 2. UnsupportedEncStringType, /// The MAC does not match. For the user key this means the master /// password was wrong; for anything else, that the data was altered or /// the wrong key was used. MacMismatch, /// The decrypted data does not end in valid PKCS#7 padding. BadPadding, /// A decrypted key that is not 64 octets. BadKeyLength, }; /// An encryption key and a MAC key: what the stretched master key, the user /// key and an item key all are. pub const SymmetricKey = struct { enc: [32]u8, mac: [32]u8, pub fn fromBytes(bytes: []const u8) Error!SymmetricKey { if (bytes.len != 64) return error.BadKeyLength; return .{ .enc = bytes[0..32].*, .mac = bytes[32..64].* }; } pub fn wipe(key: *SymmetricKey) void { crypto.secureZero(u8, &key.enc); crypto.secureZero(u8, &key.mac); } }; /// The key derivation function the account is configured with. pub const Kdf = union(enum) { pbkdf2: struct { iterations: u32 }, argon2id: struct { iterations: u32, memory_mib: u32, parallelism: u24 }, }; pub const KdfError = error{ /// Parameters below Bitwarden's own minimums: a misconfiguration, or a /// server trying to make the password cheap to guess. WeakParameters, /// The derivation itself failed, which for Argon2 means it could not get /// the threads or memory it needed. KdfFailed, OutOfMemory, }; /// Derives the 32-octet master key. /// /// `gpa` is used only by Argon2id, for its memory blocks. They are derived /// from the password, so it should be an allocator that wipes on free. pub fn masterKey(gpa: Allocator, io: std.Io, password: []const u8, email: []const u8, kdf: Kdf) KdfError![32]u8 { var lower_buf: [320]u8 = undefined; const trimmed = std.mem.trim(u8, email, " \t\r\n"); if (trimmed.len > lower_buf.len) return error.WeakParameters; const salt = std.ascii.lowerString(&lower_buf, trimmed); var out: [32]u8 = undefined; switch (kdf) { .pbkdf2 => |p| { // Bitwarden's own floor. if (p.iterations < 5000) return error.WeakParameters; crypto.pwhash.pbkdf2(&out, password, salt, p.iterations, HmacSha256) catch return error.KdfFailed; }, .argon2id => |a| { if (a.iterations < 2 or a.memory_mib < 16 or a.parallelism < 1) return error.WeakParameters; var salt_hash: [32]u8 = undefined; Sha256.hash(salt, &salt_hash, .{}); crypto.pwhash.argon2.kdf(gpa, &out, password, &salt_hash, .{ .t = a.iterations, .m = a.memory_mib * 1024, .p = a.parallelism, }, .argon2id, io) catch |err| return switch (err) { error.OutOfMemory => error.OutOfMemory, else => error.KdfFailed, }; }, } return out; } /// Expands the master key into the key that decrypts the user key. pub fn stretch(master: [32]u8) SymmetricKey { var key: SymmetricKey = undefined; HkdfSha256.expand(&key.enc, "enc", master); HkdfSha256.expand(&key.mac, "mac", master); return key; } /// The parts of a type 2 EncString, decoded. const Parts = struct { iv: [16]u8, ciphertext: []u8, mac: [32]u8, }; fn parse(gpa: Allocator, text: []const u8) (Error || Allocator.Error)!Parts { const dot = std.mem.findScalar(u8, text, '.') orelse return error.MalformedEncString; const type_num = std.fmt.parseInt(u8, text[0..dot], 10) catch return error.MalformedEncString; if (type_num != 2) return error.UnsupportedEncStringType; var it = std.mem.splitScalar(u8, text[dot + 1 ..], '|'); const iv_b64 = it.next() orelse return error.MalformedEncString; const ct_b64 = it.next() orelse return error.MalformedEncString; const mac_b64 = it.next() orelse return error.MalformedEncString; if (it.next() != null) return error.MalformedEncString; const decoder = std.base64.standard.Decoder; var parts: Parts = undefined; if ((decoder.calcSizeForSlice(iv_b64) catch return error.MalformedEncString) != 16) return error.MalformedEncString; decoder.decode(&parts.iv, iv_b64) catch return error.MalformedEncString; if ((decoder.calcSizeForSlice(mac_b64) catch return error.MalformedEncString) != 32) return error.MalformedEncString; decoder.decode(&parts.mac, mac_b64) catch return error.MalformedEncString; const ct_len = decoder.calcSizeForSlice(ct_b64) catch return error.MalformedEncString; if (ct_len == 0 or ct_len % 16 != 0) return error.MalformedEncString; parts.ciphertext = try gpa.alloc(u8, ct_len); errdefer gpa.free(parts.ciphertext); decoder.decode(parts.ciphertext, ct_b64) catch return error.MalformedEncString; return parts; } /// Decrypts an EncString, returning the plaintext allocated from `gpa`. The /// caller owns it and, if it is secret, wipes it. pub fn decrypt(gpa: Allocator, key: *const SymmetricKey, text: []const u8) (Error || Allocator.Error)![]u8 { const parts = try parse(gpa, text); defer gpa.free(parts.ciphertext); // The MAC is checked before anything is decrypted, so that nothing about // the padding of an altered ciphertext is ever observable. var expected: [32]u8 = undefined; var hmac = HmacSha256.init(&key.mac); hmac.update(&parts.iv); hmac.update(parts.ciphertext); hmac.final(&expected); if (!crypto.timing_safe.eql([32]u8, expected, parts.mac)) return error.MacMismatch; const plain = try gpa.alloc(u8, parts.ciphertext.len); errdefer { crypto.secureZero(u8, plain); gpa.free(plain); } const ctx = Aes256.initDec(key.enc); modes.cbcDecrypt(@TypeOf(ctx), ctx, plain, parts.ciphertext, parts.iv); const pad = plain[plain.len - 1]; if (pad == 0 or pad > 16) return error.BadPadding; for (plain[plain.len - pad ..]) |b| { if (b != pad) return error.BadPadding; } crypto.secureZero(u8, plain[plain.len - pad ..]); return gpa.realloc(plain, plain.len - pad) catch plain[0 .. plain.len - pad]; } /// Decrypts an EncString that holds a 64-octet key. pub fn decryptKey(gpa: Allocator, key: *const SymmetricKey, text: []const u8) (Error || Allocator.Error)!SymmetricKey { const plain = try decrypt(gpa, key, text); defer { crypto.secureZero(u8, plain); gpa.free(plain); } return SymmetricKey.fromBytes(plain); } /// Encrypts `plaintext` into a type 2 EncString. Used by the tests and by the /// test fixture that fills a Vaultwarden with an item to read back; bwgpg /// itself never writes to the vault. pub fn encrypt(gpa: Allocator, key: *const SymmetricKey, iv: [16]u8, plaintext: []const u8) Allocator.Error![]u8 { const pad: u8 = @intCast(16 - plaintext.len % 16); const padded = try gpa.alloc(u8, plaintext.len + pad); defer { crypto.secureZero(u8, padded); gpa.free(padded); } @memcpy(padded[0..plaintext.len], plaintext); @memset(padded[plaintext.len..], pad); const ctx = Aes256.initEnc(key.enc); modes.cbcEncrypt(@TypeOf(ctx), ctx, padded, padded, iv); var mac: [32]u8 = undefined; var hmac = HmacSha256.init(&key.mac); hmac.update(&iv); hmac.update(padded); hmac.final(&mac); const encoder = std.base64.standard.Encoder; var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); const w = &out.writer; w.writeAll("2.") catch return error.OutOfMemory; encoder.encodeWriter(w, &iv) catch return error.OutOfMemory; w.writeByte('|') catch return error.OutOfMemory; encoder.encodeWriter(w, padded) catch return error.OutOfMemory; w.writeByte('|') catch return error.OutOfMemory; encoder.encodeWriter(w, &mac) catch return error.OutOfMemory; return out.toOwnedSlice(); } test "encrypt and decrypt round trip at every padding length" { const gpa = testing.allocator; const key: SymmetricKey = .{ .enc = @splat(1), .mac = @splat(2) }; var msg: [40]u8 = undefined; for (&msg, 0..) |*b, i| b.* = @truncate(i); for (0..msg.len) |n| { const enc = try encrypt(gpa, &key, @splat(3), msg[0..n]); defer gpa.free(enc); const dec = try decrypt(gpa, &key, enc); defer gpa.free(dec); try testing.expectEqualSlices(u8, msg[0..n], dec); } } test "a changed ciphertext, IV or key fails the MAC" { const gpa = testing.allocator; const key: SymmetricKey = .{ .enc = @splat(1), .mac = @splat(2) }; const enc = try encrypt(gpa, &key, @splat(3), "secret note"); defer gpa.free(enc); // Flip a character in the middle of the ciphertext part. const bar = std.mem.findScalar(u8, enc, '|').?; const altered = try gpa.dupe(u8, enc); defer gpa.free(altered); altered[bar + 2] = if (altered[bar + 2] == 'A') 'B' else 'A'; try testing.expectError(error.MacMismatch, decrypt(gpa, &key, altered)); const other: SymmetricKey = .{ .enc = @splat(1), .mac = @splat(9) }; try testing.expectError(error.MacMismatch, decrypt(gpa, &other, enc)); } test "other EncString types and malformed strings are refused" { const gpa = testing.allocator; const key: SymmetricKey = .{ .enc = @splat(1), .mac = @splat(2) }; try testing.expectError(error.UnsupportedEncStringType, decrypt(gpa, &key, "0.AAAAAAAAAAAAAAAAAAAAAA==|AAAAAAAAAAAAAAAAAAAAAA==")); try testing.expectError(error.UnsupportedEncStringType, decrypt(gpa, &key, "4.AAAA")); try testing.expectError(error.MalformedEncString, decrypt(gpa, &key, "2.AAAA|AAAA")); try testing.expectError(error.MalformedEncString, decrypt(gpa, &key, "nonsense")); } test "padding is checked after the MAC" { const gpa = testing.allocator; const key: SymmetricKey = .{ .enc = @splat(1), .mac = @splat(2) }; // A block of zeros, encrypted without padding, then MACed properly: it // passes the MAC and decrypts to a last octet of zero. var block: [16]u8 = @splat(0); const ctx = Aes256.initEnc(key.enc); const iv: [16]u8 = @splat(3); modes.cbcEncrypt(@TypeOf(ctx), ctx, &block, &block, iv); var mac: [32]u8 = undefined; var hmac = HmacSha256.init(&key.mac); hmac.update(&iv); hmac.update(&block); hmac.final(&mac); const e = std.base64.standard.Encoder; var b1: [24]u8 = undefined; var b2: [24]u8 = undefined; var b3: [44]u8 = undefined; const text = try std.fmt.allocPrint(gpa, "2.{s}|{s}|{s}", .{ e.encode(&b1, &iv), e.encode(&b2, &block), e.encode(&b3, &mac) }); defer gpa.free(text); try testing.expectError(error.BadPadding, decrypt(gpa, &key, text)); } test "HKDF-Expand matches RFC 5869 test case 1" { // Test case 1's PRK and info, 42 octets of output. The stretch uses the // same function with 32 octets and info "enc" or "mac". var prk: [32]u8 = undefined; _ = try std.fmt.hexToBytes(&prk, "077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5"); var info: [10]u8 = undefined; _ = try std.fmt.hexToBytes(&info, "f0f1f2f3f4f5f6f7f8f9"); var okm: [42]u8 = undefined; HkdfSha256.expand(&okm, &info, prk); var want: [42]u8 = undefined; _ = try std.fmt.hexToBytes(&want, "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"); try testing.expectEqualSlices(u8, &want, &okm); } test "the master key is PBKDF2 of the password with the lower-cased email as salt" { // PBKDF2-HMAC-SHA256 has no RFC test vector with Bitwarden's parameters, // so this checks the derivation against std's PBKDF2 called directly. // What is under test is the salt handling: trimmed and lower-cased. const got = try masterKey(testing.allocator, testing.io, "correct horse", " User@Example.COM\n", .{ .pbkdf2 = .{ .iterations = 5000 } }); var want: [32]u8 = undefined; try crypto.pwhash.pbkdf2(&want, "correct horse", "user@example.com", 5000, HmacSha256); try testing.expectEqualSlices(u8, &want, &got); try testing.expectError(error.WeakParameters, masterKey(testing.allocator, testing.io, "x", "a@b", .{ .pbkdf2 = .{ .iterations = 1 } })); } test "the whole chain: password to user key to item field" { const gpa = testing.allocator; const email = "user@example.com"; const password = "correct horse"; const master = try masterKey(gpa, testing.io, password, email, .{ .pbkdf2 = .{ .iterations = 5000 } }); var stretched = stretch(master); var user_key_bytes: [64]u8 = undefined; for (&user_key_bytes, 0..) |*b, i| b.* = @truncate(i * 3 + 1); const protected = try encrypt(gpa, &stretched, @splat(7), &user_key_bytes); defer gpa.free(protected); const user_key = try decryptKey(gpa, &stretched, protected); try testing.expectEqualSlices(u8, &user_key_bytes, &(user_key.enc ++ user_key.mac)); const note = try encrypt(gpa, &user_key, @splat(8), "-----BEGIN PGP PRIVATE KEY BLOCK-----"); defer gpa.free(note); const plain = try decrypt(gpa, &user_key, note); defer gpa.free(plain); try testing.expectEqualStrings("-----BEGIN PGP PRIVATE KEY BLOCK-----", plain); // A wrong password gets as far as the user key's MAC and no further. const wrong = try masterKey(gpa, testing.io, "wrong horse", email, .{ .pbkdf2 = .{ .iterations = 5000 } }); var wrong_stretched = stretch(wrong); try testing.expectError(error.MacMismatch, decryptKey(gpa, &wrong_stretched, protected)); stretched.wipe(); } test "Argon2id derivation salts with SHA-256 of the email" { const gpa = testing.allocator; const got = try masterKey(gpa, testing.io, "pw", "A@B.example", .{ .argon2id = .{ .iterations = 2, .memory_mib = 16, .parallelism = 1 } }); var salt: [32]u8 = undefined; Sha256.hash("a@b.example", &salt, .{}); var want: [32]u8 = undefined; try crypto.pwhash.argon2.kdf(gpa, &want, "pw", &salt, .{ .t = 2, .m = 16 * 1024, .p = 1 }, .argon2id, testing.io); try testing.expectEqualSlices(u8, &want, &got); }