diff --git a/Cargo.lock b/Cargo.lock index 5f8b6c37..6f729290 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1062,6 +1062,7 @@ dependencies = [ "tokio", "tokio-test", "toml", + "toml_edit", "tower", "tower-http 0.7.0", "tracing", @@ -3591,6 +3592,7 @@ dependencies = [ "indexmap", "toml_datetime", "toml_parser", + "toml_writer", "winnow", ] diff --git a/Cargo.toml b/Cargo.toml index b4c1f0e5..95c284ef 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,7 @@ futures = "0.3" serde = { version = "1", features = ["derive"] } serde_json = "1" toml = "1.1" +toml_edit = "0.25" # Error handling anyhow = "1" diff --git a/docs/ENV-VARS.adoc b/docs/ENV-VARS.adoc index 8b069026..3e4872c2 100644 --- a/docs/ENV-VARS.adoc +++ b/docs/ENV-VARS.adoc @@ -64,6 +64,14 @@ environment override for this one. |`+APP_PORT+` / `+APP_HOST+` |host:port |`+[::]` / `+8081+` |`+container/entrypoint.sh+` |Read by the container entrypoint and passed to `+echidna server+` as flags. The binary itself does not read them. + +|`+ECHIDNA_SOLVER_MANIFEST+` |path |`+config/solver-manifest.toml+` +(relative to the working directory) |`+src/rust/integrity/solver_integrity.rs+` +(`+default_manifest_path+`), `+echidna integrity pin+` and +`+echidna integrity check+` |The solver binary manifest. An empty value +means the default. `+echidna integrity pin+` replaces placeholder hashes +with the SHAKE3-512 of the binaries found now; it refuses to change a real +hash that differs unless given `+--force+`. |=== === Training & evaluation (Julia) diff --git a/src/rust/cli/args.rs b/src/rust/cli/args.rs index 384622df..8611c315 100644 --- a/src/rust/cli/args.rs +++ b/src/rust/cli/args.rs @@ -192,6 +192,12 @@ pub(crate) enum Commands { op: DesignOp, }, + /// Pin solver binary hashes into the manifest, or check binaries against it + Integrity { + #[command(subcommand)] + op: IntegrityOp, + }, + /// Suggest tactic variants that close a failing lemma Suggest { /// Target in `:` form, e.g. `Foo.thy:bar` @@ -436,3 +442,31 @@ pub(crate) enum DesignOp { adopt_threshold: i64, }, } + +#[derive(Subcommand)] +pub(crate) enum IntegrityOp { + /// Replace placeholder hashes with the SHAKE3-512 of the binaries found + /// now. A real hash that differs is refused unless `--force` is given. + Pin { + /// Manifest path (default: $ECHIDNA_SOLVER_MANIFEST, else + /// config/solver-manifest.toml) + #[arg(long)] + manifest: Option, + /// Pin only these solvers (manifest keys); repeatable + #[arg(long)] + solver: Vec, + /// Replace a real hash that differs from the binary + #[arg(long)] + force: bool, + /// Report what would change without writing the manifest + #[arg(long)] + dry_run: bool, + }, + /// Hash every listed binary and print its status. Fails on `Tampered`. + Check { + /// Manifest path (default: $ECHIDNA_SOLVER_MANIFEST, else + /// config/solver-manifest.toml) + #[arg(long)] + manifest: Option, + }, +} diff --git a/src/rust/cli/integrity.rs b/src/rust/cli/integrity.rs new file mode 100644 index 00000000..f6265def --- /dev/null +++ b/src/rust/cli/integrity.rs @@ -0,0 +1,148 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell + +//! `echidna integrity`: pin solver binary hashes into the manifest, and +//! check the installed binaries against it. + +use super::IntegrityOp; +use anyhow::{Context, Result}; +use echidna::integrity::solver_integrity::{ + apply_pins, default_manifest_path, IntegrityChecker, IntegrityStatus, PinOutcome, +}; +use std::path::PathBuf; + +/// Integrity command. +/// +/// # Errors +/// +/// `pin` fails when the manifest cannot be read, parsed or written, when a +/// named solver is not in the manifest or not found, when a binary cannot be +/// read, or when a real hash differs from the binary and `--force` was not +/// given. It writes nothing in the last case. `check` fails when the +/// manifest cannot be read or when any binary is `Tampered`. +pub(crate) async fn integrity_command(op: IntegrityOp) -> Result<()> { + match op { + IntegrityOp::Pin { + manifest, + solver, + force, + dry_run, + } => pin( + manifest.unwrap_or_else(default_manifest_path), + &solver, + force, + dry_run, + ), + IntegrityOp::Check { manifest } => { + check(manifest.unwrap_or_else(default_manifest_path)).await + }, + } +} + +fn pin(path: PathBuf, solver: &[String], force: bool, dry_run: bool) -> Result<()> { + let checker = IntegrityChecker::from_manifest_file(&path)?; + let outcomes = checker.pin_entries(solver, force)?; + + let mut pins = std::collections::BTreeMap::new(); + let mut failures = Vec::new(); + for (name, outcome) in &outcomes { + match outcome { + PinOutcome::Pinned { hash, path } => { + println!("{name}: pinned {} ({})", short(hash), path.display()); + }, + PinOutcome::Unchanged { path } => { + println!("{name}: unchanged ({})", path.display()); + }, + PinOutcome::Repinned { old, hash, path } => { + println!( + "{name}: REPINNED {} -> {} ({}, --force)", + short(old), + short(hash), + path.display() + ); + }, + PinOutcome::Refused { + old, + computed, + path, + } => { + println!( + "{name}: REFUSED: manifest {} but binary {} ({})", + short(old), + short(computed), + path.display() + ); + failures.push(format!( + "{name}: the binary differs from its pinned hash (possible tampering); \ + re-pin with --force only if the change is expected" + )); + }, + PinOutcome::NotFound => { + println!("{name}: not found, left as is"); + if solver.contains(name) { + failures.push(format!("{name}: no binary found")); + } + }, + PinOutcome::Unreadable { path, error } => { + println!("{name}: UNREADABLE ({}): {error}", path.display()); + failures.push(format!("{name}: binary cannot be read")); + }, + } + if let Some(hash) = outcome.new_hash() { + pins.insert(name.clone(), hash.to_string()); + } + } + + if !failures.is_empty() { + anyhow::bail!( + "integrity pin wrote nothing to {}:\n {}", + path.display(), + failures.join("\n ") + ); + } + if pins.is_empty() { + println!("nothing to pin in {}", path.display()); + return Ok(()); + } + if dry_run { + println!( + "dry run: {} hash(es) not written to {}", + pins.len(), + path.display() + ); + return Ok(()); + } + let text = std::fs::read_to_string(&path) + .with_context(|| format!("Failed to read solver manifest: {}", path.display()))?; + let updated = apply_pins(&text, &pins)?; + std::fs::write(&path, updated) + .with_context(|| format!("Failed to write solver manifest: {}", path.display()))?; + println!("wrote {} hash(es) to {}", pins.len(), path.display()); + Ok(()) +} + +async fn check(path: PathBuf) -> Result<()> { + let checker = IntegrityChecker::from_manifest_file(&path)?; + let mut reports = checker.verify_all().await?; + reports.sort_by(|a, b| a.name.cmp(&b.name)); + let mut tampered = Vec::new(); + for r in &reports { + let at = r + .actual_path + .as_ref() + .map(|p| format!(" ({})", p.display())) + .unwrap_or_default(); + println!("{}: {:?}{at}", r.name, r.status); + if r.status == IntegrityStatus::Tampered { + tampered.push(r.name.clone()); + } + } + if !tampered.is_empty() { + anyhow::bail!("tampered solver binaries: {}", tampered.join(", ")); + } + Ok(()) +} + +fn short(hash: &str) -> &str { + hash.get(..16).unwrap_or(hash) +} diff --git a/src/rust/cli/mod.rs b/src/rust/cli/mod.rs index ecb5cc5e..ff7d26f8 100644 --- a/src/rust/cli/mod.rs +++ b/src/rust/cli/mod.rs @@ -8,6 +8,7 @@ mod args; mod corpus; mod design; +mod integrity; mod lexicon; mod prove; mod provers; @@ -19,6 +20,7 @@ mod verify; pub(crate) use args::*; pub(crate) use corpus::*; pub(crate) use design::*; +pub(crate) use integrity::*; pub(crate) use lexicon::*; pub(crate) use prove::*; pub(crate) use provers::*; diff --git a/src/rust/integrity/solver_integrity.rs b/src/rust/integrity/solver_integrity.rs index 2c0aeb21..6f549241 100644 --- a/src/rust/integrity/solver_integrity.rs +++ b/src/rust/integrity/solver_integrity.rs @@ -237,7 +237,7 @@ impl IntegrityChecker { }; // Check if manifest hash is a placeholder - if entry.shake3_512.starts_with("PLACEHOLDER") { + if entry.shake3_512.starts_with(PLACEHOLDER_PREFIX) { info!( "Solver {} has placeholder hash, computing initial hash", name @@ -424,6 +424,134 @@ pub fn integrity_gate( .peekable(); counting.peek().is_some() && counting.all(|r| r.status == IntegrityStatus::Verified) } + +/// A manifest hash that starts with this is a placeholder: it pins nothing. +pub const PLACEHOLDER_PREFIX: &str = "PLACEHOLDER"; + +/// The environment variable that names the solver manifest. +pub const SOLVER_MANIFEST_ENV: &str = "ECHIDNA_SOLVER_MANIFEST"; + +/// The solver manifest path: `$ECHIDNA_SOLVER_MANIFEST` when set and not +/// empty, otherwise `config/solver-manifest.toml` relative to the working +/// directory. +pub fn default_manifest_path() -> PathBuf { + match std::env::var_os(SOLVER_MANIFEST_ENV) { + Some(p) if !p.is_empty() => PathBuf::from(p), + _ => PathBuf::from("config/solver-manifest.toml"), + } +} + +/// What `IntegrityChecker::pin_entries` found for one manifest entry. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PinOutcome { + /// The placeholder is to be replaced by the computed hash. + Pinned { hash: String, path: PathBuf }, + /// The manifest already holds the computed hash. + Unchanged { path: PathBuf }, + /// A real manifest hash differs from the binary and `force` was given: + /// the computed hash replaces it. + Repinned { + old: String, + hash: String, + path: PathBuf, + }, + /// A real manifest hash differs from the binary and `force` was not + /// given: the manifest is left as it is. This can mean tampering. + Refused { + old: String, + computed: String, + path: PathBuf, + }, + /// No binary was found; the manifest entry is left as it is. + NotFound, + /// A binary was found but could not be read. + Unreadable { path: PathBuf, error: String }, +} + +impl PinOutcome { + /// The hash to write into the manifest, if any. + pub fn new_hash(&self) -> Option<&str> { + match self { + PinOutcome::Pinned { hash, .. } | PinOutcome::Repinned { hash, .. } => Some(hash), + _ => None, + } + } +} + +impl IntegrityChecker { + /// Compute what pinning would do for each manifest entry, or for the + /// entries named in `only` when it is not empty. Writes nothing. + /// + /// A placeholder is pinned to the SHAKE3-512 of the binary found now. + /// A real hash that differs is replaced only with `force`. This is an + /// explicit operator step; dispatch never pins. + pub fn pin_entries( + &self, + only: &[String], + force: bool, + ) -> Result> { + for name in only { + if !self.manifest.solvers.contains_key(name) { + anyhow::bail!("solver {name:?} is not in the manifest"); + } + } + let mut out = std::collections::BTreeMap::new(); + for (name, entry) in &self.manifest.solvers { + if !only.is_empty() && !only.contains(name) { + continue; + } + let outcome = match Self::find_solver_binary(entry) { + None => PinOutcome::NotFound, + Some(path) => match Self::compute_shake3_512(&path) { + Err(e) => PinOutcome::Unreadable { + path, + error: format!("{e:#}"), + }, + Ok(hash) if entry.shake3_512.starts_with(PLACEHOLDER_PREFIX) => { + PinOutcome::Pinned { hash, path } + }, + Ok(hash) if hash == entry.shake3_512 => PinOutcome::Unchanged { path }, + Ok(hash) if force => PinOutcome::Repinned { + old: entry.shake3_512.clone(), + hash, + path, + }, + Ok(computed) => PinOutcome::Refused { + old: entry.shake3_512.clone(), + computed, + path, + }, + }, + }; + out.insert(name.clone(), outcome); + } + Ok(out) + } +} + +/// Rewrite the `shake3_512` value of each solver named in `pins`, keeping +/// every comment, every other field and the order of the file. Fails when a +/// named solver has no `[solvers.]` table in `text`. +pub fn apply_pins(text: &str, pins: &std::collections::BTreeMap) -> Result { + let mut doc: toml_edit::DocumentMut = text + .parse() + .context("Failed to parse solver manifest TOML")?; + for (name, hash) in pins { + let item = doc + .get_mut("solvers") + .and_then(|s| s.as_table_like_mut()) + .and_then(|s| s.get_mut(name)) + .and_then(|e| e.as_table_like_mut()) + .and_then(|e| e.get_mut("shake3_512")) + .with_context(|| format!("solver {name:?} has no shake3_512 in the manifest"))?; + let decor = item.as_value().map(|v| v.decor().clone()); + *item = toml_edit::value(hash.as_str()); + if let (Some(decor), Some(v)) = (decor, item.as_value_mut()) { + *v.decor_mut() = decor; + } + } + Ok(doc.to_string()) +} #[cfg(test)] mod tests { use super::*; @@ -634,3 +762,149 @@ mod gate_tests { } } } + +#[cfg(test)] +mod pin_tests { + use super::*; + use std::io::Write; + use tempfile::NamedTempFile; + + fn entry(path: &Path, hash: &str) -> SolverManifestEntry { + SolverManifestEntry { + version: "1".to_string(), + shake3_512: hash.to_string(), + path: path.display().to_string(), + fallback_paths: vec![], + } + } + + fn binary(bytes: &[u8]) -> NamedTempFile { + let mut f = NamedTempFile::new().expect("temp file"); + f.write_all(bytes).expect("write"); + f + } + + fn checker(entries: Vec<(&str, SolverManifestEntry)>) -> IntegrityChecker { + IntegrityChecker::new(SolverManifest { + solvers: entries + .into_iter() + .map(|(k, e)| (k.to_string(), e)) + .collect(), + }) + } + + #[test] + fn placeholder_is_pinned_to_the_computed_hash() { + let bin = binary(b"solver one"); + let want = IntegrityChecker::compute_shake3_512(bin.path()).unwrap(); + let c = checker(vec![("z3", entry(bin.path(), PLACEHOLDER_PREFIX))]); + let out = c.pin_entries(&[], false).unwrap(); + assert_eq!( + out["z3"], + PinOutcome::Pinned { + hash: want, + path: bin.path().to_path_buf() + } + ); + } + + #[test] + fn matching_real_hash_is_unchanged() { + let bin = binary(b"solver two"); + let h = IntegrityChecker::compute_shake3_512(bin.path()).unwrap(); + let c = checker(vec![("z3", entry(bin.path(), &h))]); + let out = c.pin_entries(&[], false).unwrap(); + assert_eq!( + out["z3"], + PinOutcome::Unchanged { + path: bin.path().to_path_buf() + } + ); + } + + /// A real hash that no longer matches is a possible tamper: never + /// overwritten silently. + #[test] + fn differing_real_hash_is_refused_without_force() { + let bin = binary(b"solver three"); + let h = IntegrityChecker::compute_shake3_512(bin.path()).unwrap(); + let c = checker(vec![("z3", entry(bin.path(), "00"))]); + let out = c.pin_entries(&[], false).unwrap(); + assert_eq!( + out["z3"], + PinOutcome::Refused { + old: "00".to_string(), + computed: h.clone(), + path: bin.path().to_path_buf() + } + ); + let forced = c.pin_entries(&[], true).unwrap(); + assert_eq!( + forced["z3"], + PinOutcome::Repinned { + old: "00".to_string(), + hash: h, + path: bin.path().to_path_buf() + } + ); + } + + #[test] + fn absent_binary_is_not_found() { + let c = checker(vec![( + "z3", + entry( + Path::new("/nonexistent/echidna-pin-test-z3"), + PLACEHOLDER_PREFIX, + ), + )]); + let out = c.pin_entries(&[], false).unwrap(); + assert_eq!(out["z3"], PinOutcome::NotFound); + } + + #[test] + fn unknown_solver_name_is_an_error() { + let c = checker(vec![]); + assert!(c.pin_entries(&["nosuch".to_string()], false).is_err()); + } + + #[test] + fn only_named_solvers_are_pinned() { + let a = binary(b"a"); + let b = binary(b"b"); + let c = checker(vec![ + ("z3", entry(a.path(), PLACEHOLDER_PREFIX)), + ("cvc5", entry(b.path(), PLACEHOLDER_PREFIX)), + ]); + let out = c.pin_entries(&["cvc5".to_string()], false).unwrap(); + assert_eq!(out.len(), 1); + assert!(out.contains_key("cvc5")); + } + + /// apply_pins rewrites only the hashes it is given, and keeps comments, + /// order and every other field. + #[test] + fn apply_pins_keeps_the_rest_of_the_file() { + let text = "# header comment\n\n[solvers.z3]\nversion = \"4\"\nshake3_512 = \"PLACEHOLDER_COMPUTE_ON_FIRST_RUN\"\npath = \"/usr/bin/z3\"\n\n# cvc5 note\n[solvers.cvc5]\nversion = \"1\"\nshake3_512 = \"PLACEHOLDER_COMPUTE_ON_FIRST_RUN\"\npath = \"/usr/bin/cvc5\"\n"; + let mut pins = std::collections::BTreeMap::new(); + pins.insert("z3".to_string(), "abcd".to_string()); + let out = apply_pins(text, &pins).unwrap(); + assert_eq!( + out, + text.replacen("PLACEHOLDER_COMPUTE_ON_FIRST_RUN", "abcd", 1) + ); + let parsed: SolverManifest = toml::from_str(&out).unwrap(); + assert_eq!(parsed.solvers["z3"].shake3_512, "abcd"); + assert!(parsed.solvers["cvc5"] + .shake3_512 + .starts_with(PLACEHOLDER_PREFIX)); + } + + #[test] + fn apply_pins_rejects_an_unknown_solver() { + let text = "[solvers.z3]\nversion = \"4\"\nshake3_512 = \"x\"\npath = \"/usr/bin/z3\"\n"; + let mut pins = std::collections::BTreeMap::new(); + pins.insert("cvc5".to_string(), "abcd".to_string()); + assert!(apply_pins(text, &pins).is_err()); + } +} diff --git a/src/rust/main.rs b/src/rust/main.rs index 7508555c..b38e648c 100644 --- a/src/rust/main.rs +++ b/src/rust/main.rs @@ -155,6 +155,10 @@ async fn main() -> Result<()> { design_command(op, &formatter).await?; }, + Commands::Integrity { op } => { + integrity_command(op).await?; + }, + Commands::Suggest { target, prover,