Something went wrong. Try again.
passlib's password hash schemes, ported to Zig 0.16
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Microsoft SQL Server's password hashes: passlib's//! `passlib.handlers.mssql`.//!//! Both are `0x0100`, a four-byte salt, and SHA-1 of the password in//! UTF-16LE followed by the salt, all in upper-case hex.//!//! * `mssql2000`, from SQL Server 2000, also carries a second digest of the//! password upper-cased: 94 characters.//! * `mssql2005`, from SQL Server 2005 to 2008, dropped the second digest://! 54 characters.//!//! **Both are obsolete.** A single SHA-1 is fast enough to try billions of//! guesses a second, and `mssql2000`'s upper-case digest makes the password//! case-insensitive for anyone who attacks that half, which is all SQL//! Server 2000 itself ever checked. SQL Server 2012 moved on to SHA-512.//! They are here to read what old databases and their backups still hold.
const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;const testing = std.testing;
const Sha1 = std.crypto.hash.Sha1;const encoding = @import("../encoding.zig");const handler = @import("../handler.zig");const Context = handler.Context;const Error = handler.Error;const unicode_case = @import("../unicode_case.zig");
const ident = "0x0100";const salt_len = 4;const digest_len = Sha1.digest_length;
/// passlib's `_raw_mssql`: SHA-1 of `password`, which must be UTF-8, as/// UTF-16LE, then the salt.fn rawMssql(gpa: Allocator, password: []const u8, salt: *const [salt_len]u8) Error![digest_len]u8 { const wide = try handler.utf16le(gpa, password); defer { std.crypto.secureZero(u8, wide); gpa.free(wide); } var sha = Sha1.init(.{}); sha.update(wide); sha.update(salt); var out: [digest_len]u8 = undefined; sha.final(&out); return out;}
/// `rawMssql` of `password` upper-cased as Python's `str.upper()` does.fn rawMssqlUpper(gpa: Allocator, password: []const u8, salt: *const [salt_len]u8) Error![digest_len]u8 { const upper = try unicode_case.upper(gpa, password); defer { std.crypto.secureZero(u8, upper); gpa.free(upper); } return rawMssql(gpa, upper, salt);}
/// The raw salt and checksum a hash of `checksum_len` digest bytes holds.fn Parsed(comptime checksum_len: usize) type { return struct { salt: [salt_len]u8, checksum: [checksum_len]u8 };}
/// passlib's `_parse_mssql`: `0x0100` and exactly the right number of hex/// characters of either case.fn parse(comptime checksum_len: usize, h: []const u8) Error!Parsed(checksum_len) { if (!identifyLen(h, checksum_len)) return error.MalformedHash; var raw: [salt_len + checksum_len]u8 = undefined; _ = try encoding.hexDecode(&raw, h[ident.len..]); return .{ .salt = raw[0..salt_len].*, .checksum = raw[salt_len..].* };}
/// passlib's `_ident_mssql`: the prefix and the length, and nothing about/// the characters, so a hash with a bad character in it is identified and/// then refused.fn identifyLen(h: []const u8, checksum_len: usize) bool { return h.len == ident.len + 2 * (salt_len + checksum_len) and std.mem.startsWith(u8, h, ident);}
/// The salt from `Options`, or four random bytes.fn getSalt(io: Io, salt: ?[]const u8, buf: *[salt_len]u8) Error!*const [salt_len]u8 { if (salt) |s| { if (s.len != salt_len) return error.InvalidOptions; return s[0..salt_len]; } _ = try handler.randomBytes(io, buf); return buf;}
fn writeHash(w: *Io.Writer, salt: *const [salt_len]u8, checksum: []const u8) Error!void { var hex: [2 * (salt_len + 2 * digest_len)]u8 = undefined; try w.writeAll(ident); try w.writeAll(encoding.hexUpper(&hex, salt)); try w.writeAll(encoding.hexUpper(&hex, checksum));}
/// SQL Server 2000: `0x0100`, the salt, the digest of the password, and the/// digest of the password upper-cased with Python's full Unicode mapping.////// Verification checks only the upper-case digest, as passlib does and as/// SQL Server 2000 did, so it is case-insensitive.pub const mssql2000 = struct { pub const name = "mssql2000";
const checksum_len = 2 * digest_len;
pub const Options = struct { /// The salt, four raw bytes. Null, the default, draws a random one. salt: ?[]const u8 = null, };
pub fn identify(h: []const u8) bool { return identifyLen(h, checksum_len); }
pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { try handler.checkPasswordLen(password); var salt_buf: [salt_len]u8 = undefined; const salt = try getSalt(ctx.io, options.salt, &salt_buf); const plain = try rawMssql(ctx.gpa, password, salt); const upper = try rawMssqlUpper(ctx.gpa, password, salt); try writeHash(w, salt, &(plain ++ upper)); }
pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { try handler.checkPasswordLen(password); const parsed = try parse(checksum_len, h); const upper = try rawMssqlUpper(ctx.gpa, password, &parsed.salt); return handler.eql(parsed.checksum[digest_len..], &upper); }
/// Always false for a hash that parses: there is nothing to be out of /// date. pub fn needsUpdate(h: []const u8, options: Options) Error!bool { _ = options; _ = try parse(checksum_len, h); return false; }};
/// SQL Server 2005: `0x0100`, the salt, and the digest of the password./// It is case-sensitive.pub const mssql2005 = struct { pub const name = "mssql2005";
const checksum_len = digest_len;
pub const Options = struct { /// The salt, four raw bytes. Null, the default, draws a random one. salt: ?[]const u8 = null, };
pub fn identify(h: []const u8) bool { return identifyLen(h, checksum_len); }
pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { try handler.checkPasswordLen(password); var salt_buf: [salt_len]u8 = undefined; const salt = try getSalt(ctx.io, options.salt, &salt_buf); try writeHash(w, salt, &try rawMssql(ctx.gpa, password, salt)); }
pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { try handler.checkPasswordLen(password); const parsed = try parse(checksum_len, h); const digest = try rawMssql(ctx.gpa, password, &parsed.salt); return handler.eql(&parsed.checksum, &digest); }
/// Always false for a hash that parses: there is nothing to be out of /// date. pub fn needsUpdate(h: []const u8, options: Options) Error!bool { _ = options; _ = try parse(checksum_len, h); return false; }};
/// The schemes this module defines, in the order `registry.identify` tries/// them.pub const schemes = .{ mssql2000, mssql2005 };
comptime { for (schemes) |S| handler.check(S);}
const test_ctx: Context = .{ .io = testing.io, .gpa = testing.allocator };
fn hashTo(buf: []u8, comptime S: type, password: []const u8, options: S.Options) ![]const u8 { var w: Io.Writer = .fixed(buf); try S.hash(test_ctx, password, options, &w); return w.buffered();}
test "fixed salts reproduce passlib" { // passlib 1.7.4: mssql2000.using(salt=b"\x5b\x20\x05\x43").hash("Test") // and so on. var buf: [128]u8 = undefined; try testing.expectEqualStrings( "0x01005B200543A219F7233A7238BCA29F2CC91961C7957CC36E50979CC386A0577C1CA2FA073136EA4BCD82C0E1DB", try hashTo(&buf, mssql2000, "Test", .{ .salt = "\x5b\x20\x05\x43" }), ); try testing.expectEqualStrings( "0x010036D726AE2E8B6D187B77B633845881FB76B9F23705579D8C", try hashTo(&buf, mssql2005, "Test", .{ .salt = "\x36\xd7\x26\xae" }), ); // "straße" upper-cases to "STRASSE". try testing.expectEqualStrings( "0x010061626364852D8B3D254E63F781449BCEEAE8D0A8DD33B5B0B7F1229242C877721EF5F880209AC76F1B448E86", try hashTo(&buf, mssql2000, "stra\u{df}e", .{ .salt = "abcd" }), );}
test "round trips and case" { var buf: [128]u8 = undefined; inline for (schemes) |S| { const h = try hashTo(&buf, S, "hunter2", .{}); try testing.expect(S.identify(h)); try testing.expect(try S.verify(test_ctx, "hunter2", h)); try testing.expect(!try S.verify(test_ctx, "hunter3", h)); try testing.expect(!try S.needsUpdate(h, .{})); } // mssql2000 checks only the upper-case digest; passlib verifies "TEST" // and lower-case hex against a hash of "Test". const h2000 = "0x010061626364746FE313030AC8068B16C00AECCD7B77BFD5C5D44C5CEDE64A94E12C922F39ACF9F2C36F15E1F94E"; try testing.expect(try mssql2000.verify(test_ctx, "TEST", h2000)); var lower: [h2000.len]u8 = undefined; _ = std.ascii.lowerString(&lower, h2000); try testing.expect(try mssql2000.verify(test_ctx, "test", &lower)); try testing.expect(!try mssql2005.verify(test_ctx, "TEST", "0x010036D726AE2E8B6D187B77B633845881FB76B9F23705579D8C"));}
test "refusals" { var buf: [128]u8 = undefined; try testing.expectError(error.InvalidOptions, hashTo(&buf, mssql2005, "x", .{ .salt = "abc" })); const bad = "0x0100" ++ "z" ** 48; try testing.expect(mssql2005.identify(bad)); try testing.expectError(error.MalformedHash, mssql2005.verify(test_ctx, "x", bad)); try testing.expectError(error.InvalidPassword, hashTo(&buf, mssql2005, "\xff", .{}));}