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

import base64
import binascii
import os
import re
import struct

from . import constants, kcare, log_utils, platform_utils, process_utils, utils

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


# Subject key identifiers of the keys KernelCare kernel modules are signed with, as /proc/keys shows them
KC_SIGNING_KEY_IDS = (
    '12ff0613c0f80cfba3b2f8eba71ebc27c5a76170',  # CloudLinux key, expires 2027-01-13
    '9235c13576ad2fd2ae6d3b939c981b0a53fff84b',  # CloudLinux key, 2027-01-13 .. 2032-01-13
    '69a6d9eed3f620d5c2e13a1d211c46510a5ad9f5',  # AlmaLinux kpatch signing key
)
# The serials `modinfo -F sig_key` shows for the CloudLinux keys, without colons
KC_SIGNING_KEY_SERIALS = {'98343425306d74a6': KC_SIGNING_KEY_IDS[0], '02': KC_SIGNING_KEY_IDS[1]}
# A serial names a certificate only together with its issuer.  modinfo shows the issuer's CN as
# the signer, and both CloudLinux certificates are self-signed with this CN.  A legacy, non-PKCS#7
# signature (EL7) shows "O: CN" instead.
KC_SIGNERS = ('Kernel Module Signing Key', 'Cloud Linux Software, Inc: Kernel Module Signing Key')
# A legacy signature names its key by the key id, so modinfo shows that instead of the serial
KC_SERIALS_BY_KEY_ID = dict((key_id, serial) for serial, key_id in KC_SIGNING_KEY_SERIALS.items())

EFIVARS_PATH = '/sys/firmware/efi/efivars'
EFI_VENDORS = {
    'global': '8be4df61-93ca-11d2-aa0d-00e098032b8c',
    'shim': '605dab50-e046-4300-abb6-3dd810dd8b23',
}


def _read_uefi_var(name, vendor, max_bytes=256):
    # type: (str, str, Optional[int]) -> Optional[bytes]
    var_path = os.path.join(EFIVARS_PATH, '%s-%s' % (name, vendor))
    if not os.path.exists(var_path):
        return None
    with open(var_path, 'rb') as var:
        return var.read(max_bytes)


def is_secure_boot():  # mocked: tests/unit/test_kmod.py, test_init.py
    # type: () -> bool
    try:
        secure_boot_var = _read_uefi_var('SecureBoot', EFI_VENDORS['global'])
        if secure_boot_var:
            return secure_boot_var[-1:] == b'\x01'  # Get last byte
    except Exception:  # pragma: no cover
        pass
    return False


def _get_uefi_var_encoded(name, vendor):
    # type: (str, str) -> Optional[str]
    try:
        value_bytes = _read_uefi_var(name, vendor)
        if value_bytes is None:
            return None
    except Exception as e:
        value_bytes = str(e).encode()
    return utils.nstr(base64.urlsafe_b64encode(value_bytes))


def secure_boot_info():
    # type: () -> dict[str, Any]
    cmdline = utils.try_to_read(os.path.join(platform_utils.PROC_DIR, 'cmdline'))
    if cmdline and len(cmdline) > 1024:  # pragma: no cover
        cmdline = cmdline[:1024]
    info = {'cmdline': cmdline, 'has_efi': os.path.exists(os.path.dirname(EFIVARS_PATH))}  # type: dict[str, Any]
    if not info['has_efi']:
        return info

    try:
        info['global'] = dict((var, _get_uefi_var_encoded(var, EFI_VENDORS['global'])) for var in ('SecureBoot', 'SetupMode'))
        shim_vars = sorted(
            [var[0 : -len(EFI_VENDORS['shim']) - 1] for var in os.listdir(EFIVARS_PATH) if var.endswith(EFI_VENDORS['shim'])]
        )
        info['shim'] = {'vars': shim_vars}
        shim_exclude_vars = set(['MokListRT', 'MokListXRT', 'MokListTrustedRT', 'SbatLevelRT'])
        for var in shim_vars:
            if var in ('HSIStatus', 'MokIgnoreDB') or (var.endswith('RT') and var not in shim_exclude_vars):
                info['shim'][var] = _get_uefi_var_encoded(var, EFI_VENDORS['shim'])
    except Exception as err:
        log_utils.logwarn(str(err))

    # The KernelCare key data matters only when Secure Boot checks module signatures.  Skip it
    # otherwise: secure_boot_info() runs on every patch-level fetch, and the collectors walk the
    # ESP, read whole shim binaries and run modinfo.
    if not is_secure_boot():
        return info
    for name, collect in (('kc_keys', kcare_keys_in_kernel), ('kmod_sig_key', cached_kmod_sig_key), ('esp', esp_shim_info)):
        try:
            value = collect()
        except Exception as err:
            log_utils.logwarn('Failed to collect {0}: {1}'.format(name, err))
            continue
        if isinstance(value, dict):
            info.update(value)
        elif value is not None:
            info[name] = value
    return info


def _modinfo_field(kmod_file, field):
    # type: (str, str) -> Optional[str]
    """Return the field of kmod_file that `modinfo -F` shows, '' when it has none, None when modinfo fails."""
    code, out, _ = process_utils.run_command(['/sbin/modinfo', '-F', field, '--', kmod_file], catch_stdout=True, catch_stderr=True)
    if code != 0:
        return None
    return (out or '').strip()


def kmod_sig_key(kmod_file):
    # type: (str) -> Optional[str]
    """Return the serial of the certificate kmod_file is signed with, without colons.

    For example, '98343425306d74a6'.  A legacy signature of a KernelCare key gives the same
    serial.  '' when the module is unsigned, None when modinfo fails.
    """
    sig_key = _modinfo_field(kmod_file, 'sig_key')
    if sig_key is None:
        return None
    sig_key = sig_key.replace(':', '').lower()
    return KC_SERIALS_BY_KEY_ID.get(sig_key, sig_key)


# The end of a signed module: struct module_signature, then this magic.  The signature itself
# comes right before them.
_MODSIG_MAGIC = b'~Module signature appended~\n'
_MODSIG_INFO = struct.Struct('>BBBBB3xI')  # algo, hash, id_type, signer_len, key_id_len, sig_len
_PKEY_ID_PKCS7 = 2
_DER_OID = 0x06
_COMMON_NAME_OID = b'\x55\x04\x03'  # 2.5.4.3


def _der_items(data, start, end):
    # type: (bytearray, int, int) -> List[Tuple[int, int, int]]
    """Split data[start:end] into DER items, as (tag, content start, content end)."""
    items = []
    while start < end:
        if start + 2 > end:
            raise ValueError('truncated DER header')
        tag, size = data[start], data[start + 1]
        start += 2
        if size & 0x80:
            octets = size & 0x7F
            if not 1 <= octets <= 4 or start + octets > end:
                raise ValueError('unsupported DER length')
            size = 0
            for octet in data[start : start + octets]:
                size = (size << 8) | octet
            start += octets
        if start + size > end:
            raise ValueError('truncated DER item')
        items.append((tag, start, start + size))
        start += size
    return items


def _common_name(data, start, end):
    # type: (bytearray, int, int) -> Optional[str]
    """Return the first CN of the X.509 Name in data[start:end], as modinfo shows the signer."""
    for _, rdn_start, rdn_end in _der_items(data, start, end):
        for _, atv_start, atv_end in _der_items(data, rdn_start, rdn_end):
            atv = _der_items(data, atv_start, atv_end)
            if len(atv) == 2 and atv[0][0] == _DER_OID and bytes(data[atv[0][1] : atv[0][2]]) == _COMMON_NAME_OID:
                return utils.nstr(bytes(data[atv[1][1] : atv[1][2]]), errors='replace')
    return None


def _pkcs7_kcare_keys(kmod_file):
    # type: (str) -> Optional[Set[str]]
    """Return the KernelCare keys that sign kmod_file, by their first 8 hex digits.

    A PKCS#7 module signature can have several signers, and the kernel accepts the module when
    it trusts any of them.  modinfo shows only the first.  None when kmod_file has no PKCS#7
    signature (an unsigned module, a legacy EL7 signature), or one this parser cannot read.
    """
    try:
        with open(kmod_file, 'rb') as f:
            f.seek(0, os.SEEK_END)
            size = f.tell()
            tail = len(_MODSIG_MAGIC) + _MODSIG_INFO.size
            if size < tail:
                return None
            f.seek(size - tail)
            trailer = f.read(tail)
            if not trailer.endswith(_MODSIG_MAGIC):
                return None
            _, _, id_type, _, _, sig_len = _MODSIG_INFO.unpack(trailer[: _MODSIG_INFO.size])
            if id_type != _PKEY_ID_PKCS7 or sig_len > size - tail:
                return None
            f.seek(size - tail - sig_len)
            data = bytearray(f.read(sig_len))
    except (IOError, OSError):
        return None

    try:
        # ContentInfo ::= SEQUENCE { contentType, [0] EXPLICIT SignedData }
        content_info = _der_items(data, 0, len(data))[0]
        signed_data_wrapper = _der_items(data, content_info[1], content_info[2])[1]
        signed_data = _der_items(data, signed_data_wrapper[1], signed_data_wrapper[2])[0]
        # SignedData ends with signerInfos, a SET OF SignerInfo
        signer_infos = _der_items(data, signed_data[1], signed_data[2])[-1]
        if signer_infos[0] != 0x31:
            raise ValueError('no signerInfos')
        keys = set()
        for _, info_start, info_end in _der_items(data, signer_infos[1], signer_infos[2]):
            sid = _der_items(data, info_start, info_end)[1]
            if sid[0] == 0x80:  # [0] subjectKeyIdentifier: sign-file -k
                key_id = utils.nstr(binascii.hexlify(bytes(data[sid[1] : sid[2]])))
                if key_id in KC_SERIALS_BY_KEY_ID:
                    keys.add(key_id[:8])
            else:
                # IssuerAndSerialNumber ::= SEQUENCE { issuer Name, serialNumber INTEGER }
                issuer, serial = _der_items(data, sid[1], sid[2])[:2]
                serial_hex = utils.nstr(binascii.hexlify(bytes(data[serial[1] : serial[2]]).lstrip(b'\x00') or b'\x00'))
                if serial_hex in KC_SIGNING_KEY_SERIALS and _common_name(data, issuer[1], issuer[2]) in KC_SIGNERS:
                    keys.add(KC_SIGNING_KEY_SERIALS[serial_hex][:8])
        return keys
    except (IndexError, ValueError) as err:
        log_utils.logwarn('Cannot read the signature of {0}: {1}'.format(kmod_file, err), print_msg=False)
        return None


def kmod_kcare_keys(kmod_file):
    # type: (str) -> List[str]
    """Return the KernelCare keys that sign kmod_file, by their first 8 hex digits.

    For example, ['12ff0613', '9235c135'] for a module signed with both.  [] when no
    KernelCare key signs it, or when that cannot be told.
    """
    keys = _pkcs7_kcare_keys(kmod_file)
    if keys is None:  # a legacy signature names one key, and modinfo shows it
        serial = kmod_sig_key(kmod_file)
        keys = set()
        if serial in KC_SIGNING_KEY_SERIALS and _modinfo_field(kmod_file, 'signer') in KC_SIGNERS:
            keys.add(KC_SIGNING_KEY_SERIALS[serial or ''][:8])
    return sorted(keys)


def kcare_key_problem(kmod_file):
    # type: (str) -> Optional[str]
    """Return why the kernel would reject the KernelCare signature of kmod_file, or None.

    During the key rotation a host can trust one KernelCare key and not the other, so a key
    kmod_file is signed with has to be one the kernel trusts, not just any.  kcare.ko signed
    with both keys loads wherever either is trusted.  None also when /proc/keys cannot be read.
    """
    enrolled = kcare_keys_in_kernel()
    if enrolled is None:
        return None
    if not enrolled:
        return 'No KernelCare certificates enrolled.'
    needed = kmod_kcare_keys(kmod_file) if os.path.isfile(kmod_file) else []
    if not needed or set(needed) & set(enrolled):
        return None
    if len(needed) == 1:
        signed_with = 'the KernelCare key {0}, which is not enrolled'.format(needed[0])
    else:
        signed_with = 'the KernelCare keys {0}, none of which is enrolled'.format(', '.join(needed))
    return '{0} is signed with {1}. Enrolled KernelCare keys: {2}.'.format(kmod_file, signed_with, ', '.join(enrolled))


def _is_kernel_key(line):
    # type: (str) -> bool
    """Whether a /proc/keys line is a key the kernel holds: owned by uid 0 and of type asymmetric,
    which /proc/keys cuts to 9 characters.

    Any user can add a key of another type whose description holds a key id, and let root view it,
    so a match anywhere in /proc/keys proves nothing.
    """
    fields = line.split()
    return len(fields) > 7 and fields[5] == '0' and fields[7] == 'asymmetri'


def read_proc_keys():
    # type: () -> Optional[str]
    """/proc/keys, or None when it does not exist.

    Read as bytes: a key description may hold any byte, and on Python 3 one that is not UTF-8 would make a
    text read fail.  Such bytes become U+FFFD, and the key ids this module looks for are ASCII.
    """
    path = os.path.join(platform_utils.PROC_DIR, 'keys')
    if not os.path.exists(path):
        return None
    with open(path, 'rb') as f:
        return f.read().decode('ascii', 'replace')


def kcare_keys_in_kernel():
    # type: () -> Optional[List[str]]
    """Return the KernelCare signing keys the kernel trusts, by their first 8 hex digits.

    For example, ['12ff0613', '9235c135'].  None when /proc/keys cannot be read.

    Any user can still forge a whole line: /proc/keys prints the description of a key of type user as
    it is, newlines included.  So a key listed here may be one the kernel does not hold, and callers use
    the list for advice and reports only, never to skip work.
    """
    system_keys = read_proc_keys()
    if system_keys is None:
        return None
    # split on '\n' only, the end of each line: splitlines() would also split a description at '\r'
    kernel_keys = [line for line in system_keys.split('\n') if _is_kernel_key(line)]
    return sorted(key_id[:8] for key_id in KC_SIGNING_KEY_IDS if any(key_id in line for line in kernel_keys))


ESP_EFI_DIR = '/boot/efi/EFI'
SHIM_NAME = re.compile(r'^shim[^_]*\.efi$')  # shimx64.efi, shimaa64.efi, shim.efi; not shim_certificate.efi
_SHIM_VERSION = re.compile(br'\$Version: ([0-9A-Za-z.~+-]{1,32}) \$')
# KernelCare certwrappers carry this string, the subject of the KernelCare certificates
KC_CERT_MARKER = b'Cloud Linux Software'
# Subject key identifier of the 2027..2032 KernelCare key.  Only certwrappers built since 2026 carry it.
_KC_2027_KEY_ID = binascii.unhexlify(KC_SIGNING_KEY_IDS[1])


def read_binary(path):
    # type: (str) -> bytes
    with open(path, 'rb') as f:
        return f.read()


def _certwrapper_kind(path):
    # type: (str) -> str
    data = read_binary(path)
    if KC_CERT_MARKER not in data:
        return 'foreign'
    return 'kc-2027' if _KC_2027_KEY_ID in data else 'kc-2022'


def is_certwrapper_name(name):
    # type: (str) -> bool
    """Whether shim loads certificates from a file of this name next to it.

    From 16.0 shim loads every file whose name starts with "shim_certificate", in any case, as
    load_unbundled_trust in its shim.c does. Shim before 16.0 loads only shim_certificate.efi.
    """
    return name.lower().startswith('shim_certificate')


def shim_version(path):
    # type: (str) -> str
    """Return the version shim binary path embeds, for example '15.8', or '' when it has none."""
    match = _SHIM_VERSION.search(read_binary(path))
    return utils.nstr(match.group(1)) if match else ''


def esp_shim_info():
    # type: () -> Optional[Dict[str, str]]
    """Return the version of shim on the ESP and the kind of each certwrapper next to it.

    For example, {'shim_version': '15.8', 'certwrapper': 'kc-2027'}.  None when the ESP
    has no shim.  Shim before 16.0 imports only the first certificate of a certwrapper.
    To tell whether a host trusts the 2027 KernelCare key after a reboot, you need both.
    """
    versions = set()
    wrappers = set()
    found = False
    for root, _, files in os.walk(ESP_EFI_DIR):
        shims = [name for name in files if SHIM_NAME.match(name)]
        if not shims:
            continue
        found = True
        for name in shims:
            version = shim_version(os.path.join(root, name))
            if version:
                versions.add(version)
        for name in files:
            if is_certwrapper_name(name):
                wrappers.add(_certwrapper_kind(os.path.join(root, name)))
    if not found:
        return None
    return {'shim_version': ','.join(sorted(versions)), 'certwrapper': ','.join(sorted(wrappers)) or 'none'}


def cached_kmod():
    # type: () -> Optional[str]
    """Return the path of this kernel's newest cached kcare.ko, or None when none is cached."""
    patches_dir = os.path.join(constants.PATCH_CACHE, 'patches')
    if not os.path.isdir(patches_dir):
        return None
    marker = '-{0}-'.format(kcare.get_kernel_hash())
    kmods = [os.path.join(patches_dir, name, constants.KMOD_BIN) for name in os.listdir(patches_dir) if marker in name]
    kmods = [kmod for kmod in kmods if os.path.isfile(kmod)]
    if not kmods:
        return None
    return max(kmods, key=os.path.getctime)


def cached_kmod_sig_key():
    # type: () -> Optional[str]
    """Return the serial of the certificate that signs this kernel's newest cached kcare.ko.

    The serial names the KernelCare key the module needs:
    - '98343425306d74a6': the key that expires on 2027-01-13
    - '02': its successor, valid from 2027-01-13 to 2032-01-13
    '' when the module is unsigned.  None when no module is cached or modinfo fails.
    """
    kmod = cached_kmod()
    if kmod is None:
        return None
    sig_key = kmod_sig_key(kmod)
    return None if sig_key is None else sig_key[:40]
