Sign in

Search issue titles and bodies, change requests and comments. Private repositories you cannot read are not included.

vole
Site
Clone

Read only, no credentials:

https://rodent.software/vole.git

Write over SSH with a registered key:

git clone ssh://git@rodent.software/vole.git

Self-hosted forge that lives in your Git repo.

Sign release packages and repository metadata

a755e48a42fdbf5da4414169e516980e63a063f6 · Keenan Nemetz · 15d ago · parent 58ac37e0

Sign release packages and repository metadata

Sign the RPMs before the yum repository reads them, sign the apt Release and yum repomd metadata, and sign SHA256SUMS for direct downloads. The key arrives as the RELEASE_GPG_KEY repository secret; a pushed tag without it fails, while a local run stays unsigned with a note. Signature time is pinned to the tag commit, or to the key creation time when that is later, so a rebuild with the same key is byte-identical.

scripts/sign-release.py +301

@@ -0,0 +1,301 @@
1 #!/usr/bin/env python3
2 """Sign a release's packages and the repositories that carry them.
3
4 This script adds the signatures apt and dnf check to a release tree:
5
6 python3 scripts/sign-release.py packages --dist dist
7 # build apt/ and yum/ from the signed packages
8 python3 scripts/sign-release.py repositories --dist dist
9 # write SHA256SUMS
10 python3 scripts/sign-release.py sums --dist dist
11
12 The private key arrives as the `RELEASE_GPG_KEY` secret, armored. The script
13 imports it into a temporary GnuPG home, signs, verifies what it signed, exports
14 the public key beside the repository, and removes the key material before it
15 exits. `--key-file` does the same from a path, for local testing.
16
17 What is signed, and why:
18
19 - the RPM packages, because dnf checks each package's signature when
20 `gpgcheck=1`;
21 - the apt metadata (`InRelease` and `Release.gpg`), because apt verifies the
22 `Release` file and the hashes in it authenticate every `.deb` it lists. dpkg
23 does not check a signature on an individual `.deb`, so signing those files
24 would be a check nobody performs;
25 - the RPM repository metadata (`repomd.xml.asc`), because dnf verifies it when
26 `repo_gpgcheck=1`;
27 - `SHA256SUMS`, so a direct download can be authenticated without the
28 repository;
29 - the public key is exported to `apt/vole.gpg`, `yum/RPM-GPG-KEY-vole`, and
30 `vole-release-key.asc`, with its fingerprint in `vole-release-key.fingerprint`.
31
32 Signatures carry the tag commit time (`--epoch`) rather than the build clock, so
33 rebuilding one tag produces the same signed files. GnuPG refuses a signature
34 time before the key was created, so the time used is the later of the two; that
35 is also the value both signing tools are given, including `rpmsign` through its
36 `%_gpg_sign_cmd_extra_args` macro. A key that has expired at that time is an
37 error: rotate the key rather than sign with it.
38
39 If the repository has a committed public key at `packaging/keys/vole-release.asc`,
40 the secret must produce the same fingerprint. A rotated key and a stale committed
41 key fail here instead of publishing a key that does not match the signatures.
42 """
43
44 import argparse
45 import os
46 import shutil
47 import subprocess
48 import sys
49 import tempfile
50 import time
51 from pathlib import Path
52
53 ROOT = Path(__file__).resolve().parent.parent
54 COMMITTED_KEY = ROOT / "packaging" / "keys" / "vole-release.asc"
55 GPG = "gpg"
56
57
58 def run(cmd: list[str], capture: bool = False) -> subprocess.CompletedProcess:
59 return subprocess.run(cmd, check=True, text=True, capture_output=capture)
60
61
62 def run_bytes(cmd: list[str]) -> bytes:
63 return subprocess.run(cmd, check=True, capture_output=True).stdout
64
65
66 def gpg(home: Path, *args: str, capture: bool = False) -> subprocess.CompletedProcess:
67 return run([GPG, "--batch", "--no-tty", "--homedir", str(home), *args], capture=capture)
68
69
70 def read_key(args: argparse.Namespace) -> str | None:
71 if args.key_file:
72 try:
73 return Path(args.key_file).read_text(encoding="utf-8")
74 except OSError as err:
75 sys.exit(f"cannot read the signing key: {err}")
76 key = os.environ.get("RELEASE_GPG_KEY", "")
77 if key.strip():
78 return key
79 if args.allow_missing_key and not os.environ.get("VOLE_EVENT"):
80 # A local run is a build check, not a publication. A pushed tag has an
81 # event and must sign: an unsigned release is the failure this change
82 # exists to prevent.
83 print("RELEASE_GPG_KEY is not set; this local run leaves the release tree unsigned", file=sys.stderr)
84 return None
85 sys.exit(
86 "RELEASE_GPG_KEY is not set: store the armored private release key as a "
87 "repository secret (see RELEASING.md)"
88 )
89
90
91 def import_key(home: Path, key: str) -> None:
92 path = home / "release-key.asc"
93 path.write_text(key if key.endswith("\n") else key + "\n", encoding="utf-8")
94 path.chmod(0o600)
95 try:
96 gpg(home, "--import", str(path))
97 finally:
98 path.unlink()
99
100
101 def secret_key(home: Path, wanted: str | None) -> tuple[str, int, int]:
102 """Return the fingerprint, creation time, and expiry of the signing key."""
103 out = gpg(home, "--with-colons", "--list-secret-keys", capture=True).stdout
104 keys, current = [], None
105 for line in out.splitlines():
106 fields = line.split(":")
107 if fields[0] == "sec":
108 current = {"created": int(fields[5]), "expires": int(fields[6] or 0), "fingerprint": ""}
109 keys.append(current)
110 elif fields[0] == "fpr" and current is not None and not current["fingerprint"]:
111 current["fingerprint"] = fields[9]
112 if wanted:
113 keys = [
114 key
115 for key in keys
116 if wanted.lower() in key["fingerprint"].lower() or wanted.lower() == key["fingerprint"][-16:].lower()
117 ]
118 if not keys:
119 sys.exit("the signing key file has no secret key" + (f" matching {wanted}" if wanted else ""))
120 if len(keys) > 1:
121 sys.exit(
122 "the signing key file holds more than one secret key; keep only the release key "
123 "in the secret or name it with --key"
124 )
125 key = keys[0]
126 if not key["fingerprint"]:
127 sys.exit("cannot read the signing key's fingerprint")
128 return key["fingerprint"], key["created"], key["expires"]
129
130
131 def signing_time(epoch: int, created: int, expires: int, fingerprint: str) -> int:
132 """The signature time, pinned to the tag but never before the key existed."""
133 when = max(epoch, created)
134 if expires and when > expires:
135 sys.exit(
136 f"the release key {fingerprint} expired at {time.strftime('%Y-%m-%d', time.gmtime(expires))}; "
137 "rotate it before signing a release"
138 )
139 return when
140
141
142 def verify(home: Path, signature: Path, data: Path | None = None) -> None:
143 args = ["--verify", str(signature)] + ([str(data)] if data else [])
144 gpg(home, *args)
145
146
147 def check_committed_key(home: Path, fingerprint: str) -> None:
148 if not COMMITTED_KEY.is_file():
149 return
150 out = gpg(
151 home,
152 "--with-colons",
153 "--import-options", "show-only",
154 "--import", str(COMMITTED_KEY),
155 capture=True,
156 ).stdout
157 fingerprints = [line.split(":")[9] for line in out.splitlines() if line.startswith("fpr:")]
158 if not fingerprints:
159 sys.exit(f"cannot read a fingerprint from {COMMITTED_KEY.relative_to(ROOT)}")
160 if fingerprints[0].upper() != fingerprint.upper():
161 sys.exit(
162 f"the signing key {fingerprint} does not match "
163 f"{COMMITTED_KEY.relative_to(ROOT)} ({fingerprints[0]}); "
164 "publish the new key in the same change that rotates the secret"
165 )
166
167
168 def sign_packages(dist: Path, home: Path, fingerprint: str, when: int) -> None:
169 packages = sorted(dist.glob("vole-*.rpm"))
170 if not packages:
171 sys.exit(f"no RPM packages to sign in {dist}")
172 if shutil.which("rpm") is None:
173 sys.exit("rpm is not installed; the workflow images carry the rpm package that provides rpmsign")
174 run(
175 [
176 "rpm", "--addsign",
177 "--define", f"_gpg_name {fingerprint}",
178 "--define", f"_gpg_path {home}",
179 "--define", "__gpg /usr/bin/gpg",
180 # rpmsign asks gpg to sign a detached header/payload signature; this
181 # is where the tag time reaches gpg so a rebuild is byte-identical.
182 "--define", f"_gpg_sign_cmd_extra_args --faked-system-time {when}",
183 *[str(package) for package in packages],
184 ]
185 )
186 for package in packages:
187 # A V4 RPM keeps its signature in the immutable header, so SIGPGP and
188 # SIGGPG are empty even though the package is signed. Check the header
189 # tags rpm 4.16+ actually writes.
190 signature = run(
191 [
192 "rpm", "-qp",
193 "--qf", "%{RSAHEADER:pgpsig}|%{DSAHEADER:pgpsig}|%{SIGPGP:pgpsig}|%{SIGGPG:pgpsig}",
194 str(package),
195 ],
196 capture=True,
197 ).stdout.strip()
198 if not signature or all(part == "(none)" for part in signature.split("|")):
199 sys.exit(f"{package} is still unsigned after rpm --addsign")
200
201
202 def sign_repositories(dist: Path, home: Path, fingerprint: str, when: int) -> None:
203 release = dist / "apt" / "Release"
204 repomd = dist / "yum" / "repodata" / "repomd.xml"
205 for required in (release, repomd):
206 if not required.is_file():
207 sys.exit(f"{required} is missing; build the repositories before signing them")
208
209 inrelease = release.with_name("InRelease")
210 release_gpg = release.with_name("Release.gpg")
211 repomd_sig = repomd.with_name("repomd.xml.asc")
212
213 gpg(home, "--yes", "--faked-system-time", str(when), "--local-user", fingerprint,
214 "--armor", "--clearsign", "--output", str(inrelease), str(release))
215 gpg(home, "--yes", "--faked-system-time", str(when), "--local-user", fingerprint,
216 "--armor", "--detach-sign", "--output", str(release_gpg), str(release))
217 gpg(home, "--yes", "--faked-system-time", str(when), "--local-user", fingerprint,
218 "--armor", "--detach-sign", "--output", str(repomd_sig), str(repomd))
219
220 verify(home, inrelease)
221 verify(home, release_gpg, release)
222 verify(home, repomd_sig, repomd)
223
224 # apt wants a keyring file, not armored text, in signed-by=. dnf and the
225 # release page are easier to read armored, so both forms are published.
226 binary = run_bytes([GPG, "--batch", "--no-tty", "--homedir", str(home), "--export", fingerprint])
227 armored = gpg(home, "--armor", "--export", fingerprint, capture=True).stdout
228 (dist / "apt" / "vole.gpg").write_bytes(binary)
229 (dist / "yum" / "RPM-GPG-KEY-vole").write_text(armored, encoding="utf-8")
230 (dist / "vole-release-key.asc").write_text(armored, encoding="utf-8")
231 (dist / "vole-release-key.fingerprint").write_text(fingerprint.upper() + "\n", encoding="utf-8")
232
233
234 def sign_sums(dist: Path, home: Path, fingerprint: str, when: int) -> None:
235 sums = dist / "SHA256SUMS"
236 if not sums.is_file():
237 sys.exit(f"{sums} is missing; write the checksums before signing them")
238 signature = dist / "SHA256SUMS.asc"
239 gpg(home, "--yes", "--faked-system-time", str(when), "--local-user", fingerprint,
240 "--armor", "--detach-sign", "--output", str(signature), str(sums))
241 verify(home, signature, sums)
242
243
244 def main() -> None:
245 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
246 subparsers = parser.add_subparsers(dest="command", required=True)
247 for name, text in (
248 ("packages", "sign the RPM packages in the release tree"),
249 ("repositories", "sign apt and yum metadata and export the public key"),
250 ("sums", "sign SHA256SUMS"),
251 ):
252 sub = subparsers.add_parser(name, help=text)
253 sub.add_argument("--dist", default="dist", help="release tree (default: dist)")
254 sub.add_argument(
255 "--epoch",
256 type=int,
257 default=int(os.environ.get("SOURCE_DATE_EPOCH") or time.time()),
258 help="tag commit time in seconds (default: SOURCE_DATE_EPOCH, else the clock)",
259 )
260 sub.add_argument("--key", help="fingerprint of the secret key to use when the file holds more than one")
261 sub.add_argument("--key-file", help="read the armored private key from this file instead of RELEASE_GPG_KEY")
262 sub.add_argument(
263 "--allow-missing-key",
264 action="store_true",
265 help="a local run (no VOLE_EVENT) may continue unsigned when RELEASE_GPG_KEY is unset",
266 )
267 args = parser.parse_args()
268
269 dist = Path(args.dist).resolve()
270 if not dist.is_dir():
271 sys.exit(f"{args.dist} is not a directory")
272 key = read_key(args)
273 if key is None:
274 return
275 with tempfile.TemporaryDirectory(prefix="vole-sign-") as temporary:
276 home = Path(temporary)
277 home.chmod(0o700)
278 try:
279 import_key(home, key)
280 fingerprint, created, expires = secret_key(home, args.key)
281 # A key file is a local test key; the committed public key describes
282 # the repository's release key, which the secret must match.
283 if not args.key_file:
284 check_committed_key(home, fingerprint)
285 when = signing_time(args.epoch, created, expires, fingerprint)
286 print(f"signing with {fingerprint} at {time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(when))}")
287 if args.command == "packages":
288 sign_packages(dist, home, fingerprint, when)
289 elif args.command == "repositories":
290 sign_repositories(dist, home, fingerprint, when)
291 else:
292 sign_sums(dist, home, fingerprint, when)
293 finally:
294 gpgconf = shutil.which("gpgconf")
295 if gpgconf:
296 subprocess.run([gpgconf, "--homedir", str(home), "--kill", "all"], check=False,
297 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
298
299
300 if __name__ == "__main__":
301 main()