#!/usr/bin/python3
"""Known vulnerabilities of the installed software, for the Device Security page of GNOME Settings.

Four times a day (plinius-cve-update.timer) the issue list of the Arch Linux security tracker
(https://security.archlinux.org/issues/all.json) is downloaded and compared with the versions
in the local pacman database. Our own assessments say for single issues whether they affect
this system and how; issues without one are shown as "not assessed". After package changes
(pacman hook) the comparison runs again without a download (--offline), with the lists from the
last download. On a metered connection (mobile data) the lists are downloaded at most once a day
(METERED_INTERVAL); the runs in between compare as --offline does.

The assessments come from two places:
  - the central list on the project server (ASSESSMENTS_URL), fetched together with the tracker
    list, so that a new assessment reaches every phone within hours without a package update.
    It is signed with the key of the package repository (plinius-keyring) and used only when
    gpgv confirms that signature; a list older than the one already kept is refused, so an old
    signed copy cannot bring back outdated assessments. The verified copy and its signature are
    kept in the state directory and checked again whenever they are read.
  - the copy in this package (/usr/share/plinius-security/assessments.json), for the time
    before the first download and as a fallback.
  Both are merged per issue: the assessment with the later date wins, the central one on a tie.

The Android build properties (security patch levels) are readable by root only; the services
read them first as root (--kernel-info, ExecStartPre=+) into kernel.json.

The phone's kernel comes from the vendor boot image, not from a pacman package, so the tracker
cannot cover it. Its vulnerabilities come from the kernel CNA instead, as a list the project
server builds four times a day for this kernel release, filtered with the source files the kernel
configuration builds (tools/kernel-cves, KERNEL_CVES_URL). Issues from a CVSS score of
KERNEL_LIST_SCORE on are listed one by one in "kernel" -> "cves", the rest only counted; an
"extra" entry or an assessment of a kernel CVE still applies to it. An "extra" entry of the
kernel is left out when the running kernel's version already reaches the entry's "fixed"
version in the same branch. The list's "fixed_in_tree" (our own kernel carries fixes ahead of
its version number) does not hide one: the list is unsigned, and unsigned data only adds
issues. For a fix ahead of the version, the signed entry's "fixed" is set to the version of
our kernel that carries it.

Result: /var/lib/plinius-cve/cve.json
  {"version": 1, "checked": UNIX_TIME, "downloaded": UNIX_TIME or null, "error": TEXT or null,
   "assessments_updated": UNIX_TIME of the central list in use or null,
   "kernel": {"release": ..., "security_patch": ..., "vendor_security_patch": ...,
              "cves": {"generated", "affected", "built", "listed", "other", "assessed_harmless",
                       "not_in_branch" (fixed only in newer branches, not listed),
                       "issues": [like "issues", with "title" and "score"]},
              "cves_error": TEXT or null},
   "issues": [{"cve", "group", "package", "installed", "affected", "fixed", "status",
               "severity", "type", "assessment": {"status", "note", "date"} or null}, ...]}
An issue is listed when its package (or a package that provides it, like phosh-plinius for
phosh) is installed in a version the tracker does not call fixed, and our assessment does not
say that it leaves this system alone: "fixed" and "not_affected" are left out, the page shows
only what affects the phone ("affected", "mitigated") and what nobody has assessed yet.

Assessments file (the central one also carries "updated": UNIX_TIME of its publication):
  {"assessments": {"CVE-2025-6020": {"status": "not_affected", "note": "...", "date": "..."}},
   "extra": [{"cve": "CVE-...", "package": "kernel", "severity": "High", "type": "...",
              "status": "mitigated", "note": "...", "date": "..."}]}
  status: affected | mitigated | not_affected | fixed. A key may also be a tracker group
  (AVG-...), then it applies to all its CVEs. "extra" lists issues the tracker cannot know,
  e.g. of the vendor kernel.
"""

import argparse
import base64
import json
import os
import platform
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request

USER_AGENT = "Plinius Arch Linux"  # every request says who asks
TRACKER_URL = "https://security.archlinux.org/issues/all.json"
STATE_DIR = os.environ.get("STATE_DIRECTORY", "/var/lib/plinius-cve")
TRACKER_FILE = "arch-issues.json"
RESULT_FILE = "cve.json"
KERNEL_FILE = "kernel.json"
ASSESSMENTS = "/usr/share/plinius-security/assessments.json"
# Central assessments with a detached binary signature next to it (ASSESSMENTS_URL + ".sig"),
# published by tools/publish-assessments.sh
ASSESSMENTS_URL = "https://plinius.cais.de/security/assessments.json"
CENTRAL_FILE = "assessments.json"
# Far above the real size (about 30 kB); a server answering with endless data is cut off
CENTRAL_LIMIT = 4 * 1024 * 1024
# Vulnerabilities of the running kernel from the kernel CNA, filtered on the project server
# with the files the phone's kernel configuration builds (tools/kernel-cves). The Arch tracker
# knows only Arch's own kernel packages, and the phone's kernel is not a pacman package.
# Unsigned like the tracker list: it only adds issues, hiding one takes a signed assessment.
KERNEL_CVES_URL = "https://plinius.cais.de/security/kernel/{release}.json"
KERNEL_CVES_FILE = "kernel-cves.json"
KERNEL_CVES_LIMIT = 16 * 1024 * 1024  # about 300 kB today
# The release the server answered for without a list, with the boot it was asked in. Read by the
# NetworkManager dispatcher (90-plinius-cve): such a kernel is asked once per start, not at every
# connection. A download that did not reach the server leaves no mark.
KERNEL_UNLISTED_FILE = "kernel-unlisted"
# Right after a start or a connection the network may not resolve names yet (seen 09.11.2026:
# the dispatcher's "up" came before DNS). A download failing for that is tried again a few times
# instead of waiting for the next timer run.
NETWORK_TRIES = 4
# On a metered connection: the tracker list is about 600 kB, four times a day 70 MB a month
METERED_INTERVAL = 24 * 3600
NETWORK_RETRY_DELAY = 30  # seconds
# Listed one by one from this CVSS base score on; the others are only counted
KERNEL_LIST_SCORE = 7.0
# What the CVSS attack vector says about who can trigger an issue
ATTACK_VECTORS = {"N": "remote", "A": "local network", "L": "local", "P": "physical access"}
# The repository's signing key (ASCII armored) and the fingerprints pacman trusts or revoked
KEYRING = "/usr/share/pacman/keyrings/plinius.gpg"
TRUSTED = "/usr/share/pacman/keyrings/plinius-trusted"
REVOKED = "/usr/share/pacman/keyrings/plinius-revoked"
PACMAN_LOCAL = "/var/lib/pacman/local"
STATUSES = {"affected", "mitigated", "not_affected", "fixed"}
# Assessed as no concern for this system: not listed
HIDDEN = {"fixed", "not_affected"}


def installed_packages():
    """name -> version for installed packages, plus provided names -> (provider's version)."""
    versions, provides = {}, {}
    for entry in os.listdir(PACMAN_LOCAL):
        desc = os.path.join(PACMAN_LOCAL, entry, "desc")
        try:
            with open(desc, encoding="utf-8") as f:
                fields, key = {}, None
                for line in f:
                    line = line.rstrip("\n")
                    if line.startswith("%") and line.endswith("%"):
                        key = line[1:-1]
                        fields[key] = []
                    elif line and key:
                        fields[key].append(line)
        except OSError:
            continue
        name = fields.get("NAME", [None])[0]
        version = fields.get("VERSION", [None])[0]
        if not name or not version:
            continue
        versions[name] = version
        for p in fields.get("PROVIDES", []) + fields.get("REPLACES", []):
            # "phosh=0.57.0" or "phosh": our patched builds carry the upstream version
            base, _, pver = p.partition("=")
            provides.setdefault(base, (name, pver or version))
    return versions, provides


def vercmp(a, b):
    """pacman's version comparison: <0, 0, >0."""
    out = subprocess.run(["vercmp", a, b], capture_output=True, text=True, check=True)
    return int(out.stdout.strip())


def read_prop(path, key):
    try:
        with open(path, encoding="utf-8", errors="replace") as f:
            for line in f:
                if line.startswith(key + "="):
                    return line.split("=", 1)[1].strip() or None
    except OSError:
        pass
    return None


def kernel_info():
    """The running kernel and the Android security patch levels of the vendor system: read
    directly as root, otherwise from what --kernel-info left."""
    info = read_kernel_info()
    if info["security_patch"] or info["vendor_security_patch"]:
        return info
    try:
        with open(os.path.join(STATE_DIR, KERNEL_FILE), encoding="utf-8") as f:
            saved = json.load(f)
        if saved.get("release") == info["release"]:
            return saved
    except (OSError, ValueError):
        pass
    return info


def read_kernel_info():
    return {
        "release": platform.release(),
        "security_patch": read_prop("/system/build.prop", "ro.build.version.security_patch")
        or read_prop("/system/system/build.prop", "ro.build.version.security_patch"),
        "vendor_security_patch": read_prop("/vendor/build.prop", "ro.vendor.build.security_patch"),
    }


def parse_assessments(data):
    """(assessments by CVE or AVG, extra issues by CVE) of an assessments file, only valid entries."""
    if not isinstance(data, dict):
        return {}, {}
    raw = data.get("assessments")
    assessments = {k: v for k, v in (raw if isinstance(raw, dict) else {}).items()
                   if isinstance(v, dict) and v.get("status") in STATUSES}
    raw = data.get("extra")
    extra = {e["cve"]: e for e in (raw if isinstance(raw, list) else [])
             if isinstance(e, dict) and e.get("cve") and e.get("status") in STATUSES}
    return assessments, extra


def read_packaged():
    try:
        with open(ASSESSMENTS, encoding="utf-8") as f:
            return json.load(f)
    except (OSError, ValueError) as e:
        print(f"plinius-cve-update: no assessments in the package: {e}", file=sys.stderr)
        return None


def merge_assessments(packaged, central):
    """Per issue the assessment with the later date; the central list wins a tie, since it is
    the one that gets corrected first. Returns (assessments, list of extra issues)."""
    assessments, extra = parse_assessments(packaged)
    central_assessments, central_extra = parse_assessments(central)

    def take(entry, current):
        return current is None or str(entry.get("date", "")) >= str(current.get("date", ""))

    for key, entry in central_assessments.items():
        if take(entry, assessments.get(key)):
            assessments[key] = entry
    for key, entry in central_extra.items():
        if take(entry, extra.get(key)):
            extra[key] = entry
    return assessments, list(extra.values())


def fingerprints(path):
    """Key fingerprints in a pacman keyring list ("FPR:LEVEL:" or "FPR" per line)."""
    try:
        with open(path, encoding="utf-8") as f:
            return {line.split(":")[0].strip().upper() for line in f
                    if line.strip() and not line.startswith("#")}
    except OSError:
        return set()


def dearmor(text):
    """The binary key data of an ASCII armored key block (gpgv reads binary keyrings only)."""
    lines = [line.strip() for line in text.splitlines()]
    begin = next(i for i, line in enumerate(lines) if line.startswith("-----BEGIN PGP"))
    end = next(i for i, line in enumerate(lines) if i > begin and line.startswith("-----END PGP"))
    body = lines[begin + 1:end]
    # Armor headers ("Comment: ...") end with an empty line
    if "" in body:
        body = body[body.index("") + 1:]
    # The last line may be the CRC24 checksum ("=abcd"), not key data
    body = [line for line in body if line and not (line.startswith("=") and len(line) == 5)]
    return base64.b64decode("".join(body), validate=True)


def verify(data, signature):
    """True if signature is a valid signature of data by a key pacman trusts for this repo."""
    trusted = fingerprints(TRUSTED) - fingerprints(REVOKED)
    if not trusted:
        return False
    try:
        with open(KEYRING, encoding="ascii") as f:
            keyring = dearmor(f.read())
    except (OSError, ValueError, StopIteration) as e:
        print(f"plinius-cve-update: signing key not readable: {e}", file=sys.stderr)
        return False
    # gpgv gets an empty home of its own: nothing of the service user's (or anybody's) keys
    with tempfile.TemporaryDirectory(prefix="plinius-cve-") as tmp:
        paths = {}
        for name, content in (("keyring.gpg", keyring), ("data", data), ("data.sig", signature)):
            paths[name] = os.path.join(tmp, name)
            with open(paths[name], "wb") as f:
                f.write(content)
        result = subprocess.run(
            ["gpgv", "--homedir", tmp, "--status-fd", "1", "--keyring", paths["keyring.gpg"],
             paths["data.sig"], paths["data"]],
            capture_output=True, text=True)
    if result.returncode != 0:
        return False
    # [GNUPG:] VALIDSIG <signing key fpr> ... <primary key fpr>
    for line in result.stdout.splitlines():
        fields = line.split()
        if fields[:2] == ["[GNUPG:]", "VALIDSIG"] and len(fields) > 2:
            if fields[2].upper() in trusted or fields[-1].upper() in trusted:
                return True
    return False


def load_central():
    """The kept central assessments if their signature still holds, else None."""
    path = os.path.join(STATE_DIR, CENTRAL_FILE)
    try:
        with open(path, "rb") as f:
            data = f.read()
        with open(path + ".sig", "rb") as f:
            signature = f.read()
    except OSError:
        return None
    if not verify(data, signature):
        print("plinius-cve-update: kept central assessments fail the signature check, ignored",
              file=sys.stderr)
        return None
    try:
        central = json.loads(data)
    except ValueError:
        return None
    return central if isinstance(central, dict) else None


def fetch(url, limit=CENTRAL_LIMIT):
    req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
    with urllib.request.urlopen(req, timeout=60) as r:
        body = r.read(limit + 1)
    if len(body) > limit:
        raise ValueError(f"{url}: larger than {limit} bytes")
    return body


def valid_kernel_cves(data, release):
    return (isinstance(data, dict) and data.get("version") == 1 and data.get("release") == release
            and isinstance(data.get("generated"), int) and isinstance(data.get("issues"), list))


def load_kernel_cves(release):
    """The kept kernel list if it is for the running kernel, else None."""
    try:
        with open(os.path.join(STATE_DIR, KERNEL_CVES_FILE), encoding="utf-8") as f:
            data = json.load(f)
    except (OSError, ValueError):
        return None
    return data if valid_kernel_cves(data, release) else None


def network_error(e):
    """True for an error before any answer of the server (no route, no name resolution, timeout,
    connection lost), which may be gone a little later."""
    if isinstance(e, urllib.error.HTTPError):
        return False
    return isinstance(e, (urllib.error.URLError, TimeoutError, ConnectionError))


def boot_id():
    try:
        with open("/proc/sys/kernel/random/boot_id", encoding="ascii") as f:
            return f.read().strip()
    except OSError:
        return ""


def note_kernel_unlisted(release):
    """Notes that the server answered for this release, but without a usable list."""
    path = os.path.join(STATE_DIR, KERNEL_UNLISTED_FILE)
    with tempfile.NamedTemporaryFile("w", dir=STATE_DIR, delete=False, encoding="utf-8") as f:
        f.write(f"{release} {boot_id()}\n")
    os.replace(f.name, path)


def download_kernel_cves(release):
    """Fetches the kernel list for the running kernel and keeps it; raises otherwise (the kept
    one stays). A list older than the kept one is refused."""
    url = KERNEL_CVES_URL.format(release=urllib.parse.quote(release, safe=""))
    data = json.loads(fetch(url, KERNEL_CVES_LIMIT))
    if not valid_kernel_cves(data, release):
        raise ValueError("unexpected kernel list")
    kept = load_kernel_cves(release)
    if kept and data["generated"] < kept["generated"]:
        raise ValueError("kernel list is older than the kept one")
    write_json(KERNEL_CVES_FILE, data)


def version_numbers(version):
    """The leading numbers of a kernel version ("6.1.192-plinius4" -> (6, 1, 192)), () if none."""
    numbers = []
    for part in str(version).split("-", 1)[0].split("."):
        if not part.isdigit():
            break
        numbers.append(int(part))
    return tuple(numbers)


def fixed_by_version(kernel_version, fixed):
    """True if the running kernel is at least the fixed version of the same branch (6.1.192
    against "6.1.190"). A fix in another branch says nothing about this one: still listed."""
    running, needed = version_numbers(kernel_version), version_numbers(fixed)
    return (len(running) >= 3 and len(needed) >= 3 and running[:2] == needed[:2]
            and running >= needed)


def kernel_issues(data, kernel_version, assessments, skip):
    """(issues to list, summary) from a kernel list: CVEs from KERNEL_LIST_SCORE on one by one,
    except those a signed assessment calls fixed or harmless, those in skip (an extra entry
    says more about them) and those fixed only in newer branches: the kernel's own branch
    (6.1) has no fix for them, mostly because the bug never reached it. Those are only
    counted ("not_in_branch"), unless an assessment says something about them."""
    listed, other, hidden, not_in_branch = [], 0, 0, 0
    for k in data.get("issues", []):
        if not isinstance(k, dict) or not isinstance(k.get("cve"), str):
            continue
        cve = k["cve"]
        a = assessments.get(cve)
        if a and a.get("status") in HIDDEN:
            hidden += 1
            continue
        if cve in skip:
            continue
        fixed = k.get("fixed")
        if fixed and not k.get("branch_fixed") and not a:
            not_in_branch += 1
            continue
        score = k.get("score")
        if not isinstance(score, (int, float)) or score < KERNEL_LIST_SCORE:
            other += 1
            continue
        if fixed and not k.get("branch_fixed"):
            fixed = f"{fixed} (not in the {'.'.join(kernel_version.split('.')[:2])} branch)"
        vector = dict(p.split(":", 1) for p in str(k.get("cvss", "")).split("/")[1:] if ":" in p)
        listed.append({
            "cve": cve,
            "group": None,
            "package": "kernel",
            "installed": kernel_version,
            "affected": None,
            "fixed": fixed,
            "status": None,
            "severity": "Critical" if score >= 9 else "High",
            "type": ATTACK_VECTORS.get(vector.get("AV"), ""),
            "title": k.get("title") or None,
            "score": score,
            "assessment": a,
        })
    counts = data.get("counts") if isinstance(data.get("counts"), dict) else {}
    summary = {
        "generated": data.get("generated"),
        "affected": counts.get("affected"),
        "built": counts.get("built"),
        "listed": len(listed),
        "other": other,
        "assessed_harmless": hidden,
        "not_in_branch": not_in_branch,
    }
    return listed, summary


def download_central():
    """Fetches the central assessments and keeps them once their signature is confirmed and
    they are not older than the kept ones; raises otherwise (the kept ones stay)."""
    data = fetch(ASSESSMENTS_URL)
    signature = fetch(ASSESSMENTS_URL + ".sig")
    if not verify(data, signature):
        raise ValueError("signature of the central assessments is not valid")
    central = json.loads(data)
    updated = central.get("updated") if isinstance(central, dict) else None
    if not isinstance(updated, int):
        raise ValueError("central assessments without publication time")
    kept = load_central()
    kept_updated = kept.get("updated") if kept else None
    if isinstance(kept_updated, int):
        if updated < kept_updated:
            raise ValueError("central assessments are older than the kept ones")
        if updated == kept_updated:
            return
    # Signature first: a reader in between finds a pair that does not match and ignores it
    write_file(CENTRAL_FILE + ".sig", signature)
    write_file(CENTRAL_FILE, data)


def write_file(name, content):
    """Writes a file in the state directory atomically, readable by everyone (no secrets)."""
    fd, tmp = tempfile.mkstemp(dir=STATE_DIR, prefix="." + name)
    with os.fdopen(fd, "wb") as f:
        f.write(content)
    os.chmod(tmp, 0o644)
    os.replace(tmp, os.path.join(STATE_DIR, name))


def write_json(name, data):
    write_file(name, json.dumps(data, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))


def download():
    """Fetches the tracker list and keeps it; returns (issues, time) or raises."""
    req = urllib.request.Request(TRACKER_URL, headers={"User-Agent": USER_AGENT})
    with urllib.request.urlopen(req, timeout=60) as r:
        data = json.load(r)
    if not isinstance(data, list):
        raise ValueError("unexpected tracker data")
    now = int(time.time())
    write_json(TRACKER_FILE, {"downloaded": now, "issues": data})
    return data, now


def metered():
    """True when NetworkManager calls the connection in use metered: Metered 1 (yes) or 3
    (guessed yes, what it says for mobile data). Without NetworkManager it is not."""
    try:
        reply = subprocess.run(["busctl", "get-property", "org.freedesktop.NetworkManager",
                                "/org/freedesktop/NetworkManager", "org.freedesktop.NetworkManager",
                                "Metered"], capture_output=True, text=True, timeout=10)
    except (OSError, subprocess.SubprocessError):
        return False
    return reply.returncode == 0 and reply.stdout.strip() in ("u 1", "u 3")


def load_tracker():
    try:
        with open(os.path.join(STATE_DIR, TRACKER_FILE), encoding="utf-8") as f:
            data = json.load(f)
        return data["issues"], data["downloaded"]
    except (OSError, ValueError, KeyError):
        return None, None


def match(tracker, versions, provides, assessments):
    issues = []
    for group in tracker:
        if group.get("status") == "Not affected":
            continue
        for pkg in group.get("packages", []):
            if pkg in versions:
                installed = versions[pkg]
                shown = pkg
            elif pkg in provides:
                provider, installed = provides[pkg]
                shown = provider
            else:
                continue
            fixed = group.get("fixed")
            try:
                if fixed and vercmp(installed, fixed) >= 0:
                    continue
            except (subprocess.CalledProcessError, ValueError):
                pass
            for cve in group.get("issues", []):
                a = assessments.get(cve) or assessments.get(group.get("name"))
                # No concern for this system: nothing to show
                if a and a.get("status") in HIDDEN:
                    continue
                issues.append({
                    "cve": cve,
                    "group": group.get("name"),
                    "package": shown,
                    "installed": installed,
                    "affected": group.get("affected"),
                    "fixed": fixed,
                    "status": group.get("status"),
                    "severity": group.get("severity"),
                    "type": group.get("type"),
                    "assessment": a,
                })
    return issues


def main():
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--offline", action="store_true", help="compare with the last downloaded list only")
    ap.add_argument("--kernel-info", action="store_true",
                    help="only note the kernel and security patch levels (as root)")
    args = ap.parse_args()
    os.makedirs(STATE_DIR, exist_ok=True)
    if args.kernel_info:
        write_json(KERNEL_FILE, read_kernel_info())
        return 0

    kernel = kernel_info()
    release = kernel["release"]
    kernel_version = release.split("-", 1)[0]
    error = None
    kernel_error = None
    tracker, downloaded = None, None
    offline = args.offline
    if not offline and metered():
        _, last = load_tracker()
        if isinstance(last, int) and 0 <= time.time() - last < METERED_INTERVAL:
            print("plinius-cve-update: metered connection, lists downloaded less than a day ago are kept")
            offline = True
    if not offline:
        # The three downloads are independent: each one failing keeps its last data. Those that
        # failed before reaching the server are tried again together after a pause
        def get_tracker():
            nonlocal tracker, downloaded
            tracker, downloaded = download()

        def get_kernel():
            try:
                download_kernel_cves(release)
            except Exception as e:
                if not network_error(e):  # the server answered: no list for this kernel (yet)
                    note_kernel_unlisted(release)
                raise

        steps = {
            # network, TLS, JSON: keep the last list
            "tracker": (get_tracker, "download failed"),
            # Independent of the tracker: without it the kept and the packaged assessments apply
            "central": (download_central, "central assessments not updated"),
            # network, TLS, JSON, no list for this kernel yet
            "kernel": (get_kernel, "kernel list not updated"),
        }
        pending = list(steps)
        errors = {}
        for attempt in range(NETWORK_TRIES):
            if attempt:
                print(f"plinius-cve-update: network not reachable ({errors[pending[0]]}), "
                      f"trying again in {NETWORK_RETRY_DELAY} s", file=sys.stderr)
                time.sleep(NETWORK_RETRY_DELAY)
            for name in list(pending):
                try:
                    steps[name][0]()
                    errors.pop(name, None)
                    pending.remove(name)
                except Exception as e:
                    errors[name] = e
                    if not network_error(e):
                        pending.remove(name)
            if not pending:
                break
        for name, e in errors.items():
            print(f"plinius-cve-update: {steps[name][1]}: {e}", file=sys.stderr)
        if "tracker" in errors:
            error = str(errors["tracker"])
        if "kernel" in errors:
            kernel_error = str(errors["kernel"])
    if tracker is None:
        tracker, downloaded = load_tracker()
        if tracker is None:
            tracker = []
            error = error or "no tracker data yet"
    central = load_central()
    kernel_cves = load_kernel_cves(release)

    versions, provides = installed_packages()
    assessments, extra = merge_assessments(read_packaged(), central)
    issues = match(tracker, versions, provides, assessments)
    for e in extra:
        if e["status"] in HIDDEN:
            continue
        package = e.get("package", "")
        # Fixed in the running kernel by its version, once it reaches the version that brought
        # the fix. Not by the kernel list's "fixed_in_tree": that list is unsigned, and an
        # extra entry is signed (see KERNEL_CVES_URL)
        if package == "kernel" and fixed_by_version(kernel_version, e.get("fixed")):
            continue
        issues.append({
            "cve": e["cve"],
            "group": None,
            "package": package,
            # The phone's kernel is no pacman package: its version is the running one
            "installed": kernel_version if package == "kernel" else versions.get(package),
            "affected": None,
            "fixed": e.get("fixed"),
            "status": None,
            "severity": e.get("severity", "Unknown"),
            "type": e.get("type", ""),
            "assessment": {k: e[k] for k in ("status", "note", "date") if k in e},
        })
    if kernel_cves:
        listed, summary = kernel_issues(kernel_cves, kernel_version, assessments,
                                        {e["cve"] for e in extra})
        # A section of their own: hundreds of entries, none of them assessed, would bury the
        # few issues of the packages in "issues"
        kernel["cves"] = {**summary, "issues": listed}
    kernel["cves_error"] = kernel_error

    write_json(RESULT_FILE, {
        "version": 1,
        "checked": int(time.time()),
        "downloaded": downloaded,
        "error": error,
        "assessments_updated": central.get("updated") if central else None,
        "kernel": kernel,
        "issues": issues,
    })
    kernel_listed = len(kernel.get("cves", {}).get("issues", []))
    print(f"plinius-cve-update: {len(issues)} issues for installed packages, {kernel_listed} for the kernel"
          + (f" (tracker list from {time.strftime('%Y-%m-%d %H:%M', time.localtime(downloaded))})" if downloaded else ""))
    return 0


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