// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What every scheme has in common: the shape of its API, the errors it //! returns, and the helpers it is built from. //! //! ## The shape of a scheme //! //! A scheme is a namespace, not a value. `passlib.hash.sha512_crypt` is a //! struct with these declarations, which `check` enforces at compile time: //! //! ```zig //! pub const name: []const u8; //! pub const Options: type; // a struct whose every field has a default //! pub fn identify(hash: []const u8) bool; //! pub fn hash(ctx: Context, password: []const u8, options: Options, w: *std.Io.Writer) Error!void; //! pub fn verify(ctx: Context, password: []const u8, hash: []const u8) Error!bool; //! pub fn needsUpdate(hash: []const u8, options: Options) Error!bool; //! ``` //! //! `Options` is passlib's `using()` settings: `rounds`, `salt_size`, `ident` //! and so on, each defaulting to what passlib 1.7.4 defaults it to. A `salt` //! option, where a scheme has one, fixes the salt rather than drawing a //! random one, which is how the tests reproduce passlib's output byte for //! byte. //! //! `verify` returns false for a wrong password and `error.MalformedHash` for //! a hash this scheme cannot parse, which is what passlib's //! `ValueError` becomes. `needsUpdate` is passlib's handler-level //! `needs_update`: true when the hash was made with settings weaker than, or //! different from, the ones `options` asks for. The fields it compares are //! documented on each scheme. //! //! `registry.zig` turns each namespace into a `Scheme`, a table of function //! pointers using the default options, for code that finds out which scheme //! it has only at run time. const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const testing = std.testing; /// What a hash is computed in. /// /// The `Io` supplies random salts and, for Argon2, the threads its lanes run /// on. The allocator is for the schemes whose working memory is the point: /// scrypt and Argon2 allocate their tables, and a few formats convert the /// password to UTF-16. `user` and `realm` are the context passlib passes to /// the schemes that salt with who the password belongs to: `postgres_md5`, /// `oracle10`, `msdcc`, `msdcc2` and `htdigest`. Those return /// `error.MissingUser` or `error.MissingRealm` without them, and /// `error.InvalidUser` for a user name they cannot use; every other scheme /// ignores them. pub const Context = struct { io: Io, gpa: Allocator, user: ?[]const u8 = null, realm: ?[]const u8 = null, }; /// Every error a scheme can return. pub const Error = error{ /// The hash is not one this scheme can parse: the wrong format, a /// character outside its alphabet, a field out of range. passlib raises /// `ValueError` for these. MalformedHash, /// An `Options` field is out of the range the scheme accepts: too few /// rounds, a salt of the wrong length or alphabet, an unknown ident. InvalidOptions, /// The scheme salts with the user name and `Context.user` was null. MissingUser, /// The user name in `Context.user` cannot be used: for example, it is /// not valid UTF-8 where the scheme needs text. InvalidUser, /// The scheme salts with the realm and `Context.realm` was null. MissingRealm, /// The password cannot be hashed by this scheme: it is not valid UTF-8 /// where the scheme needs characters, it holds a NUL the scheme cannot /// carry, or SASLprep prohibits one of its characters. InvalidPassword, /// The password is longer than `max_password_len`, or than the scheme /// can take and it was asked to refuse rather than truncate. passlib's /// `PasswordSizeError` and `PasswordTruncateError`. PasswordTooLong, } || Io.Writer.Error || Allocator.Error || Io.RandomSecureError || std.crypto.pwhash.KdfError; /// passlib's `MAX_PASSWORD_SIZE`: the longest password any scheme will /// hash. Past it, `error.PasswordTooLong`. It exists so that a hostile /// multi-megabyte password cannot make a slow hash slower. pub const max_password_len = 4096; pub fn checkPasswordLen(password: []const u8) Error!void { if (password.len > max_password_len) return error.PasswordTooLong; } /// Checks at compile time that `S` has the declarations a scheme must have, /// with the types it must have them at. A scheme that drifts from the /// contract is a compile error that names it rather than a registry entry /// that fails to build somewhere else. pub fn check(comptime S: type) void { const where = @typeName(S); inline for (.{ "name", "Options", "identify", "hash", "verify", "needsUpdate" }) |decl| { if (!@hasDecl(S, decl)) @compileError(where ++ " has no `" ++ decl ++ "`"); } _ = @as([]const u8, S.name); _ = @as(S.Options, .{}); _ = @as(fn ([]const u8) bool, S.identify); _ = @as(fn (Context, []const u8, S.Options, *Io.Writer) Error!void, S.hash); _ = @as(fn (Context, []const u8, []const u8) Error!bool, S.verify); _ = @as(fn ([]const u8, S.Options) Error!bool, S.needsUpdate); } /// Constant-time equality of two byte strings. Different lengths compare /// unequal at once, since a length is public: it is part of the format. pub fn eql(a: []const u8, b: []const u8) bool { if (a.len != b.len) return false; var diff: u8 = 0; for (a, b) |x, y| diff |= x ^ y; return diff == 0; } /// `len` random characters of `chars` into `buf`, for a salt, drawn from /// `io`'s secure source. Uniform: a byte that would favour some characters /// over others is drawn again. pub fn randomChars(io: Io, buf: []u8, comptime chars: []const u8) Error![]u8 { comptime std.debug.assert(chars.len > 0 and chars.len <= 256); const limit = 256 - (256 % chars.len); var pool: [64]u8 = undefined; var used: usize = pool.len; for (buf) |*c| { while (true) { if (used == pool.len) { try io.randomSecure(&pool); used = 0; } const r = pool[used]; used += 1; if (r < limit) { c.* = chars[r % chars.len]; break; } } } return buf; } /// `buf.len` random bytes from `io`'s secure source. pub fn randomBytes(io: Io, buf: []u8) Error![]u8 { try io.randomSecure(buf); return buf; } /// `password`, which must be UTF-8, as UTF-16LE bytes, for the Windows and /// SQL Server formats. The caller frees the result. pub fn utf16le(gpa: Allocator, password: []const u8) Error![]u8 { // Validated first because `calcUtf16LeLen` in Zig 0.16.0 slices past the // end of its input when the last sequence is cut short, which is an // index-out-of-bounds panic rather than an error. The fuzzer found it. if (!std.unicode.utf8ValidateSlice(password)) return error.InvalidPassword; const len = std.unicode.calcUtf16LeLen(password) catch return error.InvalidPassword; const units = try gpa.alloc(u16, len); defer gpa.free(units); _ = std.unicode.utf8ToUtf16Le(units, password) catch return error.InvalidPassword; const out = try gpa.alloc(u8, len * 2); for (units, 0..) |u, i| std.mem.writeInt(u16, out[i * 2 ..][0..2], u, .little); return out; } /// Parses a decimal field of a hash: digits only, no sign, no leading `+`, /// and within `T`. Leading zeros are allowed only if `allow_leading_zero`, /// since several formats reject them to keep one hash to one spelling. pub fn parseDecimal(comptime T: type, s: []const u8, allow_leading_zero: bool) Error!T { if (s.len == 0) return error.MalformedHash; if (!allow_leading_zero and s.len > 1 and s[0] == '0') return error.MalformedHash; for (s) |c| if (c < '0' or c > '9') return error.MalformedHash; return std.fmt.parseInt(T, s, 10) catch error.MalformedHash; } /// Splits `s` at every `sep` into exactly `N` fields, or /// `error.MalformedHash` if there are more or fewer. pub fn splitExact(comptime N: usize, s: []const u8, sep: u8) Error![N][]const u8 { var out: [N][]const u8 = undefined; var it = std.mem.splitScalar(u8, s, sep); for (&out) |*field| field.* = it.next() orelse return error.MalformedHash; if (it.next() != null) return error.MalformedHash; return out; } /// The settings `needsUpdate` compares for a scheme with a rounds count: /// passlib's `min_desired_rounds` and `max_desired_rounds`. A hash whose /// rounds fall outside either bound needs updating. /// /// The bounds are optionals of any unsigned width, so that each scheme can /// declare them at the width of its own rounds field. pub fn roundsOutside(rounds: u64, min_desired: anytype, max_desired: anytype) bool { if (min_desired) |m| if (rounds < m) return true; if (max_desired) |m| if (rounds > m) return true; return false; } /// The longest hash `PrefixWrapper` will rewrite. Well past the longest /// hash any scheme here writes; a longer string is refused as malformed. pub const max_wrapped_len = 4096; /// passlib's `PrefixWrapper`: `Inner`'s hashes with `orig_prefix` replaced by /// `prefix`. It is how `ldap_md5_crypt` is `md5_crypt` behind `{CRYPT}`, and /// how several PBKDF2 and Django formats are other schemes renamed. /// /// `Options` are `Inner`'s. A hash is claimed only if it starts with /// `prefix` and `Inner` claims what is left once `orig_prefix` is put back. pub fn PrefixWrapper( comptime scheme_name: []const u8, comptime Inner: type, comptime prefix: []const u8, comptime orig_prefix: []const u8, ) type { check(Inner); return struct { pub const name = scheme_name; pub const Options = Inner.Options; pub const Wrapped = Inner; /// `orig_prefix` followed by `h` without `prefix`, in `buf`. fn unwrap(buf: *[max_wrapped_len]u8, h: []const u8) ?[]const u8 { if (!std.mem.startsWith(u8, h, prefix)) return null; const rest = h[prefix.len..]; if (orig_prefix.len + rest.len > buf.len) return null; @memcpy(buf[0..orig_prefix.len], orig_prefix); @memcpy(buf[orig_prefix.len..][0..rest.len], rest); return buf[0 .. orig_prefix.len + rest.len]; } pub fn identify(h: []const u8) bool { var buf: [max_wrapped_len]u8 = undefined; const inner = unwrap(&buf, h) orelse return false; return Inner.identify(inner); } pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { var buf: [max_wrapped_len]u8 = undefined; var inner: Io.Writer = .fixed(&buf); try Inner.hash(ctx, password, options, &inner); const out = inner.buffered(); // The inner scheme wrote a hash that does not start the way this // wrapper was declared to expect: a mistake in the declaration. std.debug.assert(std.mem.startsWith(u8, out, orig_prefix)); try w.writeAll(prefix); try w.writeAll(out[orig_prefix.len..]); } pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { var buf: [max_wrapped_len]u8 = undefined; const inner = unwrap(&buf, h) orelse return error.MalformedHash; return Inner.verify(ctx, password, inner); } pub fn needsUpdate(h: []const u8, options: Options) Error!bool { var buf: [max_wrapped_len]u8 = undefined; const inner = unwrap(&buf, h) orelse return error.MalformedHash; return Inner.needsUpdate(inner, options); } }; } /// `Inner` with different default options: passlib's `Inner.using(...)`. /// /// `defaults` becomes the default value of `Options`, so that the registry, /// which hashes with `.{}`, gets these settings. Everything else is /// `Inner`'s, including its name. pub fn Using(comptime Inner: type, comptime defaults: Inner.Options) type { check(Inner); return struct { pub const name = Inner.name; pub const Wrapped = Inner; pub const Options = blk: { const fields = @typeInfo(Inner.Options).@"struct".fields; var names: [fields.len][]const u8 = undefined; var types: [fields.len]type = undefined; var attrs: [fields.len]std.builtin.Type.StructField.Attributes = undefined; for (fields, 0..) |f, i| { names[i] = f.name; types[i] = f.type; attrs[i] = .{ .default_value_ptr = @ptrCast(&@field(defaults, f.name)) }; } break :blk @Struct(.auto, null, &names, &types, &attrs); }; fn inner(options: Options) Inner.Options { var out: Inner.Options = undefined; inline for (@typeInfo(Inner.Options).@"struct".fields) |f| { @field(out, f.name) = @field(options, f.name); } return out; } pub fn identify(h: []const u8) bool { return Inner.identify(h); } pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { return Inner.hash(ctx, password, inner(options), w); } pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { return Inner.verify(ctx, password, h); } pub fn needsUpdate(h: []const u8, options: Options) Error!bool { return Inner.needsUpdate(h, inner(options)); } }; } test "eql" { try testing.expect(eql("abc", "abc")); try testing.expect(!eql("abc", "abd")); try testing.expect(!eql("abc", "ab")); } test "randomChars stays in its alphabet" { var buf: [200]u8 = undefined; const got = try randomChars(testing.io, &buf, "abc"); for (got) |c| try testing.expect(c == 'a' or c == 'b' or c == 'c'); } test "utf16le" { const out = try utf16le(testing.allocator, "p\xc3\xa9"); defer testing.allocator.free(out); try testing.expectEqualSlices(u8, "p\x00\xe9\x00", out); try testing.expectError(error.InvalidPassword, utf16le(testing.allocator, "\xff")); // A sequence cut short at the end, which std's length calculation does // not survive on its own. try testing.expectError(error.InvalidPassword, utf16le(testing.allocator, "ab\xe2\x82")); } test "splitExact" { const f = try splitExact(3, "a$b$c", '$'); try testing.expectEqualStrings("b", f[1]); try testing.expectError(error.MalformedHash, splitExact(3, "a$b", '$')); try testing.expectError(error.MalformedHash, splitExact(3, "a$b$c$d", '$')); } test "parseDecimal" { try testing.expectEqual(@as(u32, 5000), try parseDecimal(u32, "5000", false)); try testing.expectError(error.MalformedHash, parseDecimal(u32, "05000", false)); try testing.expectEqual(@as(u32, 5000), try parseDecimal(u32, "05000", true)); try testing.expectError(error.MalformedHash, parseDecimal(u32, "+5", false)); try testing.expectError(error.MalformedHash, parseDecimal(u8, "300", false)); try testing.expectError(error.MalformedHash, parseDecimal(u8, "", false)); } test "PrefixWrapper" { const md5_crypt = @import("schemes/md5_crypt.zig").md5_crypt; const W = PrefixWrapper("wrapped", md5_crypt, "{X}", "$1$"); check(W); const ctx: Context = .{ .io = testing.io, .gpa = testing.allocator }; var buf: [64]u8 = undefined; var w: Io.Writer = .fixed(&buf); try W.hash(ctx, "test", .{ .salt = "test" }, &w); try testing.expectEqualStrings("{X}test$pi/xDtU5WFVRqYS6BMU8X/", w.buffered()); try testing.expect(W.identify(w.buffered())); try testing.expect(!W.identify("$1$test$pi/xDtU5WFVRqYS6BMU8X/")); try testing.expect(try W.verify(ctx, "test", w.buffered())); try testing.expectError(error.MalformedHash, W.verify(ctx, "test", "$1$test$pi/xDtU5WFVRqYS6BMU8X/")); } test "Using" { const md5_crypt = @import("schemes/md5_crypt.zig").md5_crypt; const Short = Using(md5_crypt, .{ .salt_size = 4 }); check(Short); const ctx: Context = .{ .io = testing.io, .gpa = testing.allocator }; var buf: [64]u8 = undefined; var w: Io.Writer = .fixed(&buf); try Short.hash(ctx, "test", .{}, &w); // "$1$" + four salt characters + "$" + 22. try testing.expectEqual(@as(usize, 3 + 4 + 1 + 22), w.buffered().len); }