#!/usr/bin/python3 -I
# Tells plinius-encrypt whether a password is the login password of a normal user. On the
# phone that password is the PIN of the screen lock, and the encryption password must differ
# from it: the PIN is short and typed in view of others many times a day.
#
# Reads the password from stdin (one line, a trailing newline is dropped) and compares it with
# the /etc/shadow hash of every account with a UID from UID_MIN to UID_MAX of /etc/login.defs
# (default 1000 to 60000). Hashes with libcrypt like pam_unix, so every method it supports
# works (yescrypt, sha512crypt ...). Logs nothing: unlike unix_chkpwd, a mismatch is the normal
# case here and no failed login. Root only (reads /etc/shadow).
#
# Usage: login-password-check [PASSWD SHADOW]   (other files for tests)
# Exit codes: 0 equals the password of a user, 1 equals none, 2 error (files not readable)
import ctypes
import hmac
import sys


def login_uid_range():
    """UID_MIN and UID_MAX from /etc/login.defs, else the shadow-utils defaults."""
    lo, hi = 1000, 60000
    try:
        with open("/etc/login.defs") as f:
            for line in f:
                parts = line.split()
                if len(parts) >= 2 and parts[0] in ("UID_MIN", "UID_MAX"):
                    try:
                        value = int(parts[1])
                    except ValueError:
                        continue
                    if parts[0] == "UID_MIN":
                        lo = value
                    else:
                        hi = value
    except OSError:
        pass
    return lo, hi


def main():
    passwd_file = sys.argv[1] if len(sys.argv) > 2 else "/etc/passwd"
    shadow_file = sys.argv[2] if len(sys.argv) > 2 else "/etc/shadow"

    password = sys.stdin.buffer.readline().rstrip(b"\n")
    if not password:
        return 1

    lo, hi = login_uid_range()
    try:
        with open(passwd_file, "rb") as f:
            users = set()
            for line in f:
                fields = line.rstrip(b"\n").split(b":")
                if len(fields) >= 3 and fields[2].isdigit() and lo <= int(fields[2]) <= hi:
                    users.add(fields[0])
        with open(shadow_file, "rb") as f:
            hashes = []
            for line in f:
                fields = line.rstrip(b"\n").split(b":")
                # Skip accounts without a usable password: empty, "*", or locked with "!"
                if len(fields) >= 2 and fields[0] in users and fields[1][:1] not in (b"", b"*", b"!"):
                    hashes.append(fields[1])
    except OSError as e:
        print(f"login-password-check: {e}", file=sys.stderr)
        return 2

    try:
        libcrypt = ctypes.CDLL("libcrypt.so.2")
    except OSError as e:
        print(f"login-password-check: {e}", file=sys.stderr)
        return 2
    crypt = libcrypt.crypt
    crypt.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
    crypt.restype = ctypes.c_char_p

    found = False
    # Check every hash, also after a match, so the run time does not tell which user matched
    for h in hashes:
        # The stored hash carries method, parameters and salt; crypt() fails with "*0"/"*1"
        # (never a valid hash) or NULL for a method it does not know
        result = crypt(password, h)
        if result is not None and hmac.compare_digest(result, h):
            found = True
    return 0 if found else 1


if __name__ == "__main__":
    sys.exit(main())
