Something went wrong. Try again.
passlib's password hash schemes, ported to Zig 0.16
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! passlib's `scram` format: passlib's `passlib.handlers.scram`.//!//! SCRAM (RFC 5802) is a SASL mechanism in which the client proves it knows//! a password without sending it. The server does not need the password to//! check that proof, only the "SaltedPassword"://! `Hi(SASLprep(password), salt, rounds)`, where `Hi` is PBKDF2 with HMAC over//! the mechanism's digest. A server offering SCRAM-SHA-1 and SCRAM-SHA-256//! needs one SaltedPassword for each.//!//! passlib's format stores them together, sharing one salt and one round//! count://!//! ```text//! $scram$<rounds>$<salt>$sha-1=<digest>,sha-256=<digest>,sha-512=<digest>//! ```//!//! with the salt and each digest in passlib's adapted base64 and the//! algorithms under their IANA names, sorted. SHA-1 must always be present,//! since it is the digest of the mechanism every SCRAM implementation has.//! passlib invented the format; no SCRAM server reads it directly, but each//! digest in it is exactly what such a server stores.//!//! **It is as strong as its PBKDF2.** Each digest is PBKDF2-HMAC, costing time//! and no memory, and a hash holding several digests is only as costly to//! attack as its cheapest one. Its reason to exist is to feed a SCRAM//! server; for passwords checked only by this library, prefer Argon2 or//! scrypt.
const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;const Hmac = std.crypto.auth.hmac.Hmac;const testing = std.testing;
const crypto_ext = @import("std_crypto_ext");const saslprep = @import("../saslprep.zig");const encoding = @import("../encoding.zig");const ab64 = encoding.ab64;const handler = @import("../handler.zig");const Context = handler.Context;const Error = handler.Error;
/// The largest salt passlib accepts, in bytes.pub const max_salt_size = 1024;/// SCRAM's limit on the length of a digest's name, which passlib enforces.pub const max_alg_name_len = 9;
/// The digests passlib 1.7.4 can compute a SCRAM digest with, in the order/// passlib sorts their names, which is the order a hash lists them in.////// passlib accepts any name `norm_hash_name` can make sense of, and fails/// only when it comes to compute the digest; these are the ones that succeed/// against Python's `hashlib`. MD2 and RIPEMD-160 are not among them: MD2/// has no implementation, and `ripemd-160` is longer than SCRAM allows.pub const Alg = enum { blake2b, blake2s, md4, md5, sha1, sha224, sha256, sha384, sha512, sha3_224, sha3_256, sha3_384, sha3_512,
/// The name a hash stores this digest under. pub fn ianaName(a: Alg) []const u8 { return switch (a) { .blake2b => "blake-2b", .blake2s => "blake-2s", .md4 => "md4", .md5 => "md5", .sha1 => "sha-1", .sha224 => "sha-224", .sha256 => "sha-256", .sha384 => "sha-384", .sha512 => "sha-512", .sha3_224 => "sha3-224", .sha3_256 => "sha3-256", .sha3_384 => "sha3-384", .sha3_512 => "sha3-512", }; }
fn Hash(comptime a: Alg) type { const h = std.crypto.hash; return switch (a) { .blake2b => h.blake2.Blake2b512, .blake2s => h.blake2.Blake2s256, .md4 => crypto_ext.Md4, .md5 => h.Md5, .sha1 => h.Sha1, .sha224 => h.sha2.Sha224, .sha256 => h.sha2.Sha256, .sha384 => h.sha2.Sha384, .sha512 => h.sha2.Sha512, .sha3_224 => h.sha3.Sha3_224, .sha3_256 => h.sha3.Sha3_256, .sha3_384 => h.sha3.Sha3_384, .sha3_512 => h.sha3.Sha3_512, }; }
/// The length of this digest, which is the length of its SaltedPassword. pub fn digestLen(a: Alg) usize { return switch (a) { inline else => |c| Hash(c).digest_length, }; }
/// The digest stored under `iana`, which must already be normalized. pub fn fromIana(iana: []const u8) ?Alg { for (std.enums.values(Alg)) |a| { if (std.mem.eql(u8, a.ianaName(), iana)) return a; } return null; }};
/// The longest digest any `Alg` produces.const max_digest_len = 64;
comptime { for (std.enums.values(Alg)) |a| std.debug.assert(a.digestLen() <= max_digest_len);}
/// passlib's `scram._verify_algs`: the digests `verify` checks, most/// preferred first. It checks only the first of these the hash holds.const verify_order = [_]Alg{ .sha256, .sha512, .sha224, .sha384, .sha1 };
// -- digest names ------------------------------------------------------------
/// A row of passlib's `_known_hash_names`: the IANA name (or passlib's/// stand-in for one) and every other spelling that resolves to it.const KnownName = struct { iana: []const u8, aliases: []const []const u8 };
const known_names = [_]KnownName{ .{ .iana = "md2", .aliases = &.{} }, .{ .iana = "md5", .aliases = &.{} }, .{ .iana = "sha-1", .aliases = &.{"sha1"} }, .{ .iana = "sha-224", .aliases = &.{ "sha224", "sha2-224" } }, .{ .iana = "sha-256", .aliases = &.{ "sha256", "sha2-256" } }, .{ .iana = "sha-384", .aliases = &.{ "sha384", "sha2-384" } }, .{ .iana = "sha-512", .aliases = &.{ "sha512", "sha2-512" } }, .{ .iana = "blake-2b", .aliases = &.{"blake2b"} }, .{ .iana = "blake-2s", .aliases = &.{"blake2s"} }, .{ .iana = "md4", .aliases = &.{} }, .{ .iana = "ripemd-160", .aliases = &.{ "ripemd160", "ripemd" } },};
fn lookupKnown(name: []const u8) ?[]const u8 { for (known_names) |row| { if (std.mem.eql(u8, row.iana, name)) return row.iana; for (row.aliases) |alias| if (std.mem.eql(u8, alias, name)) return row.iana; } return null;}
/// The longest name `normName` will normalize.const max_name_len = 64;
/// passlib's second attempt at a name it does not know, the regular/// expression `^[a-z]+-?(\d)?-?(\d{3,4})?$`: letters, then an optional/// revision digit and an optional three- or four-digit size, rebuilt as/// `<letters><rev>-<size>`. The alternatives are tried in the order Python's/// backtracking tries them, so that an ambiguous name such as `sha-1024`/// comes out as passlib has it, `sha1-024`.fn reshape(buf: *[max_name_len + 1]u8, s: []const u8) ?[]const u8 { var i: usize = 0; while (i < s.len and std.ascii.isLower(s[i])) i += 1; if (i == 0) return null; const rest = s[i..]; for ([_]bool{ true, false }) |dash1| for ([_]bool{ true, false }) |take_rev| for ([_]bool{ true, false }) |dash2| for ([_]usize{ 4, 3, 0 }) |size_len| { var j: usize = 0; if (dash1) { if (j < rest.len and rest[j] == '-') j += 1 else continue; } var rev: []const u8 = ""; if (take_rev) { if (j < rest.len and std.ascii.isDigit(rest[j])) { rev = rest[j .. j + 1]; j += 1; } else continue; } if (dash2) { if (j < rest.len and rest[j] == '-') j += 1 else continue; } var size: []const u8 = ""; if (size_len > 0) { if (j + size_len > rest.len) continue; const digits = rest[j .. j + size_len]; if (!allDigits(digits)) continue; size = digits; j += size_len; } if (j != rest.len) continue; var w: Io.Writer = .fixed(buf); w.print("{s}{s}", .{ s[0..i], rev }) catch return null; if (size.len > 0) w.print("-{s}", .{size}) catch return null; return w.buffered(); }; return null;}
fn allDigits(s: []const u8) bool { for (s) |c| if (!std.ascii.isDigit(c)) return false; return true;}
/// passlib's `norm_hash_name(name, "iana")`: `raw` trimmed, lower-cased,/// with `_`, ` ` and `/` made `-`, a `scram-` prefix and `-plus` suffix/// removed, then resolved through the table of known names, reshaped, or/// left as it is. Null for a name longer than `max_name_len` or holding a/// byte outside ASCII, which passlib would treat as text.fn normName(buf: *[max_name_len + 1]u8, raw: []const u8) ?[]const u8 { // Python's `str.strip()`, as far as ASCII goes. const trimmed = std.mem.trim(u8, raw, " \t\n\x0b\x0c\r\x1c\x1d\x1e\x1f"); if (trimmed.len > max_name_len) return null; var lowered: [max_name_len]u8 = undefined; for (trimmed, lowered[0..trimmed.len]) |c, *l| { if (c >= 0x80) return null; l.* = switch (c) { '_', ' ', '/' => '-', else => std.ascii.toLower(c), }; } var name: []const u8 = lowered[0..trimmed.len]; if (std.mem.startsWith(u8, name, "scram-")) { name = name["scram-".len..]; if (std.mem.endsWith(u8, name, "-plus")) name = name[0 .. name.len - "-plus".len]; } const result = lookupKnown(name) orelse if (reshape(buf, name)) |shaped| lookupKnown(shaped) orelse shaped else name; // `result` may be `buf` itself, a table entry, or part of `lowered`. std.mem.copyForwards(u8, buf, result); return buf[0..result.len];}
/// Whether `name` is already in the form `norm_hash_name` would give it,/// which passlib requires of every name in a hash.fn isNormalName(name: []const u8) bool { var buf: [max_name_len + 1]u8 = undefined; const norm = normName(&buf, name) orelse return false; return std.mem.eql(u8, norm, name);}
/// The set of digests `names` asks for, as passlib's `_norm_algs` reads a/// list: each normalized, none longer than SCRAM allows, and `sha-1` among/// them. A name that normalizes to a digest outside `Alg` is/// `error.InvalidOptions`, which in passlib is an error only once hashing/// reaches it.pub fn algSet(names: []const []const u8) Error!std.EnumSet(Alg) { var set: std.EnumSet(Alg) = .initEmpty(); for (names) |raw| { var buf: [max_name_len + 1]u8 = undefined; const norm = normName(&buf, raw) orelse return error.InvalidOptions; if (norm.len > max_alg_name_len) return error.InvalidOptions; set.insert(Alg.fromIana(norm) orelse return error.InvalidOptions); } if (!set.contains(.sha1)) return error.InvalidOptions; return set;}
// -- SASLprep ----------------------------------------------------------------
/// `password` through SASLprep as passlib's `saslprep` has it. See/// `saslprep.zig` for how that reading differs from the RFC's and from/// PostgreSQL's.fn prepare(gpa: Allocator, password: []const u8) Error!saslprep.Prepared { return saslprep.prep(gpa, password);}
/// The SaltedPassword for `alg`: PBKDF2-HMAC over its digest, as long as the/// digest.fn derive(alg: Alg, out: *[max_digest_len]u8, prepared: []const u8, salt: []const u8, rounds: u32) Error![]const u8 { switch (alg) { inline else => |a| { const H = Alg.Hash(a); const dk = out[0..H.digest_length]; try std.crypto.pwhash.pbkdf2(dk, prepared, salt, rounds, Hmac(H)); return dk; }, }}
// -- the scheme --------------------------------------------------------------
pub const scram = struct { pub const name = "scram"; const ident = "$scram$";
pub const Options = struct { /// The salt, as raw bytes, at most `max_salt_size` of them. Null, the /// default, draws `salt_size` random bytes. salt: ?[]const u8 = null, /// The length of a random salt in bytes, at most `max_salt_size`. salt_size: u16 = 12, /// PBKDF2 iterations, at least 1. rounds: u32 = 100000, /// The digests to store, by any name passlib's `norm_hash_name` /// resolves: `"sha-256"`, `"SHA256"`, `"SCRAM-SHA-256"`. `sha-1` must /// be among them. `needsUpdate` is true for a hash missing any of /// them. algs: []const []const u8 = &.{ "sha-1", "sha-256", "sha-512" }, /// `needsUpdate` is true for a hash with fewer rounds than this. min_desired_rounds: ?u32 = null, /// `needsUpdate` is true for a hash with more rounds than this. max_desired_rounds: ?u32 = null, };
pub fn identify(h: []const u8) bool { return std.mem.startsWith(u8, h, ident); }
const Parsed = struct { rounds: u32, salt_buf: [max_salt_size]u8, salt_len: usize, /// The `alg=digest,...` field, already validated. digests: []const u8,
fn salt(p: *const Parsed) []const u8 { return p.salt_buf[0..p.salt_len]; }
/// The encoded digest stored under `iana`. passlib reads the field /// into a dictionary, so a name given twice means its last value. fn find(p: *const Parsed, iana: []const u8) ?[]const u8 { var found: ?[]const u8 = null; var it = std.mem.splitScalar(u8, p.digests, ','); while (it.next()) |pair| { const eq = std.mem.findScalar(u8, pair, '=').?; if (std.mem.eql(u8, pair[0..eq], iana)) found = pair[eq + 1 ..]; } return found; } };
/// `$scram$` + rounds + `$` + salt + `$` + digests. The rounds are /// decimal with no leading zero and at least 1. Each digest is /// `name=value`, the name exactly as `norm_hash_name` would write it and /// at most nine characters, the value adapted base64 of any length, and /// `sha-1` must be among them. A digests field of bare names is /// passlib's settings string, and is refused: passlib parses it but will /// not verify against it. fn parse(h: []const u8) Error!Parsed { if (!identify(h)) return error.MalformedHash; const f = try handler.splitExact(3, h[ident.len..], '$'); var p: Parsed = .{ .rounds = undefined, .salt_buf = undefined, .salt_len = 0, .digests = f[2] }; p.rounds = try handler.parseDecimal(u32, f[0], false); if (p.rounds < 1) return error.MalformedHash; if (try ab64.decodedLen(f[1].len) > max_salt_size) return error.MalformedHash; p.salt_len = (try ab64.decode(&p.salt_buf, f[1])).len;
if (p.digests.len == 0 or std.mem.findScalar(u8, p.digests, '=') == null) return error.MalformedHash; var have_sha1 = false; var it = std.mem.splitScalar(u8, p.digests, ','); while (it.next()) |pair| { const kv = try handler.splitExact(2, pair, '='); if (!isNormalName(kv[0]) or kv[0].len > max_alg_name_len) return error.MalformedHash; _ = try ab64.decodedLen(kv[1].len); if (!encoding.allIn(kv[1], encoding.ab64_chars ++ "+")) return error.MalformedHash; if (std.mem.eql(u8, kv[0], "sha-1")) have_sha1 = true; } if (!have_sha1) return error.MalformedHash; return p; }
/// Decodes a stored digest if it is `len` bytes long. fn decodeDigest(out: *[max_digest_len]u8, encoded: []const u8, len: usize) ?[]const u8 { const n = ab64.decodedLen(encoded.len) catch return null; if (n != len) return null; return ab64.decode(out, encoded) catch null; }
pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { try handler.checkPasswordLen(password); const algs = try algSet(options.algs); if (options.rounds < 1) return error.InvalidOptions; var salt_buf: [max_salt_size]u8 = undefined; const salt = if (options.salt) |s| blk: { if (s.len > max_salt_size) return error.InvalidOptions; break :blk s; } else blk: { if (options.salt_size > max_salt_size) return error.InvalidOptions; break :blk try handler.randomBytes(ctx.io, salt_buf[0..options.salt_size]); }; const prepared = try prepare(ctx.gpa, password); defer prepared.deinit(ctx.gpa);
var salt_enc: [ab64.encodedLen(max_salt_size)]u8 = undefined; try w.print("{s}{d}${s}$", .{ ident, options.rounds, ab64.encode(&salt_enc, salt) }); var first = true; var it = algs.iterator(); while (it.next()) |alg| { var digest: [max_digest_len]u8 = undefined; const dk = try derive(alg, &digest, prepared.bytes, salt, options.rounds); var enc: [ab64.encodedLen(max_digest_len)]u8 = undefined; if (!first) try w.writeByte(','); first = false; try w.print("{s}={s}", .{ alg.ianaName(), ab64.encode(&enc, dk) }); } }
/// passlib's default verification: only the first digest of /// `sha-256`, `sha-512`, `sha-224`, `sha-384`, `sha-1` the hash holds is /// checked, and any others are ignored. A stored digest of the wrong /// length fails to match rather than being an error. `verifyFull` checks /// every digest. pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { try handler.checkPasswordLen(password); const p = try parse(h); const alg, const encoded = for (verify_order) |a| { if (p.find(a.ianaName())) |d| break .{ a, d }; } else unreachable; // parse requires sha-1 const prepared = try prepare(ctx.gpa, password); defer prepared.deinit(ctx.gpa); var digest: [max_digest_len]u8 = undefined; const dk = try derive(alg, &digest, prepared.bytes, p.salt(), p.rounds); var stored_buf: [max_digest_len]u8 = undefined; const stored = decodeDigest(&stored_buf, encoded, dk.len) orelse return false; return handler.eql(stored, dk); }
/// passlib's `verify(..., full=True)`: every digest the hash holds is /// computed and compared. A digest this library cannot compute, one of /// the wrong length, or a hash some of whose digests match and some do /// not is `error.MalformedHash`, since at least one of its digests must /// be corrupt. pub fn verifyFull(ctx: Context, password: []const u8, h: []const u8) Error!bool { try handler.checkPasswordLen(password); const p = try parse(h); const prepared = try prepare(ctx.gpa, password); defer prepared.deinit(ctx.gpa); var correct = false; var failed = false; var it = std.mem.splitScalar(u8, p.digests, ','); while (it.next()) |pair| { const eq = std.mem.findScalar(u8, pair, '=').?; const alg_name = pair[0..eq]; const encoded = pair[eq + 1 ..]; // A repeated name counts once, with its last value. if (p.find(alg_name).?.ptr != encoded.ptr) continue; const alg = Alg.fromIana(alg_name) orelse return error.MalformedHash; var digest: [max_digest_len]u8 = undefined; const dk = try derive(alg, &digest, prepared.bytes, p.salt(), p.rounds); var stored_buf: [max_digest_len]u8 = undefined; const stored = decodeDigest(&stored_buf, encoded, dk.len) orelse return error.MalformedHash; if (handler.eql(stored, dk)) correct = true else failed = true; } if (correct and failed) return error.MalformedHash; return correct; }
/// True when the hash lacks any digest `options.algs` asks for, or its /// rounds fall outside the desired bounds. Extra digests do not count. pub fn needsUpdate(h: []const u8, options: Options) Error!bool { const p = try parse(h); const want = try algSet(options.algs); var it = want.iterator(); while (it.next()) |alg| if (p.find(alg.ianaName()) == null) return true; return handler.roundsOutside(p.rounds, options.min_desired_rounds, options.max_desired_rounds); }};
/// The schemes this module defines, in the order `registry.identify` tries/// them.pub const schemes = .{scram};
comptime { handler.check(scram);}
const test_ctx: Context = .{ .io = testing.io, .gpa = testing.allocator };
fn hashWith(buf: []u8, password: []const u8, options: scram.Options) ![]const u8 { var w: Io.Writer = .fixed(buf); try scram.hash(test_ctx, password, options, &w); return w.buffered();}
const salt12 = "saltsaltsalt";
test "fixed salts reproduce passlib" { // passlib 1.7.4: scram.using(salt=b"saltsaltsalt", rounds=10).hash("test"). var buf: [2048]u8 = undefined; const h = try hashWith(&buf, "test", .{ .salt = salt12, .rounds = 10 }); try testing.expectEqualStrings("$scram$10$c2FsdHNhbHRzYWx0$sha-1=.fjFcnOrRJx9GGovX4liUqt.cv0,sha-256=iftYIr.X2dO8fTe5.dR5g2bgp1B7bGT99zWB1zK8NqM,sha-512=oFTnWSfawerKmuuHa86N2m1btBdkkGQUMOBqBBr9br4vPqtSZqKNEaj8Ta9NyWaAfwOoog6UbBL./k1HSw0rqw", h); try testing.expect(try scram.verify(test_ctx, "test", h)); try testing.expect(try scram.verifyFull(test_ctx, "test", h)); try testing.expect(!try scram.verify(test_ctx, "tesT", h)); try testing.expect(!try scram.verifyFull(test_ctx, "tesT", h));
try testing.expectEqualStrings( "$scram$10$c2FsdHNhbHRzYWx0$sha-1=.fjFcnOrRJx9GGovX4liUqt.cv0", try hashWith(&buf, "test", .{ .salt = salt12, .rounds = 10, .algs = &.{"sha-1"} }), );}
test "every digest passlib can compute, under any name it accepts" { // passlib 1.7.4: scram.using(salt=b"saltsaltsalt", rounds=10, // algs="SHA1, sha3_256 ,md5,blake2b,md4,sha-224,sha384,blake2s,sha3-224,sha3-384,sha3-512").hash("test") var buf: [2048]u8 = undefined; const h = try hashWith(&buf, "test", .{ .salt = salt12, .rounds = 10, .algs = &.{ "SHA1", " sha3_256 ", "md5", "blake2b", "md4", "sha-224", "sha384", "blake2s", "sha3-224", "sha3-384", "sha3-512" } }); try testing.expectEqualStrings("$scram$10$c2FsdHNhbHRzYWx0$blake-2b=R6KzwfVwiSdrOW/V3oxDSFP9eWonN5GPlTlQ04WIRA1lZyBF3//Dyf4UCwCz8S6oXmw0gZlMcCneal/h52vpaw,blake-2s=gsPyzJ5lHK38bcopxVAdQAY0vY.rxE3l5OmBZkp5Lac,md4=o2.pkxd0JlQ4tXDJTRKcVQ,md5=3hKW/kxWZAkjzl9SzDsJvQ,sha-1=.fjFcnOrRJx9GGovX4liUqt.cv0,sha-224=F6ZdATJvD9AM3sw.qKELqaYibaIKbSQLConQ1w,sha-384=zjltLrfzzMxP0AJaHiPyxtUS2q1D2HIzj9PwRZhC3pwF./e71MTslwhV52mTwUAM,sha3-224=dIwBjrDIda0Zj6w9lfxnVpWsCHpmU2L4Uvv5yw,sha3-256=lxV195gzN8LXkNUVvdwTWfGRKatOfFbL2h5vypHmsJo,sha3-384=9A/smaiu1JEZ1LE3bqNV6rNQ9NzauDX/PHgZhtvMGYqk0AUlW36D6xcHzVjUUEOO,sha3-512=it.yi6iqOL/ReI/3jtm.NbYd17ugs.ha508ldZbYEMH.NTw4OiPuPvkZTqAfKxUtZ06v7ZxdT/sePSnairaQ5w", h); try testing.expect(try scram.verifyFull(test_ctx, "test", h)); try testing.expect(try scram.verify(test_ctx, "test", h));}
test "SASLprep" { // passlib 1.7.4, algs="sha-1": "IX à" and "Ⅸ à" // (ROMAN NUMERAL NINE, IDEOGRAPHIC SPACE, a + combining grave) prepare // to the same string; "" (SOFT HYPHEN) prepares to "". var buf: [256]u8 = undefined; const want_ix = "$scram$10$c2FsdHNhbHRzYWx0$sha-1=98NjPzPQ.DbJIdqm0tBl8d83O.U"; try testing.expectEqualStrings(want_ix, try hashWith(&buf, "IX \xc3\xa0", .{ .salt = salt12, .rounds = 10, .algs = &.{"sha-1"} })); try testing.expectEqualStrings(want_ix, try hashWith(&buf, "\xe2\x85\xa8\xe3\x80\x80a\xcc\x80", .{ .salt = salt12, .rounds = 10, .algs = &.{"sha-1"} })); try testing.expect(try scram.verify(test_ctx, "\xe2\x85\xa8\xe3\x80\x80a\xcc\x80", want_ix));
const want_empty = "$scram$10$c2FsdHNhbHRzYWx0$sha-1=7b.i9c2Nr3HEMNxNwnPgftbwb6I"; try testing.expectEqualStrings(want_empty, try hashWith(&buf, "\xc2\xad", .{ .salt = salt12, .rounds = 10, .algs = &.{"sha-1"} })); try testing.expectEqualStrings(want_empty, try hashWith(&buf, "", .{ .salt = salt12, .rounds = 10, .algs = &.{"sha-1"} }));
// Control characters, ASCII or not, and invalid UTF-8. try testing.expectError(error.InvalidPassword, scram.verify(test_ctx, "a\tb", want_ix)); try testing.expectError(error.InvalidPassword, scram.verify(test_ctx, "\xc3\xa9\x7f", want_ix)); try testing.expectError(error.InvalidPassword, scram.verify(test_ctx, "\xff", want_ix)); // A right-to-left character followed by a left-to-right one. try testing.expectError(error.InvalidPassword, scram.verify(test_ctx, "\xd8\xa71", want_ix));
// Where passlib's reading is its own. It checks prohibited characters // after normalizing, so U+0340 prepares to U+0300: "a\u{0340}" hashes // as "\u{00E0}". try testing.expect(try scram.verify(test_ctx, "a\xcd\x80", "$scram$10$c2FsdHNhbHRzYWx0$sha-1=2Y2xhGe93bWhtGTdQFDmra6igAw")); try testing.expect(try scram.verify(test_ctx, "a\xcc\x80", "$scram$10$c2FsdHNhbHRzYWx0$sha-1=2Y2xhGe93bWhtGTdQFDmra6igAw")); // And it deletes U+200B, where PostgreSQL and the RFC's other readers // make it a space: "I\u{200B}X \u{00E0}" is "IX \u{00E0}". try testing.expect(try scram.verify(test_ctx, "I\xe2\x80\x8bX \xc3\xa0", want_ix));}
test "round trip with a random salt" { var buf: [512]u8 = undefined; const h = try hashWith(&buf, "hunter2", .{ .rounds = 5 }); try testing.expect(try scram.verify(test_ctx, "hunter2", h)); try testing.expect(!try scram.verify(test_ctx, "hunter3", h));}
test "verify checks one digest, verifyFull all of them" { // Checked against passlib 1.7.4's verify(..., full=False) and // verify(..., full=True). const sha1 = "sha-1=.fjFcnOrRJx9GGovX4liUqt.cv0"; const prefix = "$scram$10$c2FsdHNhbHRzYWx0$"; // An unknown but well-formed name: ignored by verify, uncomputable for // verifyFull. try testing.expect(try scram.verify(test_ctx, "test", prefix ++ sha1 ++ ",foo=AAAA")); try testing.expectError(error.MalformedHash, scram.verifyFull(test_ctx, "test", prefix ++ sha1 ++ ",foo=AAAA")); // A wrong-sized sha-256 is preferred to sha-1 and simply fails. try testing.expect(!try scram.verify(test_ctx, "test", prefix ++ sha1 ++ ",sha-256=AAAA")); try testing.expectError(error.MalformedHash, scram.verifyFull(test_ctx, "test", prefix ++ sha1 ++ ",sha-256=AAAA")); // A repeated name means its last value. try testing.expect(try scram.verify(test_ctx, "test", prefix ++ "sha-1=AAAA," ++ sha1)); try testing.expect(try scram.verifyFull(test_ctx, "test", prefix ++ "sha-1=AAAA," ++ sha1)); try testing.expect(!try scram.verify(test_ctx, "test", prefix ++ sha1 ++ ",sha-1=AAAA")); // md5 is not one verify checks. try testing.expect(try scram.verify(test_ctx, "test", prefix ++ sha1 ++ ",md5=AAAA")); try testing.expectError(error.MalformedHash, scram.verifyFull(test_ctx, "test", prefix ++ sha1 ++ ",md5=AAAA"));}
test "digest names" { // passlib 1.7.4: norm_hash_name(name, "iana"). const cases = [_][2][]const u8{ .{ "sha-1024", "sha1-024" }, .{ "sha1024", "sha1-024" }, .{ "foo", "foo" }, .{ "sha3-256", "sha3-256" }, .{ "sha-3-256", "sha3-256" }, .{ "sha_256", "sha-256" }, .{ " SCRAM-SHA-1-PLUS ", "sha-1" }, .{ "blake2b", "blake-2b" }, .{ "x.y", "x.y" }, .{ "a-1", "a1" }, .{ "ab1-", "ab1" }, .{ "sha2-256", "sha-256" }, .{ "ripemd", "ripemd-160" }, .{ "sha3256", "sha3-256" }, .{ "sha-12345", "sha1-2345" }, .{ "sha12", "sha12" }, .{ "sha-1-1", "sha-1-1" }, .{ "a1-12", "a1-12" }, }; for (cases) |c| { var buf: [max_name_len + 1]u8 = undefined; try testing.expectEqualStrings(c[1], normName(&buf, c[0]).?); } try testing.expect(isNormalName("sha-1")); try testing.expect(!isNormalName("sha1")); try testing.expect(!isNormalName("SHA-1")); try testing.expect(!isNormalName("sha-1024"));}
test "refusals" { // passlib 1.7.4's own malformed samples are in tests/vectors; these are // the rest of what parse checks. const prefix = "$scram$10$c2FsdHNhbHRzYWx0$"; inline for (.{ "$scram$10$c2FsdHNhbHRzYWx0$sha-1", // a settings string "$scram$10$c2FsdHNhbHRzYWx0$sha-1,sha-256", "$scram$0$c2FsdHNhbHRzYWx0$sha-1=.fjFcnOrRJx9GGovX4liUqt.cv0", "$scram$010$c2FsdHNhbHRzYWx0$sha-1=.fjFcnOrRJx9GGovX4liUqt.cv0", prefix ++ "sha-1=.fjFcnOrRJx9GGovX4liUqt.cv0,", prefix ++ "sha-1=.fjFcnOrRJx9GGovX4liUqt.cv0,sha-1024=AAAA", prefix ++ "sha-1=.fjFcnOrRJx9GGovX4liUqt.cv0,SHA-256=AAAA", prefix ++ "sha-1=.fjFcnOrRJx9GGovX4liUqt.cv0,ripemd-160=AAAA", prefix ++ "sha-1=.fjFcnOrRJx9GGovX4liUqt.cv0=", }) |h| try testing.expectError(error.MalformedHash, scram.verify(test_ctx, "test", h)); // A digest of the wrong length is well formed, and simply fails. try testing.expect(!try scram.verify(test_ctx, "test", prefix ++ "sha-1=.fjFcnOrRJx9GGovX4liUqt.cv"));
var buf: [256]u8 = undefined; var w: Io.Writer = .fixed(&buf); try testing.expectError(error.InvalidOptions, scram.hash(test_ctx, "x", .{ .algs = &.{"sha-256"} }, &w)); try testing.expectError(error.InvalidOptions, scram.hash(test_ctx, "x", .{ .algs = &.{ "sha-1", "md2" } }, &w)); try testing.expectError(error.InvalidOptions, scram.hash(test_ctx, "x", .{ .algs = &.{ "sha-1", "ripemd-160" } }, &w)); try testing.expectError(error.InvalidOptions, scram.hash(test_ctx, "x", .{ .algs = &.{} }, &w)); try testing.expectError(error.InvalidOptions, scram.hash(test_ctx, "x", .{ .rounds = 0 }, &w)); try testing.expectError(error.InvalidOptions, scram.hash(test_ctx, "x", .{ .salt_size = 1025 }, &w));}
test "needsUpdate" { // passlib 1.7.4: scram.needs_update(h) and the same after .using(...). const one = "$scram$10$c2FsdHNhbHRzYWx0$sha-1=.fjFcnOrRJx9GGovX4liUqt.cv0"; try testing.expect(try scram.needsUpdate(one, .{})); try testing.expect(!try scram.needsUpdate(one, .{ .algs = &.{"sha-1"} })); try testing.expect(try scram.needsUpdate(one, .{ .algs = &.{"sha-1"}, .min_desired_rounds = 11 })); const three = "$scram$10$c2FsdHNhbHRzYWx0$sha-1=.fjFcnOrRJx9GGovX4liUqt.cv0,sha-256=iftYIr.X2dO8fTe5.dR5g2bgp1B7bGT99zWB1zK8NqM,sha-512=oFTnWSfawerKmuuHa86N2m1btBdkkGQUMOBqBBr9br4vPqtSZqKNEaj8Ta9NyWaAfwOoog6UbBL./k1HSw0rqw"; try testing.expect(!try scram.needsUpdate(three, .{})); try testing.expect(try scram.needsUpdate(three, .{ .algs = &.{ "sha-1", "md5" } })); try testing.expect(!try scram.needsUpdate(three, .{ .algs = &.{"sha-1"} })); try testing.expectError(error.MalformedHash, scram.needsUpdate("$scram$10$c2FsdHNhbHRzYWx0$sha-1", .{}));}