#!/usr/bin/env python3
"""uFTP authentication hook: users in a text file, passwords as PBKDF2 hashes.

  uftp-auth-file auth                         the hook (uFTP runs this; name and password on stdin)
  uftp-auth-file add NAME HOME [key=value..]  add or change a user (asks the password; or reads it from stdin)
  uftp-auth-file remove NAME
  uftp-auth-file list

Settings in uftp-auth-file.conf next to the script:  users_file = /etc/uftp/hook-users   (default)
The file has one user per line, four columns separated by a tab:  name  hash  home  attributes (key=value;key=value)
"""
import base64
import hashlib
import hmac
import os
import re
import sys
import tempfile

NAME = re.compile(r"^[A-Za-z0-9._@-]{1,64}$")
PERMISSIONS = {"list", "download", "upload", "overwrite", "delete", "rename", "mkdir", "chmod", "run", "all", "none"}
ALLOWED_KEYS = {"readonly", "permissions", "max_connections", "max_download_speed", "max_upload_speed", "owner_user", "owner_group",
                "allow_from", "deny_from", "umask"}
DUMMY = "$pbkdf2-sha256$100000$AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"


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 ab64(data):
    return base64.b64encode(data).decode().rstrip("=").replace("+", ".")


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


def make_hash(password, iterations=100000):
    salt = os.urandom(16)
    return "$pbkdf2-sha256$%d$%s$%s" % (iterations, ab64(salt), ab64(hashlib.pbkdf2_hmac("sha256", password.encode(), salt, iterations)))


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


def read_users(path):
    users = {}
    if os.path.exists(path):
        for line in open(path):
            parts = line.rstrip("\n").split("\t")
            if len(parts) >= 3 and NAME.match(parts[0]):
                users[parts[0]] = parts[1:4] + [""] * (3 - len(parts[1:4]))
    return users


def write_users(path, users):
    directory = os.path.dirname(os.path.abspath(path))
    handle, temporary = tempfile.mkstemp(dir=directory)
    with os.fdopen(handle, "w") as f:
        for name in sorted(users):
            f.write("\t".join([name] + users[name]) + "\n")
    os.chmod(temporary, 0o600)
    os.replace(temporary, path)


def hook(users_file):
    name = sys.stdin.readline().rstrip("\n")
    password = sys.stdin.readline().rstrip("\n")
    if not NAME.match(name):                      # the name comes from the client: nothing else is looked at before this
        sys.exit(1)
    users = read_users(users_file)
    entry = users.get(name)
    ok = verify(entry[0] if entry else DUMMY, password)      # the same work for a name that does not exist
    if not entry or not ok:
        sys.stderr.write("refused\n")
        sys.exit(1)
    print("home=" + entry[1])
    for pair in filter(None, entry[2].split(";")):
        print(pair)
    sys.exit(0)


def main():
    users_file = conf().get("users_file", "/etc/uftp/hook-users")
    command = sys.argv[1] if len(sys.argv) > 1 else ""
    if command == "auth":
        hook(users_file)
    elif command == "add" and len(sys.argv) >= 4 and NAME.match(sys.argv[2]):
        attributes = []
        for pair in sys.argv[4:]:
            if "=" not in pair or pair.split("=", 1)[0] not in ALLOWED_KEYS or ";" in pair or "\t" in pair:
                sys.exit("not an attribute: " + pair)
            if pair.startswith("permissions=") and not set(pair.split("=", 1)[1].split(",")) <= PERMISSIONS:
                sys.exit("not a list of permissions: " + pair)
            attributes.append(pair)
        if sys.stdin.isatty():
            import getpass
            password = getpass.getpass("Password: ")
        else:
            password = sys.stdin.readline().rstrip("\n")
        users = read_users(users_file)
        users[sys.argv[2]] = [make_hash(password), sys.argv[3], ";".join(attributes)]
        write_users(users_file, users)
    elif command == "remove" and len(sys.argv) == 3:
        users = read_users(users_file)
        users.pop(sys.argv[2], None)
        write_users(users_file, users)
    elif command == "list":
        for name, entry in sorted(read_users(users_file).items()):
            print(name, entry[1], entry[2])
    else:
        sys.exit(__doc__)


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)
