diff --git a/.github/fork-ci-tests.txt b/.github/fork-ci-tests.txt index afaa2bc9b505a..ed6d9a07306c0 100644 --- a/.github/fork-ci-tests.txt +++ b/.github/fork-ci-tests.txt @@ -163,6 +163,7 @@ fork-kit/schedule-kick/tests/install.test.py unittest fork-kit/schedule-kick/tests/kick.test.py unittest fork-kit/schedule-kick/tests/late.test.py unittest fork-kit/update-policy/tests/baseline.test.py unittest +fork-kit/update-policy/tests/exposure.test.py unittest fork-kit/update-policy/tests/idle.test.py unittest fork-kit/update-policy/tests/install.test.py unittest fork-kit/update-policy/tests/tick.test.py unittest diff --git a/fork-kit/README.md b/fork-kit/README.md index 3edee2412ca6d..4937501e6b40d 100644 --- a/fork-kit/README.md +++ b/fork-kit/README.md @@ -25,7 +25,7 @@ Every kit follows the same pattern: | [pc-agents](pc-agents/README.md) | Run T3's agents on a Windows PC in a walled WSL2 distro, checked before every start (WSL2) | | [review](review/README.md) | A review skill for the merge gate: lenses picked by changed paths, the state question, a comment format checked against the gate's parser, a model eval; no installer, used from a checkout | | [schedule-kick](schedule-kick/README.md) | `schedule-kick`: start scheduled GitHub workflows on time by `workflow_dispatch` when no run exists for the slot; timer every 5 minutes (Linux, systemd) | -| [update-policy](update-policy/README.md) | Restart only when idle at the quiet hour (dev, personal), alert only (live); a daily baseline check that reports drift (Linux, Debian/Ubuntu, systemd) | +| [update-policy](update-policy/README.md) | Restart only when idle at the quiet hour (dev, personal), alert only (live); daily baseline and exposure (KEV, EPSS) checks that report only drift and what needs action (Linux, Debian/Ubuntu, systemd) | [common](common/README.md) is code the kits share, copied into each kit's version folder: the loader of the one private machine file (`/etc/fork-kit/machine.json`) where the facts of one machine live, and the installer and diff --git a/fork-kit/common/machine.example.json b/fork-kit/common/machine.example.json index 2cb47591d275c..400676081d616 100644 --- a/fork-kit/common/machine.example.json +++ b/fork-kit/common/machine.example.json @@ -128,6 +128,22 @@ "diskPaths": ["/"], "pendingDays": 3, "sshUsers": ["root", "example-agent"] + }, + "exposure": { + "enabled": true, + "epssMin": 0.1, + "fixWaitingDays": 3, + "staleDays": 3, + "maxFeedMb": 64, + "maxXmlMb": 1024, + "timeoutSeconds": 60, + "ignore": [ + { + "cve": "CVE-2021-1789", + "reason": "example: the package is not used here", + "until": "2026-12-31" + } + ] } }, "desk": { diff --git a/fork-kit/update-policy/README.md b/fork-kit/update-policy/README.md index ba5a5c0db4e91..72eab34cd8ba7 100644 --- a/fork-kit/update-policy/README.md +++ b/fork-kit/update-policy/README.md @@ -1,4 +1,4 @@ -# update-policy: restart only when idle, at the quiet hour, by role; and a daily baseline check +# update-policy: restart only when idle, at the quiet hour, by role; a daily baseline and exposure check Linux machines install security updates by themselves (`unattended-upgrades`). Some updates (a kernel, libc) need a restart. `unattended-upgrades`' own `Automatic-Reboot` restarts at a fixed time whatever runs then: long agent jobs @@ -9,7 +9,9 @@ and containers that do not come back by themselves are cut off. This kit takes r command and try again the next night; - **live** machines never restart by themselves: a needed restart raises an alert (once per quiet window) and is done by hand in a planned window; -- a **daily baseline check** compares the machine with the policy and prints (and alerts) only what drifted. +- a **daily baseline check** compares the machine with the policy and prints (and alerts) only what drifted; +- a **daily exposure check** (off unless turned on) compares the installed packages with the distribution's + security data, CISA's Known Exploited Vulnerabilities list and EPSS, and reports only what needs action. Debian or Ubuntu with systemd and cgroup v2 (`/run/reboot-required`, `apt-config`, logind's inhibitor locks); without cgroup v2 the machine always counts as busy. Plain Python 3 standard library (3.9 or @@ -24,6 +26,7 @@ later, for `zoneinfo`); nothing to install but the kit. | `update-policy baseline` | the daily check: prints only drift and alerts with it; exit 0 none, 1 drift | | `update-policy booted` | after a boot (`update-policy-boot.service`): says once that the kit's restart came back | | `update-policy status` | the role, the window, a pending restart and what the last ticks saw | +| `update-policy exposure` | the daily exposure check (below): prints only what needs action; exit 0 none, 1 any | Run them as root: they read every user's cgroups, containers and sockets. Everything they say goes to stdout, which is the journal under the units (`journalctl -u update-policy`). @@ -169,6 +172,7 @@ restart is pending; `baseline` reports it). | `baseline.diskPaths` | `["/"]` | the disks it looks at | | `baseline.pendingDays` | 3 | a restart pending longer than this is drift | | `baseline.sshUsers` | `["root"]` | users whose ssh login from outside is checked with `sshd -T -C` (Match blocks) | +| `exposure.*` | | the exposure check: see its section | **The alert command** gets the text on stdin and `UPDATE_POLICY_EVENT` (`restart-pending`, `live-restart-pending`, `restart-failed`, `apt-restarts`, `back-up`, `drift`) and `UPDATE_POLICY_HOST` in a plain @@ -210,6 +214,111 @@ nothing else; exit 1 when there is any, and the alert command gets the lines (`d A fact it cannot read is drift ("cannot read ..."), never a pass; a check that breaks is one such line, and the others still run. +## The daily exposure check + +`update-policy exposure` (`update-policy-exposure.timer`, daily around 07:00; on with `exposure.enabled`) answers +"is anything installed here, or the running kernel, exploited in the wild, or waiting for a security fix?" It prints +one line per thing that needs action (one per CVE on KEV, one per source package with a waiting fix; at most 40, the +rest counted on a last line and kept in the report), ranked KEV first then by EPSS; exit 1 when there is any line, +and the alert command gets the lines (`exposure`). To run it by hand: `systemctl start update-policy-exposure.service` +and `journalctl -u update-policy-exposure` (as root on the unit's cache it refuses: it would leave root-owned files +there; `--cache DIR` for a cache of your own). + +| Line | When | Action | +| ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | +| `KEV CVE-… is exploited in the wild: SOURCE VERSION (PKGS): update to FIXED` | a CVE on CISA's KEV list affects an installed version (or the running kernel: `and restart`) and a fixed version is out | update | +| `KEV CVE-… is exploited in the wild and has no fix yet: mitigate or watch: …` | the same, with no fixed version | mitigate, watch | +| `security fix waiting N day(s): SOURCE VERSION (PKGS) -> FIXED: CVE-…` | a source package has a security fix out, and a CVE's EPSS is at least `epssMin` or the fix has waited longer than `fixWaitingDays` | update | +| `cannot check: …` | a feed that could not be downloaded, read or that holds far fewer entries than before; no data source; packages that cannot be listed | look; never all clear | +| `drift: …` | a cached feed older than `staleDays`; an ignore entry past its date | look | +| `kernel: not checked (why)` | a note, in every report where the running kernel could not be judged (a WSL or custom kernel, no data); no finding | none | + +A fix that needs Ubuntu Pro (an `esm` version) says so. A CVE without a fix that is not on KEV is not shown (Ubuntu +lists thousands as "might be affected"); neither is a waiting fix below the thresholds (unattended-upgrades installs it +the next night). The "waiting" days count per CVE and package from the first run that saw it, kept in the cache's +state: a newer fix does not restart them, and neither does a run without usable data. + +**Installed** packages come from `dpkg-query`: installed, held, and those whose files are on disk though dpkg did not +finish (half-installed, unpacked, half-configured, triggers) all count; a status it does not know is `cannot check`. +Versions are compared in dpkg's own order. + +**The kernel** is judged by the running one only (`uname -r`), never by other kernels, headers or modules that are +installed: + +- Ubuntu: the OVAL file's own kernel tests (each kernel flavour's release pattern, and its fixed version). The flavour + is the source package of the running kernel's `linux-modules-`; a release that no flavour matches (a WSL, + mainline or custom kernel), or several match and the packages do not say which, is the note `kernel: not checked`; +- Debian: the running kernel's `linux-image-` (from `linux-signed-*`) is matched as the source `linux` the + OVAL file names; none installed is the note. + +A kernel line says `and restart`, and its waiting days count per kernel flavour, so booting a newer kernel that is +still behind keeps them. Livepatch is not read: a kernel CVE that a live patch already covers still shows until the +restart (the restart policy's planned window on a live machine). + +**Data**, each downloaded at most once a day into `/var/cache/update-policy-exposure/`, with a size cap +(`maxFeedMb`), a timeout (`timeoutSeconds`), the server's ETag / Last-Modified, https only (a redirect to anything +else is refused) and a sha256 of the stored copy (a copy that does not match is no copy): + +- the distribution's OVAL file: Ubuntu's `com.ubuntu..cve.oval.xml.bz2` (security-metadata.canonical.com) + or Debian's `oval-definitions-.xml.bz2` (debian.org), by `/etc/os-release` (`ovalUrl` to use another + copy). Debian writes "no fixed version" as "less than 0:0", and uses the same form for some entries it judged not + to affect the release, which the file cannot tell apart: such a KEV line says "has no fixed version listed by + Debian" and that an ignore entry is the way out when it does not apply; +- CISA's KEV JSON (`kevUrl`); +- FIRST.org's daily EPSS file (`epssUrl`, about 3 MB): every CVE's score, so nothing about this machine is sent + anywhere. The OVAL URL names the release codename; that is all a server learns. + +**A feed that changed** never reads as all clear. A download goes to a temporary file and is read by its own reader +before it replaces the kept copy; it is refused, the old copy kept and the reason a `cannot check` line, when: + +- it is not the format (an OVAL test kind, state operation, object or variable the reader does not know; fewer than + 90% of its package tests naming a package; no `vulnerabilities` list; no `cve,epss,percentile` header); +- it holds fewer entries than an absolute floor (OVAL 1,000 package advisories, KEV 500, EPSS 100,000), or under half + the kept copy's (the OVAL file's package advisories and kernel entries each on their own, so a big loss of one is + not hidden by the other). A feed that really shrank for good is accepted once it reads cleanly with the same + smaller counts on 3 days in a row; that day says `drift: … the feed shrank … accepted`; +- it is larger than `maxFeedMb`, or than `maxXmlMb` once decompressed, or one entry holds over 500,000 elements. + +The OVAL file is read as a stream, every finished entry is dropped, and of the kernel entries only those of the +running kernel are kept (a real file: about 265 MB for noble, 375 MB for jammy). A kernel entry it cannot read (its +version or the pattern that reads `uname -r`) is a format error too. The unit has `MemoryHigh=768M`, `MemoryMax=1G` +and low CPU and IO weights, so a hostile feed cannot take the machine's memory. A fault in the check itself is a +`cannot check` report, never a missing one. + +Other package systems (rpm, apk) fit in as one more entry of `ECOSYSTEMS` in `lib/updatepolicy/exposure.py`: their +installed list, version order and data source. + +**It runs as no one in particular:** the unit uses systemd's `DynamicUser=` (a user made for the run, the cache +folder its only writable place); only the alert step after it (`update-policy exposure-alert`, `ExecStopPost=+`) +runs as root, so the alert command can read a root-only file. It needs no secret. + +| Key | Default | What | +| ------------------------- | ------- | ----------------------------------------------------------------------------------------------- | +| `exposure.enabled` | `false` | run the check (the timer runs either way; off, it does nothing) | +| `exposure.epssMin` | 0.1 | a waiting fix with a CVE at this EPSS or above is shown at once | +| `exposure.fixWaitingDays` | 3 | a waiting fix is shown once it has waited longer than this (as this check first saw it) | +| `exposure.staleDays` | 3 | a cached feed older than this is drift | +| `exposure.maxFeedMb` | 64 | the size cap of one download | +| `exposure.maxXmlMb` | 1024 | the size cap of the OVAL file once decompressed | +| `exposure.timeoutSeconds` | 60 | the timeout of one request | +| `exposure.ovalUrl` | `""` | another `https://` copy of the distribution's OVAL file | +| `exposure.kevUrl` | `""` | another `https://` copy of the KEV JSON | +| `exposure.epssUrl` | `""` | another `https://` copy of the daily EPSS file (gzip CSV) | +| `exposure.ignore` | `[]` | `{"cve": "CVE-…", "reason": "…", "until": "YYYY-MM-DD"}`: not shown until that date, then drift | + +**Runs again, stops half-way, old or empty cache, a feed format change:** + +- runs again the same day: no download (once a day), the same lines; the next day only a changed feed is + downloaded. Two runs at once: the second finds the cache's lock held and does nothing; the report is written + before the lock is let go; +- stops half-way (a timeout's SIGTERM runs no cleanup): every write goes to a temporary file and is renamed whole; + the next run first removes temporary files a killed run left. A stop between a copy and its meta leaves a copy that + does not match its checksum: no copy, so `cannot check` until the next download; +- old or empty cache: no copy is `cannot check` (never all clear); a broken meta or state starts again from empty (a + waiting fix is then dated from today); a copy older than `staleDays` is still read and is drift. A cache of the + first format is taken over: its per-CVE EPSS file is removed and its waiting days are kept; +- a feed format change: see "A feed that changed": the old copy stays and the line names the feed. + ## Install As root, from a commit on the fork's protected `ci-release` branch (the shared @@ -225,8 +334,9 @@ update-policy status && update-policy idle; update-policy baseline `--timer` takes restarts over in an order that never leaves the machine with neither policy: 1. it writes the system units `update-policy.service` and `.timer` (every 5 minutes), - `update-policy-baseline.service` and `.timer` (daily) and `update-policy-boot.service` (once after each boot) - to `/etc/systemd/system/`, runs `systemctl daemon-reload`, enables and starts both timers and enables the boot + `update-policy-baseline.service` and `.timer` (daily), `update-policy-exposure.service` and `.timer` (daily) and + `update-policy-boot.service` (once after each boot) + to `/etc/systemd/system/`, runs `systemctl daemon-reload`, enables and starts the three timers and enables the boot unit. If that fails, it stops there: unattended-upgrades' own restarts still apply; 2. only then it writes `/etc/apt/apt.conf.d/zz-update-policy`: `Unattended-Upgrade::Automatic-Reboot "false";`. Its name sorts after the numbered files, so it wins over an `Automatic-Reboot "true"` there @@ -249,7 +359,7 @@ whether `--timer` is on) and `installed.tsv`; the tick's state in `/var/lib/upda - **Back to unattended-upgrades' own restarts:** the bootstrap with `--no-timer` (or `update-policy-install install --source /usr/local/libexec/update-policy/current --sha CURRENT_SHA --no-timer`). It removes the apt file first, so unattended-upgrades' own `Automatic-Reboot` applies again, then stops, disables and removes the units. -- **Remove:** `update-policy-install uninstall`: the same, then the code and the state. +- **Remove:** `update-policy-install uninstall`: the same, then the code, the state and the exposure cache. ## Runs again, stops half-way, old or empty state @@ -279,7 +389,8 @@ whether `--timer` is on) and `installed.tsv`; the tick's state in `/var/lib/upda ## Tests `tests/*.test.py`, run with `python3 -I -B fork-kit/update-policy/tests/NAME.test.py` from the repository root: -fake cgroups, `/proc`, sockets and programs in a temporary folder, a fixed clock. No root, no systemd, no network. -Each file ends with a red check that breaks each rule in a copy of the code (or the installer) and shows its test -then fails. What every kit's installer does is tested in +fake cgroups, `/proc`, sockets and programs in a temporary folder, a fixed clock; `exposure.test.py` reads small +recorded cuts of Ubuntu's and Debian's OVAL files and of the KEV list (`tests/fixtures/`) through a fake web. No root, +no systemd, no network. Each file ends with a red check that breaks each rule in a copy of the code (or the +installer) and shows its test then fails. What every kit's installer does is tested in [kit_install.test.py](../common/tests/kit_install.test.py); `install.test.py` covers this kit's own files. diff --git a/fork-kit/update-policy/lib/updatepolicy/baseline.py b/fork-kit/update-policy/lib/updatepolicy/baseline.py index 131e06d406043..242252cad56a5 100644 --- a/fork-kit/update-policy/lib/updatepolicy/baseline.py +++ b/fork-kit/update-policy/lib/updatepolicy/baseline.py @@ -77,7 +77,7 @@ def policy_drift(host, cfg, s, state): problem = aptconf.restart_problem(cfg) if isinstance(cfg, dict) else None if problem: out.append(problem) - for unit in OWN_UNITS: + for unit in OWN_UNITS + (('update-policy-exposure.timer',) if s['exposure']['enabled'] else ()): word = enabled(host, unit) if word != 'enabled': out.append(f'{unit} is installed but {word}, not enabled: pending restarts are neither made nor ' diff --git a/fork-kit/update-policy/lib/updatepolicy/cli.py b/fork-kit/update-policy/lib/updatepolicy/cli.py index 4c5cc75124218..286fda9050272 100644 --- a/fork-kit/update-policy/lib/updatepolicy/cli.py +++ b/fork-kit/update-policy/lib/updatepolicy/cli.py @@ -6,13 +6,16 @@ update-policy baseline the daily check: prints only drift, alerts with it; exit 0 none, 1 drift update-policy booted after a boot: says once that a restart this kit made came back (update-policy-boot) update-policy status the role, the window, a pending restart and what the last ticks saw + update-policy exposure the daily exposure check: KEV, security fixes waiting, ranked by EPSS; exit 0 none, 1 any + (update-policy-exposure.service runs it as an unprivileged user; --cache DIR) + update-policy exposure-alert sends the last exposure report through the alert command (as root, after it) The facts of the machine (role, quiet hour, time zone, alert command, ...) are in the "update-policy" section of /etc/fork-kit/machine.json. Run it as root: it reads every user's cgroups, containers and sockets. """ import argparse, datetime, json, os, sys -from updatepolicy import baseline, idle, settings, tick, window +from updatepolicy import baseline, exposure, idle, settings, tick, window LEVELS = {'err': 3, 'warning': 4, 'notice': 5, 'info': 6} EXIT_IDLE, EXIT_BUSY = 0, 75 @@ -73,6 +76,10 @@ def main(argv, host=None, read_settings=None): sub.add_parser('baseline') sub.add_parser('booted') sub.add_parser('status') + e = sub.add_parser('exposure') + e.add_argument('--cache', default=exposure.CACHE) + e2 = sub.add_parser('exposure-alert') + e2.add_argument('--cache', default=exposure.CACHE) d = sub.add_parser('docker-ps') d.add_argument('socket') a = ap.parse_args(argv) @@ -85,6 +92,10 @@ def main(argv, host=None, read_settings=None): return 1 print(json.dumps(names)) return 0 + if a.cmd == 'exposure': + return exposure.run(host, read_settings, a.cache) + if a.cmd == 'exposure-alert': + return exposure.alert(m, read_settings, a.cache) if a.cmd == 'tick': return tick.tick(m, read_settings, lambda s: idle.look(host, s)) if a.cmd == 'booted': diff --git a/fork-kit/update-policy/lib/updatepolicy/debver.py b/fork-kit/update-policy/lib/updatepolicy/debver.py new file mode 100644 index 0000000000000..dde1c9c5d98bd --- /dev/null +++ b/fork-kit/update-policy/lib/updatepolicy/debver.py @@ -0,0 +1,60 @@ +"""Debian package versions compared the way dpkg compares them (deb-version(7)): [epoch:]upstream[-revision], with +`~` sorting before everything, even the end of the string. Pure; no dpkg needed.""" +import re + +VERSION_RE = re.compile(r'^(?:([0-9]+):)?([A-Za-z0-9.+~:-]+?)(?:-([A-Za-z0-9.+~]+))?$') + + +def _order(c): + if c == '~': + return -1 + if c.isdigit(): + return 0 + if c.isalpha(): + return ord(c) + return ord(c) + 256 + + +def _part(a, b): + """dpkg's verrevcmp for one upstream or revision part.""" + i = j = 0 + while i < len(a) or j < len(b): + first = 0 + while (i < len(a) and not a[i].isdigit()) or (j < len(b) and not b[j].isdigit()): + ac = _order(a[i]) if i < len(a) else 0 + bc = _order(b[j]) if j < len(b) else 0 + if ac != bc: + return ac - bc + i, j = i + 1, j + 1 + while i < len(a) and a[i] == '0': + i += 1 + while j < len(b) and b[j] == '0': + j += 1 + while i < len(a) and a[i].isdigit() and j < len(b) and b[j].isdigit(): + if not first: + first = ord(a[i]) - ord(b[j]) + i, j = i + 1, j + 1 + if i < len(a) and a[i].isdigit(): + return 1 + if j < len(b) and b[j].isdigit(): + return -1 + if first: + return first + return 0 + + +def split(version): + """(epoch, upstream, revision). Raises ValueError for a string that is no Debian version.""" + m = VERSION_RE.match(version.strip()) + if not m: + raise ValueError(f'not a Debian version: {version!r}') + return int(m.group(1) or 0), m.group(2), m.group(3) or '' + + +def compare(a, b): + """<0, 0 or >0 as version a sorts before, with or after version b.""" + ea, ua, ra = split(a) + eb, ub, rb = split(b) + if ea != eb: + return ea - eb + return _part(ua, ub) or _part(ra, rb) diff --git a/fork-kit/update-policy/lib/updatepolicy/exposure.py b/fork-kit/update-policy/lib/updatepolicy/exposure.py new file mode 100644 index 0000000000000..d990121ebcb0a --- /dev/null +++ b/fork-kit/update-policy/lib/updatepolicy/exposure.py @@ -0,0 +1,490 @@ +"""The daily exposure check (#1045 part 3): installed packages and the running kernel against the distribution's +security data, CISA's Known Exploited Vulnerabilities (KEV) list and EPSS. It prints only what needs action, one line +per CVE (KEV) or per source package (a waiting fix), at most MAX_LINES, and exits 1 when there is any; 0 when there is +none. Notes (what it could not look at, such as "kernel: not checked") are printed too but are no finding. + +- KEV, fix available: a CVE on CISA's list that affects an installed version (or the running kernel), with a fixed + version out: update (a kernel: and restart). +- KEV, no fix yet: the same with no fixed version: mitigate or watch. +- security fix waiting: a source package with a security fix out, shown when its EPSS is at least exposure.epssMin + or a fix has been waiting for more than exposure.fixWaitingDays (dated per CVE and package from when this check + first saw it); ranked KEV first, then by EPSS. +- cannot check: a feed that could not be downloaded or read, or one far smaller than the kept copy; a distribution it + has no data source for; installed packages it cannot list. Never read as "all clear". +- drift: a cached feed older than exposure.staleDays; an ignore entry past its date. + +Data (each a feed, see feeds.py): the distribution's OVAL file (oval.py), KEV's JSON (cisa.gov), FIRST.org's daily +EPSS file (all CVEs, so nothing about this machine is sent anywhere). The ecosystems table is where another package +system (rpm, apk) gets its installed list, version order and data source. +""" +import datetime, fcntl, gzip, io, json, os, re, tempfile + +from updatepolicy import debver, feeds, oval, settings as settings_mod + +UTC = datetime.timezone.utc +one_line = settings_mod.one_line +CVE_RE = re.compile(r'^CVE-[0-9]{4}-[0-9]{4,}\Z') +KEV_URL = 'https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json' +EPSS_URL = 'https://epss.empiricalsecurity.com/epss_scores-current.csv.gz' +CACHE = '/var/cache/update-policy-exposure' +REPORT = 'report.json' +MAX_LINES = 40 +# absolute minimums of a feed's entries (a real one holds far more: noble's OVAL ~540k, KEV ~1,800, EPSS ~410k) +FLOORS = {'oval': 1000, 'kev': 500, 'epss': 100_000} +# kernel packages: judged by the running kernel only, never by what else is installed +KERNEL_PKG = re.compile(r'^linux-(image|headers|modules|modules-extra|tools|cloud-tools|buildinfo|objects|lib-rust)-') +INSTALLED, NOT_INSTALLED = frozenset('iHUFWt'), frozenset('nc') + + +class CannotCheck(Exception): + pass + + +# -- ecosystems: installed packages, version order, data source ------------------------------------------------------- + +class Dpkg: + """Debian and Ubuntu: dpkg's database, dpkg's version order, the distribution's OVAL file.""" + compare = staticmethod(debver.compare) + + def __init__(self, oval_url, no_fix='has no fix yet: mitigate or watch'): + self.oval_url, self.no_fix = oval_url, no_fix + + def installed(self, host): + """({name: [(binary, version)]}, {binary: (source, version)}). Every installed binary under its own name and + under its source's name (Debian's OVAL names source packages, Ubuntu's binaries). Installed: dpkg's status + installed, or with its files on disk (half-installed, unpacked, half-configured, triggers). Kernel packages + are left out of the first map: the running kernel is judged on its own.""" + code, out, err = host.run(['dpkg-query', '-W', '-f', + '${db:Status-Abbrev}\\t${binary:Package}\\t${Version}\\t${source:Package}\\t' + '${source:Version}\\n'], timeout=60) + if code != 0: + raise CannotCheck(f'the installed packages cannot be listed (dpkg-query: ' + f'{one_line(err.strip() or f"exit {code}", 160)})') + found, binaries = {}, {} + for line in out.splitlines(): + parts = line.split('\t') + if len(parts) != 5 or len(parts[0]) < 2: + raise CannotCheck(f'dpkg-query printed a line this check does not read ({one_line(line, 80)})') + status = parts[0][1] + if status in NOT_INSTALLED: + continue + if status not in INSTALLED: + raise CannotCheck(f'dpkg-query: a status this check does not know ({one_line(parts[0].strip(), 8)} for ' + f'{one_line(parts[1], 60)})') + binary, version, source, source_version = parts[1].split(':')[0], parts[2], parts[3], parts[4] + binaries[binary] = (source or binary, version) + if KERNEL_PKG.match(binary): + continue + found.setdefault(binary, []).append((binary, version)) + if source and source != binary: + found.setdefault(source, []).append((binary, source_version or version)) + if not binaries: + raise CannotCheck('dpkg-query listed no installed package') + return found, binaries + + +ECOSYSTEMS = { + 'ubuntu': lambda codename: Dpkg(f'https://security-metadata.canonical.com/oval/com.ubuntu.{codename}.cve.oval.xml.bz2'), + # Debian writes "no fixed version" and some "does not apply" entries alike (less than 0:0) + 'debian': lambda codename: Dpkg(f'https://www.debian.org/security/oval/oval-definitions-{codename}.xml.bz2', + 'has no fixed version listed by Debian: mitigate or watch (or, if Debian judged it ' + 'not to apply, add an ignore entry)'), +} + + +def os_release(host): + """(ID, VERSION_CODENAME) of /etc/os-release.""" + fields = {} + try: + with open(host.p('/etc/os-release'), encoding='utf-8') as f: + for line in f: + key, _, value = line.strip().partition('=') + fields[key] = value.strip().strip('"\'') + except OSError as e: + raise CannotCheck(f'/etc/os-release cannot be read ({e.strerror})') from None + return fields.get('ID', ''), fields.get('VERSION_CODENAME', '') + + +# -- feeds ------------------------------------------------------------------------------------------------------------ + +def _floor(name, n): + if n < FLOORS[name]: + raise ValueError(f'only {n} entries, under the floor of {FLOORS[name]}') + return n + + +def read_kev(path): + """{CVE: {dueDate, product}} of CISA's KEV JSON. Raises ValueError for a format it does not know.""" + with open(path, encoding='utf-8') as f: + data = json.loads(f.read(64 << 20)) + rows = data.get('vulnerabilities') if isinstance(data, dict) else None + if not isinstance(rows, list) or not rows: + raise ValueError('no "vulnerabilities" list') + out = {} + for r in rows: + cve = r.get('cveID') if isinstance(r, dict) else None + if not isinstance(cve, str) or not CVE_RE.match(cve): + raise ValueError(f'an entry without a CVE id ({one_line(repr(r), 80)})') + out[cve] = {'dueDate': str(r.get('dueDate') or ''), + 'product': f'{r.get("vendorProject", "")} {r.get("product", "")}'.strip()} + return out + + +def read_epss(path, want=None, max_bytes=256 << 20): + """FIRST.org's daily EPSS file (gzip CSV: an optional #model line, `cve,epss,percentile`, one row per CVE). Without + `want`: how many rows it holds; with it: {CVE: score} of those CVEs. Raises ValueError for a format it does not + know.""" + with gzip.open(path, 'rb') as raw: + f = io.TextIOWrapper(oval.capped(raw, max_bytes), encoding='utf-8') + line = f.readline() + if line.startswith('#'): + line = f.readline() + if line.strip() != 'cve,epss,percentile': + raise ValueError(f'no "cve,epss,percentile" header ({one_line(line.strip(), 60)})') + n, scores = 0, {} + for line in f: + cve, _, rest = line.partition(',') + score = float(rest.split(',')[0]) + if not CVE_RE.match(cve) or not 0 <= score <= 1: + raise ValueError(f'a row this check does not read ({one_line(line.strip(), 60)})') + n += 1 + if want is not None and cve in want: + scores[cve] = score + return scores if want is not None else n + + +# -- the check -------------------------------------------------------------------------------------------------------- + +def _ignores(ex, today): + active, lines = {}, [] + for entry in ex['ignore']: + if entry['until'] < today.isoformat(): + lines.append(f'drift: the ignore entry for {entry["cve"]} ended on {entry["until"]} ({entry["reason"]}): ' + 'remove it or give it a new date') + else: + active[entry['cve']] = entry + return active, lines + + +def _read_state(cache): + try: + with open(os.path.join(cache, 'state.json'), encoding='utf-8') as f: + st = json.load(f) + return st if isinstance(st, dict) and isinstance(st.get('fixSeen'), dict) else {'fixSeen': {}} + except (OSError, ValueError): + return {'fixSeen': {}} + + +def _write_json(cache, name, data): + fd, tmp = tempfile.mkstemp(dir=cache, prefix=f'.{name}.', suffix='.tmp') + with os.fdopen(fd, 'w', encoding='utf-8') as f: + json.dump(data, f, sort_keys=True) + os.chmod(tmp, 0o644) + os.replace(tmp, os.path.join(cache, name)) + + +def kernel_flavour(release, binaries): + """The flavour (Ubuntu kernel source) of the running kernel, from its installed packages, or None.""" + for name in (f'linux-modules-{release}', f'linux-image-unsigned-{release}', f'linux-image-{release}'): + if name in binaries: + source = binaries[name][0] + return re.sub(r'^linux-signed-', 'linux-', source) if source.startswith('linux-signed') else source + return None + + +def kernel_affected(data, release, binaries, distro): + """([(cve, source, binary, version, fixed, note, priority)], note or None) of the running kernel.""" + if data.counts['kernels']: # Ubuntu: the running kernel's own tests + candidates = [k for k in data.kernels if k.pattern.search(release)] + flavours = sorted({k.flavour for k in candidates}) + if not flavours: + return [], f'kernel: not checked (the running kernel {release} is none of {distro}\'s kernels in its data)' + own = kernel_flavour(release, binaries) + flavour = own if own in flavours else flavours[0] if len(flavours) == 1 else None + if flavour is None: + return [], (f'kernel: not checked (the running kernel {release} matches several kernels ' + f'({", ".join(flavours[:4])}) and its packages do not say which)') + out = [] + for k in candidates: + if k.flavour != flavour: + continue + if k.fixed is None: + out.append((k.cve, f'kernel {flavour}', f'kernel {release}', release, None, '', k.priority)) + continue + literal, capture = k.version + m = re.search(capture, release) + if not m: + return [], f'kernel: not checked (its version cannot be read from {release})' + running = literal + m.group(1) + if debver.compare(running, k.fixed) < 0: + out.append((k.cve, f'kernel {flavour}', f'kernel {release}', release, + k.fixed[2:] if k.fixed.startswith('0:') else k.fixed, '', k.priority)) + return out, None + image = next((n for n in (f'linux-image-{release}', f'linux-image-{release}-unsigned') if n in binaries), None) + if image is None: # Debian: the running image is source `linux` + return [], f'kernel: not checked (the running kernel {release} has no linux-image package)' + out = [] + for adv in data.advisories: + if 'linux' in adv.binaries: + version = binaries[image][1] + if adv.fixed is None or debver.compare(version, adv.fixed) < 0: + fixed = adv.fixed[2:] if adv.fixed and adv.fixed.startswith('0:') else adv.fixed + out.append((adv.cve, 'kernel linux', image, version, fixed, adv.note, adv.priority)) + return out, None + + +def _seen_key(cve, source, binary): + """The waiting clock's key: per CVE and package; for the kernel per flavour, so booting a newer kernel that is + still behind keeps the days.""" + return f'{cve} {source}' if source.startswith('kernel ') else f'{cve} {binary}' + + +def _names(binaries): + names = sorted(binaries) + return ', '.join(names[:3]) + (f' +{len(names) - 3}' if len(names) > 3 else '') + + +def check(host, s, cache, now, opener=feeds.urlopen): + """(lines, notes, report). Lines: what needs action, cannot-check and drift lines; [] means nothing to do. Call + under the cache's lock.""" + ex = s['exposure'] + if not ex['enabled']: + return [], [], {'v': 2, 'at': now.isoformat(), 'enabled': False, 'lines': [], 'notes': []} + feeds.sweep(cache) + try: + os.unlink(os.path.join(cache, 'epss.json')) # the first format's per-CVE EPSS answers: not used + except FileNotFoundError: + pass + today = now.date() + ignored, drift = _ignores(ex, today) + notes = [] + try: + distro, codename = os_release(host) + make = ECOSYSTEMS.get(distro) + if make is None or not re.match(r'^[a-z0-9-]{1,40}$', codename or ''): + raise CannotCheck(f'no security data source for this distribution ({one_line(distro or "unknown", 40)} ' + f'{one_line(codename, 40)}); the check knows {", ".join(sorted(ECOSYSTEMS))}') + eco = make(codename) + installed, binaries = eco.installed(host) + except CannotCheck as e: + lines = [one_line(f'cannot check: {e}', 400)] + drift + return lines, notes, {'v': 2, 'at': now.isoformat(), 'enabled': True, 'lines': lines, 'notes': notes} + cap, timeout, problems, parsed = ex['maxFeedMb'] << 20, ex['timeoutSeconds'], [], {} + release = host.kernel_release() + xml_cap = ex['maxXmlMb'] << 20 + + def check_oval(path): # a new download is read once: to check it and to use it + parsed[path] = oval.read(path, xml_cap, release) + return dict(parsed[path].counts, packages=_floor('oval', parsed[path].counts['packages'])) + got = {'oval': feeds.fetch(cache, 'oval', ex['ovalUrl'] or eco.oval_url, check_oval, now, cap, timeout, opener), + 'kev': feeds.fetch(cache, 'kev', ex['kevUrl'] or KEV_URL, lambda p: _floor('kev', len(read_kev(p))), now, + cap, timeout, opener), + 'epss': feeds.fetch(cache, 'epss', ex['epssUrl'] or EPSS_URL, lambda p: _floor('epss', read_epss(p)), now, + cap, timeout, opener)} + problems += [f.problem for f in got.values() if f.problem] + drift += [f'drift: {f.notice}' for f in got.values() if f.notice] + data = kev = None + if got['oval'].path: + try: + fresh = [d for p, d in parsed.items() if not got['oval'].problem] + data = fresh[0] if fresh else oval.read(got['oval'].path, xml_cap, release) + except (oval.FormatError, OSError) as e: + problems.append(f'oval: the kept copy cannot be read ({e})') + if got['kev'].path: + try: + kev = read_kev(got['kev'].path) + except (OSError, ValueError) as e: + problems.append(f'kev: the kept copy cannot be read ({e})') + for name, f in got.items(): + if f.path and f.fetched_at and now - f.fetched_at > datetime.timedelta(days=ex['staleDays']): + drift.append(f'drift: the cached {name} feed is {(now - f.fetched_at).days} days old (more than ' + f'{ex["staleDays"]}): the check works on old data') + lines = [f'cannot check: {p}' for p in problems] + if data is None: + lines.append('cannot check: no usable copy of the distribution\'s security data') + notes.append('kernel: not checked (no security data)') + if kev is None: + lines.append('cannot check: no usable copy of CISA\'s KEV list') + affected = [] # (cve, source, binary, version, fixed, note, priority) + for adv in data.advisories if data else (): + for name in adv.binaries: + for binary, version in installed.get(name, ()): + try: + if adv.fixed is None or eco.compare(version, adv.fixed) < 0: + affected.append((adv.cve, adv.source or name, binary, version, adv.fixed, adv.note, + adv.priority)) + except ValueError: + continue + if data is not None: + found, note = kernel_affected(data, release, binaries, distro) + affected += found + if note: + notes.append(one_line(note, 300)) + affected = [a for a in affected if a[0] not in ignored] + kev = kev or {} + state = _read_state(cache) + seen = dict(state['fixSeen']) if data is None else {} # no usable data: keep every first sight + # the first cache format keyed "BINARY FIXED": its first sights carry over (per binary) + older = {k.split(' ', 1)[0]: v for k, v in state['fixSeen'].items() if not k.startswith('CVE-')} + for cve, source, binary, _v, fixed, _n, _p in affected: + if fixed is not None: + key = _seen_key(cve, source, binary) + seen[key] = state['fixSeen'].get(key) or older.get(binary) or now.isoformat() + scores = {} + if got['epss'].path: + want = {a[0] for a in affected} + try: + scores = read_epss(got['epss'].path, want) if want else {} + except (OSError, ValueError, oval.FormatError) as e: + lines.append(one_line(f'cannot check: epss: the kept copy cannot be read ({e})', 300)) + elif 'epss' not in ' '.join(problems): + lines.append('cannot check: no usable copy of the EPSS scores') + rows = [] + by_cve = {} + for a in affected: + if a[0] in kev: + by_cve.setdefault(a[0], []).append(a) + for cve, items in by_cve.items(): + sources = {} + for _c, source, binary, version, fixed, note, _p in items: + g = sources.setdefault(source, {'binaries': set(), 'version': version, 'fixed': fixed, 'note': note}) + g['binaries'].add(binary) + if g['fixed'] is not None and (fixed is None or eco.compare(fixed, g['fixed']) > 0): + g['fixed'] = fixed # the highest fix of the source (none: no fix) + if not source.startswith('kernel') and eco.compare(version, g['version']) < 0: + g['version'] = version + parts, unfixed = [], [] + for source, g in sorted(sources.items()): + who = f'{source} {g["version"]} ({_names(g["binaries"])})' + if g['fixed'] is None: + unfixed.append(who) + else: + restart = ' and restart' if source.startswith('kernel') else '' + pro = ' (the fix needs Ubuntu Pro: esm)' if g['note'] == 'esm' else '' + parts.append(f'{who}: update to {g["fixed"]}{restart}{pro}') + top = scores.get(cve, 0.0) + info = f'(EPSS {top:.2f}; CISA due {kev[cve]["dueDate"] or "?"}; {kev[cve]["product"]})' + if parts: + text = f'KEV {cve} is exploited in the wild: ' + '; '.join(parts) + if unfixed: + text += '; no fix yet: ' + '; '.join(unfixed) + else: + text = f'KEV {cve} is exploited in the wild and {eco.no_fix}: ' + '; '.join(unfixed) + rows.append((0, -top, one_line(f'{text} {info}', 400), {'cve': cve, 'kev': True, 'epss': top, + 'action': 'update' if parts else 'mitigate', + 'sources': sorted(sources)})) + waiting = {} + for cve, source, binary, version, fixed, note, _p in affected: + if fixed is None or cve in kev: + continue + w = waiting.setdefault(source, {'binaries': set(), 'version': version, 'fixed': fixed, 'cves': set(), + 'note': '', 'since': now}) + w['binaries'].add(binary) + w['cves'].add(cve) + if eco.compare(fixed, w['fixed']) > 0: + w['fixed'] = fixed + w['note'] = w['note'] or note + first = feeds._parse_time(seen.get(_seen_key(cve, source, binary))) or now + w['since'] = min(w['since'], first) + for source, w in waiting.items(): + top = max((scores.get(c, 0.0) for c in w['cves']), default=0.0) + days = max(0, (now - w['since']).days) + if not (top >= ex['epssMin'] or days > ex['fixWaitingDays']): + continue + pro = ' (the fix needs Ubuntu Pro: esm)' if w['note'] == 'esm' else '' + restart = ' and restart' if source.startswith('kernel') else '' + cves = sorted(w['cves'], key=lambda c: (-scores.get(c, 0.0), c)) + more = f' +{len(cves) - 4}' if len(cves) > 4 else '' + text = (f'security fix waiting {days} day(s): {source} {w["version"]} ({_names(w["binaries"])}) -> ' + f'{w["fixed"]}{restart}{pro}: {", ".join(cves[:4])}{more} (EPSS {top:.2f})') + rows.append((1, -top, one_line(text, 400), {'source': source, 'version': w['version'], 'fixed': w['fixed'], + 'cves': cves, 'epss': top, 'days': days, 'action': 'update'})) + rows.sort(key=lambda r: (r[0], r[1], r[2])) + found = [r[2] for r in rows] + if len(found) > MAX_LINES: + found = found[:MAX_LINES - 1] + [f'+{len(found) - MAX_LINES + 1} more lines (all in {cache}/{REPORT})'] + lines = [one_line(x, 400) for x in lines + found + drift] + try: + _write_json(cache, 'state.json', dict(state, fixSeen=seen)) + except OSError as e: + lines.append(f'cannot check: the cache folder {cache} cannot be written ({e.strerror})') + return lines, notes, {'v': 2, 'at': now.isoformat(), 'enabled': True, 'lines': lines, 'notes': notes, + 'findings': [r[3] for r in rows]} + + +def run(host, read_settings, cache, now=None, opener=feeds.urlopen): + """`update-policy exposure`: prints the lines and notes, writes the report for the alert step; 0 none, 1 any.""" + now = now or datetime.datetime.now(UTC) + if os.geteuid() == 0 and os.path.abspath(cache) == CACHE: + print('update-policy exposure: as root it would leave root-owned files in the unit\'s cache: run ' + '`systemctl start update-policy-exposure.service` (journalctl -u update-policy-exposure), or pass ' + '--cache DIR') + return 1 + try: + s = read_settings() + except settings_mod.MachineFileError as e: + print(one_line(f'cannot check: the machine file cannot be used: {e}', 400)) + return 1 + if not s['exposure']['enabled']: + print('update-policy exposure: off (exposure.enabled is false in the machine file)') + return 0 + lock = None + try: + os.makedirs(cache, mode=0o750, exist_ok=True) + lock = os.open(os.path.join(cache, 'lock'), os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600) + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + print('update-policy exposure: another run holds the cache\'s lock: nothing to do') + return 0 + try: + lines, notes, report = check(host, s, cache, now, opener) + except Exception as e: # noqa: BLE001 - a fault is a cannot-check report, never a missing one + lines = [one_line(f'cannot check: the check failed ({type(e).__name__}: {e})', 300)] + notes, report = [], {'v': 2, 'at': now.isoformat(), 'enabled': True, 'lines': lines, 'notes': []} + try: + _write_json(cache, REPORT, report) # under the lock: no other run sweeps its temporary file + except OSError: + pass + except OSError as e: + lines, notes = [one_line(f'cannot check: the cache folder {cache} cannot be used ({e.strerror or e})', 300)], [] + finally: + if lock is not None: + os.close(lock) + for line in lines + notes: + print(one_line(line, 400)) + return 1 if lines else 0 + + +def alert(m, read_settings, cache, now=None, max_age=datetime.timedelta(hours=6)): + """`update-policy exposure-alert` (as root, after the unprivileged check): sends the report's lines (and notes) + through the alert command. A report that is missing, not a plain file, broken or old is itself one line.""" + from updatepolicy import tick + now = now or datetime.datetime.now(UTC) + try: + s = read_settings() + except settings_mod.MachineFileError: + return 1 + if not s['exposure']['enabled']: + return 0 + path = os.path.join(cache, REPORT) + notes = [] + try: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC) + with os.fdopen(fd, 'rb') as f: + report = json.loads(f.read(1 << 20).decode('utf-8')) + at = feeds._parse_time(report.get('at')) + lines, notes = report.get('lines'), report.get('notes') or [] + if not at or not isinstance(lines, list) or not isinstance(notes, list) \ + or not now - max_age <= at <= now + datetime.timedelta(minutes=5): + raise ValueError('old or broken') + lines = [one_line(x, 400) for x in lines if isinstance(x, str)][:MAX_LINES + 5] + notes = [one_line(x, 400) for x in notes if isinstance(x, str)][:5] + except (OSError, ValueError, AttributeError) as e: + lines, notes = [f'cannot check: the exposure report {path} is missing or broken ({one_line(e, 120)})'], [] + if not lines: + return 0 + if not s['alertCommand']: + return 1 # the check's own output is in the journal already + err = tick.send_alert(m, s, 'exposure', '\n'.join(lines + notes)) + return 1 if err else 0 diff --git a/fork-kit/update-policy/lib/updatepolicy/feeds.py b/fork-kit/update-policy/lib/updatepolicy/feeds.py new file mode 100644 index 0000000000000..8056b2a0ffc33 --- /dev/null +++ b/fork-kit/update-policy/lib/updatepolicy/feeds.py @@ -0,0 +1,203 @@ +"""The exposure check's feeds: downloaded at most once a day into the cache folder, with a size cap, a timeout, the +server's ETag / Last-Modified (a feed that did not change is not downloaded again) and a sha256 of what was stored. + +Per feed NAME the cache holds NAME.data and NAME.meta.json ({url, etag, lastModified, fetchedAt, sha256, size}). +A new download goes to a temporary file, is checked by the feed's own reader (a file it does not understand never +replaces a good copy; the reader returns how many entries it holds, and a download with fewer than FLOOR of the kept +copy's never replaces it either), then renamed into place, then the meta (with that count) is written. Redirects +are followed only to https. So a run stopped half-way leaves the old +copy (or none); a copy whose sha256 does not match its meta is no copy. What happened is returned as a problem +string, never raised: the caller turns it into a "cannot check" line. +""" +import datetime, hashlib, http.client, json, os, tempfile, urllib.error, urllib.request + + +UTC = datetime.timezone.utc +DAY = datetime.timedelta(hours=20) # "once a day", with room for a timer that runs a little early +AGENT = 'update-policy-exposure (fork-kit)' +CHUNK = 1 << 16 +FLOOR = 0.5 + + +class _HttpsOnly(urllib.request.HTTPRedirectHandler): + """A redirect to anything but https is refused (a feed is never read over plain http).""" + + def redirect_request(self, req, fp, code, msg, headers, newurl): + if not newurl.lower().startswith('https://'): + raise urllib.error.URLError(f'a redirect to {newurl.split("?")[0][:80]} (not https) was refused') + return super().redirect_request(req, fp, code, msg, headers, newurl) + + +_OPENER = urllib.request.build_opener(_HttpsOnly) + + +SHRINK_DAYS = 3 + + +class Fetched: + """path: the copy to read (None: none); problem: why it is not today's (None: fine); fetchedAt: when the copy + was last confirmed by the server; notice: something to say although all is fine (a shrink accepted).""" + + def __init__(self, path, problem, fetched_at, notice=None): + self.path, self.problem, self.fetched_at, self.notice = path, problem, fetched_at, notice + + +def _counts(value): + """A reader's count (a number, or {part: number}) as {part: number}.""" + if isinstance(value, dict): + return {str(k): int(v) for k, v in value.items()} + return {'entries': int(value)} + + +def _shrunk(new, kept): + """The parts of `new` under FLOOR of `kept`'s: [(part, new, kept)].""" + if not isinstance(kept, (int, dict)): + return [] + kept = _counts(kept) + return [(k, new.get(k, 0), v) for k, v in sorted(kept.items()) if new.get(k, 0) < FLOOR * v] + + +def urlopen(url, headers, timeout): + """(status, headers dict lower-case, readable). 304 is a status, not an error.""" + req = urllib.request.Request(url, headers=dict(headers, **{'User-Agent': AGENT})) + if not url.lower().startswith('https://'): + raise urllib.error.URLError('only https is read') + try: + r = _OPENER.open(req, timeout=timeout) + except urllib.error.HTTPError as e: + if e.code == 304: + return 304, {k.lower(): v for k, v in e.headers.items()}, None + raise + return r.status, {k.lower(): v for k, v in r.headers.items()}, r + + +def _sha256(path): + h = hashlib.sha256() + with open(path, 'rb') as f: + for block in iter(lambda: f.read(CHUNK), b''): + h.update(block) + return h.hexdigest() + + +def _parse_time(text): + try: + t = datetime.datetime.fromisoformat(str(text).replace('Z', '+00:00')) + return t if t.tzinfo else None + except ValueError: + return None + + +def _meta(cache, name): + try: + with open(os.path.join(cache, f'{name}.meta.json'), encoding='utf-8') as f: + meta = json.load(f) + return meta if isinstance(meta, dict) else {} + except (OSError, ValueError): + return {} + + +def _good_copy(cache, name, meta): + path = os.path.join(cache, f'{name}.data') + try: + return path if meta.get('sha256') and _sha256(path) == meta['sha256'] else None + except OSError: + return None + + +def _write_json(path, data): + fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix='.meta.', suffix='.tmp') + with os.fdopen(fd, 'w', encoding='utf-8') as f: + json.dump(data, f, sort_keys=True) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, path) + + +def fetch(cache, name, url, check, now, max_bytes, timeout, opener=urlopen): + """The feed NAME from URL into CACHE. `check(path)` returns how many entries the file holds, and raises on a file + it does not understand (the problem says why). Returns Fetched.""" + meta = _meta(cache, name) + if meta.get('url') != url: + meta = {} # another URL: an old copy is no copy of this feed + copy = _good_copy(cache, name, meta) + fetched_at = _parse_time(meta.get('fetchedAt')) if copy else None + if copy and fetched_at and fetched_at <= now < fetched_at + DAY: + return Fetched(copy, None, fetched_at) # once a day + headers = {} + if copy and meta.get('etag'): + headers['If-None-Match'] = meta['etag'] + if copy and meta.get('lastModified'): + headers['If-Modified-Since'] = meta['lastModified'] + tmp = body = None + try: + status, rh, body = opener(url, headers, timeout) + if status == 304 and copy: + meta['fetchedAt'] = now.isoformat() + _write_json(os.path.join(cache, f'{name}.meta.json'), meta) + return Fetched(copy, None, now) + if status != 200 or body is None: + raise OSError(f'HTTP {status}') + if int(rh.get('content-length') or 0) > max_bytes: + return Fetched(copy, f'{name}: larger than the cap of {max_bytes >> 20} MB', fetched_at) + fd, tmp = tempfile.mkstemp(dir=cache, prefix=f'.{name}.', suffix='.tmp') + size = 0 + with os.fdopen(fd, 'wb') as out: + while True: + block = body.read(CHUNK) + if not block: + break + size += len(block) + if size > max_bytes: + return Fetched(copy, f'{name}: larger than the cap of {max_bytes >> 20} MB', fetched_at) + out.write(block) + out.flush() + os.fsync(out.fileno()) + try: + entries = _counts(check(tmp)) + except Exception as e: # noqa: BLE001 - any reader failure means: not understood + return Fetched(copy, f'{name}: the download is in a format this check does not understand ({e})', + fetched_at) + notice = None + shrunk = _shrunk(entries, meta.get('count')) if copy else [] + if shrunk: + # a lasting shrink: the same smaller counts on SHRINK_DAYS days in a row is accepted, and said + today, seen = now.date().isoformat(), meta.get('shrink') or {} + yesterday = (now.date() - datetime.timedelta(days=1)).isoformat() + if seen.get('counts') == entries and seen.get('last') in (today, yesterday): + days = seen.get('days', 1) + (seen.get('last') == yesterday) + else: + days = 1 + what = ', '.join(f'{k} {n} under half of {v}' for k, n, v in shrunk) + if days < SHRINK_DAYS: + meta['shrink'] = {'counts': entries, 'last': today, 'days': days} + _write_json(os.path.join(cache, f'{name}.meta.json'), meta) + return Fetched(copy, f'{name}: the download holds {what} of the kept copy: kept the old copy (day ' + f'{days} of {SHRINK_DAYS}; the same smaller feed {SHRINK_DAYS} days in a row is ' + 'accepted)', fetched_at) + notice = (f'{name}: the feed shrank ({what}) and stayed so {SHRINK_DAYS} days in a row: accepted, the ' + 'smaller copy is in use') + path = os.path.join(cache, f'{name}.data') + os.replace(tmp, path) + tmp = None + meta = {'url': url, 'etag': rh.get('etag'), 'lastModified': rh.get('last-modified'), + 'fetchedAt': now.isoformat(), 'sha256': _sha256(path), 'size': size, 'count': entries} + _write_json(os.path.join(cache, f'{name}.meta.json'), meta) + return Fetched(path, None, now, notice) + except (OSError, ValueError, http.client.HTTPException) as e: + # the server's or the error's text: the caller makes every line one safe line + return Fetched(copy, f'{name}: download failed ({getattr(e, "reason", None) or e})', fetched_at) + finally: + if body is not None and hasattr(body, 'close'): + body.close() + if tmp and os.path.exists(tmp): + os.unlink(tmp) + + +def sweep(cache): + """Temporary files a killed run left (SIGTERM runs no `finally`). Call under the cache's lock.""" + for name in os.listdir(cache): + if name.startswith('.') and name.endswith('.tmp'): + try: + os.unlink(os.path.join(cache, name)) + except OSError: + pass diff --git a/fork-kit/update-policy/lib/updatepolicy/idle.py b/fork-kit/update-policy/lib/updatepolicy/idle.py index 9899d3b2d3f18..976a05e02593b 100644 --- a/fork-kit/update-policy/lib/updatepolicy/idle.py +++ b/fork-kit/update-policy/lib/updatepolicy/idle.py @@ -97,6 +97,9 @@ def docker_names(self, sock, user=None): pass return 'a broken answer' + def kernel_release(self): + return os.uname().release + def free_answer(self, path): import free_contract verdict, reason, _facts = free_contract.ask(path) diff --git a/fork-kit/update-policy/lib/updatepolicy/oval.py b/fork-kit/update-policy/lib/updatepolicy/oval.py new file mode 100644 index 0000000000000..bcc6f4a49af2f --- /dev/null +++ b/fork-kit/update-policy/lib/updatepolicy/oval.py @@ -0,0 +1,277 @@ +"""A distribution's OVAL file (Ubuntu's com.ubuntu..cve.oval.xml.bz2, Debian's +oval-definitions-.xml.bz2) read into advisories: which packages a CVE affects and in which version it is +fixed (None: no fix yet), and for Ubuntu's kernels which running kernel it affects. + +What is read: +- `dpkginfo` tests: binary (Ubuntu) or source (Debian) package names, directly or through a constant variable, and + a state "evr less than FIXED" (none: affected in every version). Debian writes "no fix yet" as "less than 0:0"; + that is read as no fixed version. +- Ubuntu's kernels: a `uname` test whose state matches the running kernel's release (one per kernel flavour), alone + (affected, no fix) or together with a `variable_test` "kernel version less than FIXED" on the local variable that + turns `uname -r` into a version. +- platform checks (the release, the architecture, the family) are known and skipped. + +Anything else a definition refers to (another test kind, a state operation other than "less than", an object or +variable that is not there) raises FormatError: a format change is "cannot check", never "no advisories". So does a +file whose decompressed size passes `max_bytes`, an entry with more than MAX_ENTRY elements, and a file where fewer +than RESOLVED of the dpkginfo tests resolve. The file is read as a stream and every finished entry is dropped, so +memory stays at what is kept (a real noble file: about 250 MB). +""" +import bz2, io, re, xml.etree.ElementTree as ET + +from updatepolicy import debver + +CVE_RE = re.compile(r'\bCVE-[0-9]{4}-[0-9]{4,}\b') +PLATFORM = frozenset({'family_test', 'textfilecontent54_test', 'textfilecontent_test'}) +KINDS = PLATFORM | {'dpkginfo_test', 'uname_test', 'variable_test'} +MAX_ENTRY = 500_000 # elements in one definition, test, object, state or variable +RESOLVED = 0.9 +SECTIONS = frozenset({'definitions', 'tests', 'objects', 'states', 'variables', 'generator'}) + + +class FormatError(Exception): + pass + + +class Advisory: + __slots__ = ('cve', 'source', 'binaries', 'fixed', 'priority', 'note') + + def __init__(self, cve, source, binaries, fixed, priority, note=''): + self.cve, self.source, self.binaries, self.fixed = cve, source, binaries, fixed + self.priority, self.note = priority, note + + +class Kernel: + """A CVE of one Ubuntu kernel flavour: `pattern` matches the running release (`uname -r`); `fixed` is the + fixed kernel version (debian evr) or None; `version` turns the release into that version.""" + __slots__ = ('cve', 'flavour', 'pattern', 'fixed', 'priority', 'version') + + def __init__(self, cve, flavour, pattern, fixed, priority, version): + self.cve, self.flavour, self.pattern, self.fixed = cve, flavour, pattern, fixed + self.priority, self.version = priority, version + + +class Data: + """advisories; kernels: the kernel entries that can match the running release (all when none was given); + counts: {'packages': N, 'kernels': M} of the whole file (M counts every kernel entry, kept or not).""" + + def __init__(self, advisories, kernels, counts): + self.advisories, self.kernels, self.counts = advisories, kernels, counts + + +class _Capped(io.RawIOBase): + """A readable that raises FormatError past `limit` bytes (the decompressed size of a bz2 or gzip file).""" + + def __init__(self, f, limit): + super().__init__() + self.f, self.limit, self.seen = f, limit, 0 + + def readable(self): + return True + + def readinto(self, b): + data = self.f.read(len(b)) + self.seen += len(data) + if self.seen > self.limit: + raise FormatError(f'larger than {self.limit >> 20} MB once decompressed') + b[:len(data)] = data + return len(data) + + +def capped(f, limit): + return io.BufferedReader(_Capped(f, limit)) + + +def _local(tag): + return tag.rsplit('}', 1)[-1] + + +def _open(path): + with open(path, 'rb') as f: + magic = f.read(3) + return bz2.open(path, 'rb') if magic == b'BZh' else open(path, 'rb') + + +def no_fix(version): + """Debian's "less than 0:0" (and 0): nothing sorts below it, so it means no fixed version.""" + try: + return debver.compare(version, '0') == 0 + except ValueError: + return False + + +def read(path, max_bytes=1 << 30, release=None): + """Data of the OVAL file at `path`. With `release` (`uname -r`), only the kernel entries whose pattern matches it + are kept (jammy's file has 887k kernel entries over 60 flavours). Raises FormatError (or OSError).""" + tests, objects, states, variables, locals_, defs = {}, {}, {}, {}, {}, [] + try: + with _open(path) as raw: + stack, sizes = [], [] + for event, el in ET.iterparse(capped(raw, max_bytes), events=('start', 'end')): + if event == 'start': + stack.append(el) + if len(stack) == 3: + sizes.append(0) + elif len(stack) > 3: + sizes[-1] += 1 + if sizes[-1] > MAX_ENTRY: + raise FormatError(f'an entry with more than {MAX_ENTRY} elements') + continue + stack.pop() + depth = len(stack) + 1 + if depth == 3: + sizes.pop() + _entry(el, tests, objects, states, variables, locals_, defs) + if depth in (2, 3) and stack: + stack[-1].remove(el) # finished entries and sections are dropped + if depth == 2 and _local(el.tag) not in SECTIONS: + raise FormatError(f'an unknown section <{_local(el.tag)}>') + except FormatError: + raise + except (ET.ParseError, EOFError, OSError, ValueError) as e: + raise FormatError(f'not readable OVAL ({type(e).__name__}: {e})') from None + if not defs or not any(t[0] == 'dpkginfo_test' for t in tests.values()): + raise FormatError(f'no {"definitions" if not defs else "dpkginfo tests"}: a format this check does not know') + return _resolve(tests, objects, states, variables, locals_, defs, release) + + +def _entry(el, tests, objects, states, variables, locals_, defs): + tag, ident = _local(el.tag), el.get('id') + kids = list(el) + if tag == 'definition': + defs.append(_definition(el)) + elif tag.endswith('_test'): + obj = next((c.get('object_ref') for c in kids if _local(c.tag) == 'object'), None) + state = next((c.get('state_ref') for c in kids if _local(c.tag) == 'state'), None) + tests[ident] = (tag, obj, state, el.get('comment') or '') + elif tag == 'dpkginfo_object': + name = next((c for c in kids if _local(c.tag) == 'name'), None) + if name is not None: + objects[ident] = ('var', name.get('var_ref')) if name.get('var_ref') else ('name', (name.text or '').strip()) + elif tag == 'variable_object': + ref = next((c for c in kids if _local(c.tag) == 'var_ref'), None) + if ref is not None: + objects[ident] = ('local', (ref.text or '').strip()) + elif tag in ('dpkginfo_state', 'variable_state'): + value = next((c for c in kids if _local(c.tag) in ('evr', 'value')), None) + if value is not None: + states[ident] = ('evr', value.get('operation') or 'equals', (value.text or '').strip()) + elif tag == 'uname_state': + release = next((c for c in kids if _local(c.tag) == 'os_release'), None) + states[ident] = ('release', release.get('operation'), (release.text or '').strip()) if release is not None \ + else ('other', None, None) + elif tag == 'constant_variable': + variables[ident] = [(v.text or '').strip() for v in kids if _local(v.tag) == 'value'] + elif tag == 'local_variable': + literal = ''.join((c.text or '') for c in el.iter() if _local(c.tag) == 'literal_component') + capture = next((c.get('pattern') for c in el.iter() if _local(c.tag) == 'regex_capture'), None) + locals_[ident] = (literal, capture) + + +def _definition(el): + """(CVE ids, priority, [[(test_ref, comment)] per criteria element], title).""" + cves, priority, groups, title = [], '', [], '' + for c in el.iter(): + tag = _local(c.tag) + if tag == 'reference' and c.get('source') == 'CVE' and CVE_RE.fullmatch(c.get('ref_id') or ''): + cves.append(c.get('ref_id')) + elif tag == 'cve': + text = (c.text or '').strip() + if CVE_RE.fullmatch(text): + cves.append(text) + priority = priority or (c.get('priority') or '') + elif tag == 'severity' and not priority: + priority = (c.text or '').strip().lower() + elif tag == 'criteria': + groups.append([(k.get('test_ref'), k.get('comment') or '') for k in c + if _local(k.tag) == 'criterion' and k.get('test_ref')]) + elif tag == 'title': + title = (c.text or '').strip() + return sorted(set(cves or CVE_RE.findall(title))), priority, groups, title + + +def _source(comment): + m = re.match(r'^(?:\(CVE-[^)]*\) )?(\S+) (?:source )?package', comment or '') + return m.group(1) if m else '' + + +def _resolve(tests, objects, states, variables, locals_, defs, release=None): + def test(ref): + t = tests.get(ref) + if t is None: + raise FormatError(f'a definition refers to a test that is not there ({ref})') + if t[0] not in KINDS: + raise FormatError(f'a test kind this check does not read ({t[0]})') + return t + + resolved = total = kernel_total = 0 + out, kernels, checked = [], [], set() + for cves, priority, groups, title in defs: + for group in groups: + kinds = [(ref, comment, test(ref)) for ref, comment in group] + unames = [(r, c, t) for r, c, t in kinds if t[0] == 'uname_test' and states.get(t[2], ('',))[0] == 'release'] + versions = [(r, c, t) for r, c, t in kinds if t[0] == 'variable_test'] + if versions and len(unames) != 1: + raise FormatError('a kernel version test without its one kernel test') + for ref, comment, t in unames: + kind, op, pattern = states[t[2]] + if op != 'pattern match': + raise FormatError(f'a kernel test with operation "{op}"') + try: + compiled = re.compile(pattern) + except re.error as e: + raise FormatError(f'a kernel pattern this check cannot read ({e})') from None + flavour = (re.search(r"kernel '([^']+)'", t[3] + ' ' + comment) or [None, 'linux'])[1] + fixed = version = None + if versions: + _r, _c, vt = versions[0] + kind, op, value = states.get(vt[2], (None, None, None)) + obj = objects.get(vt[1]) + if kind != 'evr' or op != 'less than' or not obj or obj[0] != 'local' or obj[1] not in locals_ \ + or not locals_[obj[1]][1]: + raise FormatError('a kernel version test this check does not read') + fixed, version = value, locals_[obj[1]] + if (fixed, version) not in checked: # a broken entry: cannot check, never a traceback + try: + debver.split(fixed) + if re.compile(version[1]).groups < 1: + raise ValueError('its version pattern captures nothing') + except (ValueError, re.error) as e: + raise FormatError(f'a kernel version this check cannot read ({e})') from None + checked.add((fixed, version)) + kernel_total += len(cves) + if release is not None and not compiled.search(release): + continue # another kernel than the running one + for cve in cves: + kernels.append(Kernel(cve, flavour, compiled, fixed, priority, version)) + for ref, comment, t in kinds: + if t[0] != 'dpkginfo_test': + continue + total += 1 + obj = objects.get(t[1]) + if obj is None: + raise FormatError(f'a dpkginfo test whose object is not there ({t[1]})') + names = variables.get(obj[1]) if obj[0] == 'var' else [obj[1]] if obj[0] == 'name' else None + if names is None: + raise FormatError(f'a dpkginfo object whose names are not there ({obj[1]})') + fixed = None + if t[2] is not None: + state = states.get(t[2]) + if state is None or state[0] != 'evr': + raise FormatError(f'a dpkginfo test whose state is not there ({t[2]})') + if state[1] != 'less than' or not state[2]: + raise FormatError(f'a dpkginfo state with operation "{state[1]}"') + fixed = None if no_fix(state[2]) else state[2] + names = tuple(n for n in names if n) + if not names: + continue + resolved += 1 + source = _source(comment) or names[0] + note = 'esm' if 'esm' in (comment + (fixed or '')).lower() else '' + for cve in cves: + out.append(Advisory(cve, source, names, fixed, priority, note)) + if total and resolved < RESOLVED * total: + raise FormatError(f'only {resolved} of {total} package tests name a package') + return Data(out, kernels, {'packages': len(out), 'kernels': kernel_total}) + + diff --git a/fork-kit/update-policy/lib/updatepolicy/settings.py b/fork-kit/update-policy/lib/updatepolicy/settings.py index 0a9a6910d899d..07574f8927692 100644 --- a/fork-kit/update-policy/lib/updatepolicy/settings.py +++ b/fork-kit/update-policy/lib/updatepolicy/settings.py @@ -128,6 +128,41 @@ def _ports(value): 'sshUsers': (list, ['root'], _users), } +def _ignore(value): + for e in value: + if not isinstance(e, dict) or set(e) != {'cve', 'reason', 'until'}: + return 'each entry is {"cve": "CVE-...", "reason": "...", "until": "YYYY-MM-DD"}' + if not isinstance(e['cve'], str) or not re.match(r'^CVE-[0-9]{4}-[0-9]{4,}\Z', e['cve']): + return f'{e["cve"]!r} is not a CVE id' + if not isinstance(e['reason'], str) or not e['reason'].strip(): + return f'{e["cve"]}: a reason is needed' + if not isinstance(e['until'], str) or not re.match(r'^[0-9]{4}-[0-9]{2}-[0-9]{2}\Z', e['until']): + return f'{e["cve"]}: "until" must be YYYY-MM-DD' + return None + + +def _https(value): + return None if value == '' or re.match(r'^https://[^\s]+\Z', value) else 'must be an https:// URL (or "")' + + +def _share(value): + return None if 0 <= value <= 1 else 'must be from 0 to 1' + + +EXPOSURE = { + 'enabled': (bool, False, None), + 'epssMin': ((int, float), 0.1, _share), + 'fixWaitingDays': (int, 3, _between(0, 60)), + 'staleDays': (int, 3, _between(1, 60)), + 'maxFeedMb': (int, 64, _between(1, 1024)), + 'maxXmlMb': (int, 1024, _between(16, 4096)), + 'timeoutSeconds': (int, 60, _between(5, 600)), + 'ovalUrl': (str, '', _https), + 'kevUrl': (str, '', _https), + 'epssUrl': (str, '', _https), + 'ignore': (list, [], _ignore), +} + SPEC = { 'role': (str, REQUIRED, _role), 'quietHour': (str, REQUIRED, _quiet_hour), @@ -142,6 +177,7 @@ def _ports(value): 'heavySlice': (str, 'heavy.slice', _slice), 'busyScripts': (list, [], _paths), 'baseline': (dict, {}, None), + 'exposure': (dict, {}, None), } @@ -149,6 +185,7 @@ def check(section, where): """The section as a dict with every default filled in (baseline too).""" out = machine_file.fields(section, SPEC, where) out['baseline'] = machine_file.fields(out['baseline'], BASELINE, f'{where}.baseline') + out['exposure'] = machine_file.fields(out['exposure'], EXPOSURE, f'{where}.exposure') return out diff --git a/fork-kit/update-policy/sbin/update-policy-install b/fork-kit/update-policy/sbin/update-policy-install index bae9b15f67faf..d090a4861a2a4 100644 --- a/fork-kit/update-policy/sbin/update-policy-install +++ b/fork-kit/update-policy/sbin/update-policy-install @@ -11,7 +11,8 @@ fork-kit/common/{machine_file,free_contract,kit_install}.py of one release into to it and links /usr/local/bin/update-policy and /usr/local/sbin/update-policy-install to it. With --timer the kit takes over restarts, in this order, so there is never a time with neither restart policy: it writes the system units update-policy.{service,timer} (the restart policy, every 5 minutes), update-policy-baseline.{service,timer} -(the daily baseline check) and update-policy-boot.service (the look after a boot) to /etc/systemd/system/, +(the daily baseline check), update-policy-exposure.{service,timer} (the daily exposure check) and +update-policy-boot.service (the look after a boot) to /etc/systemd/system/, enables and starts them, and only then writes /etc/apt/apt.conf.d/zz-update-policy (unattended-upgrades never restarts by itself). It then reads apt's effective Automatic-Reboot and fails while it is not false (a file apt reads later wins), unless --force. --no-timer undoes it in the other order: the apt file first (unattended-upgrades' @@ -31,12 +32,15 @@ except ImportError as e: # a copy without common/kit_install.py (changed or UNIT_DIR = '/etc/systemd/system' UNITS = ('update-policy.service', 'update-policy.timer', 'update-policy-baseline.service', - 'update-policy-baseline.timer', 'update-policy-boot.service') + 'update-policy-baseline.timer', 'update-policy-boot.service', 'update-policy-exposure.service', + 'update-policy-exposure.timer') APT_FILE = '/etc/apt/apt.conf.d/zz-update-policy' STATE_DIR = '/var/lib/update-policy' +# the exposure check's cache: systemd's DynamicUser keeps it in private/ and links it +CACHE_DIRS = ('/var/cache/update-policy-exposure', '/var/cache/private/update-policy-exposure') HEADERS = ('# update-policy kit: written by update-policy-install.', '// update-policy kit: written by update-policy-install.') -STARTED = ('update-policy.timer', 'update-policy-baseline.timer') +STARTED = ('update-policy.timer', 'update-policy-baseline.timer', 'update-policy-exposure.timer') ENABLED = STARTED + ('update-policy-boot.service',) APT_LINE = re.compile(r'^Unattended-Upgrade::Automatic-Reboot "(.*)";$') APT_FALSE = ('', '0', 'no', 'false', 'without', 'off', 'disable') @@ -55,7 +59,8 @@ class UpdatePolicyInstaller(kit_install.Installer): + tuple(f'systemd/{name}' for name in UNITS) EXECUTABLE = frozenset({'bin/update-policy', 'sbin/update-policy-install'}) PACKAGE = 'updatepolicy' - MODULES = ('__init__', 'aptconf', 'baseline', 'cli', 'idle', 'settings', 'tick', 'window') + MODULES = ('__init__', 'aptconf', 'baseline', 'cli', 'debver', 'exposure', 'feeds', 'idle', 'oval', 'settings', + 'tick', 'window') HELP = ('bin/update-policy', 'update-policy tick') HAS_CONFIG = True KIT_STEPS = ('policy-files',) @@ -181,10 +186,14 @@ class UpdatePolicyInstaller(kit_install.Installer): def kit_uninstall(self): self.take_off() - state = self.p(STATE_DIR) - if os.path.isdir(state) and not os.path.islink(state): - shutil.rmtree(state) - self.say(f'removed {STATE_DIR}') + for folder in (STATE_DIR,) + CACHE_DIRS: + real = self.p(folder) + if os.path.islink(real): + os.unlink(real) + self.say(f'removed {folder}') + elif os.path.isdir(real): + shutil.rmtree(real) + self.say(f'removed {folder}') self.say('unattended-upgrades\' own Automatic-Reboot setting applies again') def installed_summary(self, plan): diff --git a/fork-kit/update-policy/systemd/update-policy-exposure.service b/fork-kit/update-policy/systemd/update-policy-exposure.service new file mode 100644 index 0000000000000..ed775eb4989d2 --- /dev/null +++ b/fork-kit/update-policy/systemd/update-policy-exposure.service @@ -0,0 +1,29 @@ +# update-policy kit: written by update-policy-install. Do not edit: run the installer again. +[Unit] +Description=update-policy exposure: installed packages against KEV, distro security data and EPSS (fork-kit/update-policy) +ConditionPathExists=/usr/local/libexec/update-policy/current/bin/update-policy +Wants=network-online.target +After=network-online.target + +[Service] +Type=oneshot +# the check needs no privilege: a user made for the run, its own cache folder, nothing else writable +DynamicUser=yes +CacheDirectory=update-policy-exposure +CacheDirectoryMode=0750 +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +NoNewPrivileges=yes +ExecStart=/usr/bin/python3 -I -B /usr/local/libexec/update-policy/current/bin/update-policy exposure --cache /var/cache/update-policy-exposure +# as root ("+"), after the check whatever it found: the alert command may read a root-only file +ExecStopPost=+/usr/bin/python3 -I -B /usr/local/libexec/update-policy/current/bin/update-policy exposure-alert --cache /var/cache/update-policy-exposure +# findings are exit 1: the unit shows as failed until they are gone (systemctl --failed) +Nice=10 +TimeoutStartSec=30min +# with only the running kernel's entries kept, a real feed peaks near 265 MB (noble) and 375 MB (jammy); a broken +# or hostile one is stopped by the check's own caps, and by these +MemoryHigh=768M +MemoryMax=1G +CPUWeight=20 +IOWeight=20 diff --git a/fork-kit/update-policy/systemd/update-policy-exposure.timer b/fork-kit/update-policy/systemd/update-policy-exposure.timer new file mode 100644 index 0000000000000..67c27aae13c1c --- /dev/null +++ b/fork-kit/update-policy/systemd/update-policy-exposure.timer @@ -0,0 +1,11 @@ +# update-policy kit: written by update-policy-install. Do not edit: run the installer again. +[Unit] +Description=update-policy exposure once a day (fork-kit/update-policy) + +[Timer] +OnCalendar=*-*-* 07:00:00 +RandomizedDelaySec=1h +Persistent=true + +[Install] +WantedBy=timers.target diff --git a/fork-kit/update-policy/tests/exposure.test.py b/fork-kit/update-policy/tests/exposure.test.py new file mode 100644 index 0000000000000..7646109654968 --- /dev/null +++ b/fork-kit/update-policy/tests/exposure.test.py @@ -0,0 +1,821 @@ +"""update-policy exposure: Debian version order, the OVAL reader, the feed cache and the daily check, against small +recorded fixtures (tests/fixtures: cuts of Ubuntu's noble CVE OVAL with one kernel CVE, Debian's bookworm OVAL, CISA's +KEV list and FIRST.org's EPSS file), a fake web (no network), a fake dpkg-query and a fixed clock. RedCheck breaks each +rule in a copy of the code and shows its test then fails. + + python3 -I -B fork-kit/update-policy/tests/exposure.test.py +""" +import bz2, datetime, fcntl, gzip, io, json, os, shutil, subprocess, sys, tempfile, unittest, urllib.error +from unittest import mock + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import fixture as fx # noqa: E402 +from fixture import at # noqa: E402 +from updatepolicy import debver, exposure, feeds, oval # noqa: E402 + +FIXTURES = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fixtures') +UBUNTU_OVAL = 'https://security-metadata.canonical.com/oval/com.ubuntu.noble.cve.oval.xml.bz2' +DEBIAN_OVAL = 'https://www.debian.org/security/oval/oval-definitions-bookworm.xml.bz2' +NOW = at('2026-11-24 07:00') +SMALL = {'oval': 1, 'kev': 1, 'epss': 1} +NS = 'xmlns="http://oval.mitre.org/XMLSchema/oval-definitions-5" xmlns:l="x#linux"' + + +def text_of(name): + with open(os.path.join(FIXTURES, name), encoding='utf-8') as f: + return f.read() + + +def fixture_bytes(name, compress=None, replace=()): + data = text_of(name) + for a, b in replace: + assert a in data, a + data = data.replace(a, b) + data = data.encode() + return bz2.compress(data) if compress == 'bz2' else gzip.compress(data) if compress == 'gz' else data + + +def dpkg_line(binary, version, source='', source_version='', status='ii '): + return f'{status}\t{binary}\t{version}\t{source or binary}\t{source_version or version}\n' + + +def mini_oval(*advisories): + """A small OVAL file: (cve, package, fixed or None) per advisory, one dpkginfo test each.""" + defs, tests, objs, states = [], [], [], [] + for i, (cve, package, fixed) in enumerate(advisories): + defs.append(f'{cve} on X' + f'') + state = f'' if fixed else '' + tests.append(f'{state}') + objs.append(f'{package}') + if fixed: + states.append(f'{fixed}' + '') + return (f'{"".join(defs)}{"".join(tests)}' + f'{"".join(objs)}{"".join(states)}') + + +def re_error(): + import re + return re.error('bad pattern') + + +def write_tmp(case, text, name='f'): + tmp = tempfile.mkdtemp() + case.addCleanup(shutil.rmtree, tmp) + path = os.path.join(tmp, name) + with open(path, 'wb') as f: + f.write(text if isinstance(text, bytes) else text.encode()) + return path + + +class Web: + """A fake web: url -> (status, headers, bytes) or an exception; calls are recorded.""" + + def __init__(self): + self.pages, self.calls = {}, [] + + def __call__(self, url, headers, timeout): + self.calls.append((url, dict(headers))) + page = self.pages.get(url) + if page is None: + raise OSError('Name or service not known') + if isinstance(page, Exception): + raise page + status, h, body = page + if headers.get('If-None-Match') and headers['If-None-Match'] == h.get('etag'): + return 304, h, None + return status, h, io.BytesIO(body) + + +class Versions(unittest.TestCase): + TABLE = [('1.0', '1.0', 0), ('1.0', '1.1', -1), ('1.0~rc1', '1.0', -1), ('1.0', '1.0+b1', -1), + ('1:0.9', '2.0', 1), ('2.38-1ubuntu5', '2.38-1ubuntu6', -1), ('2.38-1ubuntu6', '2.38-1ubuntu6.1', -1), + ('0.18.6-2ubuntu0.1', '0.18.6-2', 1), ('1.2.4-0.2+deb12u1', '1.2.4-0.2', 1), ('1.0a', '1.0', 1), + ('1.0-1', '1.0', 1), ('5.6.1+really5.4.5-1', '5.6.0-0.1', 1), ('1.0~~', '1.0~', -1), + ('0:117.0.5938.62-1', '117.0.5938.62-1', 0), ('10', '9', 1), ('1.001', '1.1', 0), ('0:0', '0', 0), + ('0:6.8.0-31', '0:6.8.0-44', -1)] + + def test_dpkg_order(self): + for a, b, want in self.TABLE: + with self.subTest(a=a, b=b): + got = debver.compare(a, b) + self.assertEqual((got > 0) - (got < 0), want) + + def test_the_same_as_dpkg_where_dpkg_is_there(self): + if not shutil.which('dpkg'): + self.skipTest('no dpkg here') + for a, b, want in self.TABLE: + r = subprocess.run(['dpkg', '--compare-versions', a, 'lt', b]) + self.assertEqual(r.returncode == 0, want < 0, (a, b)) + + def test_not_a_version(self): + with self.assertRaises(ValueError): + debver.compare('1.0 beta', '1.0') + + +class Oval(unittest.TestCase): + def read(self, name, replace=(), **kw): + return oval.read(write_tmp(self, fixture_bytes(name, 'bz2', replace)), **kw) + + def test_ubuntu_packages_fixed_and_unfixed_and_the_kernel(self): + data = self.read('ubuntu-noble.cve.oval.xml') + found = {(a.cve, a.source): a for a in data.advisories} + glibc = found[('CVE-2023-4911', 'glibc')] + self.assertEqual((glibc.fixed, glibc.priority), ('2.38-1ubuntu6', 'high')) + self.assertIn('libc-bin', glibc.binaries) + self.assertIsNone(found[('CVE-2021-1789', 'qtwebkit-opensource-src')].fixed) + linux = [k for k in data.kernels if k.flavour == 'linux'] + self.assertEqual([(k.cve, k.fixed) for k in linux], [('CVE-2024-36971', '0:6.8.0-44')]) + self.assertTrue(linux[0].pattern.search('6.8.0-31-generic')) + self.assertEqual(linux[0].version, ('0:', r'^([\d|\.]+-\d+)[-|\w]+$')) + + def test_debian_names_source_packages_and_0_0_is_no_fix(self): + found = {(a.cve, a.source): a.fixed for a in self.read('debian-bookworm.oval.xml').advisories} + self.assertEqual(found[('CVE-2023-4863', 'libwebp')], '0:1.2.4-0.2+deb12u1') + self.assertEqual(found[('CVE-2024-36971', 'linux')], '0:6.1.94-1') + self.assertIsNone(found[('CVE-2022-22965', 'libspring-java')]) # "less than 0:0" + + def test_a_shape_it_does_not_know_is_an_error_never_fewer_advisories(self): + """Both lenses: renamed objects or another state operation silently dropped every fixed advisory.""" + cases = { + 'state operation': (('operation="less than">2.38-1ubuntu6', + 'operation="less than or equal">2.38-1ubuntu6'),), + 'object renamed': (('dpkginfo_object id=', 'dpkginfo_thing id='), ('', + '')), + 'a test kind': (('', + '')), + 'variable gone': (('', + '')), + 'unknown section': (('', ''),), + 'kernel test operation': (('operation="pattern match"', 'operation="equals"'),), + } + for name, replace in cases.items(): + with self.subTest(name), self.assertRaises(oval.FormatError): + self.read('ubuntu-noble.cve.oval.xml', replace) + + def test_package_tests_that_name_nothing_are_a_format_error(self): + mini = mini_oval(('CVE-2024-0001', 'a', '1-1'), ('CVE-2024-0002', 'b', None)) + self.assertEqual(len(oval.read(write_tmp(self, mini)).advisories), 2) + with self.assertRaises(oval.FormatError): + oval.read(write_tmp(self, mini.replace('a', ''))) + + def test_one_test_whose_object_is_gone_is_a_format_error(self): + mini = mini_oval(*[(f'CVE-2024-{i:04d}', f'p{i}', '1-1') for i in range(1, 21)]) + self.assertEqual(len(oval.read(write_tmp(self, mini)).advisories), 20) + gone = mini.replace('p4', '') + with self.assertRaisesRegex(oval.FormatError, 'whose object is not there'): + oval.read(write_tmp(self, gone)) + + def test_broken_files_are_errors(self): + for name, text in (('html', b'moved'), ('cut', b''), + ('empty', b''), ('no-tests', f'' + 'CVE-2024-0001' + ''.encode())): + with self.subTest(name=name), self.assertRaises(oval.FormatError): + oval.read(write_tmp(self, text)) + + def test_the_decompressed_size_and_one_entry_are_capped(self): + """Code lens: a 10 KB bz2 of 200 MB of unknown elements took 4.6 GB.""" + bomb = bz2.compress(f''.encode() + b'' * 2_000_000) + with self.assertRaisesRegex(oval.FormatError, 'larger than 1 MB once decompressed'): + oval.read(write_tmp(self, bomb), max_bytes=1 << 20) + big = f'' + '' * 2000 + '' + with mock.patch.object(oval, 'MAX_ENTRY', 1000), self.assertRaisesRegex(oval.FormatError, 'more than 1000'): + oval.read(write_tmp(self, big + '')) + + def test_a_broken_kernel_entry_is_a_format_error(self): + for replace in ((r'pattern="^([\d|\.]+-\d+)[-|\w]+$"', r'pattern="^[\d|\.]+$"'), + (r'pattern="^([\d|\.]+-\d+)[-|\w]+$"', r'pattern="^([\d+$"'), + ('>0:6.8.0-44<', '>0:6.8.0 44 beta<')): + with self.subTest(replace=replace), self.assertRaisesRegex(oval.FormatError, 'a kernel version'): + self.read('ubuntu-noble.cve.oval.xml', (replace,)) + + def test_only_the_running_kernels_entries_are_kept_and_all_are_counted(self): + everything = self.read('ubuntu-noble.cve.oval.xml') + mine = self.read('ubuntu-noble.cve.oval.xml', release='6.8.0-31-generic') + self.assertEqual(mine.counts, everything.counts) + self.assertEqual(everything.counts['kernels'], len(everything.kernels)) + self.assertLess(len(mine.kernels), len(everything.kernels)) + self.assertTrue(mine.kernels and all(k.pattern.search('6.8.0-31-generic') for k in mine.kernels)) + self.assertEqual(self.read('ubuntu-noble.cve.oval.xml', release='6.6.87.2-microsoft-standard-WSL2').kernels, + []) + + def test_finished_entries_and_sections_are_dropped_as_it_reads(self): + roots, real = [], oval.ET.iterparse + + def spy(source, events): + for event, el in real(source, events): + if not roots: + roots.append(el) + yield event, el + with mock.patch.object(oval.ET, 'iterparse', spy): + self.read('ubuntu-noble.cve.oval.xml') + self.assertEqual(list(roots[0]), []) # nothing kept under the root + + def test_a_less_than_state_is_the_fix(self): + data = oval.read(write_tmp(self, mini_oval(('CVE-2024-0001', 'a', '1.2-1'), ('CVE-2024-0002', 'a', '0:0')))) + self.assertEqual([(a.cve, a.fixed) for a in data.advisories], [('CVE-2024-0001', '1.2-1'), + ('CVE-2024-0002', None)]) + + +class Feeds(unittest.TestCase): + def setUp(self): + self.cache = tempfile.mkdtemp(prefix='update-policy-cache-') + self.addCleanup(shutil.rmtree, self.cache) + self.web = Web() + self.url = 'https://feeds.example/kev.json' + self.web.pages[self.url] = (200, {'etag': '"v1"', 'content-length': '5312'}, fixture_bytes('kev.json')) + + def fetch(self, now=NOW, cap=1 << 20, check=lambda p: len(exposure.read_kev(p))): + return feeds.fetch(self.cache, 'kev', self.url, check, now, cap, 10, self.web) + + def test_once_a_day_then_etag(self): + got = self.fetch() + self.assertEqual((got.problem, got.fetched_at), (None, NOW)) + self.assertEqual(len(exposure.read_kev(got.path)), 6) + self.fetch(NOW + datetime.timedelta(hours=5)) + self.assertEqual(len(self.web.calls), 1) # once a day + got = self.fetch(NOW + datetime.timedelta(days=1)) + self.assertEqual(self.web.calls[-1][1], {'If-None-Match': '"v1"'}) + self.assertEqual((got.problem, got.fetched_at), (None, NOW + datetime.timedelta(days=1))) # 304: fresh + + def test_offline_keeps_the_copy_and_says_so(self): + self.fetch() + self.web.pages[self.url] = OSError('Network is unreachable') + got = self.fetch(NOW + datetime.timedelta(days=2)) + self.assertEqual((got.path is not None, got.fetched_at), (True, NOW)) + self.assertEqual(got.problem, 'kev: download failed (Network is unreachable)') + + def test_a_download_it_does_not_understand_never_replaces_a_good_copy(self): + self.fetch() + self.web.pages[self.url] = (200, {'etag': '"v2"'}, b'{"title": "a new format", "items": []}') + got = self.fetch(NOW + datetime.timedelta(days=1)) + self.assertIn('kev: the download is in a format this check does not understand', got.problem) + self.assertEqual(len(exposure.read_kev(got.path)), 6) # the old copy stays + + def test_a_download_far_smaller_than_the_kept_copy_never_replaces_it(self): + self.fetch() + small = json.loads(fixture_bytes('kev.json')) + small['vulnerabilities'] = small['vulnerabilities'][:2] + self.web.pages[self.url] = (200, {'etag': '"v2"'}, json.dumps(small).encode()) + got = self.fetch(NOW + datetime.timedelta(days=1)) + self.assertEqual(got.problem, 'kev: the download holds entries 2 under half of 6 of the kept copy: kept the ' + 'old copy (day 1 of 3; the same smaller feed 3 days in a row is accepted)') + self.assertEqual(len(exposure.read_kev(got.path)), 6) + + def test_a_lasting_shrink_is_accepted_on_the_third_day_in_a_row_and_said(self): + self.fetch() + small = json.loads(fixture_bytes('kev.json')) + small['vulnerabilities'] = small['vulnerabilities'][:2] + self.web.pages[self.url] = (200, {'etag': '"v2"'}, json.dumps(small).encode()) + for day in (1, 2): # refused, counted + got = self.fetch(NOW + datetime.timedelta(days=day)) + self.assertIn(f'(day {day} of 3;', got.problem) + self.fetch(NOW + datetime.timedelta(days=2, hours=3)) # again the same day: still day 2 + small['vulnerabilities'] = small['vulnerabilities'][:1] # changed again: starts over + self.web.pages[self.url] = (200, {}, json.dumps(small).encode()) + self.assertIn('(day 1 of 3;', self.fetch(NOW + datetime.timedelta(days=3)).problem) + for day in (4, 5): + got = self.fetch(NOW + datetime.timedelta(days=day)) + self.assertIsNone(got.problem) + self.assertEqual(got.notice, 'kev: the feed shrank (entries 1 under half of 6) and stayed so 3 days in a ' + 'row: accepted, the smaller copy is in use') + self.assertEqual(len(exposure.read_kev(got.path)), 1) + + def test_package_and_kernel_counts_are_floored_apart(self): + self.url = 'https://feeds.example/oval.xml' + self.web.pages[self.url] = (200, {}, b'x') + counts = [{'packages': 100, 'kernels': 1000}, {'packages': 10, 'kernels': 1090}] + feeds.fetch(self.cache, 'oval', self.url, lambda p: counts[0], NOW, 1 << 20, 10, self.web) + got = feeds.fetch(self.cache, 'oval', self.url, lambda p: counts[1], NOW + datetime.timedelta(days=1), + 1 << 20, 10, self.web) + self.assertIn('the download holds packages 10 under half of 100 of the kept copy', got.problem) + + def test_the_size_cap(self): + got = self.fetch(cap=1000) + self.assertEqual((got.path, got.problem), (None, 'kev: larger than the cap of 0 MB')) + self.web.pages[self.url] = (200, {}, fixture_bytes('kev.json')) # no content-length: cut while reading + self.assertEqual(self.fetch(cap=1000).problem, 'kev: larger than the cap of 0 MB') + self.assertEqual([n for n in os.listdir(self.cache) if n.endswith('.tmp')], []) + + def test_a_copy_that_does_not_match_its_checksum_is_no_copy(self): + self.fetch() + with open(os.path.join(self.cache, 'kev.data'), 'ab') as f: + f.write(b' ') + self.web.pages[self.url] = OSError('offline') + got = self.fetch(NOW + datetime.timedelta(days=1)) + self.assertEqual((got.path, got.fetched_at), (None, None)) + + def test_another_url_starts_again(self): + self.fetch() + self.url = 'https://feeds.example/other.json' + self.web.pages[self.url] = OSError('offline') + self.assertIsNone(self.fetch().path) + + def test_only_https_and_no_redirect_to_http(self): + with self.assertRaisesRegex(urllib.error.URLError, 'only https'): + feeds.urlopen('http://feeds.example/kev.json', {}, 5) + handler = feeds._HttpsOnly() + with self.assertRaisesRegex(urllib.error.URLError, 'not https'): + handler.redirect_request(None, None, 302, 'Found', {}, 'http://evil.example/kev.json') + + def test_a_killed_runs_temporary_files_are_swept(self): + for name in ('.oval.abc.tmp', '.kev.x.tmp', 'kev.data'): + open(os.path.join(self.cache, name), 'w').close() + feeds.sweep(self.cache) + self.assertEqual(sorted(os.listdir(self.cache)), ['kev.data']) + + +class Base(fx.HostCase): + def setUp(self): + super().setUp() + floors = mock.patch.dict(exposure.FLOORS, SMALL) + floors.start() + self.addCleanup(floors.stop) + self.cache = os.path.join(self.root, 'cache') + os.makedirs(self.cache) + self.write('/etc/os-release', 'NAME="Ubuntu"\nID=ubuntu\nVERSION_CODENAME=noble\n') + self.packages = [dpkg_line('libc-bin', '2.38-1ubuntu5', 'glibc'), dpkg_line('libc6', '2.38-1ubuntu5', 'glibc'), + dpkg_line('libqt5webkit5', '5.212.0~alpha4-36ubuntu2', 'qtwebkit-opensource-src'), + dpkg_line('aide', '0.18.6-2', 'aide'), dpkg_line('bash', '5.2.21-2ubuntu4'), + dpkg_line('gcc-h8300-hms', '1:3.4.6+dfsg2-4.1'), # unfixed, not on KEV: no line + dpkg_line('linux-modules-6.8.0-45-generic', '6.8.0-45.45', 'linux'), + dpkg_line('linux-headers-6.8.0-31-generic', '6.8.0-31.31', 'linux')] + self.host.answers['dpkg-query'] = lambda argv: (0, ''.join(self.packages), '') + self.host.release = '6.8.0-45-generic' # fixed (44): no kernel line + self.web = Web() + self.web.pages[UBUNTU_OVAL] = (200, {'etag': '"o1"'}, fixture_bytes('ubuntu-noble.cve.oval.xml', 'bz2')) + self.web.pages[exposure.KEV_URL] = (200, {'etag': '"k1"'}, fixture_bytes('kev.json')) + self.web.pages[exposure.EPSS_URL] = (200, {'etag': '"e1"'}, fixture_bytes('epss.csv', 'gz')) + + def check(self, now=NOW, **over): + s = fx.make_settings(exposure=dict({'enabled': True}, **over)) + return exposure.check(self.host, s, self.cache, now, self.web) + + +class Check(Base): + def test_kev_with_a_fix_kev_without_and_nothing_else(self): + lines, notes, report = self.check() + self.assertEqual(lines, [ + 'KEV CVE-2023-4911 is exploited in the wild: glibc 2.38-1ubuntu5 (libc-bin, libc6): update to ' + '2.38-1ubuntu6 (EPSS 0.64; CISA due 2023-12-12; GNU GNU C Library)', + 'KEV CVE-2021-1789 is exploited in the wild and has no fix yet: mitigate or watch: ' + 'qtwebkit-opensource-src 5.212.0~alpha4-36ubuntu2 (libqt5webkit5) (EPSS 0.14; CISA due 2022-05-25; ' + 'Apple Multiple Products)']) + self.assertEqual(notes, []) + self.assertEqual([f['action'] for f in report['findings']], ['update', 'mitigate']) + self.assertEqual(sorted({c[0] for c in self.web.calls}), sorted([UBUNTU_OVAL, exposure.KEV_URL, + exposure.EPSS_URL])) # nothing sent + + def test_the_running_kernel_by_its_flavour(self): + self.host.release = '6.8.0-31-generic' + self.packages[-2] = dpkg_line('linux-modules-6.8.0-31-generic', '6.8.0-31.31', 'linux') + lines, notes, _ = self.check() + self.assertIn('KEV CVE-2024-36971 is exploited in the wild: kernel linux 6.8.0-31-generic ' + '(kernel 6.8.0-31-generic): update to 6.8.0-44 and restart (EPSS 0.03', '\n'.join(lines)) + self.assertEqual(notes, []) + + def test_a_kernel_it_cannot_place_is_a_note_never_a_finding(self): + self.host.release = '6.6.87.2-microsoft-standard-WSL2' + lines, notes, _ = self.check() + self.assertEqual(notes, ['kernel: not checked (the running kernel 6.6.87.2-microsoft-standard-WSL2 is none of ' + "ubuntu's kernels in its data)"]) + self.assertEqual(len(lines), 2) # the two KEV package lines only + self.host.release = '6.8.0-31-generic' # linux and linux-riscv match; no modules + self.packages = self.packages[:-2] + _, notes, _ = self.check() + self.assertIn('kernel: not checked (the running kernel 6.8.0-31-generic matches several kernels', notes[0]) + + def test_old_kernel_packages_never_give_lines(self): + self.packages = [dpkg_line('linux-headers-6.8.0-20-generic', '6.8.0-20.20', 'linux'), + dpkg_line('linux-image-6.8.0-20-generic', '6.8.0-20.20', 'linux-signed'), + dpkg_line('linux-modules-6.8.0-45-generic', '6.8.0-45.45', 'linux')] + self.assertEqual(self.check(epssMin=0, fixWaitingDays=0)[0], []) + + def test_a_fix_waiting_shows_by_epss_or_after_its_days(self): + self.packages = [dpkg_line('aide', '0.18.6-2', 'aide')] + self.assertEqual(self.check()[0], []) # EPSS 0.003, first seen today + lines = self.check(epssMin=0.001)[0] + self.assertEqual(lines, ['security fix waiting 0 day(s): aide 0.18.6-2 (aide) -> 0.18.6-2ubuntu0.1: ' + 'CVE-2025-54389 (EPSS 0.00)']) + later = NOW + datetime.timedelta(days=4) + self.assertEqual(self.check(later)[0], ['security fix waiting 4 day(s): aide 0.18.6-2 (aide) -> ' + '0.18.6-2ubuntu0.1: CVE-2025-54389 (EPSS 0.00)']) + self.packages = [dpkg_line('aide', '0.18.6-2ubuntu0.1', 'aide')] # updated: gone + self.assertEqual(self.check(later)[0], []) + + def test_the_waiting_clock_survives_a_run_without_data_and_a_newer_fix(self): + """Code lens: a run with no usable OVAL copy wrote fixSeen={}; the key held the newest fixed version.""" + self.packages = [dpkg_line('aide', '0.18.6-2', 'aide')] + self.check() # first seen now + with open(os.path.join(self.cache, 'oval.data'), 'ab') as f: + f.write(b'x') # no usable copy, and offline + self.web.pages[UBUNTU_OVAL] = OSError('offline') + self.assertIn('cannot check: no usable copy of the distribution\'s security data', + self.check(NOW + datetime.timedelta(days=2))[0]) + newer = (('0.18.6-2ubuntu0.1', '0.18.6-2ubuntu0.2'),) # a newer fix comes out + self.web.pages[UBUNTU_OVAL] = (200, {}, fixture_bytes('ubuntu-noble.cve.oval.xml', 'bz2', newer)) + lines = self.check(NOW + datetime.timedelta(days=4))[0] + self.assertEqual(lines, ['security fix waiting 4 day(s): aide 0.18.6-2 (aide) -> 0.18.6-2ubuntu0.2: ' + 'CVE-2025-54389 (EPSS 0.00)']) + + def test_a_source_waits_since_its_oldest_first_sight(self): + self.web.pages[UBUNTU_OVAL] = (200, {}, mini_oval(('CVE-2024-0001', 'a', '1.2-1')).encode()) + self.packages = [dpkg_line('a', '1.0-1')] + self.check() + self.web.pages[UBUNTU_OVAL] = (200, {}, mini_oval(('CVE-2024-0001', 'a', '1.2-1'), + ('CVE-2024-0002', 'a', '1.3-1')).encode()) + self.check(NOW + datetime.timedelta(days=3)) # a second CVE, first seen on day 3 + lines = self.check(NOW + datetime.timedelta(days=4))[0] + self.assertEqual(lines, ['security fix waiting 4 day(s): a 1.0-1 (a) -> 1.3-1: CVE-2024-0001, CVE-2024-0002 ' + '(EPSS 0.00)']) + + def test_the_kernels_waiting_clock_survives_a_reboot_into_a_newer_kernel_still_behind(self): + kev = json.loads(fixture_bytes('kev.json')) + kev['vulnerabilities'] = [v for v in kev['vulnerabilities'] if v['cveID'] != 'CVE-2024-36971'] + self.web.pages[exposure.KEV_URL] = (200, {}, json.dumps(kev).encode()) + self.host.release = '6.8.0-31-generic' + self.packages[-2] = dpkg_line('linux-modules-6.8.0-31-generic', '6.8.0-31.31', 'linux') + self.check() + self.host.release = '6.8.0-40-generic' # rebooted; 44 is the fix + self.packages[-2] = dpkg_line('linux-modules-6.8.0-40-generic', '6.8.0-40.40', 'linux') + lines = self.check(NOW + datetime.timedelta(days=4))[0] + self.assertIn('security fix waiting 4 day(s): kernel linux 6.8.0-40-generic (kernel 6.8.0-40-generic) -> ' + '6.8.0-44 and restart: CVE-2024-36971', '\n'.join(lines)) + + def test_the_first_cache_format_is_cleaned_up_and_its_clocks_kept(self): + self.packages = [dpkg_line('aide', '0.18.6-2', 'aide')] + with open(os.path.join(self.cache, 'epss.json'), 'w') as f: + json.dump({'CVE-2025-54389': [0.1, NOW.isoformat()]}, f) + with open(os.path.join(self.cache, 'state.json'), 'w') as f: # "BINARY FIXED" keys + json.dump({'fixSeen': {'aide 0.18.6-2ubuntu0.1': (NOW - datetime.timedelta(days=5)).isoformat()}}, f) + self.assertEqual(self.check()[0], ['security fix waiting 5 day(s): aide 0.18.6-2 (aide) -> 0.18.6-2ubuntu0.1: ' + 'CVE-2025-54389 (EPSS 0.00)']) + self.assertFalse(os.path.exists(os.path.join(self.cache, 'epss.json'))) + + def test_one_line_per_source_with_its_highest_fix(self): + mini = mini_oval(('CVE-2024-0001', 'a', '1.2-1'), ('CVE-2024-0002', 'a', '1.3-1'), + ('CVE-2024-0003', 'b', '2-1')) + self.web.pages[UBUNTU_OVAL] = (200, {}, mini.encode()) + self.packages = [dpkg_line('a', '1.0-1'), dpkg_line('b1', '1-1', 'b'), dpkg_line('b2', '1-1', 'b')] + lines = self.check(epssMin=0)[0] + self.assertEqual(lines, ['security fix waiting 0 day(s): a 1.0-1 (a) -> 1.3-1: CVE-2024-0001, CVE-2024-0002 ' + '(EPSS 0.00)', 'security fix waiting 0 day(s): b 1-1 (b1, b2) -> 2-1: CVE-2024-0003 ' + '(EPSS 0.00)']) + with mock.patch.object(exposure, 'MAX_LINES', 1): + lines = self.check(epssMin=0)[0] + self.assertEqual(lines[-1], f'+2 more lines (all in {self.cache}/report.json)') + + def test_held_and_half_installed_packages_count_removed_do_not_and_unknown_is_cannot_check(self): + for status in ('hi ', 'iU ', 'iF ', 'iH ', 'iW ', 'it ', 'iiR'): + with self.subTest(status=status): + self.packages = [dpkg_line('aide', '0.18.6-2', 'aide', status=status)] + self.assertIn('aide 0.18.6-2', self.check(epssMin=0)[0][0]) + for status in ('rc ', 'un '): + self.packages = [dpkg_line('aide', '0.18.6-2', 'aide', status=status), dpkg_line('bash', '5.2')] + self.assertEqual(self.check(epssMin=0)[0], []) + self.packages = [dpkg_line('aide', '0.18.6-2', 'aide', status='iX ')] + self.assertEqual(self.check()[0], ['cannot check: dpkg-query: a status this check does not know (iX for ' + 'aide)']) + + def test_ranked_kev_first_then_by_epss(self): + self.packages.append(dpkg_line('aide', '0.18.6-2', 'aide')) + lines = self.check(epssMin=0)[0] + self.assertEqual([x.split(' is ')[0].split(':')[0] for x in lines], + ['KEV CVE-2023-4911', 'KEV CVE-2021-1789', 'security fix waiting 0 day(s)']) + + def test_debian_source_names_no_fix_kev_and_the_running_image(self): + self.write('/etc/os-release', 'ID=debian\nVERSION_CODENAME=bookworm\n') + self.host.release = '6.1.0-21-amd64' + self.packages = [dpkg_line('libwebp7', '1.2.4-0.2', 'libwebp', '1.2.4-0.2'), + dpkg_line('libspring-java', '4.3.30-2'), + dpkg_line('linux-image-6.1.0-21-amd64', '6.1.90-1', 'linux-signed-amd64', '6.1.90+1'), + dpkg_line('linux-headers-6.1.0-18-amd64', '6.1.76-1', 'linux'), + dpkg_line('linux-libc-dev', '6.1.94-1', 'linux')] + self.web.pages[DEBIAN_OVAL] = (200, {}, fixture_bytes('debian-bookworm.oval.xml', 'bz2')) + lines, notes, _ = self.check() + self.assertEqual(lines, [ + 'KEV CVE-2023-4863 is exploited in the wild: libwebp 1.2.4-0.2 (libwebp7): update to 0:1.2.4-0.2+deb12u1 ' + '(EPSS 1.00; CISA due 2023-10-04; Google Chromium WebP)', + 'KEV CVE-2022-22965 is exploited in the wild and has no fixed version listed by Debian: mitigate or watch ' + '(or, if Debian judged it not to apply, add an ignore entry): libspring-java 4.3.30-2 (libspring-java) ' + '(EPSS 1.00; CISA due 2022-04-25; VMware Spring Framework)', + 'KEV CVE-2024-36971 is exploited in the wild: kernel linux 6.1.90-1 (linux-image-6.1.0-21-amd64): update ' + 'to 6.1.94-1 and restart (EPSS 0.03; CISA due 2024-08-28; Android Kernel)']) + self.assertEqual(notes, []) + self.packages = self.packages[:2] + _, notes, _ = self.check() + self.assertEqual(notes, ['kernel: not checked (the running kernel 6.1.0-21-amd64 has no linux-image ' + 'package)']) + + def test_offline_is_cannot_check_never_all_clear(self): + self.web.pages.clear() + lines, notes, _ = self.check() + self.assertEqual(lines, ['cannot check: oval: download failed (Name or service not known)', + 'cannot check: kev: download failed (Name or service not known)', + 'cannot check: epss: download failed (Name or service not known)', + 'cannot check: no usable copy of the distribution\'s security data', + 'cannot check: no usable copy of CISA\'s KEV list']) + self.assertEqual(notes, ['kernel: not checked (no security data)']) + + def test_a_stale_cache_is_drift_and_still_used(self): + self.check() + self.web.pages.clear() + lines, _, _ = self.check(NOW + datetime.timedelta(days=5)) + self.assertEqual(lines[:3], [f'cannot check: {n}: download failed (Name or service not known)' + for n in ('oval', 'kev', 'epss')]) + self.assertIn('KEV CVE-2023-4911', lines[3]) # the old copy is still read + self.assertEqual(lines[-3:], [f'drift: the cached {n} feed is 5 days old (more than 3): the check works on ' + 'old data' for n in ('oval', 'kev', 'epss')]) + + def test_a_feed_format_change_or_a_too_small_feed_is_cannot_check(self): + self.web.pages[exposure.KEV_URL] = (200, {}, b'{"catalogVersion": "2", "entries": []}') + lines, _, _ = self.check() + self.assertEqual(lines[:2], ['cannot check: kev: the download is in a format this check does not understand ' + '(no "vulnerabilities" list)', 'cannot check: no usable copy of CISA\'s KEV list']) + with mock.patch.dict(exposure.FLOORS, {'kev': 100}): + self.web.pages[exposure.KEV_URL] = (200, {}, fixture_bytes('kev.json')) + self.assertIn('cannot check: kev: the download is in a format this check does not understand (only 6 ' + 'entries, under the floor of 100)', self.check()[0]) + self.web.pages[exposure.EPSS_URL] = (200, {}, gzip.compress(b'cve,score\nCVE-2024-0001,0.1\n')) + self.assertIn('cannot check: epss: the download is in a format this check does not understand (no ' + '"cve,epss,percentile" header (cve,score))', self.check(NOW + datetime.timedelta(days=1))[0]) + + def test_ignore_until_a_date_then_drift(self): + ignore = [{'cve': 'CVE-2021-1789', 'reason': 'qtwebkit unused, removal planned', 'until': '2026-12-01'}] + lines, _, _ = self.check(ignore=ignore) + self.assertEqual([x.split(' is ')[0] for x in lines], ['KEV CVE-2023-4911']) + lines, _, _ = self.check(NOW + datetime.timedelta(days=10), ignore=ignore) + self.assertIn('KEV CVE-2021-1789', lines[1]) + self.assertEqual(lines[-1], 'drift: the ignore entry for CVE-2021-1789 ended on 2026-12-01 (qtwebkit unused, ' + 'removal planned): remove it or give it a new date') + + def test_a_distribution_without_a_source_and_dpkg_failing_cannot_check(self): + self.write('/etc/os-release', 'ID=fedora\nVERSION_CODENAME=\n') + self.assertEqual(self.check()[0], ['cannot check: no security data source for this distribution (fedora ); ' + 'the check knows debian, ubuntu']) + self.write('/etc/os-release', 'ID=ubuntu\nVERSION_CODENAME=noble\n') + self.host.answers['dpkg-query'] = (2, '', 'dpkg-query: error: cannot access archive') + self.assertEqual(self.check()[0], ['cannot check: the installed packages cannot be listed (dpkg-query: ' + 'dpkg-query: error: cannot access archive)']) + + def test_old_or_broken_cache_files_start_again(self): + for name, text in (('state.json', '[1, 2'), ('kev.meta.json', '{"url": 1}'), ('oval.data', 'not oval')): + with open(os.path.join(self.cache, name), 'w') as f: + f.write(text) + lines, _, _ = self.check() + self.assertEqual(len(lines), 2, lines) + self.assertTrue(all(x.startswith('KEV ') for x in lines)) + + def test_server_text_reaches_the_lines_as_one_line(self): + self.web.pages[exposure.KEV_URL] = OSError('bad gateway\n<0>update-policy: forged') + lines, _, _ = self.check() + self.assertIn('cannot check: kev: download failed (bad gateway\\x0a<0>update-policy: forged)', lines) + + def test_off_does_nothing(self): + s = fx.make_settings() + self.assertEqual(exposure.check(self.host, s, self.cache, NOW, self.web)[0], []) + self.assertEqual(self.web.calls, []) + + +class Commands(Base): + def run_cmd(self, now=NOW): + s = fx.make_settings(alertCommand=['/usr/local/bin/notify'], exposure={'enabled': True}) + with mock.patch('builtins.print') as out: + code = exposure.run(self.host, lambda: s, self.cache, now, self.web) + return code, [c.args[0] for c in out.call_args_list], s + + def test_run_prints_writes_the_report_and_the_alert_step_sends_it_with_the_notes(self): + self.host.release = '6.6.87.2-microsoft-standard-WSL2' + code, printed, s = self.run_cmd() + self.assertEqual((code, len(printed)), (1, 3)) + self.assertTrue(printed[-1].startswith('kernel: not checked')) + m = fx.FakeMachine(self.host, NOW) + self.assertEqual(exposure.alert(m, lambda: s, self.cache, NOW + datetime.timedelta(minutes=1)), 0) + self.assertEqual(m.alerts, [('exposure', '\n'.join(printed))]) + + def test_a_note_alone_is_no_finding_and_no_alert(self): + self.host.release = '6.6.87.2-microsoft-standard-WSL2' + self.packages = [dpkg_line('bash', '5.2.21-2ubuntu4')] + code, printed, s = self.run_cmd() + self.assertEqual((code, printed), (0, ["kernel: not checked (the running kernel 6.6.87.2-microsoft-standard-" + "WSL2 is none of ubuntu's kernels in its data)"])) + m = fx.FakeMachine(self.host, NOW) + self.assertEqual(exposure.alert(m, lambda: s, self.cache, NOW), 0) + self.assertEqual(m.alerts, []) + + def test_the_alert_step_reports_a_missing_old_or_linked_report(self): + s = fx.make_settings(alertCommand=['/usr/local/bin/notify'], exposure={'enabled': True}) + m = fx.FakeMachine(self.host, NOW) + exposure.alert(m, lambda: s, self.cache, NOW) + self.assertIn('cannot check: the exposure report', m.alerts[-1][1]) + self.run_cmd() + exposure.alert(m, lambda: s, self.cache, NOW + datetime.timedelta(days=1)) + self.assertIn('missing or broken (old or broken)', m.alerts[-1][1]) + report = os.path.join(self.cache, exposure.REPORT) + os.rename(report, report + '.real') + os.symlink(report + '.real', report) + exposure.alert(m, lambda: s, self.cache, NOW) + self.assertIn('missing or broken', m.alerts[-1][1]) + + def test_a_killed_runs_temporary_files_are_swept_and_a_second_run_waits_for_none(self): + open(os.path.join(self.cache, '.oval.abc123.tmp'), 'w').close() + self.run_cmd() + self.assertFalse(os.path.exists(os.path.join(self.cache, '.oval.abc123.tmp'))) + fd = os.open(os.path.join(self.cache, 'lock'), os.O_RDWR) + self.addCleanup(os.close, fd) + fcntl.flock(fd, fcntl.LOCK_EX) + code, printed, _ = self.run_cmd() + self.assertEqual((code, printed), (0, ["update-policy exposure: another run holds the cache's lock: nothing " + 'to do'])) + + def test_a_fault_is_a_cannot_check_report_never_a_traceback(self): + with mock.patch.object(exposure, 'check', side_effect=re_error()): + code, printed, _ = self.run_cmd() + self.assertEqual((code, printed), (1, ['cannot check: the check failed (error: bad pattern)'])) + with open(os.path.join(self.cache, exposure.REPORT)) as f: + self.assertEqual(json.load(f)['lines'], printed) + + def test_the_report_is_written_while_the_lock_is_held(self): + held, real = [], exposure._write_json + + def spy(cache, name, data): + if name == exposure.REPORT: + fd = os.open(os.path.join(cache, 'lock'), os.O_RDWR) + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + held.append(False) + except BlockingIOError: + held.append(True) + finally: + os.close(fd) + return real(cache, name, data) + with mock.patch.object(exposure, '_write_json', spy): + self.run_cmd() + self.assertEqual(held, [True]) + + def test_as_root_on_the_units_cache_it_refuses(self): + s = fx.make_settings(exposure={'enabled': True}) + with mock.patch.object(exposure.os, 'geteuid', return_value=0), mock.patch('builtins.print') as out: + self.assertEqual(exposure.run(self.host, lambda: s, exposure.CACHE, NOW, self.web), 1) + self.assertIn('systemctl start update-policy-exposure.service', out.call_args_list[0].args[0]) + self.assertEqual(self.web.calls, []) + + +class ExposureSettings(unittest.TestCase): + def test_defaults_off_and_bad_values_refused(self): + s = fx.make_settings()['exposure'] + self.assertEqual((s['enabled'], s['epssMin'], s['fixWaitingDays'], s['staleDays'], s['maxFeedMb'], + s['maxXmlMb']), (False, 0.1, 3, 3, 64, 1024)) + for bad, words in (({'ignore': [{'cve': 'CVE-2024-1', 'reason': 'x', 'until': '2026-12-01'}]}, 'not a CVE'), + ({'ignore': [{'cve': 'CVE-2024-0001', 'reason': ' ', 'until': '2026-12-01'}]}, 'reason'), + ({'ignore': [{'cve': 'CVE-2024-0001', 'reason': 'x', 'until': 'soon'}]}, 'YYYY-MM-DD'), + ({'ignore': [{'cve': 'CVE-2024-0001'}]}, 'each entry'), + ({'epssMin': 2}, 'from 0 to 1'), ({'epssUrl': 'http://x'}, 'https://'), + ({'enabled': 'yes'}, 'bool'), ({'feeds': []}, 'unknown key')): + with self.subTest(bad=bad), self.assertRaises(fx.settings.MachineFileError) as e: + fx.make_settings(exposure=bad) + self.assertIn(words, str(e.exception)) + + +MUTATIONS = { + 'dpkg order: ~ sorts first': ( + 'debver', " if c == '~':\n return -1", " if c == '~':\n return 1", + 'Versions.test_dpkg_order'), + 'oval: no tests is no format': ( + 'oval', " if not defs or not any(", " if not defs or not all(", 'Oval.test_broken_files_are_errors'), + 'oval: another state operation is a format error': ( + 'oval', " if state[1] != 'less than' or not state[2]:", + " if not state[2]:", + 'Oval.test_a_shape_it_does_not_know_is_an_error_never_fewer_advisories'), + 'oval: a missing object is a format error': ( + 'oval', " if obj is None:\n raise", + " if obj is None:\n continue\n raise", + 'Oval.test_one_test_whose_object_is_gone_is_a_format_error'), + 'oval: 0:0 is no fix': ( + 'oval', " fixed = None if no_fix(state[2]) else state[2]", + " fixed = state[2]", 'Oval.test_debian_names_source_packages_and_0_0_is_no_fix'), + 'oval: the decompressed cap': ( + 'oval', " if self.seen > self.limit:", " if False:", + 'Oval.test_the_decompressed_size_and_one_entry_are_capped'), + 'oval: package tests must resolve': ( + 'oval', " if total and resolved < RESOLVED * total:", " if False:", + 'Oval.test_package_tests_that_name_nothing_are_a_format_error'), + 'oval: a broken kernel version is a format error': ( + 'oval', " if re.compile(version[1]).groups < 1:", + " if False:", 'Oval.test_a_broken_kernel_entry_is_a_format_error'), + 'oval: only the running kernel\'s entries are kept': ( + 'oval', " if release is not None and not compiled.search(release):", + " if False:", 'Oval.test_only_the_running_kernels_entries_are_kept_and_all_are_counted'), + 'oval: finished entries are dropped': ( + 'oval', " stack[-1].remove(el) # finished entries and sections are dropped", + " pass", 'Oval.test_finished_entries_and_sections_are_dropped_as_it_reads'), + 'oval: kernel tests are read': ( + 'oval', " for cve in cves:\n kernels.append(", + " for cve in []:\n kernels.append(", + 'Oval.test_ubuntu_packages_fixed_and_unfixed_and_the_kernel'), + 'feeds: once a day': ( + 'feeds', " return Fetched(copy, None, fetched_at) # once a day", " pass", + 'Feeds.test_once_a_day_then_etag'), + 'feeds: a download is checked before it replaces the copy': ( + 'feeds', " entries = _counts(check(tmp))", " entries = {'entries': 10 ** 9}", + 'Feeds.test_a_download_it_does_not_understand_never_replaces_a_good_copy'), + 'feeds: the floor against the kept copy': ( + 'feeds', " shrunk = _shrunk(entries, meta.get('count')) if copy else []", " shrunk = []", + 'Feeds.test_a_download_far_smaller_than_the_kept_copy_never_replaces_it'), + 'feeds: each part is floored': ( + 'feeds', " return [(k, new.get(k, 0), v) for k, v in sorted(kept.items()) if new.get(k, 0) < FLOOR * v]", + " return [(k, sum(new.values()), sum(kept.values())) for k in ['all'] if sum(new.values()) < FLOOR * " + "sum(kept.values())]", 'Feeds.test_package_and_kernel_counts_are_floored_apart'), + 'feeds: a lasting shrink needs days in a row': ( + 'feeds', " if days < SHRINK_DAYS:", " if days < 2:", + 'Feeds.test_a_lasting_shrink_is_accepted_on_the_third_day_in_a_row_and_said'), + 'feeds: the size cap while reading': ( + 'feeds', " if size > max_bytes:", " if False:", 'Feeds.test_the_size_cap'), + 'feeds: the checksum': ( + 'feeds', " return path if meta.get('sha256') and _sha256(path) == meta['sha256'] else None", + " return path if os.path.exists(path) else None", + 'Feeds.test_a_copy_that_does_not_match_its_checksum_is_no_copy'), + 'feeds: no redirect to http': ( + 'feeds', " if not newurl.lower().startswith('https://'):", " if False:", + 'Feeds.test_only_https_and_no_redirect_to_http'), + 'check: the temporary files are swept': ( + 'exposure', " feeds.sweep(cache)\n", "", + 'Commands.test_a_killed_runs_temporary_files_are_swept_and_a_second_run_waits_for_none'), + 'check: fixed versions are compared': ( + 'exposure', " if adv.fixed is None or eco.compare(version, adv.fixed) < 0:", + " if True:", 'Check.test_a_fix_waiting_shows_by_epss_or_after_its_days'), + 'check: only KEV among unfixed': ( + 'exposure', " if a[0] in kev:\n by_cve", + " if a[0] in kev or a[4] is None:\n by_cve", + 'Check.test_kev_with_a_fix_kev_without_and_nothing_else'), + 'check: a fix waiting is shown only past its thresholds': ( + 'exposure', " if not (top >= ex['epssMin'] or days > ex['fixWaitingDays']):", " if False:", + 'Check.test_a_fix_waiting_shows_by_epss_or_after_its_days'), + 'check: the waiting clock survives a run without data': ( + 'exposure', " seen = dict(state['fixSeen']) if data is None else {}", " seen = {}", + 'Check.test_the_waiting_clock_survives_a_run_without_data_and_a_newer_fix'), + 'check: the highest fix of a source': ( + 'exposure', " if eco.compare(fixed, w['fixed']) > 0:\n w['fixed'] = fixed", + " if False:\n w['fixed'] = fixed", 'Check.test_one_line_per_source_with_its_highest_fix'), + 'check: held packages count': ( + 'exposure', "INSTALLED, NOT_INSTALLED = frozenset('iHUFWt'), frozenset('nc')", + "INSTALLED, NOT_INSTALLED = frozenset('i'), frozenset('ncHUFWt')", + 'Check.test_held_and_half_installed_packages_count_removed_do_not_and_unknown_is_cannot_check'), + 'check: kernel packages are judged by the running kernel only': ( + 'exposure', " if KERNEL_PKG.match(binary):\n continue\n", "", + 'Check.test_debian_source_names_no_fix_kev_and_the_running_image'), + 'check: the running kernel': ( + 'exposure', " found, note = kernel_affected(data, release, binaries, distro)", + " found, note = [], None", 'Check.test_the_running_kernel_by_its_flavour'), + 'check: an unplaced kernel is a note': ( + 'exposure', " if note:\n notes.append(", " if False:\n notes.append(", + 'Check.test_a_kernel_it_cannot_place_is_a_note_never_a_finding'), + 'check: no copy is cannot check': ( + 'exposure', " if kev is None:\n lines.append(", " if False:\n lines.append(", + 'Check.test_offline_is_cannot_check_never_all_clear'), + 'check: stale is drift': ( + 'exposure', " if f.path and f.fetched_at and now - f.fetched_at > datetime.timedelta(days=ex['staleDays']):", + " if False:", 'Check.test_a_stale_cache_is_drift_and_still_used'), + 'check: expired ignores are drift': ( + 'exposure', " if entry['until'] < today.isoformat():", " if False:", + 'Check.test_ignore_until_a_date_then_drift'), + 'check: lines are one line': ( + 'exposure', " lines = [one_line(x, 400) for x in lines + found + drift]", + " lines = lines + found + drift", 'Check.test_server_text_reaches_the_lines_as_one_line'), + 'run: a fault is a cannot-check report': ( + 'exposure', " except Exception as e: # noqa: BLE001 - a fault is a cannot-check report", + " except OSError as e: # noqa: BLE001 - a fault is a cannot-check report", + 'Commands.test_a_fault_is_a_cannot_check_report_never_a_traceback'), + 'run: the report under the lock': ( + 'exposure', " _write_json(cache, REPORT, report) # under the lock", + " pass # under the lock", 'Commands.test_the_report_is_written_while_the_lock_is_held'), + 'check: a source waits since its oldest first sight': ( + 'exposure', " w['since'] = min(w['since'], first)", " w['since'] = first", + 'Check.test_a_source_waits_since_its_oldest_first_sight'), + 'check: the kernel clock is per flavour': ( + 'exposure', " return f'{cve} {source}' if source.startswith('kernel ') else f'{cve} {binary}'", + " return f'{cve} {binary}'", + 'Check.test_the_kernels_waiting_clock_survives_a_reboot_into_a_newer_kernel_still_behind'), + 'check: the first format\'s clocks carry over': ( + 'exposure', "or older.get(binary) or now.isoformat()", "or now.isoformat()", + 'Check.test_the_first_cache_format_is_cleaned_up_and_its_clocks_kept'), + "run: not as root on the unit's cache": ( + 'exposure', " if os.geteuid() == 0 and os.path.abspath(cache) == CACHE:", " if False:", + 'Commands.test_as_root_on_the_units_cache_it_refuses'), + 'alert: an old report is no report': ( + 'exposure', " or not now - max_age <= at <= now + datetime.timedelta(minutes=5):", ":", + 'Commands.test_the_alert_step_reports_a_missing_old_or_linked_report'), +} + + +class RedCheck(unittest.TestCase): + def test_each_rule_has_a_test_that_fails_without_it(self): + if os.environ.get(fx.LIB_ENV): + self.skipTest('a red check run') + fx.red_check(self, os.path.abspath(__file__), MUTATIONS) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/fork-kit/update-policy/tests/fixture.py b/fork-kit/update-policy/tests/fixture.py index 6d933403a8123..5a094228e9188 100644 --- a/fork-kit/update-policy/tests/fixture.py +++ b/fork-kit/update-policy/tests/fixture.py @@ -38,6 +38,10 @@ def __init__(self, root): self.dockers = {} # socket -> names or why not self.users = {} # name -> pwd-like entry self.free = {} # path -> (verdict, reason) + self.release = '6.8.0-31-generic' + + def kernel_release(self): + return self.release def run(self, argv, timeout=20, user=None, stdin=None, env=None): self.calls.append((list(argv), stdin, dict(env or {}))) diff --git a/fork-kit/update-policy/tests/fixtures/debian-bookworm.oval.xml b/fork-kit/update-policy/tests/fixtures/debian-bookworm.oval.xml new file mode 100644 index 0000000000000..98d56d8caeb38 --- /dev/null +++ b/fork-kit/update-policy/tests/fixtures/debian-bookworm.oval.xml @@ -0,0 +1,267 @@ + + + + Debian + 5.11.2 + 2026-11-23T11:25:39.188-04:00 + + + + + CVE-2010-4344 exim4 + + Debian GNU/Linux 12 + exim4 + + + (cut for the test fixture) + + + + + + + + + + + + + + + + + CVE-2022-22965 libspring-java + + Debian GNU/Linux 12 + libspring-java + + + (cut for the test fixture) + + + + + + + + + + + + + + + + + CVE-2023-4863 chromium + + Debian GNU/Linux 12 + chromium + + + (cut for the test fixture) + + + + + + + + + + + + + + + + + CVE-2023-4863 firefox-esr + + Debian GNU/Linux 12 + firefox-esr + + + (cut for the test fixture) + + DSA-5496 + no info + + + + + + + + + + + + + + + CVE-2023-4863 libwebp + + Debian GNU/Linux 12 + libwebp + + + (cut for the test fixture) + + DSA-5497 + no info + + + + + + + + + + + + + + + CVE-2023-4863 thunderbird + + Debian GNU/Linux 12 + thunderbird + + + (cut for the test fixture) + + DSA-5498 + no info + + + + + + + + + + + + + + + CVE-2024-36971 linux + + Debian GNU/Linux 12 + linux + + + (cut for the test fixture) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /etc + debian_version + (\d+)\.\d + 1 + + + + exim4 + + + linux + + + thunderbird + + + firefox-esr + + + libwebp + + + libspring-java + + + chromium + + + + + 12 + + + 0:4.70-1 + + + 0:0 + + + 0:117.0.5938.62-1 + + + 0:102.15.1esr-1~deb12u1 + + + 0:1.2.4-0.2+deb12u1 + + + 1:102.15.1-1~deb12u1 + + + 0:6.1.94-1 + + + diff --git a/fork-kit/update-policy/tests/fixtures/epss.csv b/fork-kit/update-policy/tests/fixtures/epss.csv new file mode 100644 index 0000000000000..a754655804fdd --- /dev/null +++ b/fork-kit/update-policy/tests/fixtures/epss.csv @@ -0,0 +1,12 @@ +#model_version:v2026.06.15,score_date:2026-11-23T12:00:23Z +cve,epss,percentile +CVE-1999-0001,0.04753,0.921 +CVE-1999-0002,0.27858,0.98141 +CVE-2002-2439,0.00548,0.46762 +CVE-2010-4344,0.71706,0.99433 +CVE-2021-1789,0.13975,0.9664 +CVE-2022-22965,0.99638,0.99949 +CVE-2023-4863,0.99979,0.9998 +CVE-2023-4911,0.63769,0.99239 +CVE-2024-36971,0.02701,0.86305 +CVE-2025-54389,0.00285,0.21331 diff --git a/fork-kit/update-policy/tests/fixtures/kev.json b/fork-kit/update-policy/tests/fixtures/kev.json new file mode 100644 index 0000000000000..d5ec20922eba8 --- /dev/null +++ b/fork-kit/update-policy/tests/fixtures/kev.json @@ -0,0 +1,92 @@ +{ + "title": "CISA Catalog of Known Exploited Vulnerabilities", + "catalogVersion": "2026.11.23", + "dateReleased": "2026-11-23T12:54:37.9646Z", + "count": 6, + "vulnerabilities": [ + { + "cveID": "CVE-2024-36971", + "vendorProject": "Android", + "product": "Kernel", + "vulnerabilityName": "Android Kernel Remote Code Execution Vulnerability", + "dateAdded": "2024-08-07", + "shortDescription": "Android contains an unspecified vulnerability in the kernel that allows for remote code execution. This vulnerability resides in Linux Kernel and could impact other products, including but not limited to Android OS.", + "requiredAction": "Apply mitigations per vendor instructions or discontinue use of the product if mitigations are unavailable.", + "dueDate": "2024-08-28", + "knownRansomwareCampaignUse": "Unknown", + "forensicTriage": "No", + "notes": "This vulnerability affects a common open-source component, third-party library, or a protocol used by different products. Please check with specific vendors for information on patching status. For more information, please see: https://source.android.com/docs/security/bulletin/2024-08-01, https://lore.kernel.org/linux-cve-announce/20240610090330.1347021-2-lee@kernel.org/T/#u ; https://nvd.nist.gov/vuln/detail/CVE-2024-36971", + "cwes": ["CWE-416"] + }, + { + "cveID": "CVE-2023-4911", + "vendorProject": "GNU", + "product": "GNU C Library", + "vulnerabilityName": "GNU C Library Buffer Overflow Vulnerability", + "dateAdded": "2023-11-21", + "shortDescription": "GNU C Library's dynamic loader ld.so contains a buffer overflow vulnerability when processing the GLIBC_TUNABLES environment variable, allowing a local attacker to execute code with elevated privileges.", + "requiredAction": "Apply mitigations per vendor instructions or discontinue use of the product if mitigations are unavailable.", + "dueDate": "2023-12-12", + "knownRansomwareCampaignUse": "Unknown", + "forensicTriage": "No", + "notes": "This vulnerability affects a common open-source component, third-party library, or a protocol used by different products. Please check with specific vendors for information on patching status. For more information, please see: https://sourceware.org/git/?p=glibc.git;a=commitdiff;h=1056e5b4c3f2d90ed2b4a55f96add28da2f4c8fa, https://access.redhat.com/security/cve/cve-2023-4911, https://www.debian.org/security/2023/dsa-5514 ; https://nvd.nist.gov/vuln/detail/CVE-2023-4911", + "cwes": ["CWE-122"] + }, + { + "cveID": "CVE-2023-4863", + "vendorProject": "Google", + "product": "Chromium WebP", + "vulnerabilityName": "Google Chromium WebP Heap-Based Buffer Overflow Vulnerability", + "dateAdded": "2023-09-13", + "shortDescription": "Google Chromium WebP contains a heap-based buffer overflow vulnerability that allows a remote attacker to perform an out-of-bounds memory write via a crafted HTML page. This vulnerability can affect applications that use the WebP Codec.", + "requiredAction": "Apply mitigations per vendor instructions or discontinue use of the product if mitigations are unavailable.", + "dueDate": "2023-10-04", + "knownRansomwareCampaignUse": "Unknown", + "forensicTriage": "No", + "notes": "https://chromereleases.googleblog.com/2023/09/stable-channel-update-for-desktop_11.html?m=1; https://nvd.nist.gov/vuln/detail/CVE-2023-4863", + "cwes": ["CWE-787"] + }, + { + "cveID": "CVE-2021-1789", + "vendorProject": "Apple", + "product": "Multiple Products", + "vulnerabilityName": "Apple Multiple Products Type Confusion Vulnerability", + "dateAdded": "2022-05-04", + "shortDescription": "A type confusion issue affecting multiple Apple products allows processing of maliciously crafted web content, leading to arbitrary code execution.", + "requiredAction": "Apply updates per vendor instructions.", + "dueDate": "2022-05-25", + "knownRansomwareCampaignUse": "Unknown", + "forensicTriage": "No", + "notes": "https://nvd.nist.gov/vuln/detail/CVE-2021-1789", + "cwes": ["CWE-843"] + }, + { + "cveID": "CVE-2022-22965", + "vendorProject": "VMware", + "product": "Spring Framework", + "vulnerabilityName": "Spring Framework JDK 9+ Remote Code Execution Vulnerability", + "dateAdded": "2022-04-04", + "shortDescription": "Spring MVC or Spring WebFlux application running on JDK 9+ may be vulnerable to remote code execution (RCE) via data binding.", + "requiredAction": "Apply updates per vendor instructions.", + "dueDate": "2022-04-25", + "knownRansomwareCampaignUse": "Unknown", + "forensicTriage": "No", + "notes": "https://nvd.nist.gov/vuln/detail/CVE-2022-22965", + "cwes": ["CWE-94"] + }, + { + "cveID": "CVE-2010-4344", + "vendorProject": "Exim", + "product": "Exim", + "vulnerabilityName": "Exim Heap-Based Buffer Overflow Vulnerability", + "dateAdded": "2022-03-25", + "shortDescription": "Heap-based buffer overflow in the string_vformat function in string.c in Exim before 4.70 allows remote attackers to execute arbitrary code via an SMTP session.", + "requiredAction": "Apply updates per vendor instructions.", + "dueDate": "2022-04-15", + "knownRansomwareCampaignUse": "Unknown", + "forensicTriage": "No", + "notes": "https://nvd.nist.gov/vuln/detail/CVE-2010-4344", + "cwes": ["CWE-119"] + } + ] +} diff --git a/fork-kit/update-policy/tests/fixtures/ubuntu-noble.cve.oval.xml b/fork-kit/update-policy/tests/fixtures/ubuntu-noble.cve.oval.xml new file mode 100644 index 0000000000000..2372378bf8fac --- /dev/null +++ b/fork-kit/update-policy/tests/fixtures/ubuntu-noble.cve.oval.xml @@ -0,0 +1,480 @@ + + + Canonical OVAL Generator + 2 + 5.11.1 + 2026-11-19T19:32:07 + + + + + CVE-2002-2439 on Ubuntu 24.04 LTS (noble) - low + + Ubuntu 24.04 LTS + + + (cut for the test fixture) + + Low + Copyright (C) 2026 Canonical Ltd. + 2019-10-23T18:15:00Z + CVE-2002-2439 + + + + + + + + + + + + + + CVE-2021-1789 on Ubuntu 24.04 LTS (noble) - medium + + Ubuntu 24.04 LTS + + + + (cut for the test fixture) + + Medium + Copyright (C) 2026 Canonical Ltd. + 2021-03-24T00:00:00Z + CVE-2021-1789 + + + + + + + + + + CVE-2023-4911 on Ubuntu 24.04 LTS (noble) - high + + Ubuntu 24.04 LTS + + + + (cut for the test fixture) + + High + Copyright (C) 2026 Canonical Ltd. + 2023-10-03T17:00:00Z + CVE-2023-4911 + + + + + + + + + + CVE-2024-36971 on Ubuntu 24.04 LTS (noble) - high + + Ubuntu 24.04 LTS + + + + + + + + + + + + + + + + + + + + + + + + (cut for the test fixture) + + High + Copyright (C) 2026 Canonical Ltd. + 2024-06-10T09:15:00Z + CVE-2024-36971 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + CVE-2025-54389 on Ubuntu 24.04 LTS (noble) - medium + + Ubuntu 24.04 LTS + + + + (cut for the test fixture) + + Medium + Copyright (C) 2026 Canonical Ltd. + 2025-08-14T14:00:00Z + CVE-2025-54389 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + oval:com.ubuntu.noble:var:200 + + + + + + + + + + + + + + + + + + + + + + + 6\.8\.0\-\d+(\-generic|\-generic\-64k) + + + 6\.8\.0\-\d+(\-azure) + + + 6\.8\.0\-\d+(\-ibm) + + + 6\.8\.0\-\d+(\-lowlatency|\-lowlatency\-64k) + + + 6\.8\.0\-\d+(\-nvidia|\-nvidia\-64k) + + + 6\.8\.0\-\d+(\-nvidia\-lowlatency|\-nvidia\-lowlatency\-64k) + + + 6\.8\.0\-\d+(\-oem) + + + 6\.8\.0\-\d+(\-oracle|\-oracle\-64k) + + + 6\.8\.0\-\d+(\-raspi) + + + riscv64 + 6\.8\.0\-\d+(\-generic) + + + 6\.8\.0\-\d+(\-aws) + + + 6\.8\.0\-\d+(\-gcp) + + + 6\.8\.0\-\d+(\-gke) + + + 0:6.8.0-44 + + + 0:6.8.0-1015 + + + 0:6.8.0-1014 + + + 0:6.8.0-1010 + + + 0:6.8.0-1012 + + + 0:6.8.0-1013 + + + 0:6.8.0-1011 + + + 2.38-1ubuntu6 + + + 0.18.6-2ubuntu0.1 + + + + + + 0: + + + + + + + gcc-arm-none-eabi + gcc-arm-none-eabi-source + + + gcc-h8300-hms + + + g++-mingw-w64 + g++-mingw-w64-i686 + g++-mingw-w64-i686-posix + g++-mingw-w64-i686-win32 + g++-mingw-w64-x86-64 + g++-mingw-w64-x86-64-posix + g++-mingw-w64-x86-64-win32 + gcc-mingw-w64 + gcc-mingw-w64-base + gcc-mingw-w64-i686 + gcc-mingw-w64-i686-posix + gcc-mingw-w64-i686-posix-runtime + gcc-mingw-w64-i686-win32 + gcc-mingw-w64-i686-win32-runtime + gcc-mingw-w64-x86-64 + gcc-mingw-w64-x86-64-posix + gcc-mingw-w64-x86-64-posix-runtime + gcc-mingw-w64-x86-64-win32 + gcc-mingw-w64-x86-64-win32-runtime + gfortran-mingw-w64 + gfortran-mingw-w64-i686 + gfortran-mingw-w64-i686-posix + gfortran-mingw-w64-i686-win32 + gfortran-mingw-w64-x86-64 + gfortran-mingw-w64-x86-64-posix + gfortran-mingw-w64-x86-64-win32 + gnat-mingw-w64 + gnat-mingw-w64-i686 + gnat-mingw-w64-i686-posix + gnat-mingw-w64-i686-win32 + gnat-mingw-w64-x86-64 + gnat-mingw-w64-x86-64-posix + gnat-mingw-w64-x86-64-win32 + gobjc++-mingw-w64 + gobjc++-mingw-w64-i686 + gobjc++-mingw-w64-i686-posix + gobjc++-mingw-w64-i686-win32 + gobjc++-mingw-w64-x86-64 + gobjc++-mingw-w64-x86-64-posix + gobjc++-mingw-w64-x86-64-win32 + gobjc-mingw-w64 + gobjc-mingw-w64-i686 + gobjc-mingw-w64-i686-posix + gobjc-mingw-w64-i686-win32 + gobjc-mingw-w64-x86-64 + gobjc-mingw-w64-x86-64-posix + gobjc-mingw-w64-x86-64-win32 + + + libqt5webkit5 + qml-module-qtwebkit + + + glibc-source + libc-bin + libc-dev-bin + libc-devtools + libc6 + libc6-amd64 + libc6-dev-amd64 + libc6-dev-i386 + libc6-dev-s390 + libc6-dev-x32 + libc6-i386 + libc6-prof + libc6-s390 + libc6-x32 + locales + locales-all + nscd + + + aide + aide-common + aide-dynamic + + + diff --git a/fork-kit/update-policy/tests/install.test.py b/fork-kit/update-policy/tests/install.test.py index 2312b15591954..26fb3394aa3ff 100644 --- a/fork-kit/update-policy/tests/install.test.py +++ b/fork-kit/update-policy/tests/install.test.py @@ -18,7 +18,8 @@ UNIT_DIR = '/etc/systemd/system' UNITS = tuple(f'{UNIT_DIR}/{n}' for n in ('update-policy.service', 'update-policy.timer', 'update-policy-baseline.service', 'update-policy-baseline.timer', - 'update-policy-boot.service')) + 'update-policy-boot.service', 'update-policy-exposure.service', + 'update-policy-exposure.timer')) APT = '/etc/apt/apt.conf.d/zz-update-policy' FILES = UNITS + (APT,) FOREIGN = 'Unattended-Upgrade::Automatic-Reboot "true";\n' @@ -54,14 +55,14 @@ def test_fresh_install_without_the_timer_writes_nothing_outside_the_kit(self): code, out, err = self.install() self.assertEqual(code, 0, err) self.assertEqual(self.config(), {'version': 1, 'timer': False}) - self.assertEqual(self.there(), [False] * 6) + self.assertEqual(self.there(), [False] * len(FILES)) self.assertIn(', no timer', out) self.assertEqual(self.run_main('self-check')[0], 0) def test_the_timer_writes_the_units_and_turns_apts_own_restarts_off(self): code, out, err = self.install('--timer') self.assertEqual(code, 0, err) - self.assertEqual(self.there(), [True] * 6) + self.assertEqual(self.there(), [True] * len(FILES)) self.assertIn('enabled and started update-policy.timer, update-policy-baseline.timer', out) self.assertIn('\nUnattended-Upgrade::Automatic-Reboot "false";\n', self.read(APT)) self.assertTrue(self.read(APT).startswith('// update-policy kit: written by update-policy-install.')) @@ -73,6 +74,11 @@ def test_the_timer_writes_the_units_and_turns_apts_own_restarts_off(self): self.assertIn('update-policy baseline\n', self.read(UNITS[2])) self.assertIn('Persistent=true\n', self.read(UNITS[3])) self.assertIn('update-policy booted\n', self.read(UNITS[4])) + exposure = self.read(UNITS[5]) + self.assertIn('\nDynamicUser=yes\n', exposure) # the check runs unprivileged, + self.assertIn('\nExecStopPost=+/usr/bin/python3 -I -B /usr/local/libexec/update-policy/current/bin/' + 'update-policy exposure-alert', exposure) # the alert as root + self.assertIn('Persistent=true\n', self.read(UNITS[6])) self.assertIn('WantedBy=multi-user.target\n', self.read(UNITS[4])) self.assertTrue(self.config()['timer']) self.assertEqual(self.run_main('self-check')[0], 0) @@ -102,7 +108,7 @@ def test_every_stop_half_way_with_the_timer_then_run_again(self): self.assertTrue(os.path.islink(self.path('/usr/local/bin/update-policy'))) code, _, err = self.install('--timer') self.assertEqual(code, 0, err) - self.assertEqual(self.there(), [True] * 6) + self.assertEqual(self.there(), [True] * len(FILES)) self.assertEqual(self.run_main('self-check')[0], 0) def test_the_units_are_on_before_apt_stops_restarting_and_off_after_it_starts_again(self): @@ -110,33 +116,36 @@ def test_the_units_are_on_before_apt_stops_restarting_and_off_after_it_starts_ag itself, and the apt file comes last; --no-timer and uninstall take the apt file away first.""" self.assertEqual(self.install('--timer')[0], 0) self.assertEqual(self.calls, [(('daemon-reload',), False), - (('enable', '--now', 'update-policy.timer', 'update-policy-baseline.timer'), False), + (('enable', '--now', 'update-policy.timer', 'update-policy-baseline.timer', + 'update-policy-exposure.timer'), False), (('enable', 'update-policy-boot.service'), False)]) self.calls.clear() code, out, _ = self.install('--no-timer') self.assertEqual(code, 0) self.assertEqual(self.calls, [(('disable', '--now', 'update-policy.timer', 'update-policy-baseline.timer', - 'update-policy-boot.service'), False), (('daemon-reload',), False)]) - self.assertEqual(self.there(), [False] * 6) + 'update-policy-exposure.timer', 'update-policy-boot.service'), False), + (('daemon-reload',), False)]) + self.assertEqual(self.there(), [False] * len(FILES)) self.assertIn('unattended-upgrades\' own Automatic-Reboot setting applies', out) self.assertEqual(self.install()[0], 0) # again without the option: still off - self.assertEqual(self.there(), [False] * 6) + self.assertEqual(self.there(), [False] * len(FILES)) self.assertEqual(self.install('--timer')[0], 0) self.calls.clear() self.assertEqual(self.run_main('uninstall')[0], 0) self.assertEqual([c[0][0] for c in self.calls], ['disable', 'daemon-reload']) - self.assertEqual(self.there(), [False] * 6) + self.assertEqual(self.there(), [False] * len(FILES)) def test_units_that_cannot_be_enabled_leave_apts_own_restarts_on(self): self.systemctl_error = {'enable': 'Failed to enable unit: Access denied'} code, _, err = self.install('--timer') self.assertEqual(code, 1) - self.assertIn('systemctl enable --now update-policy.timer update-policy-baseline.timer failed (Failed to ' + self.assertIn('systemctl enable --now update-policy.timer update-policy-baseline.timer ' + 'update-policy-exposure.timer failed (Failed to ' 'enable unit: Access denied)', err) self.assertFalse(os.path.exists(self.path(APT))) self.systemctl_error = {} self.assertEqual(self.install('--timer')[0], 0) # fixed: run again finishes it - self.assertEqual(self.there(), [True] * 6) + self.assertEqual(self.there(), [True] * len(FILES)) def test_apt_still_restarting_by_itself_fails_the_install_unless_forced(self): self.apt_value = 'true' # /etc/apt/apt.conf or a zzz- file wins @@ -157,15 +166,18 @@ def test_apt_still_restarting_by_itself_fails_the_install_unless_forced(self): def test_uninstall_leaves_nothing_the_state_too(self): self.assertEqual(self.install('--timer', sha=SHA1)[0], 0) self.assertEqual(self.install(sha=SHA2)[0], 0) # upgrade without the option: kept - self.assertEqual(self.there(), [True] * 6) + self.assertEqual(self.there(), [True] * len(FILES)) + os.makedirs(self.path('/var/cache/private/update-policy-exposure')) + os.symlink('private/update-policy-exposure', self.path('/var/cache/update-policy-exposure')) os.makedirs(self.path('/var/lib/update-policy')) with open(self.path('/var/lib/update-policy/state.json'), 'w') as f: f.write('{}') code, out, _ = self.run_main('uninstall') self.assertEqual(code, 0) - self.assertEqual(self.there(), [False] * 6) + self.assertEqual(self.there(), [False] * len(FILES)) for gone in ('/usr/local/libexec/update-policy', '/etc/update-policy', '/usr/local/bin/update-policy', - '/usr/local/sbin/update-policy-install', '/var/lib/update-policy'): + '/usr/local/sbin/update-policy-install', '/var/lib/update-policy', + '/var/cache/update-policy-exposure', '/var/cache/private/update-policy-exposure'): self.assertFalse(os.path.lexists(self.path(gone)), gone) self.assertEqual(self.run_main('uninstall')[0], 0) # again: nothing left, still fine