#!/usr/bin/python3 -I
# SPDX-License-Identifier: MIT
"""Put the post-quantum key exchange first in GnuTLS's default priority.

GNOME and GTK programs (glib-networking with libsoup, WebKitGTK, Evolution, Online Accounts,
GNOME Settings) take GnuTLS's default priority, NORMAL. GnuTLS has the hybrid groups
X25519-MLKEM768, SECP256R1-MLKEM768 and SECP384R1-MLKEM1024, but NORMAL offers none of them,
so these programs agree on X25519 or P-256 alone, which a recorded session does not protect
against a quantum computer later.

"add" sets default-priority-string in the [overrides] section of /etc/gnutls/config (a backup
file of gnutls; GnuTLS reads no directory of drop-ins): NORMAL with the hybrid groups first and
NORMAL's classic groups after them, so a server without ML-KEM still answers as before.
"remove" takes out what "add" put in and leaves the rest of the file as it was.

plinius-security.install runs it at install, upgrade and removal, plinius-gnutls-pq.hook after
gnutls is installed or upgraded. A default-priority-string of the administrator is left alone.
"""
import os
import sys
import tempfile

CONF = "/etc/gnutls/config"
MARK = "# plinius-security: ML-KEM key exchange first (plinius-gnutls-pq), removed with the package"
SECTION_MARK = "# plinius-security: section added for the line below"
KEY = "default-priority-string"
GROUPS = ("X25519-MLKEM768", "SECP256R1-MLKEM768", "SECP384R1-MLKEM1024",
          "X25519", "SECP256R1", "SECP384R1", "SECP521R1", "X448",
          "FFDHE2048", "FFDHE3072", "FFDHE4096", "FFDHE6144", "FFDHE8192")
LINE = f"{KEY} = NORMAL:-GROUP-ALL:" + ":".join("+GROUP-" + g for g in GROUPS)


def is_key(line, key=KEY):
    s = line.strip()
    return not s.startswith("#") and "=" in s and s.split("=", 1)[0].strip() == key


def is_section(line, name=None):
    s = line.strip()
    return s.startswith("[") and s.endswith("]") and (name is None or s[1:-1].strip() == name)


def add(lines):
    """The lines with our setting, or None if they stay as they are."""
    if MARK in lines:
        i = lines.index(MARK) + 1
        if i < len(lines) and is_key(lines[i]):
            if lines[i] == LINE:
                return None
            return lines[:i] + [LINE] + lines[i + 1:]
        return lines[:i] + [LINE] + lines[i:]
    if any(is_key(line) for line in lines):
        print(f"plinius-gnutls-pq: {CONF} has a {KEY} of its own, left as it is", file=sys.stderr)
        return None
    for i, line in enumerate(lines):
        if is_section(line, "overrides"):
            return lines[:i + 1] + [MARK, LINE] + lines[i + 1:]
    gap = [""] if lines and lines[-1].strip() else []
    return lines + gap + [SECTION_MARK, "[overrides]", MARK, LINE]


def remove(lines):
    """The lines without what add() put in."""
    out = []
    i = 0
    while i < len(lines):
        line = lines[i]
        if line == MARK:
            i += 1
            if i < len(lines) and is_key(lines[i]):
                i += 1
            continue
        if line == SECTION_MARK and i + 1 < len(lines) and is_section(lines[i + 1], "overrides"):
            j = i + 2
            while j < len(lines) and not is_section(lines[j]):
                j += 1
            rest = remove(lines[i + 2:j])
            if any(r.strip() for r in rest):
                # Settings of the administrator in the section: it stays, without our marks
                out += [lines[i + 1]] + rest
            elif j == len(lines) and out and not out[-1].strip():
                out.pop()  # the empty line add() put before the section at the end
            i = j
            continue
        out.append(line)
        i += 1
    return out


def write(lines):
    """Replace CONF by lines, keeping its owner and mode."""
    st = os.stat(CONF)
    fd, tmp = tempfile.mkstemp(prefix=".config.", dir=os.path.dirname(CONF))
    try:
        with os.fdopen(fd, "w") as f:
            f.write("".join(line + "\n" for line in lines))
            f.flush()
            os.fchown(f.fileno(), st.st_uid, st.st_gid)
            os.fchmod(f.fileno(), st.st_mode & 0o7777)
            os.fsync(f.fileno())
        os.replace(tmp, CONF)
    except BaseException:
        os.unlink(tmp)
        raise


def main(argv):
    if len(argv) != 2 or argv[1] not in ("add", "remove"):
        print("Usage: plinius-gnutls-pq add|remove", file=sys.stderr)
        return 2
    if not os.path.isfile(CONF):
        return 0  # gnutls not installed: plinius-gnutls-pq.hook runs again when it comes
    with open(CONF) as f:
        lines = f.read().splitlines()
    new = add(lines) if argv[1] == "add" else remove(lines)
    if new is not None and new != lines:
        write(new)
    return 0


if __name__ == "__main__":  # pragma: no cover - run as a program in test_runs_as_a_program
    sys.exit(main(sys.argv))
