#!/usr/bin/env python3
"""uFTP authentication hook: users of an LDAP directory, checked with a bind (an example to adapt: not tried against a real server in the uFTP suite).

Settings in uftp-auth-ldap.conf next to the script:
  uri       = ldaps://ldap.example.com
  dn        = uid=%s,ou=people,dc=example,dc=com      %s is the name of the user
  home      = /srv/ftp/%s                              %s is the name of the user (the folder must exist)
  readonly  = 0                                        1 = every LDAP user is read only
  permissions, max_connections, max_download_speed, max_upload_speed, owner_user, owner_group, allow_from, deny_from, umask: the same for every user (optional)
  command   = /usr/bin/ldapwhoami                      (default)
The password goes to ldapwhoami on its standard input (-y /dev/stdin), never in the arguments, where every user of the machine could read it.
A bind with an empty password is an ANONYMOUS bind in LDAP and always works: the script refuses an empty password before anything else.
"""
import os
import re
import subprocess
import sys

NAME = re.compile(r"^[A-Za-z0-9._@-]{1,64}$")
KEYS = ("permissions", "max_connections", "max_download_speed", "max_upload_speed", "owner_user", "owner_group", "allow_from", "deny_from", "umask")


def conf():
    values = {"command": "/usr/bin/ldapwhoami", "readonly": "0"}
    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 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) or password == "":
        sys.exit(1)
    if "uri" not in settings or "dn" not in settings or "home" not in settings:
        sys.stderr.write("uri, dn and home are not set\n")
        sys.exit(3)
    command = [settings["command"], "-x", "-H", settings["uri"], "-D", settings["dn"] % name, "-y", "/dev/stdin", "-o", "nettimeout=3"]
    try:
        result = subprocess.run(command, input=password, capture_output=True, text=True, timeout=4)
    except (OSError, subprocess.TimeoutExpired) as error:
        sys.stderr.write("ldapwhoami: %s\n" % error)
        sys.exit(3)
    if result.returncode == 49:                        # invalid credentials
        sys.exit(1)
    if result.returncode != 0:                         # the server did not answer, or another error
        sys.stderr.write("ldapwhoami: status %d\n" % result.returncode)
        sys.exit(3)
    print("home=" + settings["home"] % name)
    if settings["readonly"] == "1":
        print("readonly=1")
    for key in KEYS:
        if key in settings:
            print("%s=%s" % (key, settings[key]))


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)
