// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Sun MD5-Crypt: passlib's `passlib.handlers.sun_md5_crypt`. //! //! The `$md5$` format Sun introduced in Solaris 9 Update 2, 2003, and //! documented only by its source in OpenSolaris. It runs MD5 for 4096 rounds //! plus a configurable number more, and on each round a "coin flip" drawn //! from bits of the previous digest decides whether a fixed passage of //! Hamlet, act 3 scene 1, is mixed in along with the round number. //! //! A hash is `$md5$` for no extra rounds, or `$md5,rounds=N$` for `N`, then //! a salt, then `$$` and a 22-character checksum. Everything before the //! checksum but its last `$` is what is hashed as the salt. Some hashes in //! the wild have a single `$` before the checksum; for those, the "bare //! salt" ones, the salt is hashed without a trailing `$`. They verify here, //! as they do in passlib, but passlib 1.7.4 has no way to write one, and //! neither does this. //! //! **It is obsolete.** It was replaced on Solaris by the SHA-crypt formats, //! and its design had no review outside Sun. It is here to check passwords //! already stored with it. const std = @import("std"); const Io = std.Io; const Md5 = std.crypto.hash.Md5; const testing = std.testing; const encoding = @import("../encoding.zig"); const h64 = encoding.h64; const handler = @import("../handler.zig"); const Context = handler.Context; const Error = handler.Error; pub const min_rounds = 0; /// passlib's bound: the most extra rounds for which the total, 4096 more, /// still fits in 32 bits. pub const max_rounds = std.math.maxInt(u32) - 4096; pub const default_salt_len = 8; const checksum_len = 22; /// The passage mixed into a round when its coin flip comes up one: Hamlet, /// act 3 scene 1, from Project Gutenberg's etext, and the NUL that ends the /// C string holding it in Sun's source. const magic_hamlet = \\To be, or not to be,--that is the question:-- \\Whether 'tis nobler in the mind to suffer \\The slings and arrows of outrageous fortune \\Or to take arms against a sea of troubles, \\And by opposing end them?--To die,--to sleep,-- \\No more; and by a sleep to say we end \\The heartache, and the thousand natural shocks \\That flesh is heir to,--'tis a consummation \\Devoutly to be wish'd. To die,--to sleep;-- \\To sleep! perchance to dream:--ay, there's the rub; \\For in that sleep of death what dreams may come, \\When we have shuffled off this mortal coil, \\Must give us pause: there's the respect \\That makes calamity of so long life; \\For who would bear the whips and scorns of time, \\The oppressor's wrong, the proud man's contumely, \\The pangs of despis'd love, the law's delay, \\The insolence of office, and the spurns \\That patient merit of the unworthy takes, \\When he himself might his quietus make \\With a bare bodkin? who would these fardels bear, \\To grunt and sweat under a weary life, \\But that the dread of something after death,-- \\The undiscover'd country, from whose bourn \\No traveller returns,--puzzles the will, \\And makes us rather bear those ills we have \\Than fly to others that we know not of? \\Thus conscience does make cowards of us all; \\And thus the native hue of resolution \\Is sicklied o'er with the pale cast of thought; \\And enterprises of great pith and moment, \\With this regard, their currents turn awry, \\And lose the name of action.--Soft you now! \\The fair Ophelia!--Nymph, in thy orisons \\Be all my sins remember'd. ++ "\n\x00"; /// The order the digest's bytes are encoded in: the same as MD5-crypt's. const transpose = [_]u8{ 12, 6, 0, 13, 7, 1, 14, 8, 2, 15, 9, 3, 5, 10, 4, 11 }; /// The digest bytes each of the seven bits of a round's `x` index is drawn /// from, as `{ ia, ib }` pairs. A bit of the previous digest chooses which /// of the two tables a round uses. const x_rounds: [2][7][2]u8 = blk: { var t: [2][7][2]u8 = undefined; for (0..7) |i| { t[0][i] = .{ i, i + 3 }; t[1][i] = .{ i + 1, i + 4 }; } break :blk t; }; /// As `x_rounds`, for a round's `y` index. const y_rounds: [2][7][2]u8 = blk: { var t: [2][7][2]u8 = undefined; for (0..7) |i| { t[0][i] = .{ i + 8, (i + 11) & 15 }; t[1][i] = .{ (i + 9) & 15, (i + 12) & 15 }; } break :blk t; }; /// Bit `bit` of the 128-bit digest `r`, counting from the low bit of byte 0. fn digestBit(r: *const [16]u8, bit: u8) u1 { return @truncate(r[(bit >> 3) & 15] >> @as(u3, @truncate(bit))); } /// A seven-bit index into the digest's bits, built from the pairs in /// `table` as Sun's source does, with passlib's inlining of it. fn bitIndex(r: *const [16]u8, table: *const [7][2]u8) u8 { var out: u8 = 0; for (table, 0..) |pair, i| { const a = r[pair[0]]; const b = r[pair[1]]; const v = r[(a >> @as(u3, @intCast(b % 5))) & 15] >> @as(u1, @truncate(b >> @as(u3, @truncate(a)))); out |= @as(u8, digestBit(r, v)) << @as(u3, @intCast(i)); } return out; } /// The parts of a hash or configuration string. const Parsed = struct { rounds: u32, salt: []const u8, /// Whether the salt is hashed without a trailing `$`. bare_salt: bool, /// Null for a configuration string, which has no checksum. checksum: ?[]const u8, }; /// The 22-character checksum for `password` under the configuration /// `rounds`, `salt` and `bare_salt`. fn compute(password: []const u8, rounds: u32, salt: []const u8, bare_salt: bool, out: *[checksum_len]u8) void { var result: [Md5.digest_length]u8 = undefined; var first = Md5.init(.{}); first.update(password); // The configuration string, as passlib renders it, is the salt. var prefix_buf: [32]u8 = undefined; const prefix = if (rounds > 0) std.fmt.bufPrint(&prefix_buf, "$md5,rounds={d}$", .{rounds}) catch unreachable else "$md5$"; first.update(prefix); first.update(salt); if (!bare_salt) first.update("$"); first.final(&result); const real_rounds: u64 = 4096 + @as(u64, rounds); var round: u64 = 0; while (round < real_rounds) : (round += 1) { const shift: u3 = @truncate(round); const x_sel: u1 = @truncate(result[@as(usize, @truncate(round >> 3)) & 15] >> shift); const y_sel: u1 = @truncate(result[@as(usize, @truncate((round + 64) >> 3)) & 15] >> shift); const x = bitIndex(&result, &x_rounds[x_sel]); const y = bitIndex(&result, &y_rounds[y_sel]); const coin = digestBit(&result, x) ^ digestBit(&result, y); var h = Md5.init(.{}); h.update(&result); if (coin != 0) h.update(magic_hamlet); var digits: [20]u8 = undefined; h.update(std.fmt.bufPrint(&digits, "{d}", .{round}) catch unreachable); h.final(&result); } _ = h64.encodeTransposed(out, &result, &transpose); } pub const sun_md5_crypt = struct { pub const name = "sun_md5_crypt"; pub const Options = struct { /// The salt, of `./0-9A-Za-z` and of any length. Null, the default, /// draws a random one of `salt_size` characters. salt: ?[]const u8 = null, /// The length of a random salt. passlib sets no maximum. salt_size: usize = default_salt_len, /// The number of rounds past the fixed 4096, from 0 to /// 4,294,963,199. rounds: u32 = 34_000, /// `needsUpdate` reports a hash with fewer rounds than this. min_desired_rounds: ?u32 = null, /// `needsUpdate` reports a hash with more rounds than this. max_desired_rounds: ?u32 = null, }; /// A prefix check, as passlib's is: `$md5$` or `$md5,`. pub fn identify(h: []const u8) bool { return std.mem.startsWith(u8, h, "$md5$") or std.mem.startsWith(u8, h, "$md5,"); } /// passlib's `from_string`, whose rules for telling the salt from the /// checksum exist to accept both `$$` and bare-salt hashes and both /// kinds of configuration string. The rounds field must be the /// canonical decimal spelling of a nonzero count. fn parse(h: []const u8) Error!Parsed { var rounds: u64 = 0; var salt_idx: usize = undefined; if (std.mem.startsWith(u8, h, "$md5$")) { salt_idx = "$md5$".len; } else if (std.mem.startsWith(u8, h, "$md5,rounds=")) { const start = "$md5,rounds=".len; const idx = std.mem.findScalarPos(u8, h, start, '$') orelse return error.MalformedHash; rounds = try handler.parseDecimal(u64, h[start..idx], false); if (rounds == 0 or rounds > max_rounds) return error.MalformedHash; salt_idx = idx + 1; } else return error.MalformedHash; var salt: []const u8 = undefined; var checksum: ?[]const u8 = null; var bare_salt = false; if (std.mem.findScalarLast(u8, h[salt_idx..], '$')) |rel| { const chk_idx = salt_idx + rel; if (chk_idx == h.len - 1) { // A configuration string ending in `$`, for a `$$` hash. if (chk_idx > salt_idx and h[h.len - 2] == '$') return error.MalformedHash; salt = h[salt_idx .. h.len - 1]; } else if (h[chk_idx - 1] == '$') { // A `$$` hash. When the salt is empty, the `$` before this // one is the prefix's own, and passlib reads the salt as // empty all the same. salt = h[salt_idx..@max(salt_idx, chk_idx - 1)]; checksum = h[chk_idx + 1 ..]; } else { // A bare-salt hash, with a single `$` before the checksum. salt = h[salt_idx..chk_idx]; checksum = h[chk_idx + 1 ..]; bare_salt = true; } } else { // A configuration string with no trailing `$`, for a bare-salt // hash. salt = h[salt_idx..]; bare_salt = true; } if (!h64.isValid(salt)) return error.MalformedHash; if (checksum) |c| { if (c.len != checksum_len or !h64.isValid(c)) return error.MalformedHash; } return .{ .rounds = @intCast(rounds), .salt = salt, .bare_salt = bare_salt, .checksum = checksum }; } pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { try handler.checkPasswordLen(password); if (options.rounds > max_rounds) return error.InvalidOptions; var owned: ?[]u8 = null; defer if (owned) |o| ctx.gpa.free(o); const salt = if (options.salt) |s| blk: { if (!h64.isValid(s)) return error.InvalidOptions; break :blk s; } else blk: { const buf = try ctx.gpa.alloc(u8, options.salt_size); owned = buf; break :blk try handler.randomChars(ctx.io, buf, encoding.hash64_chars); }; var checksum: [checksum_len]u8 = undefined; compute(password, options.rounds, salt, false, &checksum); if (options.rounds > 0) { try w.print("$md5,rounds={d}${s}$${s}", .{ options.rounds, salt, checksum }); } else { try w.print("$md5${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); // A configuration string has nothing to compare against. const expected = parsed.checksum orelse return error.MalformedHash; var checksum: [checksum_len]u8 = undefined; compute(password, parsed.rounds, parsed.salt, parsed.bare_salt, &checksum); return handler.eql(expected, &checksum); } /// True when the hash's rounds fall outside `min_desired_rounds` and /// `max_desired_rounds`. Like passlib's, it accepts a configuration /// string as well as a hash. pub fn needsUpdate(h: []const u8, options: Options) Error!bool { const lo = options.min_desired_rounds; const hi = options.max_desired_rounds; // passlib's `using()` refuses these. if (lo) |r| if (r > max_rounds) return error.InvalidOptions; if (hi) |r| if (r > max_rounds) return error.InvalidOptions; if (lo) |l| if (hi) |u| if (u < l) return error.InvalidOptions; const parsed = try parse(h); return handler.roundsOutside(parsed.rounds, lo, hi); } }; /// The schemes this module defines, in the order `registry.identify` tries /// them. pub const schemes = .{sun_md5_crypt}; comptime { handler.check(sun_md5_crypt); } const test_ctx: Context = .{ .io = testing.io, .gpa = testing.allocator }; test "the passage is passlib's" { // len(MAGIC_HAMLET) and hashlib.md5(MAGIC_HAMLET).hexdigest() in // passlib 1.7.4. try testing.expectEqual(@as(usize, 1517), magic_hamlet.len); var digest: [Md5.digest_length]u8 = undefined; Md5.hash(magic_hamlet, &digest, .{}); var hex: [32]u8 = undefined; try testing.expectEqualStrings("3425548f2607d3747f134e56bd7a1066", encoding.hexLower(&hex, &digest)); } test "fixed salts reproduce passlib" { // passlib 1.7.4: sun_md5_crypt.using(salt=..., rounds=...).hash(...). const cases = .{ .{ "test", "abc", 0, "$md5$abc$$R22/WJ0bvMXjKsvO6rmi3." }, .{ "test", "abc", 100, "$md5,rounds=100$abc$$T/fUcGfBc0o4d/bM5clot." }, .{ "this", "3UqYqndY", 0, "$md5$3UqYqndY$$6P.aaWOoucxxq.l00SS9k0" }, .{ "t\x00st", "", 0, "$md5$$$v22sfXEKptdOX3C9MXLkB/" }, .{ "test", "abcdefghijklmnopqrstuvwxyz", 1, "$md5,rounds=1$abcdefghijklmnopqrstuvwxyz$$lvSz/Rk5rCrVhe5kBcb.21" }, }; inline for (cases) |c| { var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); try sun_md5_crypt.hash(test_ctx, c[0], .{ .salt = c[1], .rounds = c[2] }, &w); try testing.expectEqualStrings(c[3], w.buffered()); try testing.expect(try sun_md5_crypt.verify(test_ctx, c[0], c[3])); } } test "the quirks of telling salt from checksum" { // A bare-salt hash from passlib's known-answer table. try testing.expect(try sun_md5_crypt.verify(test_ctx, "passwd", "$md5$RPgLF6IJ$WTvAlUJ7MqH5xak2FMEwS/")); // passlib reads `$md5$$` and a checksum as an empty salt followed by its // `$`: the same configuration as `$md5$$$` and a checksum. try testing.expect(try sun_md5_crypt.verify(test_ctx, "test", "$md5$$tAH9M8p.Xqzc7yrW9CJGS1")); try testing.expect(try sun_md5_crypt.verify(test_ctx, "test", "$md5$$$tAH9M8p.Xqzc7yrW9CJGS1")); } test "round trip with a random salt" { var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); try sun_md5_crypt.hash(test_ctx, "hunter2", .{ .rounds = 10 }, &w); const h = w.buffered(); try testing.expectEqual(@as(usize, "$md5,rounds=10$".len + 8 + 2 + 22), h.len); try testing.expect(try sun_md5_crypt.verify(test_ctx, "hunter2", h)); try testing.expect(!try sun_md5_crypt.verify(test_ctx, "hunter3", h)); } test "refusals" { const chk = "a" ** 22; try testing.expectError(error.MalformedHash, sun_md5_crypt.verify(test_ctx, "x", "$md5,rounds=5000")); try testing.expectError(error.MalformedHash, sun_md5_crypt.verify(test_ctx, "x", "$md5,rounds=0$abc$$" ++ chk)); try testing.expectError(error.MalformedHash, sun_md5_crypt.verify(test_ctx, "x", "$md5,rounds=05$abc$$" ++ chk)); try testing.expectError(error.MalformedHash, sun_md5_crypt.verify(test_ctx, "x", "$md5,rounds=+5$abc$$" ++ chk)); try testing.expectError(error.MalformedHash, sun_md5_crypt.verify(test_ctx, "x", "$md5,rounds=4294963200$abc$$" ++ chk)); try testing.expectError(error.MalformedHash, sun_md5_crypt.verify(test_ctx, "x", "$md5,foo")); try testing.expectError(error.MalformedHash, sun_md5_crypt.verify(test_ctx, "x", "$md5$a$b$" ++ chk)); try testing.expectError(error.MalformedHash, sun_md5_crypt.verify(test_ctx, "x", "$md5$abc$$")); try testing.expectError(error.MalformedHash, sun_md5_crypt.verify(test_ctx, "x", "$md5$abc$")); try testing.expectError(error.MalformedHash, sun_md5_crypt.verify(test_ctx, "x", "$md5$abc")); try testing.expectError(error.MalformedHash, sun_md5_crypt.verify(test_ctx, "x", "$md5$abc$$" ++ "a" ** 21)); var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); try testing.expectError(error.InvalidOptions, sun_md5_crypt.hash(test_ctx, "x", .{ .rounds = max_rounds + 1 }, &w)); try testing.expectError(error.InvalidOptions, sun_md5_crypt.hash(test_ctx, "x", .{ .salt = "a$b" }, &w)); } test "needsUpdate" { const h = "$md5$abc$$" ++ "a" ** 22; try testing.expect(!try sun_md5_crypt.needsUpdate(h, .{})); try testing.expect(try sun_md5_crypt.needsUpdate(h, .{ .min_desired_rounds = 5 })); try testing.expect(!try sun_md5_crypt.needsUpdate("$md5,rounds=10$abc$", .{ .min_desired_rounds = 5 })); try testing.expect(try sun_md5_crypt.needsUpdate("$md5,rounds=10$abc", .{ .max_desired_rounds = 5 })); }