// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Microsoft Windows' password hashes: passlib's `passlib.handlers.windows`. //! //! * `lmhash`, the LAN Manager hash from OS/2 and Windows before NT: the //! password upper-cased, padded or cut to fourteen bytes, and each half //! used as a DES key to encrypt the constant `KGS!@#$%`. //! * `nthash`, the NT hash that replaced it: MD4 of the password in //! UTF-16LE. `bsd_nthash` is the same thing behind FreeBSD's `$3$$`. //! * `msdcc` and `msdcc2`, the Domain Cached Credentials a Windows machine //! keeps so a domain user can log in while the domain controller is out //! of reach: the NT hash salted with the lower-cased user name, and //! version 2 of it, which adds 10240 rounds of PBKDF2-HMAC-SHA1. //! //! All of them are 32 hex characters with no prefix. passlib accepts either //! case and writes lower case. //! //! **Every one of them is obsolete, and most are broken outright.** //! `lmhash` is two independent seven-character DES keys drawn from an //! upper-case alphabet; rainbow tables for the whole space have been public //! since 2003. `nthash` is one unsalted MD4, and anyone holding it can log in //! with it directly, without learning the password, by passing the hash. //! `msdcc` is salted only with a user name. `msdcc2` is the only one with a //! work factor, and 10240 rounds of SHA-1 is cheap on a GPU. They are here to //! read what is stored in Windows' own databases and in the systems that //! copied them, such as Samba's. const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const testing = std.testing; const crypto_ext = @import("std_crypto_ext"); const Md4 = crypto_ext.Md4; const Des = crypto_ext.Des; const encoding = @import("../encoding.zig"); const handler = @import("../handler.zig"); const Context = handler.Context; const Error = handler.Error; const unicode_case = @import("../unicode_case.zig"); const hex_len = 32; /// passlib's `StaticHandler` parse for these formats: 32 hex characters of /// either case, lower-cased. fn parseHex(h: []const u8) Error![hex_len]u8 { if (h.len != hex_len or !encoding.allIn(h, encoding.hex_chars)) return error.MalformedHash; var out: [hex_len]u8 = undefined; for (&out, h) |*o, c| o.* = std.ascii.toLower(c); return out; } fn identifyHex(h: []const u8) bool { _ = parseHex(h) catch return false; return true; } // -- lmhash ----------------------------------------------------------------- /// The LAN Manager hash. /// /// passlib takes a text password, upper-cases it with Python's /// `str.upper()`, and encodes it to the OEM code page, `cp437` by default. /// Here the password is already bytes in whatever OEM code page the system /// used, so it takes passlib's path for a password given as bytes: only the /// ASCII letters are upper-cased, and every other byte is hashed as it is. /// A caller holding text must upper-case it and encode it to the code page /// first, as passlib would; `é` in code page 437 must arrive as `É`, 0x90, /// not as 0x82. /// /// Only fourteen bytes count. By default a longer password is silently /// truncated, as Windows did; `truncate_error` makes `hash` refuse it. pub const lmhash = struct { pub const name = "lmhash"; /// The number of password bytes that count. pub const truncate_size = 14; pub const Options = struct { /// Refuse a password longer than fourteen bytes with /// `error.PasswordTooLong` rather than hash only its first fourteen. truncate_error: bool = false, }; const magic = "KGS!@#$%"; /// A seven-byte half of the password as a DES key, with a parity bit /// after every seven bits: passlib's `expand_des_key`. fn expandKey(half: *const [7]u8) [8]u8 { var wide: [8]u8 = .{0} ++ half.*; const v = std.mem.readInt(u64, &wide, .big); var key: [8]u8 = undefined; for (&key, 0..) |*k, i| k.* = @as(u8, @truncate(v >> @intCast(49 - 7 * i))) << 1; return key; } /// passlib's `lmhash.raw` for a password given as bytes: the 16-byte /// hash. pub fn raw(password: []const u8) [16]u8 { var padded = [_]u8{0} ** truncate_size; defer std.crypto.secureZero(u8, &padded); const n = @min(password.len, truncate_size); for (padded[0..n], password[0..n]) |*p, c| p.* = std.ascii.toUpper(c); var out: [16]u8 = undefined; Des.initEnc(expandKey(padded[0..7])).encrypt(out[0..8], magic); Des.initEnc(expandKey(padded[7..14])).encrypt(out[8..16], magic); return out; } pub fn identify(h: []const u8) bool { return identifyHex(h); } pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { _ = ctx; try handler.checkPasswordLen(password); if (options.truncate_error and password.len > truncate_size) return error.PasswordTooLong; var out: [hex_len]u8 = undefined; try w.writeAll(encoding.hexLower(&out, &raw(password))); } pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { _ = ctx; try handler.checkPasswordLen(password); const stored = try parseHex(h); var out: [hex_len]u8 = undefined; return handler.eql(&stored, encoding.hexLower(&out, &raw(password))); } pub fn needsUpdate(h: []const u8, options: Options) Error!bool { _ = options; _ = try parseHex(h); return false; } }; // -- nthash ----------------------------------------------------------------- /// The NT hash: MD4 of the password in UTF-16LE. The password must be /// UTF-8. pub const nthash = struct { pub const name = "nthash"; pub const Options = struct {}; /// passlib's `nthash.raw`: the 16-byte hash. pub fn raw(gpa: Allocator, password: []const u8) Error![16]u8 { const wide = try handler.utf16le(gpa, password); defer { std.crypto.secureZero(u8, wide); gpa.free(wide); } var out: [16]u8 = undefined; Md4.hash(wide, &out, .{}); return out; } pub fn identify(h: []const u8) bool { return identifyHex(h); } pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { _ = options; try handler.checkPasswordLen(password); var out: [hex_len]u8 = undefined; try w.writeAll(encoding.hexLower(&out, &try raw(ctx.gpa, password))); } pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { try handler.checkPasswordLen(password); const stored = try parseHex(h); var out: [hex_len]u8 = undefined; return handler.eql(&stored, encoding.hexLower(&out, &try raw(ctx.gpa, password))); } pub fn needsUpdate(h: []const u8, options: Options) Error!bool { _ = options; _ = try parseHex(h); return false; } }; /// FreeBSD's spelling of the NT hash, as `/etc/master.passwd` holds it: /// `$3$$` and the 32 hex characters. pub const bsd_nthash = handler.PrefixWrapper("bsd_nthash", nthash, "$3$$", ""); // -- msdcc and msdcc2 ------------------------------------------------------- /// The user name as the salt: lower-cased as Python lower-cases text, then /// UTF-16LE. The caller frees it. /// /// passlib requires a user, so this returns `error.MissingUser` without /// one. A user that is not UTF-8 is `error.InvalidUser`, since it cannot be /// lower-cased as text; passlib raises `UnicodeDecodeError` for it. fn userSalt(gpa: Allocator, ctx: Context) Error![]u8 { const user = ctx.user orelse return error.MissingUser; const lower = unicode_case.lower(gpa, user) catch |err| switch (err) { error.InvalidPassword => return error.InvalidUser, else => |e| return e, }; defer gpa.free(lower); return handler.utf16le(gpa, lower); } /// `MD4(MD4(UTF-16LE(password)) || salt)`: passlib's `msdcc.raw`, and the /// first step of `msdcc2`. fn dcc1(gpa: Allocator, password: []const u8, salt: []const u8) Error![16]u8 { var md4 = Md4.init(.{}); const inner = try nthash.raw(gpa, password); md4.update(&inner); md4.update(salt); var out: [16]u8 = undefined; md4.final(&out); return out; } /// Domain Cached Credentials, version 1: the NT hash, salted with the user /// name from `Context.user`. /// /// The user name is lower-cased with Python's full Unicode case mapping, /// including a final capital sigma becoming `ς`, since that is what passlib /// does before encoding it. pub const msdcc = struct { pub const name = "msdcc"; pub const Options = struct {}; fn compute(ctx: Context, password: []const u8, out: *[hex_len]u8) Error!void { const salt = try userSalt(ctx.gpa, ctx); defer ctx.gpa.free(salt); _ = encoding.hexLower(out, &try dcc1(ctx.gpa, password, salt)); } pub fn identify(h: []const u8) bool { return identifyHex(h); } pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { _ = options; try handler.checkPasswordLen(password); var out: [hex_len]u8 = undefined; try compute(ctx, password, &out); try w.writeAll(&out); } pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { try handler.checkPasswordLen(password); const stored = try parseHex(h); var out: [hex_len]u8 = undefined; try compute(ctx, password, &out); return handler.eql(&stored, &out); } pub fn needsUpdate(h: []const u8, options: Options) Error!bool { _ = options; _ = try parseHex(h); return false; } }; /// Domain Cached Credentials, version 2, from Windows Vista on: `msdcc`'s /// hash run through PBKDF2-HMAC-SHA1 for 10240 rounds, salted again with the /// user name, and cut to sixteen bytes. pub const msdcc2 = struct { pub const name = "msdcc2"; pub const Options = struct {}; pub const rounds = 10240; fn compute(ctx: Context, password: []const u8, out: *[hex_len]u8) Error!void { const salt = try userSalt(ctx.gpa, ctx); defer ctx.gpa.free(salt); const tmp = try dcc1(ctx.gpa, password, salt); var dk: [16]u8 = undefined; try std.crypto.pwhash.pbkdf2(&dk, &tmp, salt, rounds, std.crypto.auth.hmac.HmacSha1); _ = encoding.hexLower(out, &dk); } pub fn identify(h: []const u8) bool { return identifyHex(h); } pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { _ = options; try handler.checkPasswordLen(password); var out: [hex_len]u8 = undefined; try compute(ctx, password, &out); try w.writeAll(&out); } pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { try handler.checkPasswordLen(password); const stored = try parseHex(h); var out: [hex_len]u8 = undefined; try compute(ctx, password, &out); return handler.eql(&stored, &out); } pub fn needsUpdate(h: []const u8, options: Options) Error!bool { _ = options; _ = try parseHex(h); return false; } }; /// The schemes this module defines, in the order `registry.identify` tries /// them. pub const schemes = .{ lmhash, nthash, bsd_nthash, msdcc, msdcc2 }; comptime { for (schemes) |S| handler.check(S); } const test_ctx: Context = .{ .io = testing.io, .gpa = testing.allocator }; fn hashTo(buf: []u8, comptime S: type, ctx: Context, password: []const u8, options: S.Options) ![]const u8 { var w: Io.Writer = .fixed(buf); try S.hash(ctx, password, options, &w); return w.buffered(); } test "hashes reproduce passlib" { // passlib 1.7.4: lmhash.hash(b"OLDPASSWORD") and so on. var buf: [64]u8 = undefined; try testing.expectEqualStrings("c9b81d939d6fd80cd408e6b105741864", try hashTo(&buf, lmhash, test_ctx, "OLDPASSWORD", .{})); try testing.expectEqualStrings("e52cac67419a9a224a3b108f3fa6cb6d", try hashTo(&buf, lmhash, test_ctx, "password", .{})); try testing.expectEqualStrings("ed4874e7460a9d8baad3b435b51404ee", try hashTo(&buf, lmhash, test_ctx, "p\xe9ss", .{})); try testing.expectEqualStrings("cbc501a4d2227783cbc501a4d2227783", try hashTo(&buf, lmhash, test_ctx, "a" ** 20, .{})); try testing.expectEqualStrings("8846f7eaee8fb117ad06bdd830b7586c", try hashTo(&buf, nthash, test_ctx, "password", .{})); try testing.expectEqualStrings("$3$$8846f7eaee8fb117ad06bdd830b7586c", try hashTo(&buf, bsd_nthash, test_ctx, "password", .{})); const admin: Context = .{ .io = testing.io, .gpa = testing.allocator, .user = "Administrator" }; try testing.expectEqualStrings("25fd08fa89795ed54207e6e8442a6ca0", try hashTo(&buf, msdcc, admin, "password", .{})); try testing.expectEqualStrings("4c253e4b65c007a8cd683ea57bc43c76", try hashTo(&buf, msdcc2, admin, "password", .{})); // msdcc.hash("password", user="ΣΑΣ") and user="σας" agree, since the // final sigma lower-cases to ς; user="İX" lower-cases to three // characters. const sigma: Context = .{ .io = testing.io, .gpa = testing.allocator, .user = "\u{3a3}\u{391}\u{3a3}" }; try testing.expectEqualStrings("c062429b52a6d449dc4d4c3d10600539", try hashTo(&buf, msdcc, sigma, "password", .{})); const dotted: Context = .{ .io = testing.io, .gpa = testing.allocator, .user = "\u{130}X" }; try testing.expectEqualStrings("79f341be04fb6027643d5db394031685", try hashTo(&buf, msdcc, dotted, "password", .{})); } test "verification and identification" { try testing.expect(try nthash.verify(test_ctx, "password", "8846F7EAEE8FB117AD06BDD830B7586C")); try testing.expect(!try nthash.verify(test_ctx, "Password", "8846f7eaee8fb117ad06bdd830b7586c")); try testing.expect(!nthash.identify("$3$$8846f7eaee8fb117ad06bdd830b7586c")); try testing.expect(bsd_nthash.identify("$3$$8846f7eaee8fb117ad06bdd830b7586c")); try testing.expect(!bsd_nthash.identify("$3$$zz")); // lmhash upper-cases, so case does not matter to it. try testing.expect(try lmhash.verify(test_ctx, "PASSWORD", "e52cac67419a9a224a3b108f3fa6cb6d")); // passlib: lmhash.hash(b"\x82") and lmhash.hash(b"\x90"). Bytes past // ASCII are not upper-cased, so code page 437's é and É differ. try testing.expect(try lmhash.verify(test_ctx, "\x82", "565d1c9af3514c4eaad3b435b51404ee")); try testing.expect(!try lmhash.verify(test_ctx, "\x90", "565d1c9af3514c4eaad3b435b51404ee")); } test "refusals" { var buf: [64]u8 = undefined; try testing.expectError(error.PasswordTooLong, hashTo(&buf, lmhash, test_ctx, "a" ** 15, .{ .truncate_error = true })); try testing.expectError(error.MissingUser, hashTo(&buf, msdcc, test_ctx, "x", .{})); try testing.expectError(error.MissingUser, hashTo(&buf, msdcc2, test_ctx, "x", .{})); const bad_user: Context = .{ .io = testing.io, .gpa = testing.allocator, .user = "\xff" }; try testing.expectError(error.InvalidUser, hashTo(&buf, msdcc, bad_user, "x", .{})); try testing.expectError(error.InvalidUser, hashTo(&buf, msdcc2, bad_user, "x", .{})); // A malformed hash is reported before a missing user, as passlib parses // first. try testing.expectError(error.MalformedHash, msdcc.verify(test_ctx, "x", "zz")); try testing.expectError(error.InvalidPassword, hashTo(&buf, nthash, test_ctx, "\xff", .{})); }