diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index c902acf32..a898d567a 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -218,10 +218,49 @@ jobs: path: launcher/out/* retention-days: 3 - release: + sign: needs: [decide, build] runs-on: ubuntu-latest timeout-minutes: 10 + # The only job that holds the release signing key, a secret of the `release` environment, which only main's real + # releases enter (dry runs sign with a throwaway key). It runs no code from the repository but + # tools/ci/sign_release.sh, which calls only the runner's sha256sum and OpenSSL (docs/release-flow.md). + environment: ${{ needs.decide.outputs.dry_run != 'true' && 'release' || '' }} + steps: + - uses: actions/checkout@v4 + with: + sparse-checkout: tools/ci/sign_release.sh + sparse-checkout-cone-mode: false + persist-credentials: false + - uses: actions/download-artifact@v4 + with: + path: dist + pattern: horizon-launcher-* + merge-multiple: true + - name: Sign the checksums (SHA256SUMS, SHA256SUMS.sig) + env: + RELEASE_SIGNING_KEY: ${{ secrets.RELEASE_SIGNING_KEY }} + RELEASE_SIGNING_KEY_NEXT: ${{ secrets.RELEASE_SIGNING_KEY_NEXT }} + EPHEMERAL: ${{ needs.decide.outputs.dry_run == 'true' && 'yes' || '' }} + TAG: ${{ needs.decide.outputs.tag }} + run: bash tools/ci/sign_release.sh "$TAG" dist/horizon-launcher-* + - uses: actions/upload-artifact@v4 + with: + name: signature + path: dist/SHA256SUMS* + if-no-files-found: error + retention-days: 3 + - uses: actions/upload-artifact@v4 + if: needs.decide.outputs.dry_run == 'true' + with: + name: ephemeral.pub + path: dist/ephemeral.pub + retention-days: 3 + + release: + needs: [decide, build, sign] + runs-on: ubuntu-latest + timeout-minutes: 15 permissions: contents: write steps: @@ -239,6 +278,13 @@ jobs: with: path: dist merge-multiple: true + - name: The signature, checked as launchers check it + env: + TAG: ${{ needs.decide.outputs.tag }} + EPHEMERAL: ${{ needs.decide.outputs.dry_run == 'true' && 'yes' || '' }} + run: | + key=(); [[ -n "$EPHEMERAL" ]] && key=(--key "$(cat dist/ephemeral.pub)") + cargo run --locked --quiet -p horizon-release-sign -- verify --tag "$TAG" --publishing "${key[@]}" dist # Never marked latest: Horizon's own releases stay the repository's latest. - name: Publish ${{ needs.decide.outputs.tag }} if: needs.decide.outputs.dry_run != 'true' @@ -246,8 +292,9 @@ jobs: GH_TOKEN: ${{ github.token }} TAG: ${{ needs.decide.outputs.tag }} run: | + signature=(); [[ -f dist/SHA256SUMS.sig ]] && signature=(dist/SHA256SUMS.sig) gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \ - --notes-file notes/body.md --latest=false dist/horizon-launcher-* + --notes-file notes/body.md --latest=false dist/horizon-launcher-* dist/SHA256SUMS "${signature[@]}" - name: Dry run, the release that would be published if: needs.decide.outputs.dry_run == 'true' run: | diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index bd916514b..1a4a89bf6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -217,10 +217,51 @@ jobs: if-no-files-found: error retention-days: 3 - publish: + sign: needs: [decide, build] runs-on: ubuntu-latest timeout-minutes: 10 + # The only job that holds the release signing key, a secret of the `release` environment, which only main's real + # releases enter (dry runs sign with a throwaway key). It runs no code from the repository but + # tools/ci/sign_release.sh, which calls only the runner's sha256sum and OpenSSL (docs/release-flow.md). + environment: ${{ needs.decide.outputs.dry_run != 'true' && 'release' || '' }} + steps: + - uses: actions/checkout@v4 + with: + sparse-checkout: tools/ci/sign_release.sh + sparse-checkout-cone-mode: false + persist-credentials: false + - uses: actions/download-artifact@v4 + with: + path: dist + pattern: horizon-* + merge-multiple: true + - name: Sign the checksums (SHA256SUMS, SHA256SUMS.sig) + env: + RELEASE_SIGNING_KEY: ${{ secrets.RELEASE_SIGNING_KEY }} + RELEASE_SIGNING_KEY_NEXT: ${{ secrets.RELEASE_SIGNING_KEY_NEXT }} + EPHEMERAL: ${{ needs.decide.outputs.dry_run == 'true' && 'yes' || '' }} + TAG: ${{ needs.decide.outputs.tag }} + run: | + bash tools/ci/sign_release.sh "$TAG" dist/horizon-linux-x86_64.tar.gz dist/horizon-windows-x64.zip \ + dist/horizon-macos-arm64.zip dist/horizon-server-linux-x86_64.tar.gz + - uses: actions/upload-artifact@v4 + with: + name: signature + path: dist/SHA256SUMS* + if-no-files-found: error + retention-days: 3 + - uses: actions/upload-artifact@v4 + if: needs.decide.outputs.dry_run == 'true' + with: + name: ephemeral.pub + path: dist/ephemeral.pub + retention-days: 3 + + publish: + needs: [decide, build, sign] + runs-on: ubuntu-latest + timeout-minutes: 15 permissions: contents: write steps: @@ -238,15 +279,23 @@ jobs: with: path: dist merge-multiple: true + - name: The signature, checked as launchers check it + env: + TAG: ${{ needs.decide.outputs.tag }} + EPHEMERAL: ${{ needs.decide.outputs.dry_run == 'true' && 'yes' || '' }} + run: | + key=(); [[ -n "$EPHEMERAL" ]] && key=(--key "$(cat dist/ephemeral.pub)") + cargo run --locked --quiet -p horizon-release-sign -- verify --tag "$TAG" --publishing "${key[@]}" dist - name: Publish ${{ needs.decide.outputs.tag }} if: needs.decide.outputs.dry_run != 'true' env: GH_TOKEN: ${{ github.token }} TAG: ${{ needs.decide.outputs.tag }} run: | + signature=(); [[ -f dist/SHA256SUMS.sig ]] && signature=(dist/SHA256SUMS.sig) gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \ --notes-file notes/body.md --latest dist/horizon-linux-x86_64.tar.gz dist/horizon-windows-x64.zip \ - dist/horizon-macos-arm64.zip dist/horizon-server-linux-x86_64.tar.gz + dist/horizon-macos-arm64.zip dist/horizon-server-linux-x86_64.tar.gz dist/SHA256SUMS "${signature[@]}" - name: Dry run, the release that would be published if: needs.decide.outputs.dry_run == 'true' run: | diff --git a/Cargo.lock b/Cargo.lock index ea7bc6449..4100e167f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1554,6 +1554,14 @@ dependencies = [ "serde_json", ] +[[package]] +name = "horizon-release-sign" +version = "0.1.0" +dependencies = [ + "base64", + "ring", +] + [[package]] name = "horizon-server" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 409bf4689..bc67ec748 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server", "third_party/wgpu-hal"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] +members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] resolver = "2" [workspace.package] diff --git a/crates/horizon-release-sign/Cargo.toml b/crates/horizon-release-sign/Cargo.toml new file mode 100644 index 000000000..0585adcf8 --- /dev/null +++ b/crates/horizon-release-sign/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "horizon-release-sign" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version = "1.85" +description = "Signed release checksums: release.yml signs SHA256SUMS, the launcher and horizon-server check them before installing" + +[dependencies] +# Ed25519 and SHA-256, already in every build through rustls (ureq's TLS): no new crypto code. +ring = "0.17" +base64 = "0.22" + +[lints] +workspace = true diff --git a/crates/horizon-release-sign/release-keys.txt b/crates/horizon-release-sign/release-keys.txt new file mode 100644 index 000000000..ea2579203 --- /dev/null +++ b/crates/horizon-release-sign/release-keys.txt @@ -0,0 +1,4 @@ +# The public keys Horizon's releases are signed with (docs/security.md, "Signed updates"): one base64 Ed25519 +# key per line. The launcher and horizon-server build these in and refuse a download no key here signed. +# The private keys exist only as the RELEASE_SIGNING_KEY secret(s) of the repository's `release` environment. +# Changing this file needs Ludovic's review (.github/CODEOWNERS). diff --git a/crates/horizon-release-sign/src/lib.rs b/crates/horizon-release-sign/src/lib.rs new file mode 100644 index 000000000..09f9a37b4 --- /dev/null +++ b/crates/horizon-release-sign/src/lib.rs @@ -0,0 +1,345 @@ +//! Signed release checksums (docs/security.md, "Signed updates"). +//! +//! Every release carries `SHA256SUMS` (`sha256sum`'s format, ` ` per line) and +//! `SHA256SUMS.sig`: one base64 Ed25519 signature per line, each over `horizon release \n` +//! followed by SHA256SUMS's bytes, so a signed list can't be passed off under another tag. +//! release.yml and launcher.yml sign with the key(s) in the `release` environment's secrets +//! (tools/ci/sign_release.sh, OpenSSL only); the launcher and `horizon-server update` check a +//! download against the public keys built in from `release-keys.txt` before installing it, and +//! refuse it otherwise. + +use base64::{Engine, engine::general_purpose::STANDARD}; +use ring::signature::{ED25519, Ed25519KeyPair, KeyPair, UnparsedPublicKey}; + +/// The checksum list's asset name. +pub const SUMS: &str = "SHA256SUMS"; +/// Its signatures' asset name. +pub const SIGNATURE: &str = "SHA256SUMS.sig"; + +const KEYS: &str = include_str!("../release-keys.txt"); + +/// An Ed25519 public key. +pub type PublicKey = [u8; 32]; + +/// The public keys built in: those in `release-keys.txt`. A file that doesn't parse gives none, +/// so every download is refused rather than trusted (a test keeps the file valid). +pub fn trusted_keys() -> Vec { + parse_keys(KEYS).unwrap_or_default() +} + +/// The keys in a keys file: one base64 key per line; blank lines and `#` comments are skipped. +pub fn parse_keys(text: &str) -> Result, String> { + text.lines() + .map(str::trim) + .filter(|line| !line.is_empty() && !line.starts_with('#')) + .map(|line| { + let bytes = STANDARD + .decode(line) + .map_err(|e| format!("{line}: not base64 ({e})"))?; + PublicKey::try_from(bytes.as_slice()) + .map_err(|_| format!("{line}: not a 32-byte Ed25519 public key")) + }) + .collect() +} + +/// What a signature covers: the tag, then the checksum list. +pub fn message(tag: &str, sums: &[u8]) -> Vec { + let mut message = format!("horizon release {tag}\n").into_bytes(); + message.extend_from_slice(sums); + message +} + +/// A checksum list for `(file name, SHA-256 hex)` pairs, as `sha256sum` writes it. +pub fn sums_file(files: &[(String, String)]) -> String { + files + .iter() + .map(|(name, hex)| format!("{hex} {name}\n")) + .collect() +} + +/// The `(file name, SHA-256 hex)` pairs of a checksum list (` ` or ` *`). +pub fn parse_sums(text: &str) -> Result, String> { + text.lines() + .filter(|line| !line.trim().is_empty()) + .map(|line| { + let (hex, name) = line + .split_once(' ') + .ok_or_else(|| format!("{SUMS}: {line:?} is not ` `"))?; + let name = name.strip_prefix([' ', '*']).unwrap_or(name); + if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) || name.is_empty() { + return Err(format!("{SUMS}: {line:?} is not ` `")); + } + Ok((name.to_string(), hex.to_ascii_lowercase())) + }) + .collect() +} + +/// Checks that one of `keys` signed `sums` for `tag`, and returns the list. +pub fn verify( + tag: &str, + sums: &[u8], + signature: &str, + keys: &[PublicKey], +) -> Result, String> { + if keys.is_empty() { + return Err( + "This build has no release key built in, so it can't check downloads: none are installed." + .into(), + ); + } + let message = message(tag, sums); + let signed = signature + .lines() + .filter_map(|line| STANDARD.decode(line.trim()).ok()) + .any(|signature| { + keys.iter().any(|key| { + UnparsedPublicKey::new(&ED25519, key) + .verify(&message, &signature) + .is_ok() + }) + }); + if !signed { + return Err(format!( + "{tag}'s signature doesn't match Horizon's release key, so it was not installed. \ + The download may have been tampered with: please report it on Discord or GitHub." + )); + } + let text = std::str::from_utf8(sums).map_err(|_| format!("{SUMS} is not text"))?; + parse_sums(text) +} + +/// The signed SHA-256 of `asset` in release `tag`, or why the download must be refused. +/// `sums` and `signature` are the release's SHA256SUMS and SHA256SUMS.sig, None when it has none. +pub fn signed_digest( + tag: &str, + asset: &str, + sums: Option<&[u8]>, + signature: Option<&str>, + keys: &[PublicKey], +) -> Result { + let (Some(sums), Some(signature)) = (sums, signature) else { + return Err(format!( + "{tag} is not signed, and Horizon installs only signed releases: pick a newer version." + )); + }; + verify(tag, sums, signature, keys)? + .into_iter() + .find(|(name, _)| name == asset) + .map(|(_, hex)| hex) + .ok_or_else(|| { + format!("{asset} is not in {tag}'s signed checksums, so it was not installed.") + }) +} + +/// Whether a downloaded file's SHA-256 (`got`) is the signed one. +pub fn check(asset: &str, expected: &str, got: &str) -> Result<(), String> { + if expected.eq_ignore_ascii_case(got) { + Ok(()) + } else { + Err(format!( + "{asset} doesn't match its signed checksum (corrupted or tampered with), so it was \ + not installed. Try again." + )) + } +} + +/// SHA-256 over data that arrives in pieces (a download). +pub struct Sha256(ring::digest::Context); + +impl Default for Sha256 { + fn default() -> Self { + Self(ring::digest::Context::new(&ring::digest::SHA256)) + } +} + +impl Sha256 { + pub fn update(&mut self, bytes: &[u8]) { + self.0.update(bytes); + } + + pub fn hex(self) -> String { + self.0 + .finish() + .as_ref() + .iter() + .map(|b| format!("{b:02x}")) + .collect() + } +} + +/// The SHA-256 of `bytes`, in hex. +pub fn sha256_hex(bytes: &[u8]) -> String { + let mut hash = Sha256::default(); + hash.update(bytes); + hash.hex() +} + +/// A private signing key: `keygen` makes them, and tests sign with them (releases are signed by +/// OpenSSL in tools/ci/sign_release.sh, from the same PKCS#8 document). +pub struct SigningKey(Ed25519KeyPair); + +impl SigningKey { + /// A new key, and its PKCS#8 document in base64 (what the secret holds). + /// + /// The document is PKCS#8 v1 (RFC 8410: the 32-byte seed alone), which every OpenSSL 3 reads; + /// ring makes v2 (with the public key too), which OpenSSL 3.0, Ubuntu's, refuses. + pub fn generate() -> Result<(Self, String), String> { + const V2_PREFIX: [u8; 16] = [ + 0x30, 0x51, 0x02, 0x01, 0x01, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, + 0x04, 0x20, + ]; + const V1_PREFIX: [u8; 16] = [ + 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, + 0x04, 0x20, + ]; + let v2 = Ed25519KeyPair::generate_pkcs8(&ring::rand::SystemRandom::new()) + .map_err(|_| "no randomness to make a key with".to_string())?; + let seed = v2 + .as_ref() + .strip_prefix(&V2_PREFIX) + .and_then(|rest| rest.get(..32)) + .ok_or("ring's key document has an unexpected layout")?; + let v1 = [&V1_PREFIX[..], seed].concat(); + let key = Ed25519KeyPair::from_pkcs8_maybe_unchecked(&v1) + .map_err(|_| "the new key doesn't parse".to_string())?; + let same = Ed25519KeyPair::from_pkcs8(v2.as_ref()) + .is_ok_and(|k| k.public_key().as_ref() == key.public_key().as_ref()); + if !same { + return Err("the new key's two forms disagree".into()); + } + Ok((Self(key), STANDARD.encode(&v1))) + } + + /// The key a secret holds (base64 PKCS#8). The error never quotes the secret. + pub fn from_base64(text: &str) -> Result { + let document = STANDARD + .decode(text.trim()) + .map_err(|_| "the signing key is not base64".to_string())?; + Ed25519KeyPair::from_pkcs8_maybe_unchecked(&document) + .map(Self) + .map_err(|_| "the signing key is not an Ed25519 PKCS#8 key".to_string()) + } + + pub fn public(&self) -> PublicKey { + PublicKey::try_from(self.0.public_key().as_ref()).expect("Ed25519 public keys are 32 bytes") + } + + /// The public key in base64, as release-keys.txt lists it. + pub fn public_base64(&self) -> String { + STANDARD.encode(self.public()) + } + + /// A signature line for SHA256SUMS.sig. + pub fn sign(&self, tag: &str, sums: &[u8]) -> String { + STANDARD.encode(self.0.sign(&message(tag, sums)).as_ref()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn signed(tag: &str) -> (SigningKey, String, String) { + let (key, _) = SigningKey::generate().unwrap(); + let sums = sums_file(&[ + ("horizon-linux-x86_64.tar.gz".into(), sha256_hex(b"linux")), + ("horizon-windows-x64.zip".into(), sha256_hex(b"windows")), + ]); + let signature = key.sign(tag, sums.as_bytes()) + "\n"; + (key, sums, signature) + } + + #[test] + fn the_built_in_keys_file_parses() { + assert!(parse_keys(KEYS).is_ok()); + } + + #[test] + fn a_signed_release_gives_its_digests() { + let (key, sums, signature) = signed("v2026.10.19"); + let digest = signed_digest( + "v2026.10.19", + "horizon-windows-x64.zip", + Some(sums.as_bytes()), + Some(&signature), + &[key.public()], + ); + assert_eq!(digest, Ok(sha256_hex(b"windows"))); + assert!(check("x", &sha256_hex(b"windows"), &sha256_hex(b"windows")).is_ok()); + assert!(check("x", &sha256_hex(b"windows"), &sha256_hex(b"linux")).is_err()); + } + + #[test] + fn tampering_is_refused() { + let (key, sums, signature) = signed("v2026.10.19"); + let keys = [key.public()]; + // Another tag: an old signed list replayed for a new release. + assert!(verify("v2026.10.20", sums.as_bytes(), &signature, &keys).is_err()); + // A changed checksum. + let changed = sums.replacen(&sha256_hex(b"linux"), &sha256_hex(b"evil"), 1); + assert!(verify("v2026.10.19", changed.as_bytes(), &signature, &keys).is_err()); + // Another key. + let (other, _) = SigningKey::generate().unwrap(); + assert!( + verify( + "v2026.10.19", + sums.as_bytes(), + &signature, + &[other.public()] + ) + .is_err() + ); + // No signature, no keys, an asset that isn't listed. + let none = signed_digest("v2026.10.19", "a", None, None, &keys).unwrap_err(); + assert!(none.contains("not signed"), "{none}"); + assert!(verify("v2026.10.19", sums.as_bytes(), &signature, &[]).is_err()); + let missing = signed_digest( + "v2026.10.19", + "horizon-macos-arm64.zip", + Some(sums.as_bytes()), + Some(&signature), + &keys, + ); + assert!(missing.unwrap_err().contains("not in")); + } + + #[test] + fn any_line_signed_by_any_trusted_key_passes() { + // While rotating, releases carry one signature per key and launchers trust one or both. + let (old, sums, old_line) = signed("v1"); + let (new, _) = SigningKey::generate().unwrap(); + let both = format!("{old_line}{}\n", new.sign("v1", sums.as_bytes())); + assert!(verify("v1", sums.as_bytes(), &both, &[old.public()]).is_ok()); + assert!(verify("v1", sums.as_bytes(), &both, &[new.public()]).is_ok()); + assert!(verify("v1", sums.as_bytes(), "garbage\n\n", &[old.public()]).is_err()); + } + + #[test] + fn keys_round_trip_through_their_text_forms() { + let (key, secret) = SigningKey::generate().unwrap(); + // PKCS#8 v1 (version 0, the seed alone): what OpenSSL 3.0 reads. + let document = STANDARD.decode(&secret).unwrap(); + assert_eq!((document.len(), document[4]), (48, 0)); + let again = SigningKey::from_base64(&format!("{secret}\n")).unwrap(); + assert_eq!(again.public(), key.public()); + assert_eq!( + parse_keys(&format!("# comment\n\n{}\n", key.public_base64())), + Ok(vec![key.public()]) + ); + assert!(parse_keys("AAAA\n").is_err()); + let error = SigningKey::from_base64("bm90IGEga2V5").err().unwrap(); + assert!(!error.contains("bm90")); + } + + #[test] + fn checksum_lists_read_both_sha256sum_forms() { + let hex = sha256_hex(b"x"); + let list = + parse_sums(&format!("{hex} a.zip\n{} *b.tar.gz\n", hex.to_uppercase())).unwrap(); + assert_eq!( + list, + [("a.zip".into(), hex.clone()), ("b.tar.gz".into(), hex)] + ); + assert!(parse_sums("nothex a.zip\n").is_err()); + } +} diff --git a/crates/horizon-release-sign/src/main.rs b/crates/horizon-release-sign/src/main.rs new file mode 100644 index 000000000..108b5192a --- /dev/null +++ b/crates/horizon-release-sign/src/main.rs @@ -0,0 +1,139 @@ +//! horizon-release-sign: checks a release's signed checksums, and makes new keys +//! (docs/release-flow.md, "Signed checksums"). The signing itself is tools/ci/sign_release.sh: the +//! job that holds the private key runs only the runner's sha256sum and OpenSSL, no code from the +//! repository. +//! +//! horizon-release-sign verify --tag v2026.10.19 [--key ] [--publishing] +//! horizon-release-sign keygen --public-out key.pub | gh secret set RELEASE_SIGNING_KEY --env release +//! +//! `verify` checks SHA256SUMS.sig and every file SHA256SUMS lists with the keys built in from +//! release-keys.txt (or `--key`), as the launcher does. With `--publishing` (release.yml) a release +//! may go out unsigned, or signed with a key nobody can check yet, only while release-keys.txt +//! lists no key; once it lists one, anything launchers would refuse fails the release. + +use horizon_release_sign::{SIGNATURE, SUMS, Sha256, SigningKey, parse_keys, trusted_keys, verify}; +use std::io::{IsTerminal, Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; + +fn main() -> ExitCode { + let args: Vec = std::env::args().skip(1).collect(); + let result = match args.first().map(String::as_str) { + Some("verify") => check_folder(&args[1..]), + Some("keygen") => keygen(&args[1..]), + _ => Err( + "usage: horizon-release-sign verify --tag [--key ]... [--publishing] \ + | keygen --public-out " + .into(), + ), + }; + match result { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("horizon-release-sign: {e}"); + ExitCode::FAILURE + } + } +} + +/// The values of every `--name value` in `args`, and the other arguments. +fn options(args: &[String], name: &str) -> (Vec, Vec) { + let mut values = Vec::new(); + let mut rest = Vec::new(); + let mut it = args.iter(); + while let Some(arg) = it.next() { + if arg == name { + values.extend(it.next().cloned()); + } else { + rest.push(arg.clone()); + } + } + (values, rest) +} + +fn tag_of(args: &[String]) -> Result<(String, Vec), String> { + let (tags, rest) = options(args, "--tag"); + let tag = tags.into_iter().next().ok_or("--tag is needed")?; + Ok((tag, rest)) +} + +fn file_hash(path: &Path) -> Result { + let mut file = std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?; + let mut hash = Sha256::default(); + let mut buffer = vec![0; 1 << 16]; + loop { + let n = file + .read(&mut buffer) + .map_err(|e| format!("{}: {e}", path.display()))?; + if n == 0 { + return Ok(hash.hex()); + } + hash.update(&buffer[..n]); + } +} + +/// Checks a folder holding a release's assets, as the launcher does. +fn check_folder(args: &[String]) -> Result<(), String> { + let (tag, rest) = tag_of(args)?; + let (keys, rest) = options(&rest, "--key"); + let publishing = rest.iter().any(|a| a == "--publishing"); + let folder = PathBuf::from( + rest.iter() + .find(|a| *a != "--publishing") + .ok_or("verify needs the release's folder")?, + ); + let keys = if keys.is_empty() { + trusted_keys() + } else { + parse_keys(&keys.join("\n"))? + }; + let sums = std::fs::read(folder.join(SUMS)).map_err(|e| format!("{SUMS}: {e}"))?; + let listed = match std::fs::read_to_string(folder.join(SIGNATURE)) { + Ok(signature) if !keys.is_empty() => verify(&tag, &sums, &signature, &keys)?, + Ok(_) if publishing => { + println!( + "::warning::{tag}: signed, but release-keys.txt lists no key yet, so launchers can't check it" + ); + horizon_release_sign::parse_sums(&String::from_utf8_lossy(&sums))? + } + Err(_) if publishing && keys.is_empty() => { + println!( + "::warning::{tag}: published with {SUMS} but unsigned: release-keys.txt lists no key yet" + ); + horizon_release_sign::parse_sums(&String::from_utf8_lossy(&sums))? + } + Ok(_) => return Err("no key to check the signature with".into()), + Err(_) => { + return Err(format!( + "{tag} has no {SIGNATURE}: launchers would refuse it (is the release environment's \ + RELEASE_SIGNING_KEY set?)" + )); + } + }; + for (name, hex) in &listed { + horizon_release_sign::check(name, hex, &file_hash(&folder.join(name))?)?; + } + println!("{tag}: {} files match {SUMS}", listed.len()); + Ok(()) +} + +/// Prints a new private key to stdout, which must be a pipe (into `gh secret set`), never a +/// terminal, and writes its public key to `--public-out`. +fn keygen(args: &[String]) -> Result<(), String> { + let (public_out, _) = options(args, "--public-out"); + let public_out = public_out + .into_iter() + .next() + .ok_or("keygen needs --public-out ")?; + if std::io::stdout().is_terminal() { + return Err( + "keygen writes the private key to its output: pipe it into `gh secret set`".into(), + ); + } + let (key, secret) = SigningKey::generate()?; + std::fs::write(&public_out, key.public_base64() + "\n").map_err(|e| e.to_string())?; + let mut out = std::io::stdout().lock(); + out.write_all(secret.as_bytes()) + .and_then(|()| out.flush()) + .map_err(|e| e.to_string()) +} diff --git a/crates/horizon-release-sign/tests/cli.rs b/crates/horizon-release-sign/tests/cli.rs new file mode 100644 index 000000000..8e9d5f047 --- /dev/null +++ b/crates/horizon-release-sign/tests/cli.rs @@ -0,0 +1,182 @@ +//! The release steps as release.yml runs them: `sums`, tools/ci/sign_release.sh (OpenSSL), `verify`. +use horizon_release_sign::{SIGNATURE, SUMS, SigningKey, trusted_keys}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +const TAG: &str = "v2026.10.19"; + +fn folder(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "horizon-release-sign-{name}-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("horizon-linux-x86_64.tar.gz"), b"linux build").unwrap(); + std::fs::write(dir.join("horizon-windows-x64.zip"), b"windows build").unwrap(); + let sums = horizon_release_sign::sums_file(&[ + ( + "horizon-linux-x86_64.tar.gz".into(), + horizon_release_sign::sha256_hex(b"linux build"), + ), + ( + "horizon-windows-x64.zip".into(), + horizon_release_sign::sha256_hex(b"windows build"), + ), + ]); + std::fs::write(dir.join(SUMS), sums).unwrap(); + dir +} + +fn tool(args: &[&str], paths: &[&Path]) -> Output { + Command::new(env!("CARGO_BIN_EXE_horizon-release-sign")) + .args(args) + .args(paths) + .output() + .unwrap() +} + +fn verify(dir: &Path, extra: &[&str]) -> Output { + let mut args = vec!["verify", "--tag", TAG]; + args.extend(extra); + tool(&args, &[dir]) +} + +/// An OpenSSL 3 (the runner's), or None on a machine without one (macOS ships LibreSSL). +fn openssl() -> Option { + [ + "openssl", + "/opt/homebrew/opt/openssl@3/bin/openssl", + "/usr/local/opt/openssl@3/bin/openssl", + ] + .into_iter() + .find(|o| { + Command::new(o) + .arg("version") + .output() + .is_ok_and(|v| v.stdout.starts_with(b"OpenSSL 3")) + }) + .map(String::from) +} + +fn sign_script(dir: &Path, env: &[(&str, &str)]) -> Output { + let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/ci/sign_release.sh"); + let mut cmd = Command::new("bash"); + cmd.arg(script) + .arg(TAG) + .arg(dir.join("horizon-linux-x86_64.tar.gz")) + .arg(dir.join("horizon-windows-x64.zip")) + .env_remove("RELEASE_SIGNING_KEY") + .env_remove("RELEASE_SIGNING_KEY_NEXT"); + cmd.env("OPENSSL", openssl().unwrap()); + for (k, v) in env { + cmd.env(k, v); + } + cmd.output().unwrap() +} + +#[test] +fn a_signature_made_like_openssls_checks_and_tampering_fails() { + let dir = folder("lib"); + let (key, _) = SigningKey::generate().unwrap(); + let sums = std::fs::read(dir.join(SUMS)).unwrap(); + std::fs::write(dir.join(SIGNATURE), key.sign(TAG, &sums) + "\n").unwrap(); + assert!( + verify(&dir, &["--key", &key.public_base64()]) + .status + .success() + ); + std::fs::write(dir.join("horizon-windows-x64.zip"), b"tampered").unwrap(); + let out = verify(&dir, &["--key", &key.public_base64()]); + assert!(!out.status.success()); + assert!(String::from_utf8_lossy(&out.stderr).contains("doesn't match its signed checksum")); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn unsigned_releases_go_out_only_until_a_key_is_listed() { + let dir = folder("unsigned"); + assert_eq!( + verify(&dir, &["--publishing"]).status.success(), + trusted_keys().is_empty() + ); + assert!(!verify(&dir, &[]).status.success()); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn the_openssl_script_signs_what_the_launcher_checks() { + if openssl().is_none() { + eprintln!("no OpenSSL 3 here: tools/ci/sign_release.sh is tested on Linux"); + return; + } + // A dry run: a throwaway key, its public key for the check. + let dir = folder("ephemeral"); + std::fs::remove_file(dir.join(SUMS)).unwrap(); // the script writes its own + let out = sign_script(&dir, &[("EPHEMERAL", "yes")]); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let key = std::fs::read_to_string(dir.join("ephemeral.pub")).unwrap(); + assert!(verify(&dir, &["--key", key.trim()]).status.success()); + std::fs::remove_dir_all(dir).unwrap(); + + // A release: both secrets (rotating), as keygen makes them; each signature line checks alone. + let dir = folder("secret"); + let (old, old_secret) = SigningKey::generate().unwrap(); + let (new, new_secret) = SigningKey::generate().unwrap(); + let out = sign_script( + &dir, + &[ + ("RELEASE_SIGNING_KEY", &old_secret), + ("RELEASE_SIGNING_KEY_NEXT", &new_secret), + ], + ); + let printed = format!( + "{}{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + assert!(out.status.success(), "{printed}"); + assert!(!printed.contains(&old_secret) && !printed.contains(&new_secret)); + assert_eq!( + std::fs::read_to_string(dir.join(SIGNATURE)) + .unwrap() + .lines() + .count(), + 2 + ); + assert!( + verify(&dir, &["--key", &old.public_base64()]) + .status + .success() + ); + assert!( + verify(&dir, &["--key", &new.public_base64()]) + .status + .success() + ); + let (other, _) = SigningKey::generate().unwrap(); + assert!( + !verify(&dir, &["--key", &other.public_base64()]) + .status + .success() + ); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn keygen_writes_the_secret_to_a_pipe_and_the_public_key_to_a_file() { + let dir = folder("keygen"); + let public = dir.join("key.pub"); + let out = tool(&["keygen", "--public-out"], &[&public]); + assert!(out.status.success()); + let key = SigningKey::from_base64(&String::from_utf8(out.stdout).unwrap()).unwrap(); + assert_eq!( + std::fs::read_to_string(&public).unwrap().trim(), + key.public_base64() + ); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/docs/release-flow.md b/docs/release-flow.md index e5fee9d07..3386b4af2 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -162,6 +162,41 @@ runs the game: GitHub's runners have neither a GPU worth the name nor the game f Kira posts every published release in #releases and pings the releases role only when the notes have a `### New` section. +### Signed checksums + +Every game and launcher release carries `SHA256SUMS` (the archives' SHA-256, `sha256sum`'s format) and +`SHA256SUMS.sig`: one base64 Ed25519 signature per line over `horizon release \n` followed by SHA256SUMS, +so a signed list can't be reused under another tag. + +- A `sign` job of its own makes them: `tools/ci/sign_release.sh` runs the runner's `sha256sum` and OpenSSL and + nothing else. It is the only job that holds the private key, the `RELEASE_SIGNING_KEY` secret of the + repository's `release` environment, which only real releases from main enter (`environment:` is empty in dry + runs, which sign with a throwaway key). No code from the repository runs beside the key, so no pull request + can read it by changing what a build compiles; the key is in no file, no log and no password vault, and nobody + needs to read it. +- The publish job then checks the signature the way launchers do (`horizon-release-sign verify --publishing`, + crates/horizon-release-sign), against the public keys built in from + `crates/horizon-release-sign/release-keys.txt`. While that file lists no key, releases go out with SHA256SUMS + alone and a warning (today's releases keep working). Once it lists one, a missing secret or a key it doesn't + list fails the release before anything is published, instead of publishing something launchers would refuse. +- Making the key: `tools/ci/new_release_key.sh` pipes a new key from `horizon-release-sign keygen` straight into + `gh secret set RELEASE_SIGNING_KEY --env release` and prints only the public key, which then goes into + release-keys.txt by pull request. + +**Rotating the key** (a new key every year, or at once if the old one may have leaked). The publish job signs +with every key the environment holds, `RELEASE_SIGNING_KEY` and `RELEASE_SIGNING_KEY_NEXT`, and the two names take +turns: + +1. `tools/ci/new_release_key.sh ` makes the next key; add its public key to release-keys.txt + beside the old one. From then on every release is signed with both keys (one line each). +2. Wait until launchers and servers built with both keys are in use (a few weeks: launchers update themselves). +3. Delete the old key's secret (`gh secret delete --env release`) and its line in release-keys.txt. + The next rotation makes its new key under the name just freed. + +If the old key may have leaked, skip the wait: remove its public key from release-keys.txt at once and delete +its secret. Launchers built before the new key cannot check releases signed only with it: they refuse to install +them with a clear message, and players download the launcher again from the website once. + ### Starting one by hand ```sh diff --git a/tools/ci/new_release_key.sh b/tools/ci/new_release_key.sh new file mode 100755 index 000000000..dc2a23742 --- /dev/null +++ b/tools/ci/new_release_key.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Makes a release signing key (docs/security.md, "Signed updates"): the private key goes straight from +# horizon-release-sign into the `release` environment's secret through a pipe (never on disk, never printed, +# never in the Agents vault); the public key is printed for crates/horizon-release-sign/release-keys.txt. +# Needs a gh login that may write the repository's environment secrets (the maintainer's), and the `release` +# environment to exist. +# +# tools/ci/new_release_key.sh # the first key: RELEASE_SIGNING_KEY +# tools/ci/new_release_key.sh RELEASE_SIGNING_KEY_NEXT # rotating: the next key, signed with alongside +set -euo pipefail +secret=${1:-RELEASE_SIGNING_KEY} +case "$secret" in RELEASE_SIGNING_KEY|RELEASE_SIGNING_KEY_NEXT) ;; *) echo "unknown secret $secret" >&2; exit 2 ;; esac +repo=${GITHUB_REPOSITORY:-ludovic111/horizon} +cd "$(dirname "$0")/../.." +gh api "repos/$repo/environments/release" > /dev/null || { + echo "The release environment doesn't exist yet: create it first (docs/security.md)." >&2; exit 1; } +public=$(mktemp) +trap 'rm -f "$public"' EXIT +cargo run --quiet --locked -p horizon-release-sign -- keygen --public-out "$public" \ + | gh secret set "$secret" --env release --repo "$repo" +echo "$secret is set in $repo's release environment. Its public key, for crates/horizon-release-sign/release-keys.txt:" +cat "$public" diff --git a/tools/ci/sign_release.sh b/tools/ci/sign_release.sh new file mode 100755 index 000000000..4fa03ebd1 --- /dev/null +++ b/tools/ci/sign_release.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Signs a release (docs/release-flow.md, "Signed checksums"): writes SHA256SUMS for the files given, then +# SHA256SUMS.sig beside them, one base64 Ed25519 signature per line over "horizon release \n" + SHA256SUMS, +# for every key set in RELEASE_SIGNING_KEY and RELEASE_SIGNING_KEY_NEXT (base64 PKCS#8, the `release` +# environment's secrets). The job that runs this holds the private keys, so it runs nothing from the repository +# but this file, which calls only the runner's sha256sum and OpenSSL; the publish job then checks the result +# with horizon-release-sign, as launchers do. +# EPHEMERAL=yes (dry runs) signs with a throwaway key instead and writes its public key to ephemeral.pub. +# tools/ci/sign_release.sh v2026.10.19 dist/horizon-linux-x86_64.tar.gz dist/horizon-windows-x64.zip ... +set -euo pipefail +tag=$1; shift +dir=$(dirname "$1") +openssl=${OPENSSL:-openssl} +if command -v sha256sum > /dev/null; then sha=(sha256sum); else sha=(shasum -a 256); fi +umask 077 +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT + +names=() +for file in "$@"; do + [[ "$(dirname "$file")" == "$dir" ]] || { echo "$file: every file must be in $dir" >&2; exit 1; } + names+=("$(basename "$file")") +done +(cd "$dir" && "${sha[@]}" -- "${names[@]}") > "$dir/SHA256SUMS" +{ printf 'horizon release %s\n' "$tag"; cat "$dir/SHA256SUMS"; } > "$work/message" +rm -f "$dir/SHA256SUMS.sig" "$dir/ephemeral.pub" + +sign_with() { # the key file in $1 + "$openssl" pkeyutl -sign -rawin -inkey "$1" -keyform DER -in "$work/message" -out "$work/signature" + # base64 of the 64 bytes on one line (GNU base64 wraps at 76 characters). + base64 < "$work/signature" | tr -d '\n' >> "$dir/SHA256SUMS.sig" + echo >> "$dir/SHA256SUMS.sig" + rm -f "$1" "$work/signature" +} + +if [[ -n "${EPHEMERAL:-}" ]]; then + "$openssl" genpkey -algorithm ed25519 -outform DER -out "$work/key" + "$openssl" pkey -inform DER -in "$work/key" -pubout -outform DER | tail -c 32 | base64 > "$dir/ephemeral.pub" + sign_with "$work/key" +else + for name in RELEASE_SIGNING_KEY RELEASE_SIGNING_KEY_NEXT; do + if [[ -n "${!name:-}" ]]; then + # From the environment into a private temporary file: never an argument, never printed. + printf '%s' "${!name}" | base64 --decode > "$work/key" + sign_with "$work/key" + fi + done +fi +echo "$tag: SHA256SUMS lists ${#names[@]} files; $( [[ -f "$dir/SHA256SUMS.sig" ]] && echo "signed with $(wc -l < "$dir/SHA256SUMS.sig" | tr -d ' ') key(s)" || echo "no signing key, so unsigned")"