# SPDX-FileCopyrightText: Defame1297 and contributors # SPDX-License-Identifier: GPL-3.0-or-later """Warn before the Gitea release signing key stops verifying Gitea releases. roles/gitea/tasks/download.yml fetches the release key from gitea_gpg_key_url on every download, requires the pinned primary fingerprint gitea_gpg_key_id and accepts only a valid signature by that key or one of its subkeys. An expired or revoked key, or a release signed by another key, makes every install and update fail closed. This script finds that out ahead of time, read-only: 1. it fetches the key into a throwaway GNUPGHOME (removed on exit) and requires the pinned primary fingerprint; 2. it fails when the primary key, or a signing-capable subkey that is valid now, is revoked or expired, or expires within the window (default 60 days), or when no valid signing-capable key is left; 3. it downloads only the signature file (.asc) of the pinned release, never the binary, and fails unless it holds at least one signature and the issuer of every signature in it is the pinned key or one of its subkeys, valid and signing-capable (as the role requires). It checks who signed the release and that the key is valid, not the signature itself: without the binary there is nothing to verify it against, so a corrupt or bad .asc fails only in the role. .gitea/workflows/gitea-release-key.yml (the `Gitea release key` workflow) runs it weekly, on demand and on pull requests that change the role defaults or the check. python3 -I scripts/check_gitea_release_key.py [--defaults roles/gitea/defaults/main.yml] [--window-days 60] [--key-url URL] [--fingerprint FPR] [--signature-url URL] The URLs and the fingerprint come from the role defaults, so the pins live in one place; the options override the default of the same name before the templates are rendered, so --fingerprint alone also changes the key URL built from it (a file:// URL works too, which the tests use). The only templates rendered are `{{ name }}` and `{{ name | upper }}` of other top-level defaults; anything else (filters, `{% %}`, `{# #}`) fails. Findings are printed as ::error:: / ::warning:: workflow annotations. Exit 0 when the key and the signature are fine, 1 on a finding, 2 when the check itself cannot run (bad input, network, gpg). Needs gpg and PyYAML. What to do on a failure: * A key that expires within the window: if Gitea extends the expiry and republishes the key, nothing changes in the role, because it fetches the key on every download; re-run the check once the key source serves the new expiry. If Gitea moves to a new key, verify the new fingerprint from Gitea's own announcement, then update gitea_gpg_key_id (and gitea_gpg_key_url if the source changes) in the role defaults. * A revoked or expired key, or a release signed by another key: the role refuses that release, so installs and updates of it fail until gitea_gpg_key_id is updated as above. Do not loosen the check in the role to get past it. * Exit 2 (the check could not run): usually the network or the keyserver; re-run the workflow before reading anything into it. """ import argparse import datetime import os import pathlib import re import shutil import signal import subprocess import sys import tempfile import time import urllib.request import yaml DEFAULTS = pathlib.Path(__file__).resolve().parents[1] / "roles/gitea/defaults/main.yml" TEMPLATE = re.compile(r"\{\{\s*([a-z_][a-z0-9_]*)\s*(\|\s*upper\s*)?\}\}") FPR = re.compile(r"^[0-9A-F]{40}$") ISSUER_FPR = re.compile(r"\(issuer fpr v4 ([0-9A-Fa-f]{40})\)") ISSUER_KEYID = re.compile(r"\(issuer key ID ([0-9A-Fa-f]{16})\)") SIG_PACKET = re.compile(r"^:signature packet:.*$", re.MULTILINE) SIGNING = "s" # lowercase: the key's own capability (uppercase is the whole key's) class CheckError(Exception): """The check could not run (input, network, gpg); not a finding about the key.""" def render(name, values, depth=0): """Value of the default `name` with its `{{ var }}` / `{{ var | upper }}` references filled in.""" if depth > 10: raise CheckError(f"template recursion too deep while rendering {name}") value = values.get(name) if not isinstance(value, str): raise CheckError(f"{name} is missing from the defaults or is not a string") def sub(match): out = render(match.group(1), values, depth + 1) return out.upper() if match.group(2) else out out = TEMPLATE.sub(sub, value) if any(mark in out for mark in ("{{", "{%", "{#")): raise CheckError( f"{name} uses a template this script does not render: {value!r}" ) return out def inputs_from_defaults(path, overrides=None): """(key_url, fingerprint, signature_url, version) from the gitea role defaults. overrides replace defaults of the same name before rendering, so a template that refers to an overridden name (gitea_gpg_key_url to gitea_gpg_key_id) follows the override. """ try: values = yaml.safe_load(pathlib.Path(path).read_text(encoding="utf-8")) except (OSError, yaml.YAMLError) as exc: raise CheckError(f"cannot read {path}: {exc}") from exc if not isinstance(values, dict): raise CheckError(f"{path} is not a mapping") values.update({k: v for k, v in (overrides or {}).items() if v is not None}) return ( render("gitea_gpg_key_url", values), render("gitea_gpg_key_id", values), render("gitea_signature_url", values), render("gitea_version", values), ) def fetch(url, dest): req = urllib.request.Request(url, headers={"User-Agent": "gitea-release-key-check"}) try: with urllib.request.urlopen( req, timeout=60 ) as resp: # https, or file:// in the tests data = resp.read(1024 * 1024) except (OSError, ValueError) as exc: raise CheckError(f"cannot fetch {url}: {exc}") from exc if not data: raise CheckError(f"{url} returned nothing") dest.write_bytes(data) def gpg(home, *args): cmd = ["gpg", "--homedir", str(home), "--batch", "--no-autostart", *args] try: res = subprocess.run(cmd, capture_output=True, text=True, check=False) except OSError as exc: raise CheckError(f"cannot run gpg: {exc}") from exc if res.returncode != 0: raise CheckError( f"{' '.join(cmd[4:])} failed (rc {res.returncode}): {res.stderr.strip()}" ) return res.stdout def parse_keys(colons): """{primary fpr: [key, ...]} from --with-colons --fixed-list-mode, the primary first. Each key: {"fpr", "kind" (pub/sub), "validity", "expires" (epoch or None), "caps"}. """ keys, current, pending = {}, None, None for line in colons.splitlines(): f = line.split(":") if f[0] in ("pub", "sub"): pending = { "kind": f[0], "validity": f[1], "expires": int(f[6]) if f[6] else None, "caps": f[11] if len(f) > 11 else "", } elif f[0] == "fpr" and pending is not None: pending["fpr"] = f[9].upper() if pending["kind"] == "pub": current = pending["fpr"] keys[current] = [] if current is not None: keys[current].append(pending) pending = None return keys def day(epoch): return datetime.datetime.fromtimestamp(epoch, datetime.UTC).strftime("%Y-%m-%d") def state(key, now): """'revoked', 'expired' or None (usable now).""" if key["validity"] == "r": return "revoked" if key["validity"] == "e" or (key["expires"] is not None and key["expires"] <= now): return "expired" return None def check_key(keys, fingerprint, window_days, now): """(errors, warnings, notes) about the pinned key and its signing-capable subkeys.""" errors, warnings, notes = [], [], [] horizon = now + window_days * 86400 primary = keys[fingerprint][0] bad = state(primary, now) if bad: errors.append( f"the primary key {fingerprint} is {bad}: every Gitea install and update fails" ) return errors, warnings, notes if primary["expires"] is not None and primary["expires"] <= horizon: errors.append( f"the primary key {fingerprint} expires on {day(primary['expires'])}, within {window_days} days: " "if Gitea extends it, nothing changes here (the role fetches the key on every download); " "if Gitea moves to a new key, update gitea_gpg_key_id" ) else: notes.append( f"primary key {fingerprint}: valid, " f"{'no expiry' if primary['expires'] is None else 'expires ' + day(primary['expires'])}" ) usable = 0 for key in keys[fingerprint]: if SIGNING not in key["caps"]: continue what = "primary key" if key["kind"] == "pub" else "signing subkey" bad = state(key, now) if bad: notes.append( f"{what} {key['fpr']} is {bad} (ignored unless it signed the release)" ) continue usable += 1 if key["kind"] == "sub": if key["expires"] is not None and key["expires"] <= horizon: errors.append( f"the signing subkey {key['fpr']} expires on {day(key['expires'])}, within {window_days} days" ) else: notes.append( f"signing subkey {key['fpr']}: valid, " f"{'no expiry' if key['expires'] is None else 'expires ' + day(key['expires'])}" ) if not usable: errors.append( f"the key {fingerprint} has no valid signing-capable key or subkey" ) return errors, warnings, notes def check_signature(packets, keys, fingerprint, now): """(errors, warnings, notes) about the issuers of the signatures in the release .asc. Like the role: at least one signature, and every one by a valid signing key of the pinned key. """ errors, warnings, notes = [], [], [] starts = [m.start() for m in SIG_PACKET.finditer(packets)] if not starts: return ["the release signature file holds no signature"], warnings, notes # A signature packet's subpackets follow its header line, up to the next packet ("# off=" or # the next ":... packet:" line). chunks = [] for start in starts: rest = packets[start:] nxt = re.search(r"^(?:#|:)", rest[1:], re.MULTILINE) chunks.append(rest if nxt is None else rest[: nxt.start() + 1]) own = {k["fpr"]: k for k in keys[fingerprint]} for chunk in chunks: e, w, n = check_issuer(chunk, own, fingerprint, now) errors += e warnings += w notes += n return errors, warnings, notes def check_issuer(chunk, own, fingerprint, now): """(errors, warnings, notes) about the issuer of one signature packet.""" errors, warnings, notes = [], [], [] match = ISSUER_FPR.search(chunk) if match: label = match.group(1).upper() issuer = own.get(label) else: keyid = ISSUER_KEYID.search(chunk) or re.search( r"keyid ([0-9A-Fa-f]{16})", chunk ) if not keyid: return ["a release signature names no issuer"], warnings, notes label = keyid.group(1).upper() hits = [k for f, k in own.items() if f.endswith(label)] issuer = hits[0] if len(hits) == 1 else None warnings.append( f"a release signature has no issuer fingerprint, matched on the key ID {label} only" ) if issuer is None: errors.append( f"the release is signed by {label}, which is not the key {fingerprint} or one of its subkeys: " "the role rejects it" ) return errors, warnings, notes bad = state(issuer, now) if bad: errors.append( f"the release is signed by {issuer['fpr']}, which is {bad}: the role rejects the signature" ) elif SIGNING not in issuer["caps"]: errors.append( f"the release is signed by {issuer['fpr']}, which is not signing-capable" ) else: notes.append( f"release signature issuer {issuer['fpr']}: a valid signing key of {fingerprint}" ) return errors, warnings, notes def run(key_url, fingerprint, signature_url, window_days, now=None): """(errors, warnings, notes); raises CheckError when the check cannot run.""" now = int(time.time()) if now is None else now fingerprint = fingerprint.upper() if not FPR.match(fingerprint): raise CheckError( f"the pinned fingerprint {fingerprint!r} is not a 40-hex-digit v4 fingerprint" ) if window_days < 0: raise CheckError("the window must not be negative") home = pathlib.Path(tempfile.mkdtemp(prefix="gitea-key.")) # 0700, as gpg wants try: fetch(key_url, home / "key.asc") fetch(signature_url, home / "release.asc") gpg(home, "--import", str(home / "key.asc")) keys = parse_keys( gpg(home, "--with-colons", "--fixed-list-mode", "--list-keys") ) if fingerprint not in keys: return ( [ f"{key_url} did not provide the pinned key {fingerprint} (got: {', '.join(keys) or 'none'})" ], [], [], ) errors, warnings, notes = check_key(keys, fingerprint, window_days, now) e2, w2, n2 = check_signature( gpg(home, "--list-packets", str(home / "release.asc")), keys, fingerprint, now, ) return errors + e2, warnings + w2, notes + n2 finally: subprocess.run( ["gpgconf", "--homedir", str(home), "--kill", "all"], capture_output=True, check=False, ) shutil.rmtree(home, ignore_errors=True) def main(argv=None): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument( "--defaults", default=str(DEFAULTS), help="gitea role defaults to read the pins from", ) parser.add_argument( "--window-days", type=int, default=60, help="fail when a key expires within this many days", ) parser.add_argument("--key-url", help="override gitea_gpg_key_url") parser.add_argument("--fingerprint", help="override gitea_gpg_key_id") parser.add_argument("--signature-url", help="override gitea_signature_url") args = parser.parse_args(argv) # SIGTERM (a cancelled job) must still run the cleanup in run()'s finally. signal.signal(signal.SIGTERM, lambda *_: sys.exit(143)) try: key_url, fingerprint, signature_url, version = inputs_from_defaults( args.defaults, { "gitea_gpg_key_url": args.key_url, "gitea_gpg_key_id": args.fingerprint, "gitea_signature_url": args.signature_url, }, ) print( f"key: {key_url}\nfingerprint: {fingerprint}\nsignature: {signature_url}" f"{f' (gitea {version})' if version else ''}\nwindow: {args.window_days} days" ) errors, warnings, notes = run( key_url, fingerprint, signature_url, args.window_days ) except CheckError as exc: print(f"::error::Gitea release key check could not run: {exc}") return 2 for note in notes: print(f"ok: {note}") for warning in warnings: print(f"::warning::{warning}") for error in errors: print(f"::error::{error}") print( "FAIL" if errors else "OK: the Gitea release key and the pinned release's signature pass" ) summary = os.environ.get("GITHUB_STEP_SUMMARY") if summary and (errors or warnings): with open(summary, "a", encoding="utf-8") as fh: fh.write( "## Gitea release key\n\n" + "".join(f"- {m}\n" for m in errors + warnings) ) return 1 if errors else 0 if __name__ == "__main__": sys.exit(main())