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

Settings in uftp-auth-mysql.conf next to the script (keep it 0600):
  defaults_file = /etc/uftp/mysql.cnf     a client option file with [client] host, user, password, database (the password is NOT on a command line)
  command       = /usr/bin/mysql          (default)
The table:  uftp_users(name VARCHAR(64) PRIMARY KEY, password_hash VARCHAR(255), home VARCHAR(255), enabled TINYINT, readonly TINYINT, permissions VARCHAR(100),
                       max_connections INT, max_download_speed INT, max_upload_speed INT,
                       owner_user VARCHAR(64), owner_group VARCHAR(64), allow_from VARCHAR(1000), deny_from VARCHAR(1000), umask VARCHAR(4))
The name of the client is checked against ^[A-Za-z0-9._@-]{1,64}$ BEFORE it is put in the query: that set has no character that can leave a quoted string.
"""
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")


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)
    query = ("SELECT password_hash, home, readonly, permissions, max_connections, max_download_speed, max_upload_speed, "
         "owner_user, owner_group, allow_from, deny_from, umask "
             "FROM uftp_users WHERE name = '%s' AND enabled = 1" % name)
    command = [settings.get("command", "/usr/bin/mysql")]
    if "defaults_file" in settings:
        command.append("--defaults-extra-file=" + settings["defaults_file"])      # must be the first option of the client
        command.insert(1, command.pop())
    command += ["--batch", "--skip-column-names", "--connect-timeout=3", "-e", query]
    try:
        result = subprocess.run(command, capture_output=True, text=True, timeout=4, stdin=subprocess.DEVNULL)
    except (OSError, subprocess.TimeoutExpired) as error:
        sys.stderr.write("mysql: %s\n" % error)
        sys.exit(3)                                    # not available
    if result.returncode != 0:
        sys.stderr.write("mysql: " + result.stderr.strip().split("\n")[0] + "\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 not in ("", "NULL") 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)
