Something went wrong. Try again.
passlib's password hash schemes, ported to Zig 0.16
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The `userPassword` formats of LDAP directories: passlib's//! `passlib.handlers.ldap_digests`.//!//! RFC 2307 stores a password in LDAP as `{SCHEME}` followed by the value.//! OpenLDAP and the directories that copied it use these://!//! * `{MD5}` and `{SHA}`: an unsalted digest, in padded base64.//! * `{SMD5}`, `{SSHA}`, `{SSHA256}`, `{SSHA512}`: the digest of the password//! followed by a salt, and the salt appended after the digest, all in//! padded base64.//! * `{CRYPT}`: whatever the system `crypt(3)` makes, behind the prefix. The//! `ldap_*_crypt` schemes are the Unix `crypt` schemes wrapped this way.//! * No prefix at all: the password in plain text.//!//! **The digest formats are weak.** One pass of a fast hash, salted or not,//! costs an attacker almost nothing per guess. Directories that still hold//! them should rehash with `{CRYPT}` over something slow, or move to a//! scheme with a work factor.
const std = @import("std");const Io = std.Io;const testing = std.testing;
const encoding = @import("../encoding.zig");const b64 = encoding.b64;const handler = @import("../handler.zig");const Context = handler.Context;const Error = handler.Error;const bcrypt = @import("bcrypt.zig");const des_crypt = @import("des_crypt.zig");const md5_crypt = @import("md5_crypt.zig");const misc = @import("misc.zig");const sha1_crypt = @import("sha1_crypt.zig");const sha2_crypt = @import("sha2_crypt.zig");
const base64_padded_chars = encoding.base64_chars ++ "=";
/// `{SCHEME}` and the unsalted digest in padded base64.////// Any string with the prefix is claimed, as passlib claims it. Verifying/// compares the base64 text, so a stored value of the wrong length is simply/// a password that does not match, and only a character outside the base64/// alphabet is `error.MalformedHash`.pub fn Base64Digest(comptime scheme_name: []const u8, comptime ident: []const u8, comptime Hash: type) type { return struct { pub const name = scheme_name; pub const Options = struct {};
const encoded_len = b64.encodedLen(Hash.digest_length);
pub fn identify(h: []const u8) bool { return std.mem.startsWith(u8, h, ident); }
fn compute(password: []const u8, out: *[encoded_len]u8) void { var digest: [Hash.digest_length]u8 = undefined; Hash.hash(password, &digest, .{}); _ = b64.encode(out, &digest); }
pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { _ = ctx; _ = options; try handler.checkPasswordLen(password); var out: [encoded_len]u8 = undefined; compute(password, &out); try w.writeAll(ident); try w.writeAll(&out); }
fn parse(h: []const u8) Error![]const u8 { if (!identify(h)) return error.MalformedHash; const checksum = h[ident.len..]; if (!encoding.allIn(checksum, base64_padded_chars)) return error.MalformedHash; return checksum; }
pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { _ = ctx; const checksum = try parse(h); try handler.checkPasswordLen(password); var out: [encoded_len]u8 = undefined; compute(password, &out); return handler.eql(checksum, &out); }
pub fn needsUpdate(h: []const u8, options: Options) Error!bool { _ = options; _ = try parse(h); return false; } };}
/// `{SCHEME}` and, in padded base64, the digest of the password and salt/// followed by the salt. The salt is 4 to 16 raw bytes.pub fn SaltedBase64Digest( comptime scheme_name: []const u8, comptime ident: []const u8, comptime Hash: type, comptime default_salt_size: u8, comptime min_encoded: usize,) type { return struct { pub const name = scheme_name; pub const min_salt_size = 4; pub const max_salt_size = 16;
pub const Options = struct { /// The salt, 4 to 16 bytes. Null, the default, draws a random /// one of `salt_size` bytes. salt: ?[]const u8 = null, salt_size: u8 = default_salt_size, };
const digest_len = Hash.digest_length;
pub fn identify(h: []const u8) bool { return std.mem.startsWith(u8, h, ident); }
const Parsed = struct { checksum: [digest_len]u8, salt: [max_salt_size]u8, salt_len: usize, };
/// passlib matches `ident` then at least `min_encoded` base64 /// characters and up to two `=`, decodes it the way Python does, and /// splits the digest from the salt. fn parse(h: []const u8) Error!Parsed { if (!identify(h)) return error.MalformedHash; const body = h[ident.len..]; var chars = body.len; while (chars > 0 and body.len - chars < 2 and body[chars - 1] == '=') chars -= 1; if (chars < min_encoded or !encoding.allIn(body[0..chars], encoding.base64_chars)) return error.MalformedHash; const len = try b64.decodedLen(body); if (len < digest_len + min_salt_size or len > digest_len + max_salt_size) return error.MalformedHash; var data: [digest_len + max_salt_size]u8 = undefined; _ = try b64.decode(&data, body); var parsed: Parsed = .{ .checksum = data[0..digest_len].*, .salt = undefined, .salt_len = len - digest_len }; @memcpy(parsed.salt[0..parsed.salt_len], data[digest_len..len]); return parsed; }
fn compute(password: []const u8, salt: []const u8) [digest_len]u8 { var hasher = Hash.init(.{}); hasher.update(password); hasher.update(salt); var out: [digest_len]u8 = undefined; hasher.final(&out); return out; }
pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { try handler.checkPasswordLen(password); var salt_buf: [max_salt_size]u8 = undefined; const salt = if (options.salt) |s| blk: { if (s.len < min_salt_size or s.len > max_salt_size) return error.InvalidOptions; break :blk s; } else blk: { if (options.salt_size < min_salt_size or options.salt_size > max_salt_size) return error.InvalidOptions; break :blk try handler.randomBytes(ctx.io, salt_buf[0..options.salt_size]); }; var data: [digest_len + max_salt_size]u8 = undefined; data[0..digest_len].* = compute(password, salt); @memcpy(data[digest_len..][0..salt.len], salt); var out: [b64.encodedLen(digest_len + max_salt_size)]u8 = undefined; try w.writeAll(ident); try w.writeAll(b64.encode(&out, data[0 .. digest_len + salt.len])); }
pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { _ = ctx; const parsed = try parse(h); try handler.checkPasswordLen(password); const got = compute(password, parsed.salt[0..parsed.salt_len]); return handler.eql(&parsed.checksum, &got); }
pub fn needsUpdate(h: []const u8, options: Options) Error!bool { _ = options; _ = try parse(h); return false; } };}
const Md5 = std.crypto.hash.Md5;const Sha1 = std.crypto.hash.Sha1;const Sha256 = std.crypto.hash.sha2.Sha256;const Sha512 = std.crypto.hash.sha2.Sha512;
pub const ldap_md5 = Base64Digest("ldap_md5", "{MD5}", Md5);pub const ldap_sha1 = Base64Digest("ldap_sha1", "{SHA}", Sha1);pub const ldap_salted_md5 = SaltedBase64Digest("ldap_salted_md5", "{SMD5}", Md5, 4, 27);pub const ldap_salted_sha1 = SaltedBase64Digest("ldap_salted_sha1", "{SSHA}", Sha1, 4, 32);pub const ldap_salted_sha256 = SaltedBase64Digest("ldap_salted_sha256", "{SSHA256}", Sha256, 8, 48);pub const ldap_salted_sha512 = SaltedBase64Digest("ldap_salted_sha512", "{SSHA512}", Sha512, 8, 91);
/// Whether `h` looks like an RFC 2307 value, which `ldap_plaintext` must not/// claim: passlib's `^\{\w+\}.*$`.////// Python's `\w` on text takes letters and digits of every script. Here the/// hash is bytes, so any byte from 0x80 up counts as a word character, which/// agrees with Python for UTF-8 letters. Python's `.` does not match a/// newline, and its `$` also matches before a final one, so a value with a/// newline anywhere but at its very end does not match.fn isRfc2307(h: []const u8) bool { if (h.len < 3 or h[0] != '{') return false; var i: usize = 1; while (i < h.len and (std.ascii.isAlphanumeric(h[i]) or h[i] == '_' or h[i] >= 0x80)) i += 1; if (i == 1 or i == h.len or h[i] != '}') return false; const rest = h[i + 1 ..]; const newline = std.mem.findScalar(u8, rest, '\n') orelse return true; return newline == rest.len - 1;}
/// The password in plain text: any non-empty string that is not an RFC 2307/// `{SCHEME}` value. That is nearly every string, so the registry treats it/// as a catch-all and `registry.identify` never answers with it.pub const ldap_plaintext = misc.Plaintext("ldap_plaintext", struct { fn claims(h: []const u8) bool { return h.len > 0 and !isRfc2307(h); }}.claims, true);
/// `{CRYPT}` in front of a Unix `crypt` scheme's hash.pub fn LdapCrypt(comptime scheme_name: []const u8, comptime Inner: type) type { return handler.PrefixWrapper(scheme_name, Inner, "{CRYPT}", "");}
pub const ldap_des_crypt = LdapCrypt("ldap_des_crypt", des_crypt.des_crypt);pub const ldap_bsdi_crypt = LdapCrypt("ldap_bsdi_crypt", des_crypt.bsdi_crypt);pub const ldap_md5_crypt = LdapCrypt("ldap_md5_crypt", md5_crypt.md5_crypt);pub const ldap_bcrypt = LdapCrypt("ldap_bcrypt", bcrypt.bcrypt);pub const ldap_sha1_crypt = LdapCrypt("ldap_sha1_crypt", sha1_crypt.sha1_crypt);pub const ldap_sha256_crypt = LdapCrypt("ldap_sha256_crypt", sha2_crypt.sha256_crypt);pub const ldap_sha512_crypt = LdapCrypt("ldap_sha512_crypt", sha2_crypt.sha512_crypt);
/// The schemes this module defines, in the order `registry.identify` tries/// them. `ldap_plaintext` claims nearly every string, so it is last.pub const schemes = .{ ldap_md5, ldap_sha1, ldap_salted_md5, ldap_salted_sha1, ldap_salted_sha256, ldap_salted_sha512, ldap_sha512_crypt, ldap_sha256_crypt, ldap_sha1_crypt, ldap_bcrypt, ldap_md5_crypt, ldap_bsdi_crypt, ldap_des_crypt, ldap_plaintext,};
comptime { for (schemes) |S| handler.check(S);}
const test_ctx: Context = .{ .io = testing.io, .gpa = testing.allocator };
test "unsalted" { try testing.expect(try ldap_md5.verify(test_ctx, "password", "{MD5}X03MO1qnZdYdgyfeuILPmQ==")); // passlib 1.7.4: only a character outside base64 is an error. try testing.expect(!try ldap_md5.verify(test_ctx, "password", "{MD5}X03MO1qnZdYdgyfeuILPmQ")); try testing.expect(!try ldap_md5.verify(test_ctx, "password", "{MD5}")); try testing.expectError(error.MalformedHash, ldap_md5.verify(test_ctx, "password", "{MD5}abc$"));}
test "salted" { // passlib 1.7.4: ldap_salted_md5.using(salt=b"abcd").hash("password") var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); try ldap_salted_md5.hash(test_ctx, "password", .{ .salt = "abcd" }, &w); const got = w.buffered(); try testing.expectEqualStrings("{SMD5}++18jMg8ZSwt3EL7ARFIjWFiY2Q=", got); try testing.expect(try ldap_salted_md5.verify(test_ctx, "password", got)); try testing.expect(!try ldap_salted_md5.verify(test_ctx, "passwore", got)); // Too short a salt, and too long: 27 characters and a pad decode to a // four-byte salt, and 48 characters to a twenty-byte one. try testing.expect(!try ldap_salted_md5.verify(test_ctx, "x", "{SMD5}" ++ "A" ** 27 ++ "=")); try testing.expectError(error.MalformedHash, ldap_salted_md5.verify(test_ctx, "x", "{SMD5}" ++ "A" ** 48)); try testing.expectError(error.MalformedHash, ldap_salted_md5.verify(test_ctx, "x", "{SMD5}abc"));}
test "plaintext" { try testing.expect(!ldap_plaintext.identify("")); try testing.expect(!ldap_plaintext.identify("{X}y")); try testing.expect(ldap_plaintext.identify("{X}y\nz")); try testing.expect(ldap_plaintext.identify("password")); try testing.expectError(error.MalformedHash, ldap_plaintext.verify(test_ctx, "{X}y", "{X}y"));}