garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /src/release.rs

raw

//! Release signatures: the owner's key on a build of midas, which root on the
//! hub checks before it runs that build as itself (`midas hub self-update`).
//!
//! The hub's machine is assumed compromisable (DESIGN.md §6), and its user
//! publishes the midas binary that the self-update then runs as root: whoever
//! is that user is root on the hub, unless root checks something that user
//! cannot make. That is a signature by a key the hub never holds — the owner's,
//! on their own machine (`midas sign keygen`, `midas sign build`). The
//! public half is `/etc/midas/release.pub`, root's; `self_update` in hub.conf
//! says whether the hub insists on it (`signed`), trusts its own publish
//! (`hub`: how it was until 2026-11-21, and still the default, since a
//! workspace with no release key would otherwise stop updating itself the day
//! it took this build) or never updates itself (`off`).
//!
//! ECDSA P-256 over SHA-256 — the `p256` crate the push notifications already
//! sign with, deterministic (RFC 6979), so no random number is drawn at
//! signing. The key is its 32 raw bytes, the public key the compressed point,
//! the signature 64 raw bytes; each file is one line, a label and base64, so a
//! wrong file is told from a corrupt one.

use std::fs;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};

use anyhow::{anyhow, bail, Context, Result};
use data_encoding::BASE64;
use p256::ecdsa::signature::{Signer, Verifier};
use p256::ecdsa::{Signature, SigningKey, VerifyingKey};

/// The release key's public half on the hub's machine, root's.
pub const RELEASE_PUB: &str = "/etc/midas/release.pub";
/// Where a published build of midas waits for the self-update (hub.conf's
/// midas target publishes into it; `units/midas-self-update.path` watches it).
pub const NEXT: &str = "/usr/local/lib/midas/next";

const KEY_LABEL: &str = "midas-release-key-v1";
const PUB_LABEL: &str = "midas-release-public-v1";
const SIG_LABEL: &str = "midas-release-signature-v1";

/// `~/.config/midas/release.key` unless said otherwise.
pub fn default_key() -> PathBuf {
    let home = std::env::var("HOME").unwrap_or_default();
    PathBuf::from(format!("{home}/.config/midas/release.key"))
}

fn write_line(path: &Path, label: &str, bytes: &[u8], mode: u32) -> Result<()> {
    if let Some(p) = path.parent() {
        fs::create_dir_all(p)?;
    }
    let mut f = fs::OpenOptions::new().write(true).create_new(true).mode(mode).open(path)
        .with_context(|| format!("writing {} (it is not overwritten)", path.display()))?;
    std::io::Write::write_all(&mut f, format!("{label} {}\n", BASE64.encode(bytes)).as_bytes())?;
    Ok(())
}

fn read_line(path: &Path, label: &str) -> Result<Vec<u8>> {
    let text = fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    let mut w = text.split_whitespace();
    match (w.next(), w.next()) {
        (Some(l), Some(b)) if l == label => BASE64.decode(b.as_bytes()).map_err(|_| anyhow!("{} is not a {label}", path.display())),
        (Some(l), _) => bail!("{} is a {l}, not a {label}", path.display()),
        _ => bail!("{} is empty", path.display()),
    }
}

fn signing_key(path: &Path) -> Result<SigningKey> {
    SigningKey::from_slice(&read_line(path, KEY_LABEL)?).map_err(|_| anyhow!("{} holds no P-256 key", path.display()))
}

fn verifying_key(path: &Path) -> Result<VerifyingKey> {
    VerifyingKey::from_sec1_bytes(&read_line(path, PUB_LABEL)?).map_err(|_| anyhow!("{} holds no P-256 public key", path.display()))
}

fn public_line(key: &SigningKey) -> String {
    format!("{PUB_LABEL} {}", BASE64.encode(VerifyingKey::from(key).to_encoded_point(true).as_bytes()))
}

/// `midas sign keygen`: a new key at `path` (0600, never over an old one),
/// and its public line on stdout, for `/etc/midas/release.pub` on the hub.
pub fn keygen(path: &Path) -> Result<i32> {
    let mut urandom = fs::File::open("/dev/urandom")?;
    let key = loop {
        let mut b = [0u8; 32];
        std::io::Read::read_exact(&mut urandom, &mut b)?;
        // Nearly every 32 bytes is a valid scalar; the rest is drawn again.
        if let Ok(k) = SigningKey::from_slice(&b) {
            write_line(path, KEY_LABEL, &b, 0o600)?;
            break k;
        }
    };
    eprintln!("key written to {}. Its public half, for the hub (sudo midas hub setup --release-key -):", path.display());
    println!("{}", public_line(&key));
    Ok(0)
}

/// `midas sign public`: the public line of the key at `path`.
pub fn public(path: &Path) -> Result<i32> {
    println!("{}", public_line(&signing_key(path)?));
    Ok(0)
}

/// The signature file beside `file`.
pub fn sig_path(file: &Path) -> PathBuf {
    let mut s = file.as_os_str().to_owned();
    s.push(".sig");
    PathBuf::from(s)
}

/// `midas sign build <file>`: `<file>.sig` beside it, by the key at `key`.
pub fn sign(key: &Path, file: &Path) -> Result<i32> {
    let k = signing_key(key)?;
    let bytes = fs::read(file).with_context(|| format!("reading {}", file.display()))?;
    let sig: Signature = k.sign(&bytes);
    let out = sig_path(file);
    let _ = fs::remove_file(&out);
    write_line(&out, SIG_LABEL, &sig.to_bytes(), 0o644)?;
    eprintln!("{} signed: {}", file.display(), out.display());
    Ok(0)
}

/// `file` carries a good signature (`sig`, default `<file>.sig`) by the key
/// whose public half is at `pubkey`; an error says which part is not so.
pub fn verify(pubkey: &Path, file: &Path, sig: Option<&Path>) -> Result<()> {
    let vk = verifying_key(pubkey)?;
    let sig_file = sig.map(Path::to_path_buf).unwrap_or_else(|| sig_path(file));
    let sig = Signature::from_slice(&read_line(&sig_file, SIG_LABEL)?).map_err(|_| anyhow!("{} holds no signature", sig_file.display()))?;
    let bytes = fs::read(file).with_context(|| format!("reading {}", file.display()))?;
    vk.verify(&bytes, &sig).map_err(|_| anyhow!("{} does not match the signature in {} by the key in {}", file.display(), sig_file.display(), pubkey.display()))
}

/// `midas sign verify <file> --pubkey <path>`: exit 0 when `verify` says so.
pub fn verify_cmd(pubkey: &Path, file: &Path, sig: Option<&Path>) -> Result<i32> {
    verify(pubkey, file, sig)?;
    eprintln!("{} is signed by the key in {}", file.display(), pubkey.display());
    Ok(0)
}

/// `midas hub self-update` (root; `units/midas-self-update.service` runs it
/// with the installed midas, never with the published one): what hub.conf's
/// `self_update` says about the build waiting in `next`, then that build's
/// `hub setup`, which installs it, updates the services and restarts the hub.
pub fn self_update(next: &Path) -> Result<i32> {
    // SAFETY: geteuid has no preconditions.
    if unsafe { libc::geteuid() } != 0 {
        bail!("the self-update is root's: the midas-self-update service runs it");
    }
    let c = crate::conf::read(Path::new(crate::conf::HUB_CONF))?.unwrap_or_default();
    let bin = next.join("midas");
    if !bin.is_file() {
        bail!("nothing to install: no {}", bin.display());
    }
    let mac = next.join("midas-macos-aarch64");
    let policy = if c.self_update.is_empty() { "hub" } else { c.self_update.as_str() };
    let outcome = match policy {
        "off" => Err(anyhow!("self_update is off in hub.conf: {} stays published, not installed", bin.display())),
        "signed" => {
            let pubkey = Path::new(RELEASE_PUB);
            verify(pubkey, &bin, None)
                .and_then(|_| if mac.is_file() { verify(pubkey, &mac, None) } else { Ok(()) })
                .context("the published midas carries no good signature by the release key, so it is not installed")
        }
        "hub" => Ok(()),
        other => Err(anyhow!("hub.conf's self_update is {other:?}, not hub, signed or off: nothing installed")),
    };
    if let Err(e) = outcome {
        crate::deploy::root_emit("self_update_refused", serde_json::json!({"policy": policy, "what": format!("{e:#}")}));
        return Err(e);
    }
    let mut cmd = std::process::Command::new(&bin);
    cmd.args(["hub", "setup"]);
    if mac.is_file() {
        cmd.arg("--node-binary").arg(format!("macos-aarch64={}", mac.display()));
    }
    let err = std::os::unix::process::CommandExt::exec(&mut cmd);
    bail!("running {} hub setup: {err}", bin.display())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn scratch(name: &str) -> PathBuf {
        let d = std::env::temp_dir().join(format!("midas-release-{name}-{}", std::process::id()));
        let _ = fs::remove_dir_all(&d);
        fs::create_dir_all(&d).unwrap();
        d
    }

    #[test]
    fn a_signature_holds_for_the_bytes_signed_and_for_nothing_else() {
        let d = scratch("sign");
        let key = d.join("k/release.key");
        keygen(&key).unwrap();
        assert_eq!(fs::metadata(&key).unwrap().permissions().mode() & 0o777, 0o600);
        assert!(keygen(&key).is_err(), "never over an old key");
        let pubkey = d.join("release.pub");
        fs::write(&pubkey, public_line(&signing_key(&key).unwrap()) + "\n").unwrap();
        let bin = d.join("midas");
        fs::write(&bin, b"ELF of a build").unwrap();
        sign(&key, &bin).unwrap();
        verify(&pubkey, &bin, None).unwrap();
        fs::write(&bin, b"ELF of another build").unwrap();
        assert!(verify(&pubkey, &bin, None).unwrap_err().to_string().contains("does not match"));
        // Another key's signature, a wrong file in a key's place, a corrupt line.
        let other = d.join("other.key");
        keygen(&other).unwrap();
        sign(&other, &bin).unwrap();
        assert!(verify(&pubkey, &bin, None).is_err());
        assert!(verify(&key, &bin, None).unwrap_err().to_string().contains("not a midas-release-public-v1"));
        fs::write(&pubkey, "midas-release-public-v1 ****\n").unwrap();
        assert!(verify(&pubkey, &bin, None).is_err());
        let _ = fs::remove_dir_all(&d);
    }

    use std::os::unix::fs::PermissionsExt;
}