// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The DES `crypt` family: passlib's `passlib.handlers.des_crypt`. //! //! `des_crypt` is the original Unix `crypt(3)`, from Seventh Edition Unix in //! 1979: the first eight characters of the password, seven bits of each, //! become a DES key; a two-character salt perturbs DES's expansion table; //! and a block of zeros is encrypted 25 times. The 64 bits that come out are //! eleven characters of `h64big`. The others are its descendants. //! //! * `bsdi_crypt`, BSDi's extended DES (`_` + four characters of rounds + //! four of salt), which folds the whole password into the key and makes //! the round count a setting. //! * `bigcrypt`, from HP-UX and Digital Unix, which hashes each further //! eight characters with `des_crypt` separately and appends the result. //! * `crypt16`, from Ultrix and Tru64, which hashes the first eight //! characters with 20 rounds and the next eight with five. //! //! **All of them are obsolete, and badly.** A 56-bit key and a 12-bit salt //! were weak in 1979; today a GPU tries every `des_crypt` password in days. //! `des_crypt` ignores everything past the eighth character and the high bit //! of every character. `bigcrypt` and `crypt16` hash eight-character pieces //! independently, so each can be attacked on its own. `bsdi_crypt` is the //! least bad and is still DES. They are here to check passwords already //! stored with them, in old `/etc/shadow` files and in the directories //! migrated out of old systems, so that those can be rehashed. //! //! passlib picks between the operating system's `crypt` and its own DES; //! this is always its own, `crypt3` from `std_crypto_ext`, which is //! passlib's `des_encrypt_int_block`. const std = @import("std"); const Io = std.Io; const testing = std.testing; const crypt3 = @import("std_crypto_ext").crypt3; const encoding = @import("../encoding.zig"); const h64 = encoding.h64; const h64big = encoding.h64big; const handler = @import("../handler.zig"); const Context = handler.Context; const Error = handler.Error; /// The characters of an `h64big`-encoded 64-bit block. const block_chars = 11; // -- what passlib's regular expressions accept ------------------------------ /// The length in bytes of the character at the start of `s` if it matches /// passlib's `[./a-z0-9]` under `re.IGNORECASE`, or null. /// /// `identify` reads the hash as text, and Python's case-insensitive matching /// folds four characters outside ASCII onto the letters in that class: /// U+0130 and U+0131 onto `i`, U+017F onto `s`, and the Kelvin sign U+212A /// onto `k`. So passlib identifies a string holding them, then refuses to /// parse it because it is not ASCII. fn classCharLen(s: []const u8) ?usize { const c = s[0]; if (c < 0x80) return if (h64.value(c) != null) 1 else null; inline for (.{ "\xc4\xb0", "\xc4\xb1", "\xc5\xbf", "\xe2\x84\xaa" }) |seq| { if (std.mem.startsWith(u8, s, seq)) return seq.len; } return null; } /// The number of characters in `s`, if every one of them matches the class /// above, or null. A single trailing newline is left out, since Python's `$` /// matches just before one. fn classCount(s: []const u8) ?usize { const body = if (std.mem.endsWith(u8, s, "\n")) s[0 .. s.len - 1] else s; var n: usize = 0; var i: usize = 0; while (i < body.len) : (n += 1) i += classCharLen(body[i..]) orelse return null; return n; } /// `s` without the single trailing newline passlib's regular expressions /// let through, if it is otherwise all `h64` characters; else /// `error.MalformedHash`. This is what `from_string` sees once the hash has /// been decoded as ASCII and matched. fn asciiBody(s: []const u8) Error![]const u8 { const body = if (std.mem.endsWith(u8, s, "\n")) s[0 .. s.len - 1] else s; if (!h64.isValid(body)) return error.MalformedHash; return body; } // -- the primitives --------------------------------------------------------- /// passlib's `_crypt_secret_to_key`: the first eight bytes of `secret`, each /// with its high bit dropped and shifted into the top seven bits, as a DES /// key. A shorter secret is padded with zeros. fn secretToKey(secret: []const u8) [8]u8 { var key = [_]u8{0} ** 8; for (key[0..@min(secret.len, 8)], secret[0..@min(secret.len, 8)]) |*k, c| k.* = (c & 0x7f) << 1; return key; } fn keyFromInt(v: u64) [8]u8 { var key: [8]u8 = undefined; std.mem.writeInt(u64, &key, v, .big); return key; } /// Refuses a NUL, which the C implementations take as the end of the /// password and passlib refuses rather than silently truncate at. fn refuseNul(password: []const u8) Error!void { if (std.mem.findScalar(u8, password, 0) != null) return error.InvalidPassword; } /// passlib's `_raw_des_crypt`: eleven characters for `secret` under the /// two-character `salt`. fn rawDesCrypt(secret: []const u8, salt: *const [2]u8, out: *[block_chars]u8) Error!void { const salt_value = h64.decodeInt(12, salt) catch return error.MalformedHash; const result = crypt3(secretToKey(secret), salt_value, 25, 0); h64big.encodeInt(64, out, result); } /// A salt given in `Options`: exactly `len` characters of `h64`. fn checkSalt(s: []const u8, comptime len: usize) Error!*const [len]u8 { if (s.len != len or !h64.isValid(s)) return error.InvalidOptions; return s[0..len]; } // -- des_crypt -------------------------------------------------------------- /// Traditional DES `crypt`: a two-character salt and eleven characters of /// checksum, thirteen in all, with no prefix. /// /// Only the first eight bytes of the password count. By default a longer one /// is silently truncated, as `crypt(3)` does; `truncate_error` makes `hash` /// refuse it instead. pub const des_crypt = struct { pub const name = "des_crypt"; /// The number of password bytes that count. pub const truncate_size = 8; pub const Options = struct { /// The salt, two characters of `./0-9A-Za-z`. Null, the default, /// draws a random one. salt: ?[]const u8 = null, /// Refuse a password longer than eight bytes with /// `error.PasswordTooLong` rather than hash only its first eight. truncate_error: bool = false, }; /// passlib's regular expression: two salt characters, then eleven more /// or nothing. pub fn identify(h: []const u8) bool { const n = classCount(h) orelse return false; return n == 2 or n == 2 + block_chars; } const Parsed = struct { salt: *const [2]u8, checksum: ?[]const u8 }; /// passlib's `from_string`, which does not use its regular expression: /// the first two characters are the salt, and the rest, if there is any, /// must be exactly eleven checksum characters. fn parse(h: []const u8) Error!Parsed { if (h.len < 2 or !h64.isValid(h[0..2])) return error.MalformedHash; const rest = h[2..]; if (rest.len == 0) return .{ .salt = h[0..2], .checksum = null }; if (rest.len != block_chars or !h64.isValid(rest)) return error.MalformedHash; return .{ .salt = h[0..2], .checksum = rest }; } pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { try handler.checkPasswordLen(password); var salt_buf: [2]u8 = undefined; const salt = if (options.salt) |s| try checkSalt(s, 2) else (try handler.randomChars(ctx.io, &salt_buf, encoding.hash64_chars))[0..2]; if (options.truncate_error and password.len > truncate_size) return error.PasswordTooLong; try refuseNul(password); var checksum: [block_chars]u8 = undefined; try rawDesCrypt(password, salt, &checksum); try w.print("{s}{s}", .{ salt, checksum }); } pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { _ = ctx; try handler.checkPasswordLen(password); const parsed = try parse(h); const stored = parsed.checksum orelse return error.MalformedHash; try refuseNul(password); var checksum: [block_chars]u8 = undefined; try rawDesCrypt(password, parsed.salt, &checksum); return handler.eql(stored, &checksum); } /// Always false for a hash or configuration string that parses: there is /// nothing to be out of date. pub fn needsUpdate(h: []const u8, options: Options) Error!bool { _ = options; _ = try parse(h); return false; } }; // -- bsdi_crypt ------------------------------------------------------------- /// BSDi's extended DES `crypt`: `_`, four characters of rounds, four of /// salt, and eleven of checksum. /// /// The whole password counts: each further eight bytes are folded into the /// key by encrypting the key with itself and XORing them in. The rounds and /// the salt are 24-bit integers in little-endian `h64`. /// /// An even round count can reveal that a key is one of DES's weak keys, so /// `hash` always makes the count odd, as passlib does, and `needsUpdate` is /// true for any hash with an even one. pub const bsdi_crypt = struct { pub const name = "bsdi_crypt"; pub const default_rounds = 5001; pub const min_rounds = 1; pub const max_rounds = (1 << 24) - 1; pub const Options = struct { /// The salt, four characters of `./0-9A-Za-z`. Null, the default, /// draws a random one. salt: ?[]const u8 = null, /// Rounds, from 1 to 16777215. An even count is raised by one. rounds: u32 = default_rounds, /// `needsUpdate` is true for a hash with fewer rounds than this. min_desired_rounds: ?u32 = null, /// `needsUpdate` is true for a hash with more rounds than this. max_desired_rounds: ?u32 = null, }; /// passlib's regular expression: `_`, eight characters of rounds and /// salt, then eleven of checksum or nothing. pub fn identify(h: []const u8) bool { if (!std.mem.startsWith(u8, h, "_")) return false; const n = classCount(h[1..]) orelse return false; return n == 8 or n == 8 + block_chars; } const Parsed = struct { rounds: u24, salt: *const [4]u8, checksum: ?[]const u8 }; fn parse(h: []const u8) Error!Parsed { if (!std.mem.startsWith(u8, h, "_")) return error.MalformedHash; const body = try asciiBody(h[1..]); if (body.len != 8 and body.len != 8 + block_chars) return error.MalformedHash; const rounds = h64.decodeInt(24, body[0..4]) catch return error.MalformedHash; if (rounds < min_rounds) return error.MalformedHash; return .{ .rounds = rounds, .salt = body[4..8], .checksum = if (body.len > 8) body[8..] else null, }; } /// passlib's `_bsdi_secret_to_key`. fn secretToFoldedKey(secret: []const u8) [8]u8 { var key = std.mem.readInt(u64, &secretToKey(secret), .big); var i: usize = 8; while (i < secret.len) : (i += 8) { const next = std.mem.readInt(u64, &secretToKey(secret[i..@min(i + 8, secret.len)]), .big); key = crypt3(keyFromInt(key), 0, 1, key) ^ next; } return keyFromInt(key); } fn compute(password: []const u8, rounds: u24, salt: *const [4]u8, out: *[block_chars]u8) Error!void { try refuseNul(password); const salt_value = h64.decodeInt(24, salt) catch return error.MalformedHash; h64big.encodeInt(64, out, crypt3(secretToFoldedKey(password), salt_value, rounds, 0)); } pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { try handler.checkPasswordLen(password); if (options.rounds < min_rounds or options.rounds > max_rounds) return error.InvalidOptions; const rounds: u24 = @intCast(options.rounds | 1); var salt_buf: [4]u8 = undefined; const salt = if (options.salt) |s| try checkSalt(s, 4) else (try handler.randomChars(ctx.io, &salt_buf, encoding.hash64_chars))[0..4]; var checksum: [block_chars]u8 = undefined; try compute(password, rounds, salt, &checksum); var rounds_chars: [4]u8 = undefined; h64.encodeInt(24, &rounds_chars, rounds); try w.print("_{s}{s}{s}", .{ rounds_chars, salt, checksum }); } pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { _ = ctx; try handler.checkPasswordLen(password); const parsed = try parse(h); const stored = parsed.checksum orelse return error.MalformedHash; var checksum: [block_chars]u8 = undefined; try compute(password, parsed.rounds, parsed.salt, &checksum); return handler.eql(stored, &checksum); } /// True for an even round count, and for rounds outside /// `min_desired_rounds` and `max_desired_rounds`. pub fn needsUpdate(h: []const u8, options: Options) Error!bool { const parsed = try parse(h); if (parsed.rounds & 1 == 0) return true; return handler.roundsOutside(parsed.rounds, options.min_desired_rounds, options.max_desired_rounds); } }; // -- bigcrypt --------------------------------------------------------------- /// HP-UX's `bigcrypt`: a two-character salt, then eleven characters of /// `des_crypt` for each eight bytes of the password. /// /// The first block is `des_crypt` of the first eight bytes under the salt. /// Each later block is `des_crypt` of the next eight bytes, salted with the /// first two characters of the block before it. A password of up to eight /// bytes hashes exactly as `des_crypt` does. pub const bigcrypt = struct { pub const name = "bigcrypt"; /// The longest password `hash` can write a hash for with the buffer it /// uses; anything longer is past `handler.max_password_len` anyway. const max_blocks = (handler.max_password_len + 7) / 8; pub const Options = struct { /// The salt, two characters of `./0-9A-Za-z`. Null, the default, /// draws a random one. salt: ?[]const u8 = null, }; /// passlib's regular expression: two salt characters, then any number of /// eleven-character blocks, including none. pub fn identify(h: []const u8) bool { const n = classCount(h) orelse return false; return n >= 2 and (n - 2) % block_chars == 0; } const Parsed = struct { salt: *const [2]u8, checksum: ?[]const u8 }; fn parse(h: []const u8) Error!Parsed { const body = try asciiBody(h); if (body.len < 2 or (body.len - 2) % block_chars != 0) return error.MalformedHash; return .{ .salt = body[0..2], .checksum = if (body.len > 2) body[2..] else null }; } /// The checksum for `password`, one block per eight bytes and at least /// one, into `out`. fn compute(password: []const u8, salt: *const [2]u8, out: *[max_blocks * block_chars]u8) Error![]const u8 { try refuseNul(password); try rawDesCrypt(password, salt, out[0..block_chars]); var len: usize = block_chars; var i: usize = 8; while (i < password.len) : (i += 8) { const block_salt = out[len - block_chars ..][0..2]; try rawDesCrypt(password[i..@min(i + 8, password.len)], block_salt, out[len..][0..block_chars]); len += block_chars; } return out[0..len]; } pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { try handler.checkPasswordLen(password); var salt_buf: [2]u8 = undefined; const salt = if (options.salt) |s| try checkSalt(s, 2) else (try handler.randomChars(ctx.io, &salt_buf, encoding.hash64_chars))[0..2]; var buf: [max_blocks * block_chars]u8 = undefined; const checksum = try compute(password, salt, &buf); try w.print("{s}{s}", .{ salt, checksum }); } pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { _ = ctx; try handler.checkPasswordLen(password); const parsed = try parse(h); const stored = parsed.checksum orelse return error.MalformedHash; var buf: [max_blocks * block_chars]u8 = undefined; const checksum = try compute(password, parsed.salt, &buf); return handler.eql(stored, checksum); } /// Always false for a hash or configuration string that parses. pub fn needsUpdate(h: []const u8, options: Options) Error!bool { _ = options; _ = try parse(h); return false; } }; // -- crypt16 ---------------------------------------------------------------- /// Ultrix's `crypt16`: a two-character salt and 22 characters of checksum. /// /// The first eight bytes of the password are DES-encrypted 20 times under /// the salt and the next eight five times, and the two blocks are /// concatenated. Only sixteen bytes count; by default a longer password is /// silently truncated, and `truncate_error` makes `hash` refuse it. /// /// Unlike the rest of the family, passlib does not refuse a NUL here: it is /// hashed as a zero byte. pub const crypt16 = struct { pub const name = "crypt16"; /// The number of password bytes that count. pub const truncate_size = 16; const checksum_len = 2 * block_chars; pub const Options = struct { /// The salt, two characters of `./0-9A-Za-z`. Null, the default, /// draws a random one. salt: ?[]const u8 = null, /// Refuse a password longer than sixteen bytes with /// `error.PasswordTooLong` rather than hash only its first sixteen. truncate_error: bool = false, }; pub fn identify(h: []const u8) bool { const n = classCount(h) orelse return false; return n == 2 or n == 2 + checksum_len; } const Parsed = struct { salt: *const [2]u8, checksum: ?[]const u8 }; fn parse(h: []const u8) Error!Parsed { const body = try asciiBody(h); if (body.len != 2 and body.len != 2 + checksum_len) return error.MalformedHash; return .{ .salt = body[0..2], .checksum = if (body.len > 2) body[2..] else null }; } fn compute(password: []const u8, salt: *const [2]u8, out: *[checksum_len]u8) Error!void { const salt_value = h64.decodeInt(12, salt) catch return error.MalformedHash; const first = crypt3(secretToKey(password), salt_value, 20, 0); const second = crypt3(secretToKey(if (password.len > 8) password[8..@min(password.len, 16)] else ""), salt_value, 5, 0); h64big.encodeInt(64, out[0..block_chars], first); h64big.encodeInt(64, out[block_chars..], second); } pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { try handler.checkPasswordLen(password); var salt_buf: [2]u8 = undefined; const salt = if (options.salt) |s| try checkSalt(s, 2) else (try handler.randomChars(ctx.io, &salt_buf, encoding.hash64_chars))[0..2]; if (options.truncate_error and password.len > truncate_size) return error.PasswordTooLong; var checksum: [checksum_len]u8 = undefined; try compute(password, salt, &checksum); try w.print("{s}{s}", .{ salt, checksum }); } pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { _ = ctx; try handler.checkPasswordLen(password); const parsed = try parse(h); const stored = parsed.checksum orelse return error.MalformedHash; var checksum: [checksum_len]u8 = undefined; try compute(password, parsed.salt, &checksum); return handler.eql(stored, &checksum); } /// Always false for a hash or configuration string that parses. pub fn needsUpdate(h: []const u8, options: Options) Error!bool { _ = options; _ = try parse(h); return false; } }; /// The schemes this module defines, in the order `registry.identify` tries /// them. pub const schemes = .{ des_crypt, bsdi_crypt, bigcrypt, crypt16 }; comptime { for (schemes) |S| handler.check(S); } const test_ctx: Context = .{ .io = testing.io, .gpa = testing.allocator }; fn hashTo(buf: []u8, comptime S: type, password: []const u8, options: S.Options) ![]const u8 { var w: Io.Writer = .fixed(buf); try S.hash(test_ctx, password, options, &w); return w.buffered(); } test "fixed salts reproduce passlib" { // passlib 1.7.4: des_crypt.using(salt="ab").hash("password"), and the // same for the others with the salts and rounds shown. var buf: [64]u8 = undefined; try testing.expectEqualStrings("abJnggxhB/yWI", try hashTo(&buf, des_crypt, "password", .{ .salt = "ab" })); try testing.expectEqualStrings("abJnggxhB/yWI", try hashTo(&buf, des_crypt, "passwordLONGER", .{ .salt = "ab" })); try testing.expectEqualStrings("_7C/.abcdpsRgFoP9Jr2", try hashTo(&buf, bsdi_crypt, "password", .{ .salt = "abcd" })); // An even count is made odd. try testing.expectEqualStrings("_7C/.abcdpsRgFoP9Jr2", try hashTo(&buf, bsdi_crypt, "password", .{ .salt = "abcd", .rounds = 5000 })); try testing.expectEqualStrings("_/...abcd1RKQdUOHv.s", try hashTo(&buf, bsdi_crypt, "a longer password", .{ .salt = "abcd", .rounds = 1 })); try testing.expectEqualStrings("abUXTrsTSbDWcGgbIny2UYmwihtGHOhYsC.", try hashTo(&buf, bigcrypt, "This is very long passwd", .{ .salt = "ab" })); try testing.expectEqualStrings("abMi9VfflX1iMmF1QH4PEr.E", try hashTo(&buf, crypt16, "password", .{ .salt = "ab" })); try testing.expectEqualStrings("abNlMs2u9NEcUPl0hGp6sEVQ", try hashTo(&buf, crypt16, "pass\x00word0123456789", .{ .salt = "ab" })); } test "round trips with random salts" { var buf: [64]u8 = undefined; inline for (schemes) |S| { const h = try hashTo(&buf, S, "hunter2 and more", .{}); try testing.expect(S.identify(h)); try testing.expect(try S.verify(test_ctx, "hunter2 and more", h)); try testing.expect(!try S.verify(test_ctx, "hunter3", h)); try testing.expect(!try S.needsUpdate(h, .{})); } } test "passlib's regular expressions, quirks included" { // Python's `$` matches before a trailing newline, and passlib's // `from_string` for these three then ignores it. try testing.expect(bsdi_crypt.identify("_7C/.abcdpsRgFoP9Jr2\n")); try testing.expect(try bsdi_crypt.verify(test_ctx, "password", "_7C/.abcdpsRgFoP9Jr2\n")); try testing.expect(try bigcrypt.verify(test_ctx, "password", "abJnggxhB/yWI\n")); try testing.expect(try crypt16.verify(test_ctx, "password", "abMi9VfflX1iMmF1QH4PEr.E\n")); // des_crypt's `from_string` does not use the expression, and refuses it. try testing.expect(des_crypt.identify("abJnggxhB/yWI\n")); try testing.expectError(error.MalformedHash, des_crypt.verify(test_ctx, "password", "abJnggxhB/yWI\n")); // The Kelvin sign matches `k` case-insensitively. try testing.expect(des_crypt.identify("a\xe2\x84\xaa")); try testing.expectError(error.MalformedHash, des_crypt.verify(test_ctx, "x", "a\xe2\x84\xaa")); // A configuration string identifies and has nothing to verify against. try testing.expect(des_crypt.identify("ab")); try testing.expect(bigcrypt.identify("ab")); try testing.expectError(error.MalformedHash, des_crypt.verify(test_ctx, "x", "ab")); try testing.expect(!try des_crypt.needsUpdate("ab", .{})); try testing.expectError(error.MalformedHash, bigcrypt.verify(test_ctx, "x", "ab" ++ "a" ** 12)); } test "bsdi_crypt rounds" { // passlib: needs_update is true for an even count, "_0..." being 2. try testing.expect(try bsdi_crypt.needsUpdate("_0...abcdpsRgFoP9Jr2", .{})); try testing.expect(!try bsdi_crypt.verify(test_ctx, "password", "_0...abcdpsRgFoP9Jr2")); try testing.expect(try bsdi_crypt.needsUpdate("_7C/.abcdpsRgFoP9Jr2", .{ .min_desired_rounds = 6000 })); try testing.expect(try bsdi_crypt.needsUpdate("_7C/.abcdpsRgFoP9Jr2", .{ .max_desired_rounds = 5000 })); // Zero rounds is identified and refused. try testing.expect(bsdi_crypt.identify("_....abcdpsRgFoP9Jr2")); try testing.expectError(error.MalformedHash, bsdi_crypt.verify(test_ctx, "x", "_....abcdpsRgFoP9Jr2")); var buf: [64]u8 = undefined; try testing.expectError(error.InvalidOptions, hashTo(&buf, bsdi_crypt, "x", .{ .rounds = 0 })); try testing.expectError(error.InvalidOptions, hashTo(&buf, bsdi_crypt, "x", .{ .rounds = 1 << 24 })); } test "refusals" { var buf: [64]u8 = undefined; try testing.expectError(error.PasswordTooLong, hashTo(&buf, des_crypt, "123456789", .{ .truncate_error = true })); try testing.expectError(error.PasswordTooLong, hashTo(&buf, crypt16, "12345678901234567", .{ .truncate_error = true })); try testing.expectError(error.InvalidPassword, hashTo(&buf, des_crypt, "a\x00b", .{})); try testing.expectError(error.InvalidPassword, hashTo(&buf, bsdi_crypt, "a\x00b", .{})); try testing.expectError(error.InvalidPassword, hashTo(&buf, bigcrypt, "12345678a\x00b", .{})); try testing.expectError(error.InvalidOptions, hashTo(&buf, des_crypt, "x", .{ .salt = "a!" })); try testing.expectError(error.InvalidOptions, hashTo(&buf, des_crypt, "x", .{ .salt = "abc" })); try testing.expectError(error.MalformedHash, des_crypt.verify(test_ctx, "x", "a")); try testing.expectError(error.MalformedHash, des_crypt.verify(test_ctx, "x", "abJnggxhB/yW!")); }