// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Oracle Database's password hashes: passlib's `passlib.handlers.oracle`. //! //! * `oracle10`, the hash Oracle 7 through 10g kept in `SYS.USER$`: the //! user name and password, upper-cased and concatenated, in UTF-16BE, //! encrypted with DES-CBC under a fixed key, then encrypted again under //! the last block of that. Sixteen upper-case hex characters. //! * `oracle11`, 11g's replacement: SHA-1 of the password and a ten-byte //! random salt, written `S:` + 40 hex characters of digest + 20 of salt. //! //! **Both are obsolete.** `oracle10` is case-insensitive, salted only with //! the user name, so every `SYSTEM` account shares a table, and a single //! DES key's worth of work. `oracle11` is a single salted SHA-1, fast //! enough to try billions of guesses a second. Oracle 12c moved on to //! PBKDF2 and SHA-512. They are here to read what old databases and the //! audits of them still hold. const std = @import("std"); const Io = std.Io; const testing = std.testing; const crypto_ext = @import("std_crypto_ext"); const Des = crypto_ext.Des; 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"); // -- oracle10 --------------------------------------------------------------- /// The Oracle 7 to 10g hash, salted with the user name from `Context.user`. /// /// The user name and the password, both UTF-8, are concatenated and /// upper-cased with Python's full Unicode mapping, as passlib does, so `ß` /// becomes `SS`. passlib requires a user: without one, `error.MissingUser`, /// and for a user that is not UTF-8, `error.InvalidUser`. Verification /// accepts hex of either case. pub const oracle10 = struct { pub const name = "oracle10"; pub const Options = struct {}; const hex_len = 16; const magic = [8]u8{ 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF }; fn parse(h: []const u8) Error![hex_len]u8 { if (h.len != hex_len or !encoding.allIn(h, encoding.hex_chars)) return error.MalformedHash; var out: [hex_len]u8 = undefined; for (&out, h) |*o, c| o.* = std.ascii.toUpper(c); return out; } /// passlib's `des_cbc_encrypt`: `input`, which is a whole number of /// blocks, DES-CBC-encrypted under `key` with a zero IV, and only the /// last block kept. With no input at all that is the IV. fn desCbcMac(key: [8]u8, input: []const u8) [8]u8 { var chain = [_]u8{0} ** 8; const des = Des.initEnc(key); var i: usize = 0; while (i < input.len) : (i += 8) { var block: [8]u8 = undefined; for (&block, input[i..][0..8], chain) |*b, x, y| b.* = x ^ y; des.encrypt(&chain, &block); } return chain; } fn compute(ctx: Context, password: []const u8, out: *[hex_len]u8) Error!void { const gpa = ctx.gpa; const user = ctx.user orelse return error.MissingUser; if (!std.unicode.utf8ValidateSlice(user)) return error.InvalidUser; if (!std.unicode.utf8ValidateSlice(password)) return error.InvalidPassword; const joined = try std.mem.concat(gpa, u8, &.{ user, password }); defer { std.crypto.secureZero(u8, joined); gpa.free(joined); } const upper = try unicode_case.upper(gpa, joined); defer { std.crypto.secureZero(u8, upper); gpa.free(upper); } const wide = try handler.utf16le(gpa, upper); defer { std.crypto.secureZero(u8, wide); gpa.free(wide); } // UTF-16BE, NUL-padded to a whole number of DES blocks. const padded = try gpa.alloc(u8, std.mem.alignForward(usize, wide.len, 8)); defer { std.crypto.secureZero(u8, padded); gpa.free(padded); } @memset(padded, 0); var i: usize = 0; while (i < wide.len) : (i += 2) { padded[i] = wide[i + 1]; padded[i + 1] = wide[i]; } const first = desCbcMac(magic, padded); const second = desCbcMac(first, padded); _ = encoding.hexUpper(out, &second); } pub fn identify(h: []const u8) bool { _ = parse(h) catch return false; return true; } pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { _ = options; try handler.checkPasswordLen(password); var out: [hex_len]u8 = undefined; try compute(ctx, password, &out); try w.writeAll(&out); } pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { try handler.checkPasswordLen(password); const stored = try parse(h); var out: [hex_len]u8 = undefined; try compute(ctx, password, &out); return handler.eql(&stored, &out); } pub fn needsUpdate(h: []const u8, options: Options) Error!bool { _ = options; _ = try parse(h); return false; } }; // -- oracle11 --------------------------------------------------------------- /// The Oracle 11g hash: `S:`, then SHA-1 of the password bytes and the /// ten-byte salt as 40 hex characters, then the salt as 20. /// /// passlib matches it case-insensitively and upper-cases the digest, but /// requires the salt in upper case: a lower-case salt is identified and is /// `error.MalformedHash` to verify. A single trailing newline is accepted, /// since Python's `$` matches before one. pub const oracle11 = struct { pub const name = "oracle11"; const checksum_len = 40; const salt_len = 20; pub const Options = struct { /// The salt, 20 upper-case hex characters. Null, the default, draws /// a random one. salt: ?[]const u8 = null, }; /// passlib's regular expression, `^S:[0-9a-f]{40}[0-9a-f]{20}$` under /// `re.IGNORECASE`. Python's case folding makes U+017F, `ſ`, match the /// `S`; such a string is identified and then refused, as it is not ASCII. pub fn identify(h: []const u8) bool { var rest = h; if (std.mem.startsWith(u8, rest, "S:") or std.mem.startsWith(u8, rest, "s:")) { rest = rest[2..]; } else if (std.mem.startsWith(u8, rest, "\xc5\xbf:")) { rest = rest[3..]; } else return false; if (std.mem.endsWith(u8, rest, "\n")) rest = rest[0 .. rest.len - 1]; return rest.len == checksum_len + salt_len and encoding.allIn(rest, encoding.hex_chars); } const Parsed = struct { checksum: [checksum_len]u8, salt: *const [salt_len]u8 }; fn parse(h: []const u8) Error!Parsed { if (!identify(h) or !std.ascii.isAscii(h[0])) return error.MalformedHash; const body = h[2..][0 .. checksum_len + salt_len]; const salt = body[checksum_len..]; if (!encoding.allIn(salt, encoding.upper_hex_chars)) return error.MalformedHash; var checksum: [checksum_len]u8 = undefined; for (&checksum, body[0..checksum_len]) |*o, c| o.* = std.ascii.toUpper(c); return .{ .checksum = checksum, .salt = salt[0..salt_len] }; } fn compute(password: []const u8, salt: *const [salt_len]u8, out: *[checksum_len]u8) Error!void { var raw_salt: [salt_len / 2]u8 = undefined; _ = try encoding.hexDecode(&raw_salt, salt); var sha = Sha1.init(.{}); sha.update(password); sha.update(&raw_salt); var digest: [Sha1.digest_length]u8 = undefined; sha.final(&digest); _ = encoding.hexUpper(out, &digest); } 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: *const [salt_len]u8 = if (options.salt) |s| blk: { if (s.len != salt_len or !encoding.allIn(s, encoding.upper_hex_chars)) return error.InvalidOptions; break :blk s[0..salt_len]; } else (try handler.randomChars(ctx.io, &salt_buf, encoding.upper_hex_chars))[0..salt_len]; var checksum: [checksum_len]u8 = undefined; try compute(password, salt, &checksum); try w.print("S:{s}{s}", .{ checksum, salt }); } pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { _ = ctx; try handler.checkPasswordLen(password); const parsed = try parse(h); var checksum: [checksum_len]u8 = undefined; try compute(password, parsed.salt, &checksum); return handler.eql(&parsed.checksum, &checksum); } /// 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(h); return false; } }; /// The schemes this module defines, in the order `registry.identify` tries /// them. pub const schemes = .{ oracle10, oracle11 }; comptime { for (schemes) |S| handler.check(S); } fn hashTo(buf: []u8, comptime S: type, ctx: Context, password: []const u8, options: S.Options) ![]const u8 { var w: Io.Writer = .fixed(buf); try S.hash(ctx, password, options, &w); return w.buffered(); } fn withUser(user: ?[]const u8) Context { return .{ .io = testing.io, .gpa = testing.allocator, .user = user }; } test "hashes reproduce passlib" { // passlib 1.7.4: oracle10.hash("tiger", user="scott") and so on. var buf: [80]u8 = undefined; try testing.expectEqualStrings("F894844C34402B67", try hashTo(&buf, oracle10, withUser("scott"), "tiger", .{})); try testing.expectEqualStrings("0000000000000000", try hashTo(&buf, oracle10, withUser(""), "", .{})); // "straße" upper-cases to "STRASSE", and "táБℓə" to "TÁБℓƏ". try testing.expectEqualStrings("3F63DD220146C004", try hashTo(&buf, oracle10, withUser("bob"), "stra\u{df}e", .{})); try testing.expectEqualStrings("B915A853F297B281", try hashTo(&buf, oracle10, withUser("System"), "t\u{e1}\u{411}\u{2113}\u{259}", .{})); try testing.expectEqualStrings( "S:CA7B41C05052F8FB9B3E669A24DD33BF69F6F1284FDE0A1E4B5DBE7D8B1B", try hashTo(&buf, oracle11, withUser(null), "password", .{ .salt = "4FDE0A1E4B5DBE7D8B1B" }), ); } test "round trips and case" { var buf: [80]u8 = undefined; const h = try hashTo(&buf, oracle11, withUser(null), "hunter2", .{}); try testing.expect(oracle11.identify(h)); try testing.expect(try oracle11.verify(withUser(null), "hunter2", h)); try testing.expect(!try oracle11.verify(withUser(null), "hunter3", h)); try testing.expect(try oracle10.verify(withUser("SCOTT"), "TIGER", "f894844c34402b67")); // passlib accepts a lower-case "s:" and a trailing newline, and refuses // a lower-case salt. const good = "S:CA7B41C05052F8FB9B3E669A24DD33BF69F6F1284FDE0A1E4B5DBE7D8B1B"; try testing.expect(try oracle11.verify(withUser(null), "password", "s" ++ good[1..])); try testing.expect(try oracle11.verify(withUser(null), "password", good ++ "\n")); try testing.expectError(error.MalformedHash, oracle11.verify(withUser(null), "password", good[0..42] ++ "4fde0a1e4b5dbe7d8b1b")); try testing.expect(oracle11.identify("\u{17f}" ++ good[1..])); try testing.expectError(error.MalformedHash, oracle11.verify(withUser(null), "password", "\u{17f}" ++ good[1..])); try testing.expect(!try oracle11.needsUpdate(good, .{})); } test "refusals" { var buf: [80]u8 = undefined; try testing.expectError(error.MissingUser, hashTo(&buf, oracle10, withUser(null), "x", .{})); try testing.expectError(error.InvalidUser, hashTo(&buf, oracle10, withUser("\xff"), "x", .{})); try testing.expectError(error.MalformedHash, oracle10.verify(withUser(null), "x", "zz")); try testing.expectError(error.InvalidPassword, hashTo(&buf, oracle10, withUser("u"), "\xff", .{})); try testing.expectError(error.InvalidOptions, hashTo(&buf, oracle11, withUser(null), "x", .{ .salt = "4fde0a1e4b5dbe7d8b1b" })); try testing.expectError(error.InvalidOptions, hashTo(&buf, oracle11, withUser(null), "x", .{ .salt = "4FDE" })); }