diff --git a/build.zig b/build.zig index 69fd77b..0634bbc 100644 --- a/build.zig +++ b/build.zig @@ -23,13 +23,17 @@ pub fn build(b: *std.Build) void { "vector-scheme", "Run only this scheme's rows of the passlib vectors", )); + // Always at least ReleaseSafe: the tables include Argon2 at 64 MiB and + // bcrypt at cost 12, which take most of a minute in a Debug build, and + // ReleaseSafe keeps every check that makes a failure a failure. + const vector_optimize: std.builtin.OptimizeMode = if (optimize == .Debug) .ReleaseSafe else optimize; const vector_tests = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("tests/vectors.zig"), .target = target, - .optimize = optimize, + .optimize = vector_optimize, .imports = &.{ - .{ .name = "passlib", .module = mod }, + .{ .name = "passlib", .module = passlibModule(b, target, vector_optimize, false) }, .{ .name = "vector_options", .module = vector_options.createModule() }, }, }), @@ -84,6 +88,31 @@ pub fn build(b: *std.Build) void { }) }}, }), }); + // The converse of the vectors: hashes made here, checked by passlib + // 1.7.4 itself. It needs the devshell's python, so it is a step of its + // own rather than part of `test`. + const crosscheck = b.addExecutable(.{ + .name = "zig-passlib-crosscheck", + .root_module = b.createModule(.{ + .root_source_file = b.path("tools/crosscheck.zig"), + .target = b.graph.host, + .optimize = .ReleaseSafe, + .imports = &.{ + .{ .name = "passlib", .module = fuzz_run.root_module.import_table.get("fuzz_targets").?.import_table.get("passlib").? }, + .{ .name = "fuzz_targets", .module = fuzz_run.root_module.import_table.get("fuzz_targets").? }, + }, + }), + }); + const run_crosscheck = b.addRunArtifact(crosscheck); + const hashes = run_crosscheck.addOutputFileArg("hashes.tsv"); + const run_passlib = b.addSystemCommand(&.{"python3"}); + run_passlib.addFileArg(b.path("tools/crosscheck.py")); + run_passlib.addFileArg(hashes); + run_passlib.has_side_effects = true; + const crosscheck_step = b.step("crosscheck", "Have passlib 1.7.4 verify hashes made here (needs the devshell)"); + crosscheck_step.dependOn(&run_passlib.step); + check_step.dependOn(&crosscheck.step); + const run_fuzz = b.addRunArtifact(fuzz_run); run_fuzz.stdio = .inherit; if (b.args) |a| run_fuzz.addArgs(a); diff --git a/tests/fuzz.zig b/tests/fuzz.zig index edb187f..e482c03 100644 --- a/tests/fuzz.zig +++ b/tests/fuzz.zig @@ -88,7 +88,7 @@ fn fuzzParse(_: void, smith: *Smith) !void { /// Settings that keep each costly scheme at its cheapest, so that the round /// trip exercises every scheme and not only the fast ones. -fn hashCheap(scheme: *const passlib.Scheme, ctx: passlib.Context, password: []const u8, w: *std.Io.Writer) !void { +pub fn hashCheap(scheme: *const passlib.Scheme, ctx: passlib.Context, password: []const u8, w: *std.Io.Writer) !void { const h = passlib.hash; inline for (.{ .{ "bcrypt", h.bcrypt, .{ .rounds = 4 } }, diff --git a/tools/crosscheck.py b/tools/crosscheck.py new file mode 100644 index 0000000..2089faa --- /dev/null +++ b/tools/crosscheck.py @@ -0,0 +1,70 @@ +# SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie +# SPDX-License-Identifier: MIT + +"""Asks passlib 1.7.4 to verify the hashes tools/crosscheck.zig made. + +Each line is `scheme, hex(password), user, realm, hex(hash)`, tab-separated. +Every hash must verify with passlib under the same scheme, and a password +that differs from it must not. The schemes that verify nothing +(unix_disabled, unix_fallback, django_disabled) must verify nothing. +""" + +import os +import sys +import warnings + +warnings.simplefilter("ignore") +# passlib 1.7.4 cannot drive the bcrypt package nixpkgs has; see flake.nix. +os.environ["PASSLIB_BUILTIN_BCRYPT"] = "enabled" + +import passlib +from passlib.registry import get_crypt_handler + +assert passlib.__version__ == "1.7.4", passlib.__version__ + +DISABLED = {"unix_disabled", "unix_fallback", "django_disabled"} + + +def main(path): + failures = 0 + checked = 0 + with open(path) as f: + for line in f: + scheme, password, user, realm, hash = line.rstrip("\n").split("\t") + password = bytes.fromhex(password) + hash = bytes.fromhex(hash).decode("utf-8") + handler = get_crypt_handler(scheme) + context = set(getattr(handler, "context_kwds", ())) + kwds = {} + if "user" in context: + kwds["user"] = user + if "realm" in context: + kwds["realm"] = realm + try: + ok = handler.verify(password, hash, **kwds) + except Exception as e: + ok = "%s: %s" % (type(e).__name__, e) + want = scheme not in DISABLED + checked += 1 + if ok is not want: + failures += 1 + print("%s: passlib says %r for %r, password %r" % (scheme, ok, hash, password)) + continue + # A leading byte every scheme sees: it shifts the eight bytes DES + # crypt reads and the 72 bcrypt reads, lmhash's upper-casing + # leaves it alone, and it is printable, which SASLprep insists + # on. + wrong = b"Q" + password + try: + bad = handler.verify(wrong, hash, **kwds) + except Exception as e: + bad = "%s: %s" % (type(e).__name__, e) + if bad is not False: + failures += 1 + print("%s: passlib says %r for %r, wrong password %r" % (scheme, bad, hash, wrong)) + print("%d hashes checked, %d failures" % (checked, failures)) + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1])) diff --git a/tools/crosscheck.zig b/tools/crosscheck.zig new file mode 100644 index 0000000..976b08b --- /dev/null +++ b/tools/crosscheck.zig @@ -0,0 +1,99 @@ +// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie +// SPDX-License-Identifier: MIT + +//! Hashes made here, for passlib to check: the other half of the vectors. +//! +//! `tests/vectors.zig` shows that this library reads what passlib wrote. +//! This shows the converse. Every scheme hashes a spread of passwords with +//! random salts, at its cheapest settings, and writes one line per hash to +//! the file named on the command line: +//! +//! ``` +//! scheme hex(password) user realm hex(hash) +//! ``` +//! +//! `tools/crosscheck.py` then asks passlib 1.7.4 to verify each one. +//! `zig build crosscheck` runs both. + +const std = @import("std"); +const passlib = @import("passlib"); +const targets = @import("fuzz_targets"); + +/// Passwords worth trying: empty, ASCII, the characters that separate a +/// hash's fields, and text that is not ASCII, including characters SASLprep +/// maps and the NT hash needs surrogates for. +const fixed_passwords = [_][]const u8{ + "", + "password", + "Tr0ub4dor&3", + "$:{}=,.", + "\xc3\xa9t\xc3\xa9", + "\xe2\x82\xac\xc2\xa5$", + "\xe4\xb8\xad\xe6\x96\x87", + "\xf0\x9f\x98\x80", + "a" ** 80, +}; + +const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 !#%&*+-./:;<=>?@^_~"; + +pub fn main(init: std.process.Init) !void { + const io = init.io; + const gpa = init.gpa; + + var args: std.process.Args.Iterator = .init(init.minimal.args); + _ = args.skip(); + const path = args.next() orelse { + std.debug.print("usage: crosscheck OUTPUT\n", .{}); + std.process.exit(2); + }; + + var file = try std.Io.Dir.cwd().createFile(io, path, .{}); + defer file.close(io); + var file_buffer: [4096]u8 = undefined; + var fw = file.writer(io, &file_buffer); + const out = &fw.interface; + + targets.backing = gpa; + targets.io = io; + + var seed: u64 = undefined; + io.random(std.mem.asBytes(&seed)); + var prng: std.Random.DefaultPrng = .init(seed); + const random = prng.random(); + + var written: usize = 0; + var refused: usize = 0; + for (&passlib.registry.all) |*scheme| { + var random_passwords: [4][24]u8 = undefined; + var passwords: [fixed_passwords.len + random_passwords.len][]const u8 = undefined; + for (fixed_passwords, 0..) |p, i| passwords[i] = p; + for (&random_passwords, 0..) |*buf, i| { + const len = random.uintLessThan(usize, buf.len); + for (buf[0..len]) |*c| c.* = alphabet[random.uintLessThan(usize, alphabet.len)]; + passwords[fixed_passwords.len + i] = buf[0..len]; + } + + for (passwords, 0..) |password, i| { + // passlib hashes the empty password to the empty string under + // ldap_plaintext and then refuses that string, and so does this + // port, so there is nothing to ask it. + if (std.mem.eql(u8, scheme.name, "ldap_plaintext") and password.len == 0) continue; + var user_buf: [16]u8 = undefined; + const user = try std.fmt.bufPrint(&user_buf, "user{d}", .{i}); + const ctx: passlib.Context = .{ .io = io, .gpa = gpa, .user = user, .realm = "realm" }; + var hash_buf: [2048]u8 = undefined; + var w: std.Io.Writer = .fixed(&hash_buf); + targets.hashCheap(scheme, ctx, password, &w) catch |err| switch (err) { + error.InvalidPassword, error.PasswordTooLong => { + refused += 1; + continue; + }, + else => return err, + }; + try out.print("{s}\t{x}\t{s}\t{s}\t{x}\n", .{ scheme.name, password, user, "realm", w.buffered() }); + written += 1; + } + } + try out.flush(); + std.debug.print("{d} hashes written, {d} passwords refused by their scheme\n", .{ written, refused }); +}