# Copyright (c) TuxCare, Inc. All rights reserved.
# Licensed under TUXCARE LICENSE AGREEMENT
# https://tuxcare.com/legal/

"""Put the KernelCare certwrapper next to shim, so that a Secure Boot host trusts KernelCare modules.

`kcarectl --setup-kcare-certs MODE` runs this, and so does setup_kcare_certs.sh, which the package
scriptlets call. Like `--fsync`, it runs before the config and the log: a scriptlet runs it while yum
or dpkg holds its lock. info alone, which only a person runs, reads kcare.conf first.

The modes:
- install: put the shipped certwrapper next to shim, or replace a KernelCare one there.
- force: the same, even next to a shim that would stop trusting the current KernelCare key after a
  reboot.
- update: replace only a KernelCare certwrapper that is already there, never next to a shim older
  than 16.0. The package runs it on every install and upgrade, so it says nothing and exits 0 on a
  host that has none. It exits
  UPDATE_REFUSED_OLD_SHIM when it leaves the certwrapper next to such a shim, which only a shim
  upgrade changes. Any other failure prints a WARNING that the certwrapper may be out of date: the
  package goes on whatever it returns.
- info: change nothing, and print the state of the KernelCare certificates and what to do, if
  anything, to keep kcare.ko loading across the 2027-01-13 key switch.
"""

import binascii
import os
import re
import sys
import time

from . import config_handlers, fs_utils, secure_boot, utils

if False:  # pragma: no cover
    from typing import List, Optional, Tuple  # noqa: F401

SETUP_SCRIPT = '/usr/share/kcare/secure_boot/setup_kcare_certs.sh'
SHIPPED_CERTWRAPPER = '/usr/share/kcare/secure_boot/shim_certificate.efi'
CERTWRAPPER_NAME = 'shim_certificate.efi'
# Of the temporary file next to the certwrapper. shim loads every file whose name starts with
# "shim_certificate", so the default, the certwrapper's own name and a suffix, would not do.
TMP_PREFIX = '.kcare_certwrapper.'
MODES = ('install', 'force', 'update', 'info')
# update left the certwrapper next to shim that loads only its first certificate. The apt hook
# (apt_post_invoke.sh) tells it from a failure: only a shim upgrade changes it, so it is not retried.
UPDATE_REFUSED_OLD_SHIM = 3

# shim before 16.0 imports only the first certificate of a certwrapper, and only from
# shim_certificate.efi: load_cert_file in its shim.c copies the first EFI_SIGNATURE_LIST of the .db
# section. From 16.0 it loads them all, from every file whose name starts with "shim_certificate",
# whatever the case. Ours lists the key KernelCare signs modules with from 2027-01-13 first. Until
# then, a host with an older shim stops trusting the key the current modules are signed with after
# its next reboot.
KEY_SWITCH_DATE = '20270113'
FIRST_SHIM_WITH_ALL_CERTS = '16.0'

# The KernelCare keys, by the first 8 hex digits of their subject key identifier, as
# secure_boot.kcare_keys_in_kernel() and secure_boot.kmod_kcare_keys() name them
OLD_KEY = secure_boot.KC_SIGNING_KEY_IDS[0][:8]  # signs KernelCare modules until 2027-01-13
NEW_KEY = secure_boot.KC_SIGNING_KEY_IDS[1][:8]  # signs them from 2027-01-13 to 2032-01-13
KEY_NAMES = {
    OLD_KEY: OLD_KEY + ' (expires 2027-01-13)',
    NEW_KEY: NEW_KEY + ' (2027-01-13 to 2032-01-13)',
}

# AlmaLinux signs kcare.ko for its own kernels with this key, which they trust from the start. There
# the KernelCare certificates go unused.
ALMALINUX_KEY = secure_boot.KC_SIGNING_KEY_IDS[2][:8]
KEY_NAMES[ALMALINUX_KEY] = ALMALINUX_KEY + ' (AlmaLinux)'


def _out(message):
    # type: (str) -> None
    utils.print_wrapper(message)


def _err(message):
    # type: (str) -> None
    utils.print_wrapper(message, file=sys.stderr)


def today():
    # type: () -> str
    """Today's date in UTC, as YYYYMMDD."""
    return time.strftime('%Y%m%d', time.gmtime())


def version_lt(left, right):
    # type: (str, str) -> bool
    """Whether version left is older than version right, as `sort -V` orders them.

    Numbers compare as numbers (9.0 < 16.1), and a "~" part sorts before even the end of the version,
    so a pre-release comes before its release (16.1~rc1 < 16.1).
    """

    def key(version):
        # type: (str) -> List[Tuple[int, int, str]]
        parts = []
        for part in re.findall(r'~|[0-9]+|[A-Za-z]+', version):
            if part == '~':
                parts.append((-1, 0, ''))
            elif part.isdigit():
                parts.append((1, int(part), ''))
            else:
                parts.append((2, 0, part))
        return parts + [(0, 0, '')]  # the end of the version

    return key(left) < key(right)


def is_kcare_certwrapper(path):
    # type: (str) -> bool
    try:
        return secure_boot.KC_CERT_MARKER in secure_boot.read_binary(path)
    except (IOError, OSError):
        return False


def _kcare_certwrapper_anywhere():
    # type: () -> bool
    for root, _, files in os.walk(secure_boot.ESP_EFI_DIR):
        if CERTWRAPPER_NAME in files and is_kcare_certwrapper(os.path.join(root, CERTWRAPPER_NAME)):
            return True
    return False


def kernel_trusts_almalinux_key():
    # type: () -> bool
    return ALMALINUX_KEY in (secure_boot.kcare_keys_in_kernel() or [])


def find_shims():
    # type: () -> List[str]
    """The shim binaries on the ESP, sorted."""
    shims = []  # type: List[str]
    for root, _, files in os.walk(secure_boot.ESP_EFI_DIR):
        shims.extend(os.path.join(root, name) for name in files if secure_boot.SHIM_NAME.match(name))
    return sorted(shims)


def same_content(path, other):
    # type: (str, str) -> bool
    """Whether the two files have the same content. A file that cannot be read counts as different."""
    try:
        return secure_boot.read_binary(path) == secure_boot.read_binary(other)
    except (IOError, OSError):
        return False


def loads_all_certs(version):
    # type: (str) -> bool
    """Whether shim of this version loads every certificate; an unreadable version counts as older."""
    return bool(version) and not version_lt(version, FIRST_SHIM_WITH_ALL_CERTS)


def _shim_loading_only_first_cert(shims):
    # type: (List[str]) -> Optional[str]
    """Describe the first shim that loads only the first certificate, if there is one.

    A shim whose version cannot be read may be such a shim, so it counts too.
    """
    for shim in shims:
        try:
            version = secure_boot.shim_version(shim)
        except (IOError, OSError):
            version = ''
        if not version:
            return '{0} is shim of unknown version, which may load'.format(shim)
        if not loads_all_certs(version):
            return '{0} is shim {1}, which loads'.format(shim, version)
    return None


def replace_certwrapper(cert_wrapper):
    # type: (str) -> None
    """Replace cert_wrapper with the shipped one, never rewriting it in place.

    After a power cut or a failed write (a full ESP), a truncated certwrapper may carry no KernelCare
    certificate for shim, nor the marker that update looks for, so no later upgrade would repair it.
    The copy goes to a temporary file next to it, which is synced and renamed over it. A failed
    sync before the rename leaves the old certwrapper in place.
    """
    fs_utils.atomic_write(cert_wrapper, secure_boot.read_binary(SHIPPED_CERTWRAPPER), mode='wb', tmp_prefix=TMP_PREFIX)


def run(mode):
    # type: (str) -> int
    """setup(mode) or info(), reporting a crash on stderr: not to the crash reporter, since a package
    scriptlet must not reach the network."""
    try:
        if mode == 'info':
            # Run by hand, not by a scriptlet, and it finds the cached kcare.ko for the kernel as
            # kcare.conf sets it up, such as its KERNEL_VERSION_FILE.
            config_handlers.set_settings_from_config_file()
            rc = info()
        else:
            rc = setup(mode)
    except Exception as e:
        _err('Error: {0}'.format(e))
        rc = 1
    # The package runs update and goes on whatever it returns, so a failure has to say what it may
    # leave behind and how to retry: an old certwrapper stops working at the 2027-01-13 key switch.
    if mode == 'update' and rc not in (0, UPDATE_REFUSED_OLD_SHIM):
        _err('WARNING: the KernelCare certificates next to shim may be out of date.')
        _err('  Fix the error above, then run as root: {0} --update'.format(SETUP_SCRIPT))
    return rc


def _is_root():
    # type: () -> bool
    """Whether we run as root, which reading the ESP and /proc/keys needs. Says so when not."""
    if os.geteuid() == 0:
        return True
    _err('{0} should be run as root'.format(SETUP_SCRIPT))
    return False


def setup(mode):
    # type: (str) -> int
    """Install or update the KernelCare certwrapper next to shim; return the exit code."""
    if not _is_root():
        return 1

    update = mode == 'update'
    if update and not _kcare_certwrapper_anywhere():
        return 0
    # On a kernel that trusts the AlmaLinux key, the KernelCare certificates go unused, and the output says
    # so.  It never skips the work on that ground: any user can forge a /proc/keys line that shows the key
    # as one the kernel holds (see secure_boot.kcare_keys_in_kernel()), and so stop --update.
    if kernel_trusts_almalinux_key():
        _out(
            'Note: The running kernel trusts the AlmaLinux key that signs its KernelCare modules, so it needs no '
            'KernelCare certificates.'
        )

    if not os.path.isdir(secure_boot.ESP_EFI_DIR):
        _err('No EFI directory found. Please ensure /boot/efi is mounted.')
        return 1
    shims = find_shims()
    if not shims:
        _err('No shim binary found. Please ensure shim is installed.')
        return 1
    shim_dir = os.path.dirname(shims[0])
    if any(os.path.dirname(shim) != shim_dir for shim in shims):
        _err('Confused: multiple shim locations found:')
        for shim in shims:
            _err('  {0}'.format(shim))
        return 1

    cert_wrapper = os.path.join(shim_dir, CERTWRAPPER_NAME)
    exists = os.path.isfile(cert_wrapper)
    if exists and same_content(cert_wrapper, SHIPPED_CERTWRAPPER):
        _out('KernelCare certificates at {0} are up to date.'.format(cert_wrapper))
        return 0
    ours = exists and is_kcare_certwrapper(cert_wrapper)
    if update and not ours:
        _err('No KernelCare certificates next to shim in {0}, nothing to update.'.format(shim_dir))
        return 0

    # Only update mode and the time before the key switch care about the shim version.
    old_shim = _shim_loading_only_first_cert(shims) if update or today() < KEY_SWITCH_DATE else None
    # The package never updates the certwrapper next to such a shim, whatever the date: after the
    # reboot, a cached kcare.ko signed with the current key only would fail to load. The admin fetches
    # the modules signed with the new key first, then installs it by hand.
    if update and old_shim:
        _err('WARNING: {0} only the first KernelCare certificate, the key for modules from 2027-01-13.'.format(old_shim))
        _err('  The KernelCare certificates at {0} were not updated.'.format(cert_wrapper))
        _err('  On or after 2027-01-13, run as root:')
        _err('    kcarectl --update')
        _err('    {0} --force'.format(SETUP_SCRIPT))
        _err('  and reboot.  Or update shim to {0} or later and run: {1}'.format(FIRST_SHIM_WITH_ALL_CERTS, SETUP_SCRIPT))
        return UPDATE_REFUSED_OLD_SHIM

    if old_shim and today() < KEY_SWITCH_DATE:
        force = mode == 'force'
        _err(
            '{0}: {1} only the first KernelCare certificate, the key for modules from 2027-01-13.'.format(
                'WARNING' if force else 'ERROR', old_shim
            )
        )
        _err('  After a reboot before 2027-01-13, the current KernelCare modules fail to load ("kmod load error").')
        _err('  Run this script on or after 2027-01-13, or update shim to {0} or later first.'.format(FIRST_SHIM_WITH_ALL_CERTS))
        if not force:
            _err('Nothing was changed. To install the certificates anyway, run: {0} --force'.format(SETUP_SCRIPT))
            return 1

    if ours:
        _out('Found KernelCare certificates at {0}, updating...'.format(cert_wrapper))
    elif exists:
        _err('File {0} already exists, cannot rewrite it.'.format(cert_wrapper))
        return 1
    else:
        _out('Installing KernelCare certificates to {0}'.format(cert_wrapper))

    try:
        replace_certwrapper(cert_wrapper)
    except (IOError, OSError) as e:
        # A failing disk fails the command (kcarectl/AGENTS.md), but the message says whether the
        # rename already happened: a failed sync of the directory after it leaves the new file in place.
        if os.path.isfile(cert_wrapper) and same_content(cert_wrapper, SHIPPED_CERTWRAPPER):
            _err('{0} was replaced, but syncing it to disk failed: {1}'.format(cert_wrapper, e))
        else:
            _err('Failed to replace {0}: {1}'.format(cert_wrapper, e))
        return 1
    _out('Done! Please reboot for the changes to take effect.')
    return 0


def keys_line(keys):
    # type: (List[str]) -> str
    return ', '.join(KEY_NAMES.get(key, key) for key in keys) or 'none'


def cert_keys(path):
    # type: (str) -> List[str]
    """The KernelCare keys certificate file path carries, in the order of its certificates.

    A certificate carries its subject key identifier, so each key is found by those bytes.
    """
    data = secure_boot.read_binary(path)
    found = []
    for key_id in (secure_boot.KC_SIGNING_KEY_IDS[0], secure_boot.KC_SIGNING_KEY_IDS[1]):
        offset = data.find(binascii.unhexlify(key_id))
        if offset >= 0:
            found.append((offset, key_id[:8]))
    return [key for _, key in sorted(found)]


def secure_boot_state():
    # type: () -> str
    if not os.path.isdir(os.path.dirname(secure_boot.EFIVARS_PATH)):
        return 'off, the system did not boot with UEFI'
    var = os.path.join(secure_boot.EFIVARS_PATH, 'SecureBoot-' + secure_boot.EFI_VENDORS['global'])
    try:
        # an efivars file holds 4 bytes of attributes, then the value
        value = secure_boot.read_binary(var)[4:5]
    except (IOError, OSError):
        value = b''
    return {b'\x01': 'on', b'\x00': 'off'}.get(value, 'unknown, cannot read {0}'.format(var))


def _certwrappers_next_to(shim_dir):
    # type: (str) -> List[str]
    """The files next to shim whose name starts with "shim_certificate", whatever the case."""
    names = sorted(name for name in os.listdir(shim_dir) if secure_boot.is_certwrapper_name(name))
    return [os.path.join(shim_dir, name) for name in names if os.path.isfile(os.path.join(shim_dir, name))]


def _loaded_keys(version, wrappers):
    # type: (str, List[str]) -> List[str]
    """The KernelCare keys shim of this version loads at boot from the certwrappers next to it."""
    if loads_all_certs(version):
        return sorted(set(key for wrapper in wrappers for key in cert_keys(wrapper)))
    first = [wrapper for wrapper in wrappers if os.path.basename(wrapper).lower() == CERTWRAPPER_NAME]
    return cert_keys(first[0])[:1] if first else []


def _signed_with(kmod_keys):
    # type: (List[str]) -> str
    if kmod_keys:
        return 'kcare.ko for this kernel is signed with {0}'.format(keys_line(kmod_keys))
    return 'KernelCare modules are signed with {0} until then'.format(keys_line([OLD_KEY]))


def _no_reboot_todo(loaded, needed, kmod_keys, before_switch, january):
    # type: (List[str], List[str], List[str], bool, List[str]) -> List[str]
    """What to do when a reboot through this shim would leave kcare.ko unloadable: shim loads no key
    that signs it. january: the steps for 2027-01-13 and later."""
    if before_switch:
        return [
            'Do not reboot before 2027-01-13, unless the kernel trusts {0} in another way, such as an '
            'enrolled MOK.'.format(keys_line(needed)),
            'This shim loads only {0}, and {1}.'.format(keys_line(loaded), _signed_with(kmod_keys)),
        ] + january
    return [
        'Run: kcarectl --update, and reboot: this shim loads only {0}, and {1}.'.format(keys_line(loaded), _signed_with(kmod_keys))
    ]


def shim_todo(shim, version, loaded, trusted, kmod_keys):
    # type: (str, str, List[str], List[str], List[str]) -> List[str]
    """What to do so that the kernel booted through shim trusts a key kcare.ko is signed with, now and
    from 2027-01-13. Nothing when nothing needs doing.

    loaded: the KernelCare keys this shim loads at boot. trusted: those the running kernel trusts.
    kmod_keys: those that sign the cached kcare.ko for the running kernel, [] when unknown. A key the
    kernel trusts may come from a certwrapper or be enrolled as a MOK, and nothing the OS can read
    tells which: shim puts both into MokListRT.
    """
    shim_dir = os.path.dirname(shim)
    wrapper = os.path.join(shim_dir, CERTWRAPPER_NAME)
    all_certs = loads_all_certs(version)
    before_switch = today() < KEY_SWITCH_DATE
    # kcare.ko loads after a reboot only when shim loads a key that signs it
    needed = kmod_keys or [OLD_KEY if before_switch else NEW_KEY]
    missing = [key for key in loaded if key not in trusted]
    reboot = ['Reboot, so that the kernel trusts {0}.'.format(keys_line(missing))] if missing else []
    # Every advice to reboot first checks that a reboot keeps a key that signs kcare.ko.
    reboot_is_safe = bool(set(needed) & set(loaded))
    newer_shim = 'update shim to {0} or later'.format(FIRST_SHIM_WITH_ALL_CERTS)

    if os.path.isfile(wrapper) and same_content(wrapper, SHIPPED_CERTWRAPPER):
        if reboot_is_safe:
            return reboot
        january = ['On or after 2027-01-13, run: kcarectl --update, and reboot.  Or {0}, and reboot.'.format(newer_shim)]
        return _no_reboot_todo(loaded, needed, kmod_keys, before_switch, january)

    if os.path.isfile(wrapper) and is_kcare_certwrapper(wrapper):
        if all_certs:
            return ['Update the KernelCare certificates: run {0}, and reboot.'.format(SETUP_SCRIPT)]
        if not before_switch:
            return ['Run: kcarectl --update, then {0}, and reboot.'.format(SETUP_SCRIPT)]
        january = [
            'On or after 2027-01-13, run: kcarectl --update, then {0} --force, and reboot.'.format(SETUP_SCRIPT),
            'Or {0}, then run {1}, and reboot.'.format(newer_shim, SETUP_SCRIPT),
        ]
        if reboot and not reboot_is_safe:
            return _no_reboot_todo(loaded, needed, kmod_keys, before_switch, january)
        return (
            reboot
            + [
                'Nothing {0}before 2027-01-13.  On or after it, run: kcarectl --update, then {1} --force, and '
                'reboot.'.format('else ' if reboot else '', SETUP_SCRIPT)
            ]
            + january[1:]
        )

    if NEW_KEY not in loaded:
        # This shim loads the 2027 key from no certwrapper. If the kernel trusts it anyway, it may be an
        # enrolled MOK, which survives a reboot, or a certwrapper removed since the boot, which does not.
        mok = ['Not needed if {0} is enrolled as a MOK.'.format(keys_line([NEW_KEY]))] if NEW_KEY in trusted else []
        if not os.path.isfile(wrapper):
            if all_certs or not before_switch:
                return ['Install the KernelCare certificates: run {0}, and reboot.'.format(SETUP_SCRIPT)] + mok
            return [
                'Install the KernelCare certificates: run {0} --force, and reboot.'.format(SETUP_SCRIPT),
                'This shim loads only {0} from them, which signs KernelCare modules from 2027-01-13.'.format(keys_line([NEW_KEY])),
            ] + mok
        copy = 'copy {0} to {1}, and reboot.'.format(SHIPPED_CERTWRAPPER, os.path.join(shim_dir, 'shim_certificate_kernelcare.efi'))
        if all_certs:
            return ["{0} is not KernelCare's.  To add the KernelCare certificates, {1}".format(wrapper, copy)] + mok
        return [
            "{0} is not KernelCare's, and shim older than {1} loads no other file.".format(wrapper, FIRST_SHIM_WITH_ALL_CERTS),
            'To add the KernelCare certificates, {0}, then {1}'.format(newer_shim, copy),
        ] + mok

    if reboot and not reboot_is_safe:
        january = ['On or after 2027-01-13, run: kcarectl --update, and reboot.']
        return _no_reboot_todo(loaded, needed, kmod_keys, before_switch, january)
    return reboot


def info():
    # type: () -> int
    """Print the state of the KernelCare certificates and what to do, if anything; change nothing."""
    if not _is_root():
        return 1
    state = secure_boot_state()
    trusted = secure_boot.kcare_keys_in_kernel()
    kmod = secure_boot.cached_kmod()
    kmod_keys = secure_boot.kmod_kcare_keys(kmod) if kmod else []
    _out('Secure Boot: {0}'.format(state))
    _out('Keys the running kernel trusts: {0}'.format('unknown, cannot read /proc/keys' if trusted is None else keys_line(trusted)))
    if kmod_keys:
        _out('{0} is signed with: {1}'.format(kmod, keys_line(kmod_keys)))
    elif kmod:
        # kmod_kcare_keys() gives [] both for another key and for a signature it cannot read
        _out('{0} is signed with none of the KernelCare keys, or with a signature that cannot be read.'.format(kmod))
    else:
        _out('No kcare.ko is cached for the running kernel.')
    _out('The package ships {0} with KernelCare keys: {1}'.format(SHIPPED_CERTWRAPPER, keys_line(cert_keys(SHIPPED_CERTWRAPPER))))
    trusted_keys = trusted or []

    shims = []  # type: List[str]
    if os.path.isdir(secure_boot.ESP_EFI_DIR):
        shims = find_shims()
    else:
        _out('No EFI directory found. Is /boot/efi mounted?')
    todo = []  # type: List[str]
    for shim in shims:
        try:
            version = secure_boot.shim_version(shim)
        except (IOError, OSError):
            version = ''
        _out('')
        _out('shim {0}, version {1}'.format(shim, version or 'unknown'))
        wrappers = []  # the ones that could be read
        for wrapper in _certwrappers_next_to(os.path.dirname(shim)):
            try:
                keys = cert_keys(wrapper)
            except (IOError, OSError) as e:
                _out('  {0}: cannot be read: {1}'.format(wrapper, e))
                continue
            if same_content(wrapper, SHIPPED_CERTWRAPPER):
                kind = 'KernelCare, the one the package ships'
            elif is_kcare_certwrapper(wrapper):
                kind = 'KernelCare, not the one the package ships'
            else:
                kind = 'not KernelCare'
            _out('  {0}: {1}'.format(wrapper, kind))
            _out('    KernelCare keys: {0}'.format(keys_line(keys)))
            wrappers.append(wrapper)
        if not loads_all_certs(version):
            if not version:
                _out('  Its version cannot be read, so it counts as older than {0}.'.format(FIRST_SHIM_WITH_ALL_CERTS))
            _out('  Shim older than {0} loads only the first certificate of shim_certificate.efi.'.format(FIRST_SHIM_WITH_ALL_CERTS))
        loaded = _loaded_keys(version, wrappers)
        _out('  KernelCare keys this shim loads at boot: {0}'.format(keys_line(loaded)))
        prefix = '{0}: '.format(shim) if len(shims) > 1 else ''
        todo.extend(prefix + line for line in shim_todo(shim, version, loaded, trusted_keys, kmod_keys))

    _out('')
    shim_dirs = sorted(set(os.path.dirname(shim) for shim in shims))
    if state.startswith('off'):
        _out('What to do: nothing. Secure Boot is off, so the kernel does not require a trusted signature on kcare.ko.')
    elif trusted is None:
        _out('What to do: cannot tell, without the keys the running kernel trusts.')
    elif ALMALINUX_KEY in trusted:
        _out(
            'What to do: nothing. The running kernel trusts the AlmaLinux key, which signs kcare.ko for '
            'AlmaLinux kernels.  The KernelCare certificates are not needed.'
        )
    elif not shims:
        _out('What to do: cannot tell, no shim found in /boot/efi/EFI.')
    elif todo and len(shim_dirs) > 1:
        _out('What to do:')
        _out(
            '  shim is in several directories, {0}, so {1} changes nothing.  Where a step below runs it, copy {2} '
            'next to that shim, as shim_certificate.efi, instead.'.format(', '.join(shim_dirs), SETUP_SCRIPT, SHIPPED_CERTWRAPPER)
        )
        for line in todo:
            _out('  ' + line)
    elif todo:
        _out('What to do:')
        for line in todo:
            _out('  ' + line)
    else:
        _out('What to do: nothing.')
    return 0
