#!/usr/bin/python3
"""Issue a MariaDB server certificate for the address used by clients."""

import fcntl
import ipaddress
import os
import pwd
import re
import secrets
import shutil
import socket
import stat
import subprocess
import sys
import tempfile
from pathlib import Path

CERTS = Path('/etc/mysql/certificates')
STORE = CERTS / '.turnkey-server-identity'
SERVER_CONF = Path('/etc/mysql/mariadb.conf.d/50-server.cnf')


def run(*args, input_data=None):
    result = subprocess.run(args, input=input_data, stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE, timeout=90)
    if result.returncode:
        raise RuntimeError('{} failed: {}'.format(args[0],
                           result.stderr.decode(errors='replace').strip()))
    return result.stdout


def identity(value):
    try:
        return str(ipaddress.ip_address(value)), 'IP'
    except ValueError:
        pass
    if len(value) > 253 or not re.fullmatch(
            r'[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?'
            r'(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*', value):
        raise ValueError('Enter a hostname or IP address without a URL, port, or wildcard.')
    return value.lower(), 'DNS'


def restart():
    run('systemctl', 'restart', 'mysql')


def legacy_tls_config():
    """Recognize the exact default settings disabled by older TurnKey images."""
    info = SERVER_CONF.lstat()
    if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
        return None
    original = SERVER_CONF.read_bytes()
    updated = original
    for name, filename in (('ca', 'ca.pem'), ('cert', 'cert.pem'), ('key', 'cert.key')):
        line = '#ssl-{} = {}'.format(name, CERTS / filename).encode()
        if updated.splitlines().count(line) != 1 or updated.count(line + b'\n') != 1:
            return None
        updated = updated.replace(line + b'\n', line[1:] + b'\n', 1)
    options = run('mariadbd', '--print-defaults').decode(errors='strict')
    if re.search(r'(?:^|\s)--(?:loose[-_])?(?:ssl|skip[-_]ssl|tls)(?:[-_=\s]|$)', options):
        return None
    return original, updated


def check_active_paths():
    output = run('mysql', '-u', 'root', '--protocol=socket', '--skip-ssl',
                 '--batch', '--skip-column-names', '-e',
                 "SELECT COALESCE(@@GLOBAL.ssl_ca,''), COALESCE(@@GLOBAL.ssl_cert,''), "
                 "COALESCE(@@GLOBAL.ssl_key,''), @@GLOBAL.port;")
    values = output.decode('utf-8', errors='strict').strip('\n').split('\t')
    expected = [str(CERTS / name) for name in ('ca.pem', 'cert.pem', 'cert.key')]
    legacy = None
    if len(values) == 4 and values[:3] == ['', '', '']:
        legacy = legacy_tls_config()
    if len(values) != 4 or (values[:3] != expected and legacy is None):
        raise RuntimeError('MySQL is not using the standard TLS certificate paths. '
                           'Configure its certificate with the provider of the current settings, '
                           'or enable TLS using the standard paths before continuing.')
    try:
        port = int(values[3])
        if not 1 <= port <= 65535:
            raise ValueError('invalid port')
        with socket.create_connection(('127.0.0.1', port), timeout=3):
            pass
    except (OSError, ValueError) as exc:
        raise RuntimeError('MySQL must accept local TCP connections for certificate verification. '
                           'Check its listening address and port before continuing.') from exc
    return port, legacy


def replace_server_config(expected, replacement):
    """Replace a recognized config only while it still matches the inspected version."""
    info = SERVER_CONF.lstat()
    if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
        raise RuntimeError('The MySQL configuration has unexpected ownership or links.')
    if SERVER_CONF.read_bytes() != expected:
        raise RuntimeError('The MySQL configuration changed during setup; review it before retrying.')
    descriptor, name = tempfile.mkstemp(prefix='.turnkey-mysql-', dir=SERVER_CONF.parent)
    temporary = Path(name)
    try:
        with os.fdopen(descriptor, 'wb') as stream:
            os.fchmod(stream.fileno(), stat.S_IMODE(info.st_mode))
            os.fchown(stream.fileno(), info.st_uid, info.st_gid)
            stream.write(replacement)
            stream.flush()
            os.fsync(stream.fileno())
        if SERVER_CONF.read_bytes() != expected:
            raise RuntimeError('The MySQL configuration changed during setup; review it before retrying.')
        os.replace(temporary, SERVER_CONF)
        sync_directory(SERVER_CONF.parent)
    finally:
        temporary.unlink(missing_ok=True)


def protect_certificates(mysql):
    """Remove mysql's ability to replace paths used by this root helper."""
    flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
    directory = os.open(CERTS, flags)
    try:
        info = os.fstat(directory)
        if info.st_uid not in (0, mysql.pw_uid):
            raise RuntimeError('The MySQL certificate directory has an unexpected owner.')
        def check_entry(name):
            item = os.stat(name, dir_fd=directory, follow_symlinks=False)
            if stat.S_ISLNK(item.st_mode):
                expected = str(Path(STORE.name) / 'current' / name)
                if name in ('cert.pem', 'cert.key') and os.readlink(name, dir_fd=directory) == expected:
                    return False
                raise RuntimeError('The server certificate uses custom symbolic links; configure its identity with the certificate provider.')
            if not stat.S_ISREG(item.st_mode) or item.st_nlink != 1 or item.st_uid not in (0, mysql.pw_uid):
                raise RuntimeError('The MySQL certificate files have unexpected ownership or links.')
            return True
        # Check before changing ownership so a custom layout is untouched.
        for name in ('ca.pem', 'ca.key', 'cert.pem', 'cert.key'):
            check_entry(name)
        # The released image owns this directory as mysql. Transfer it first,
        # so entries cannot be replaced while their ownership is checked.
        os.fchmod(directory, 0o750)
        os.fchown(directory, 0, mysql.pw_gid)
        os.fsync(directory)
        for name in ('ca.pem', 'ca.key', 'cert.pem', 'cert.key'):
            if not check_entry(name):
                continue
            descriptor = os.open(name, os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory)
            try:
                item = os.fstat(descriptor)
                if not stat.S_ISREG(item.st_mode) or item.st_nlink != 1 or item.st_uid not in (0, mysql.pw_uid):
                    raise RuntimeError('The MySQL certificate files have unexpected ownership or links.')
                os.fchmod(descriptor, 0o400 if name == 'ca.key' else 0o440)
                os.fchown(descriptor, 0, mysql.pw_gid)
                os.fsync(descriptor)
            finally:
                os.close(descriptor)
        os.fsync(directory)
    finally:
        os.close(directory)


def sync_directory(path):
    descriptor = os.open(path, os.O_RDONLY | os.O_DIRECTORY)
    try:
        os.fsync(descriptor)
    finally:
        os.close(descriptor)


def replace_link(path, target):
    temporary = path.parent / ('.identity-link-' + secrets.token_hex(12))
    try:
        os.symlink(target, temporary)
        os.replace(temporary, path)
        sync_directory(path.parent)
    finally:
        if temporary.is_symlink():
            temporary.unlink()


def sync_file(path):
    with path.open('rb') as stream:
        os.fsync(stream.fileno())


def managed_pair(cert, key, mysql):
    """Migrate the current pair without ever selecting mismatched files."""
    try:
        STORE.mkdir(mode=0o750)
        os.chown(STORE, 0, mysql.pw_gid)
        os.chmod(STORE, 0o750)
        sync_directory(CERTS)
    except FileExistsError:
        info = STORE.lstat()
        if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
            raise RuntimeError('The MySQL identity directory is not safely owned; check its permissions.')
    current = STORE / 'current'
    if not current.is_symlink():
        if current.exists():
            raise RuntimeError('The MySQL identity selector is not a symbolic link.')
        # Preserve custom symlink layouts rather than silently replacing them.
        if cert.is_symlink() or key.is_symlink():
            raise RuntimeError('The server certificate uses custom symbolic links; configure its identity with the certificate provider.')
        generation = 'generation-' + secrets.token_hex(12)
        old = STORE / generation
        old.mkdir(mode=0o750)
        os.chown(old, 0, mysql.pw_gid)
        os.chmod(old, 0o750)
        for source, name in ((cert, 'cert.pem'), (key, 'cert.key')):
            destination = old / name
            shutil.copy2(source, destination)
            info = source.stat()
            os.chown(destination, info.st_uid, info.st_gid)
            sync_file(destination)
        sync_directory(old)
        sync_directory(STORE)
        replace_link(current, generation)
    generation = os.readlink(current)
    if not re.fullmatch(r'generation-[0-9a-f]{24}', generation):
        raise RuntimeError('The MySQL identity selector has an unexpected target.')
    previous = STORE / generation
    if not previous.is_dir() or previous.is_symlink():
        raise RuntimeError('The current MySQL certificate pair is missing.')
    previous_info = previous.lstat()
    if previous_info.st_uid != 0 or previous_info.st_mode & 0o022:
        raise RuntimeError('The current MySQL certificate pair has unsafe permissions.')
    for name in ('cert.pem', 'cert.key'):
        pair_info = (previous / name).lstat()
        if (not stat.S_ISREG(pair_info.st_mode) or pair_info.st_nlink != 1 or
                pair_info.st_uid != 0 or pair_info.st_mode & 0o022):
            raise RuntimeError('The current MySQL certificate pair has unsafe permissions.')
    for path, name in ((key, 'cert.key'), (cert, 'cert.pem')):
        expected_link = str(Path(STORE.name) / 'current' / name)
        if path.is_symlink():
            if os.readlink(path) != expected_link:
                raise RuntimeError('The server certificate uses custom symbolic links; configure its identity with the certificate provider.')
        elif path.read_bytes() != (previous / name).read_bytes():
            raise RuntimeError('The server certificate changed during setup; restore the previous configuration before retrying.')
        else:
            # At this point both old and new paths contain the same bytes.
            # A crash between these replacements leaves a matching pair.
            replace_link(path, expected_link)
    return current, generation


def served_certificate(name, kind, expected, port):
    option = '-verify_ip' if kind == 'IP' else '-verify_hostname'
    output = run('openssl', 's_client', '-starttls', 'mysql', '-connect',
                 '127.0.0.1:{}'.format(port), '-CAfile', str(CERTS / 'ca.pem'),
                 '-verify_return_error', option, name, input_data=b'')
    start = output.find(b'-----BEGIN CERTIFICATE-----')
    end = output.find(b'-----END CERTIFICATE-----', start)
    if start < 0 or end < 0:
        raise RuntimeError('The database did not present a certificate.')
    pem = output[start:end + len(b'-----END CERTIFICATE-----')] + b'\n'
    actual = run('openssl', 'x509', '-outform', 'DER', input_data=pem)
    if actual != expected:
        raise RuntimeError('The database is serving a different certificate.')


def issue(name, kind):
    ca, ca_key = CERTS / 'ca.pem', CERTS / 'ca.key'
    cert, key = CERTS / 'cert.pem', CERTS / 'cert.key'
    if any(not path.is_file() for path in (ca, ca_key, cert, key)):
        raise RuntimeError('The existing CA or server certificate is missing. Restore it before continuing.')
    port, legacy = check_active_paths()
    mysql = pwd.getpwnam('mysql')
    protect_certificates(mysql)
    ca_public = run('openssl', 'x509', '-in', str(ca), '-pubkey', '-noout')
    key_public = run('openssl', 'pkey', '-in', str(ca_key), '-pubout')
    if ca_public != key_public:
        raise RuntimeError('The CA certificate and private key do not match. Restore the original CA before continuing.')

    with tempfile.TemporaryDirectory(prefix='.identity-', dir=CERTS) as directory:
        tmp = Path(directory)
        new_key, request, new_cert = (tmp / 'key', tmp / 'request', tmp / 'cert')
        extensions = tmp / 'extensions'
        extensions.write_text('subjectAltName={} : {}\nextendedKeyUsage=serverAuth\n'.format(kind, name))
        run('openssl', 'req', '-new', '-newkey', 'rsa:2048', '-nodes',
            '-keyout', str(new_key), '-out', str(request), '-subj', '/CN=MySQL server')
        run('openssl', 'x509', '-req', '-in', str(request), '-CA', str(ca),
            '-CAkey', str(ca_key), '-set_serial', '0x' + secrets.token_hex(16),
            '-days', '365000', '-extfile', str(extensions), '-out', str(new_cert))
        run('openssl', 'verify', '-CAfile', str(ca), str(new_cert))
        expected = run('openssl', 'x509', '-in', str(new_cert), '-outform', 'DER')
        for path in (new_key, new_cert):
            os.chown(path, 0, mysql.pw_gid)
            os.chmod(path, 0o440)
        current, previous = managed_pair(cert, key, mysql)
        generation = 'generation-' + secrets.token_hex(12)
        new_pair = STORE / generation
        new_pair.mkdir(mode=0o750)
        os.chown(new_pair, 0, mysql.pw_gid)
        os.chmod(new_pair, 0o750)
        os.replace(new_key, new_pair / 'cert.key')
        os.replace(new_cert, new_pair / 'cert.pem')
        sync_file(new_pair / 'cert.key')
        sync_file(new_pair / 'cert.pem')
        sync_directory(new_pair)
        sync_directory(STORE)
        try:
            if legacy:
                replace_server_config(*legacy)
            # Both public paths follow this one atomic selector.
            replace_link(current, generation)
            restart()
            served_certificate(name, kind, expected, port)
        except Exception as failure:
            try:
                replace_link(current, previous)
                if legacy and SERVER_CONF.read_bytes() != legacy[0]:
                    replace_server_config(legacy[1], legacy[0])
                restart()
            except Exception as rollback:
                raise RuntimeError('Certificate setup failed: {}. Restoring the previous certificate also failed: {}. Check the MySQL service and retained certificate pairs in {}.'.format(failure, rollback, STORE)) from rollback
            raise RuntimeError('Certificate setup failed; the previous certificate was restored: {}'.format(failure)) from failure


def certificate_status(cert=None, managed=True):
    cert = str(cert or CERTS / 'cert.pem')
    output = run('openssl', 'x509', '-in', cert, '-noout', '-ext', 'subjectAltName')
    expiry = run('openssl', 'x509', '-in', cert, '-noout', '-enddate')
    name = output.decode(errors='replace').strip() or 'The current certificate has no hostname or IP address.'
    end = expiry.decode(errors='replace').strip().removeprefix('notAfter=')
    renewal = ('To renew, issue a certificate for the same address.' if managed else
               'To renew, use the provider that manages this certificate.')
    return 'Certificate file: {}\n{}\nExpires: {}\n{}'.format(cert, name, end, renewal)


def current_certificate_status():
    output = run('mysql', '-u', 'root', '--protocol=socket', '--skip-ssl',
                 '--batch', '--skip-column-names', '-e',
                 "SELECT @@GLOBAL.have_ssl, COALESCE(@@GLOBAL.ssl_ca,''), "
                 "COALESCE(@@GLOBAL.ssl_cert,''), COALESCE(@@GLOBAL.ssl_key,'');")
    values = output.decode('utf-8', errors='strict').strip('\n').split('\t')
    if len(values) != 4:
        raise RuntimeError('Could not determine the active MariaDB TLS settings.')
    if values[0] != 'YES':
        return 'MariaDB TLS is unavailable. Configure TLS before issuing a certificate.'
    if not values[2]:
        return ('MariaDB uses an automatically generated certificate. '
                'Issue a certificate to set the hostname or IP address clients verify.')
    expected = [str(CERTS / name) for name in ('ca.pem', 'cert.pem', 'cert.key')]
    return certificate_status(values[2], managed=values[1:] == expected)


def main():
    if sys.argv[1:] == ['status']:
        try:
            print(current_certificate_status())
            return 0
        except (OSError, RuntimeError, subprocess.TimeoutExpired) as exc:
            print('Current certificate identity unavailable: {}'.format(exc), file=sys.stderr)
            return 1
    if len(sys.argv) != 3 or sys.argv[1] != 'set':
        print('Usage: turnkey-mysql-identity status | set HOSTNAME_OR_IP', file=sys.stderr)
        return 2
    try:
        name, kind = identity(sys.argv[2])
        with open('/run/lock/turnkey-mysql-identity.lock', 'w') as lock:
            fcntl.flock(lock, fcntl.LOCK_EX)
            issue(name, kind)
        print('MySQL is serving a certificate for {}. Configure clients to trust /etc/mysql/certificates/ca.pem.'.format(name))
        try:
            print(certificate_status())
        except (OSError, RuntimeError, subprocess.TimeoutExpired):
            print('Could not read the certificate expiry. Open MySQL Server Identity to check it.')
        return 0
    except (OSError, ValueError, RuntimeError, subprocess.TimeoutExpired) as exc:
        print(str(exc), file=sys.stderr)
        return 1


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