#!/usr/bin/python3
"""uFTP authentication hook: users in PostgreSQL (an example to adapt: it was not tried against a real server in the uFTP suite).

Settings in uftp-auth-postgres.conf next to the script (keep it 0600):
  service  = uftp                 a service in ~/.pg_service.conf or PGSERVICEFILE (host, dbname, user, password): nothing secret on a command line
  command  = /usr/bin/psql        (default)
The table:  uftp_users(name text primary key, password_hash text, home text, enabled boolean, readonly boolean, permissions text,
                       max_connections int, max_download_speed int, max_upload_speed int,
                       owner_user text, owner_group text, allow_from text, deny_from text, umask text)
The name of the client goes to psql as a VARIABLE (-v name=...) and the query uses :'name', which psql quotes itself.
"""
import base64
import hashlib
import hmac
import os
import re
import subprocess
import sys

NAME = re.compile(r"^[A-Za-z0-9._@-]{1,64}$")
DUMMY = "$pbkdf2-sha256$100000$AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
KEYS = ("readonly", "permissions", "max_connections", "max_download_speed", "max_upload_speed", "owner_user", "owner_group", "allow_from", "deny_from", "umask")
QUERY = ("SELECT password_hash, home, CASE WHEN readonly THEN 1 ELSE 0 END, permissions, max_connections, max_download_speed, max_upload_speed, "
         "owner_user, owner_group, allow_from, deny_from, umask "
         "FROM uftp_users WHERE name = :'name' AND enabled")


def conf():
    values = {}
    path = os.path.abspath(__file__) + ".conf"
    if os.path.exists(path):
        for line in open(path):
            line = line.strip()
            if line and not line.startswith("#") and "=" in line:
                key, value = line.split("=", 1)
                values[key.strip()] = value.strip()
    return values


def unab64(text):
    return base64.b64decode(text.replace(".", "+") + "=" * (-len(text) % 4))


def verify(stored, password):
    try:
        _, scheme, iterations, salt, digest = stored.split("$")
        return scheme == "pbkdf2-sha256" and hmac.compare_digest(hashlib.pbkdf2_hmac("sha256", password.encode(), unab64(salt), int(iterations)), unab64(digest))
    except (ValueError, TypeError):
        return False


def main():
    if len(sys.argv) < 2 or sys.argv[1] != "auth":
        sys.exit(__doc__)
    settings = conf()
    name = sys.stdin.readline().rstrip("\n")
    password = sys.stdin.readline().rstrip("\n")
    if not NAME.match(name):
        sys.exit(1)
    command = [settings.get("command", "/usr/bin/psql"), "-X", "-q", "-A", "-t", "-F", "\t", "-v", "ON_ERROR_STOP=1", "-v", "name=" + name]
    if "service" in settings:
        command.append("service=" + settings["service"] + " connect_timeout=3")
    try:
        result = subprocess.run(command, input=QUERY + ";\n", capture_output=True, text=True, timeout=4)   # the query goes on stdin: psql expands :'name'
    except (OSError, subprocess.TimeoutExpired) as error:
        sys.stderr.write("psql: %s\n" % error)
        sys.exit(3)
    if result.returncode != 0:
        sys.stderr.write("psql: " + (result.stderr.strip().split("\n")[0] if result.stderr.strip() else "failed") + "\n")
        sys.exit(3)
    row = result.stdout.rstrip("\n").split("\t") if result.stdout.strip() else None
    ok = verify(row[0] if row else DUMMY, password)
    if not row or not ok or len(row) < 2 + len(KEYS):
        sys.exit(1)
    print("home=" + row[1])
    for key, value in zip(KEYS, row[2:]):
        if value != "" and not (key == "readonly" and value == "0"):
            print("%s=%s" % (key, value))


if __name__ == "__main__":
    try:
        main()
    except SystemExit:
        raise
    except Exception as error:              # any other failure is "not available" (3), never "refused" (1) or "accepted"
        sys.stderr.write("error: %s\n" % error)
        sys.exit(3)
