Something went wrong. Try again.
passlib's password hash schemes, ported to Zig 0.16
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319# SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us># SPDX-License-Identifier: MIT
"""Writes passlib 1.7.4's test vectors out as ZON, for tests/vectors.zig.
Two sets:
* tests/vectors/known.zon -- every known-answer table in passlib's own test suite (known_correct_hashes, known_alternate_hashes, known_correct_configs, known_malformed_hashes, known_unidentified_hashes and known_other_hashes), read out of the test classes themselves, so nothing is transcribed by hand.* tests/vectors/generated.zon -- hashes passlib makes here and now, from random passwords with random salts, for every scheme it can make one for.
Each row carries the password as the bytes passlib actually hashed. Where thetest gives text, it is encoded the way the handler would encode it: UTF-8,or the handler's own default encoding (cp437 for lmhash), or the encoding arow names. Each row with a verifiable hash also carries a wrong password thatpasslib has confirmed does *not* verify, since for some schemes (DES cryptstops at eight characters, bcrypt at 72, lmhash ignores case) the obviouswrong password is not wrong.
Run it in the devshell, whose python has passlib 1.7.4, bcrypt andargon2-cffi:
nix develop -c python3 tools/gen_vectors.py"""
import importlibimport inspectimport osimport randomimport sysimport warnings
warnings.simplefilter("ignore")
# passlib's own bcrypt, since 1.7.4 cannot drive bcrypt 5.x; see flake.nix.# It has to be set before passlib first looks for a backend.os.environ["PASSLIB_BUILTIN_BCRYPT"] = "enabled"
import passlibfrom passlib import hash as phfrom passlib.registry import list_crypt_handlers, get_crypt_handlerfrom passlib.tests.utils import HandlerCase
assert passlib.__version__ == "1.7.4", passlib.__version__
HERE = os.path.dirname(os.path.abspath(__file__))OUT = os.path.join(HERE, "..", "tests", "vectors")
TEST_MODULES = [ "passlib.tests.test_handlers", "passlib.tests.test_handlers_argon2", "passlib.tests.test_handlers_bcrypt", "passlib.tests.test_handlers_cisco", "passlib.tests.test_handlers_django", "passlib.tests.test_handlers_pbkdf2", "passlib.tests.test_handlers_scrypt",]
def zon_string(b): if isinstance(b, str): b = b.encode("utf-8") out = [] for c in b: if c == 0x22: out.append('\\"') elif c == 0x5C: out.append("\\\\") elif 0x20 <= c < 0x7F: out.append(chr(c)) else: out.append("\\x%02x" % c) return '"' + "".join(out) + '"'
def zon_opt(b): return "null" if b is None else zon_string(b)
def to_bytes(secret, handler, kwds): if isinstance(secret, bytes): return secret encoding = kwds.get("encoding") or getattr(handler, "default_encoding", None) or "utf-8" # lmhash upper-cases text before encoding it, and upper-cases bytes only # in ASCII, so the bytes that hash the same as the text are those of the # text upper-cased. if handler.name == "lmhash": secret = secret.upper() return secret.encode(encoding)
def context_of(kwds): return kwds.get("user"), kwds.get("realm")
def call_kwds(kwds, handler): """The keywords to pass passlib for this row, dropping what it ignores.""" allowed = set(getattr(handler, "context_kwds", ())) return {k: v for k, v in kwds.items() if k in allowed}
def verifies(handler, secret, hash, kwds): try: return bool(handler.verify(secret, hash, **call_kwds(kwds, handler))) except (ValueError, TypeError): return None
def wrong_password(handler, secret_bytes, hash, kwds): """A password passlib confirms does not verify against `hash`.""" for candidate in (b"x" + secret_bytes, secret_bytes + b"x", b"\x01wrong\x01", b"Z" * 3): if candidate == secret_bytes: continue if verifies(handler, candidate, hash, kwds) is False: return candidate return None
class Rows: def __init__(self): self.rows = [] self.seen = set()
def add(self, **row): key = tuple(sorted((k, v if not isinstance(v, list) else tuple(v)) for k, v in row.items())) if key in self.seen: return self.seen.add(key) self.rows.append(row)
def write(self, path): with open(path, "w") as f: # REUSE-IgnoreStart f.write("// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>\n") f.write("// SPDX-License-Identifier: MIT\n") # REUSE-IgnoreEnd f.write("//\n") f.write("// Generated by tools/gen_vectors.py from passlib %s. Do not edit.\n\n" % passlib.__version__) f.write(".{\n") for r in self.rows: fields = [ ".scheme = %s" % zon_string(r["scheme"]), ".kind = .%s" % r["kind"], ".hash = %s" % zon_string(r["hash"]), ] if r.get("password") is not None: fields.append(".password = %s" % zon_string(r["password"])) if r.get("wrong") is not None: fields.append(".wrong = %s" % zon_string(r["wrong"])) if r.get("user") is not None: fields.append(".user = %s" % zon_string(r["user"])) if r.get("realm") is not None: fields.append(".realm = %s" % zon_string(r["realm"])) f.write(" .{ " + ", ".join(fields) + " },\n") f.write("}\n")
def test_classes(): seen = {} for name in TEST_MODULES: try: mod = importlib.import_module(name) except Exception as e: # django missing, and so on print("skipping %s: %s" % (name, e), file=sys.stderr) continue for _, cls in inspect.getmembers(mod, inspect.isclass): if not issubclass(cls, HandlerCase) or getattr(cls, "handler", None) is None: continue seen.setdefault(cls.handler.name, []).append(cls) return seen
def instance_of(cls): try: return cls("test_70_hashes") except Exception: return None
def known(classes): rows = Rows() for scheme, clss in sorted(classes.items()): for cls in clss: inst = instance_of(cls) if inst is None: continue handler = cls.handler disabled = bool(getattr(handler, "is_disabled", False))
def populate(secret): kwds = {} s = inst.populate_context(secret, kwds) # UserHandlerMixin supplies a default user where a row has none. if getattr(inst, "requires_user", False) and "user" not in kwds: kwds["user"] = inst.default_user return s, kwds
def correct(kind, secret, hash, check_hash=None): s, kwds = populate(secret) b = to_bytes(s, handler, kwds) user, realm = context_of(kwds) row = dict(scheme=scheme, kind=kind, hash=hash, password=b, user=user, realm=realm) if not disabled: ok = verifies(handler, b, hash, kwds) if ok is not True: print("%s: passlib does not verify its own %s row %r" % (scheme, kind, hash), file=sys.stderr) return row["wrong"] = wrong_password(handler, b, hash, kwds) rows.add(**row)
for secret, hash in cls.known_correct_hashes: correct("disabled" if disabled else "correct", secret, hash) for alt, secret, hash in cls.known_alternate_hashes: correct("disabled" if disabled else "correct", secret, alt) for config, secret, hash in cls.known_correct_configs: _, kwds = populate(secret) user, realm = context_of(kwds) # Some test classes fake the error for a config string their # handler actually verifies (sun_md5_crypt's do_verify raises # for anything ending "$.................DUMMY"), so ask the # handler itself. if verifies(handler, "stub", config, kwds) is not None: print("%s: passlib verifies config %r rather than refusing it" % (scheme, config), file=sys.stderr) continue rows.add(scheme=scheme, kind="config", hash=config, user=user, realm=realm) _, stub_kwds = populate("stub") user, realm = context_of(stub_kwds) for hash in cls.known_malformed_hashes: rows.add(scheme=scheme, kind="malformed", hash=hash, user=user, realm=realm) for hash in cls.known_unidentified_hashes: rows.add(scheme=scheme, kind="unidentified", hash=hash, user=user, realm=realm) if not cls.accepts_all_hashes: for other, hash in cls.known_other_hashes: kind = "own" if other == scheme else "foreign" rows.add(scheme=scheme, kind=kind, hash=hash, user=user, realm=realm) return rows
# Settings that keep generated hashes cheap without leaving the ranges the# schemes accept.CHEAP = { "argon2": dict(memory_cost=64, rounds=1, parallelism=1), "django_argon2": dict(memory_cost=64, rounds=1, parallelism=1), "scrypt": dict(rounds=4, block_size=4, parallelism=1),}
PASSWORD_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 !#$%&*+-./:;<=>?@^_~"UNICODE_CHARS = "éü߀¥Ω中\U0001f600"
def cheap(handler): name = handler.name if name in CHEAP: return handler.using(**CHEAP[name]) if "rounds" in getattr(handler, "setting_kwds", ()): low = getattr(handler, "min_rounds", None) or 1 if getattr(handler, "rounds_cost", "linear") == "log2": return handler.using(rounds=max(low, 4)) return handler.using(rounds=max(low, 1000 if low < 1000 else low)) return handler
def generated(rng): rows = Rows() for name in list_crypt_handlers(): handler = get_crypt_handler(name) if getattr(handler, "is_disabled", False) or name in ("unix_fallback",): continue try: h = cheap(handler) except Exception as e: print("%s: cannot configure: %s" % (name, e), file=sys.stderr) continue context = set(getattr(handler, "context_kwds", ())) for i in range(6): length = rng.randrange(0, 24) chars = PASSWORD_CHARS + (UNICODE_CHARS if i % 2 else "") secret = "".join(rng.choice(chars) for _ in range(length)) kwds = {} if "user" in context: kwds["user"] = "user%d" % rng.randrange(1000) if "realm" in context: kwds["realm"] = "realm%d" % rng.randrange(1000) try: hash = h.hash(secret, **kwds) except Exception as e: print("%s: cannot hash %r: %s" % (name, secret, e), file=sys.stderr) continue b = to_bytes(secret, handler, kwds) # passlib can make a hash it will not then read: ldap_plaintext # hashes the empty password to the empty string, which it does # not identify. if verifies(handler, b, hash, kwds) is not True: print("%s: passlib does not verify its own hash %r" % (name, hash), file=sys.stderr) continue rows.add( scheme=name, kind="correct", hash=hash, password=b, user=kwds.get("user"), realm=kwds.get("realm"), wrong=wrong_password(handler, b, hash, kwds), ) return rows
def main(): os.makedirs(OUT, exist_ok=True) classes = test_classes() k = known(classes) k.write(os.path.join(OUT, "known.zon")) g = generated(random.Random(0x7061736c)) g.write(os.path.join(OUT, "generated.zon")) print("known: %d rows over %d schemes; generated: %d rows" % (len(k.rows), len(classes), len(g.rows)))
if __name__ == "__main__": main()