Something went wrong. Try again.
passlib's password hash schemes, ported to Zig 0.16
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What every scheme must do with a hash string nobody chose.//!//! A stored hash is input, and it may be damaged or hostile. Whatever it//! holds, `identify`, `needsUpdate` and `verify` must answer or return an//! error: never panic, never read out of bounds, never leak. That is the//! property every target here checks, across every scheme at once.//!//! **What is not fuzzed, and why.** A hash says how expensive it is to check.//! `$2b$31$` is two billion bcrypt rounds, `ln=30` in scrypt is a gigabyte//! times its block size, and an Argon2 `m=` field can ask for terabytes.//! Verifying such a hash is slow or runs out of memory by design, here as in//! passlib, and a fuzzer would spend its time finding exactly that. So//! `verify` is fuzzed only for the schemes whose cost is fixed. For the rest,//! `needsUpdate` runs the same parser without computing anything, and the//! round-trip target hashes with them at their lowest cost.//!//! Each target is an ordinary test as well, run over its seeds by `zig build//! test`, and `zig build fuzz-run` drives them from a loop of our own; see//! `tools/fuzz.zig`.
const builtin = @import("builtin");const std = @import("std");const Allocator = std.mem.Allocator;const testing = std.testing;const Smith = std.testing.Smith;
const passlib = @import("passlib");
/// The allocator the schemes are handed. The standalone driver points it at/// a debug allocator it checks for leaks after every input.pub var backing: Allocator = if (builtin.is_test) testing.allocator else undefined;/// The `Io` the schemes are handed, for random salts. The standalone driver/// sets it to its own.pub var io: std.Io = if (builtin.is_test) testing.io else undefined;
fn context() passlib.Context { return .{ .io = io, .gpa = backing, .user = "user", .realm = "realm" };}
/// The schemes whose cost does not come from the hash, so that verifying any/// string against them is cheap.const fixed_cost = [_][]const u8{ "md5_crypt", "apr_md5_crypt", "des_crypt", "bigcrypt", "crypt16", "hex_md4", "hex_md5", "hex_sha1", "hex_sha256", "hex_sha512", "htdigest", "ldap_md5", "ldap_sha1", "ldap_salted_md5", "ldap_salted_sha1", "ldap_salted_sha256", "ldap_salted_sha512", "ldap_plaintext", "ldap_hex_md5", "ldap_hex_sha1", "ldap_md5_crypt", "ldap_des_crypt", "roundup_plaintext", "plaintext", "unix_disabled", "unix_fallback", "django_salted_md5", "django_salted_sha1", "django_des_crypt", "django_disabled", "mssql2000", "mssql2005", "postgres_md5", "lmhash", "nthash", "bsd_nthash", "msdcc", "mysql323", "mysql41", "oracle10", "oracle11", "cisco_pix", "cisco_asa", "cisco_type7", "cisco_type4", "cisco_type8", "cisco_type9",};
fn isFixedCost(name: []const u8) bool { for (fixed_cost) |n| if (std.mem.eql(u8, n, name)) return true; return false;}
// -- parsing ---------------------------------------------------------------
/// Every scheme's `identify` and `needsUpdate`, and the fixed-cost schemes'/// `verify`, over one string. Errors are answers; only a panic or a leak is/// a failure, and the test runner and the driver catch those.fn parseProperty(input: []const u8) !void { for (&passlib.registry.all) |*s| { _ = s.identify(input); _ = s.needsUpdate(input) catch {}; if (isFixedCost(s.name)) _ = s.verify(context(), "password", input) catch {}; } _ = passlib.identify(input);}
test "fuzz parse" { for (hash_seeds) |seed| try parseProperty(seed); try testing.fuzz({}, fuzzParse, .{});}
fn fuzzParse(_: void, smith: *Smith) !void { var buffer: [512]u8 = undefined; const len = smith.slice(&buffer); try parseProperty(buffer[0..len]);}
// -- round trips -------------------------------------------------------------
/// Settings that keep each costly scheme at its cheapest, so that the round/// trip exercises every scheme and not only the fast ones.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 } }, .{ "bcrypt_sha256", h.bcrypt_sha256, .{ .rounds = 4 } }, .{ "ldap_bcrypt", h.ldap_bcrypt, .{ .rounds = 4 } }, .{ "django_bcrypt", h.django_bcrypt, .{ .rounds = 4 } }, .{ "django_bcrypt_sha256", h.django_bcrypt_sha256, .{ .rounds = 4 } }, .{ "scrypt", h.scrypt, .{ .rounds = 4, .block_size = 4, .parallelism = 1 } }, .{ "argon2", h.argon2, .{ .rounds = 1, .memory_cost = 8, .parallelism = 1 } }, .{ "django_argon2", h.django_argon2, .{ .rounds = 1, .memory_cost = 8, .parallelism = 1 } }, .{ "sha256_crypt", h.sha256_crypt, .{ .rounds = 1000 } }, .{ "sha512_crypt", h.sha512_crypt, .{ .rounds = 1000 } }, .{ "ldap_sha256_crypt", h.ldap_sha256_crypt, .{ .rounds = 1000 } }, .{ "ldap_sha512_crypt", h.ldap_sha512_crypt, .{ .rounds = 1000 } }, .{ "sha1_crypt", h.sha1_crypt, .{ .rounds = 1 } }, .{ "ldap_sha1_crypt", h.ldap_sha1_crypt, .{ .rounds = 1 } }, .{ "sun_md5_crypt", h.sun_md5_crypt, .{ .rounds = 0 } }, .{ "bsdi_crypt", h.bsdi_crypt, .{ .rounds = 1 } }, .{ "ldap_bsdi_crypt", h.ldap_bsdi_crypt, .{ .rounds = 1 } }, .{ "phpass", h.phpass, .{ .rounds = 7 } }, .{ "fshp", h.fshp, .{ .rounds = 1 } }, .{ "pbkdf2_sha1", h.pbkdf2_sha1, .{ .rounds = 1 } }, .{ "pbkdf2_sha256", h.pbkdf2_sha256, .{ .rounds = 1 } }, .{ "pbkdf2_sha512", h.pbkdf2_sha512, .{ .rounds = 1 } }, .{ "ldap_pbkdf2_sha1", h.ldap_pbkdf2_sha1, .{ .rounds = 1 } }, .{ "ldap_pbkdf2_sha256", h.ldap_pbkdf2_sha256, .{ .rounds = 1 } }, .{ "ldap_pbkdf2_sha512", h.ldap_pbkdf2_sha512, .{ .rounds = 1 } }, .{ "cta_pbkdf2_sha1", h.cta_pbkdf2_sha1, .{ .rounds = 1 } }, .{ "dlitz_pbkdf2_sha1", h.dlitz_pbkdf2_sha1, .{ .rounds = 1 } }, .{ "grub_pbkdf2_sha512", h.grub_pbkdf2_sha512, .{ .rounds = 1 } }, .{ "django_pbkdf2_sha1", h.django_pbkdf2_sha1, .{ .rounds = 1 } }, .{ "django_pbkdf2_sha256", h.django_pbkdf2_sha256, .{ .rounds = 1 } }, .{ "scram", h.scram, .{ .rounds = 1 } }, .{ "cisco_asa_pbkdf2", h.cisco_asa_pbkdf2, .{ .rounds = 1 } }, }) |entry| { if (std.mem.eql(u8, scheme.name, entry[0])) { // The literal in the table has a type of its own, so its fields // are copied into the scheme's `Options` one by one. var options: entry[1].Options = .{}; inline for (@typeInfo(@TypeOf(entry[2])).@"struct".fields) |f| { @field(options, f.name) = @field(entry[2], f.name); } return entry[1].hash(ctx, password, options, w); } } // atlassian_pbkdf2_sha1 and msdcc2 have fixed costs that are merely // slow, and everything else is fast. return scheme.hash(ctx, password, w);}
/// A password hashed by the scheme the first byte picks verifies, and the/// same password with a byte changed at the front does not, unless the/// scheme could not hash the password in the first place.////// Changing the *first* byte matters: DES `crypt` reads only eight bytes of/// the password and seven bits of each, bcrypt 72 bytes, and the LM hash/// upper-cases, so a change anywhere else, or of case, or of the top bit, is/// invisible to some of them.fn roundTripProperty(input: []const u8) !void { if (input.len < 1) return; const scheme = &passlib.registry.all[input[0] % passlib.registry.all.len]; const password = input[1..]; const ctx = context();
var buf: [2048]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); hashCheap(scheme, ctx, password, &w) catch |err| switch (err) { // Passwords a scheme refuses: not UTF-8 where it needs text, a NUL // where it cannot carry one, too long, or refused by SASLprep. error.InvalidPassword, error.PasswordTooLong => return, else => return err, }; const h = w.buffered(); if (!scheme.identify(h)) { // passlib's ldap_plaintext hashes the empty password to the empty // string, which it then does not claim, and this port does the same. if (std.mem.eql(u8, scheme.name, "ldap_plaintext") and password.len == 0) return; return error.OwnHashNotIdentified; }
const disabled = std.mem.eql(u8, scheme.name, "unix_disabled") or std.mem.eql(u8, scheme.name, "unix_fallback") or std.mem.eql(u8, scheme.name, "django_disabled"); const ok = try scheme.verify(ctx, password, h); if (ok == disabled) return error.OwnHashNotVerified;
if (password.len > 0 and !disabled) { var other: [512]u8 = undefined; @memcpy(other[0..password.len], password); // A different letter in every scheme's eyes: not the same letter in // the other case, which lmhash cannot tell apart, and not the same // low seven bits, which is all of a byte DES `crypt` keeps. const low = password[0] & 0x7f; other[0] = if (low == 'a' or low == 'A') 'b' else 'a'; if (scheme.verify(ctx, other[0..password.len], h)) |wrong| { if (wrong) return error.WrongPasswordVerified; } else |err| switch (err) { error.InvalidPassword, error.PasswordTooLong => {}, else => return err, } }}
test "fuzz round trip" { for (0..passlib.registry.all.len) |i| { var seed: [9]u8 = "\x00password".*; seed[0] = @intCast(i); try roundTripProperty(&seed); } try testing.fuzz({}, fuzzRoundTrip, .{});}
fn fuzzRoundTrip(_: void, smith: *Smith) !void { var buffer: [256]u8 = undefined; const len = smith.slice(&buffer); try roundTripProperty(buffer[0..len]);}
// -- encodings ---------------------------------------------------------------
/// Every decoder takes any string without panicking, and what one encodes/// the matching decoder gives back.fn encodingProperty(input: []const u8) !void { const e = passlib.encoding; var out: [1024]u8 = undefined; var back: [1024]u8 = undefined; inline for (.{ e.h64, e.h64big, e.bcrypt64, e.ab64, e.b64s }) |E| { _ = E.decode(&out, input) catch {}; const enc = E.encode(&out, input[0..@min(input.len, 700)]); const dec = try E.decode(&back, enc); try testing.expectEqualSlices(u8, input[0..@min(input.len, 700)], dec); } _ = e.b64.decode(&out, input) catch {}; const enc = e.b64.encode(&out, input[0..@min(input.len, 700)]); try testing.expectEqualSlices(u8, input[0..@min(input.len, 700)], try e.b64.decode(&back, enc));}
test "fuzz encoding" { for (hash_seeds) |seed| try encodingProperty(seed); try testing.fuzz({}, fuzzEncoding, .{});}
fn fuzzEncoding(_: void, smith: *Smith) !void { var buffer: [700]u8 = undefined; const len = smith.slice(&buffer); try encodingProperty(buffer[0..len]);}
// -- seeds -------------------------------------------------------------------
const Vector = struct { scheme: []const u8, kind: enum { correct, disabled, config, malformed, unidentified, own, foreign }, hash: []const u8, password: ?[]const u8 = null, wrong: ?[]const u8 = null, user: ?[]const u8 = null, realm: ?[]const u8 = null,};
/// Every hash string in passlib's own test tables, well-formed and not:/// the best corpus there is for a parser, since it is what the parsers were/// written against.const hash_seeds = blk: { const known: []const Vector = @import("vectors/known.zon"); @setEvalBranchQuota(100_000); var out: [known.len][]const u8 = undefined; for (known, 0..) |v, i| out[i] = v.hash; const final = out; break :blk final;};
const password_seeds = [_][]const u8{ "\x00password", "\x05", "\x10\xc3\xa9t\xc3\xa9", "\x20" ++ "a" ** 80, "\x30pass\x00word", "\x40\xff\xfe", "\x41\xe2\x82\xac\xc2\xa5$",};
// -- the table the standalone driver reads ------------------------------------
pub const Target = struct { name: []const u8, run: *const fn (input: []const u8) anyerror!void, corpus: []const []const u8, /// The size of the buffer the target reads its one slice into. /// /// `Smith.slice` yields an *empty* slice for a length larger than the /// buffer rather than a truncated one, so a generator that does not know /// this number hands the target nothing at all most of the time. content_max: usize,};
fn Driven(comptime one: fn (void, *Smith) anyerror!void) type { return struct { fn run(input: []const u8) anyerror!void { var smith: Smith = .{ .in = input }; return one({}, &smith); } };}
pub const all = [_]Target{ .{ .name = "parse", .run = Driven(fuzzParse).run, .corpus = &hash_seeds, .content_max = 512 }, .{ .name = "round-trip", .run = Driven(fuzzRoundTrip).run, .corpus = &password_seeds, .content_max = 256 }, .{ .name = "encoding", .run = Driven(fuzzEncoding).run, .corpus = &hash_seeds, .content_max = 700 },};