diff --git a/Cargo.lock b/Cargo.lock index 00c3b9b..3086df3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1877,6 +1877,7 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" name = "iz-core" version = "0.1.0" dependencies = [ + "aws-lc-rs", "base64 0.23.1", "bytes", "calamine", diff --git a/README.md b/README.md index 109f210..0db3c74 100644 --- a/README.md +++ b/README.md @@ -139,9 +139,11 @@ With a `[backup]` section, iz writes a backup set into `dir` every `interval_hou - `iz.db`: a consistent copy of the database, - `attachments/`: the local attachment files, -- `manifest.json`: a SHA-256 for each file. +- `manifest.json`: a SHA-256 for each file, and +- `manifest.mac`: an HMAC-SHA256 of `manifest.json`, keyed from `iz.key`. -Backups do not copy `iz.key`. Keep that copy separately, as described in First run. +Backups do not copy `iz.key`. Keep that copy separately, as described in First run. A set can only be checked +and restored with the same `iz.key` that wrote it; a set without a valid `manifest.mac` is refused. Restore with the server stopped: @@ -151,7 +153,7 @@ iz restore --from /var/lib/iz/backups/ sudo systemctl start iz ``` -`iz restore` checks the set against `manifest.json` before it writes anything. A set that fails the +`iz restore` checks the set's `manifest.mac`, then the files against `manifest.json`, before it writes anything. A set that fails the check is not restored. Do not copy the live database file by hand: it is written while iz runs. ## Command line diff --git a/crates/iz-core/Cargo.toml b/crates/iz-core/Cargo.toml index 331a3f9..73984f0 100644 --- a/crates/iz-core/Cargo.toml +++ b/crates/iz-core/Cargo.toml @@ -10,6 +10,7 @@ publish = false workspace = true [dependencies] +aws-lc-rs.workspace = true base64.workspace = true bytes.workspace = true calamine.workspace = true diff --git a/crates/iz-core/src/manifest.rs b/crates/iz-core/src/manifest.rs index 47b236d..e83333e 100644 --- a/crates/iz-core/src/manifest.rs +++ b/crates/iz-core/src/manifest.rs @@ -8,15 +8,18 @@ //! file is in the directory that the manifest does not list. A manifest that is not valid JSON, or //! names another version, is refused too. //! -//! The manifest only detects changes to the set: someone who rewrites files and the manifest together -//! is not caught. Keeping the backup directory readable only by the service user is the protection -//! against that. +//! The manifest is authenticated. `manifest.mac` next to it holds the HMAC-SHA256 of the exact bytes of +//! `manifest.json`, keyed by a subkey of the instance key (`iz.key`, which lives outside the set). The +//! MAC is checked before the manifest is parsed or any listed file is read, so someone who can write to +//! the backup directory cannot change a file and its manifest consistently. Without the instance key a +//! set is refused. A set written before the MAC existed is refused too. use std::collections::BTreeSet; use std::fs::File; use std::io::Read; use std::path::{Component, Path, PathBuf}; +use aws_lc_rs::hmac; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; @@ -24,10 +27,17 @@ use crate::error::{Error, Result}; /// The file name of the manifest inside a set. pub const MANIFEST_NAME: &str = "manifest.json"; +/// The file name of the MAC of the manifest inside a set: lowercase hex of the 32-byte HMAC-SHA256. +pub const MAC_NAME: &str = "manifest.mac"; /// The only manifest version this build reads and writes. pub const MANIFEST_VERSION: u32 = 1; /// Largest manifest read, in bytes. Reason: a manifest lists files; a huge one is not ours. pub const MANIFEST_MAX_BYTES: u64 = 16 * 1024 * 1024; +/// Largest MAC file read, in bytes. Reason: the MAC is 64 hex digits; anything larger is not ours. +pub const MAC_MAX_BYTES: u64 = 256; +/// The label that derives the manifest subkey from the instance key. Reason: a distinct label keeps this +/// key separate from any other use of the instance key. +const MAC_LABEL: &[u8] = b"iz backup manifest v1"; /// One file of a set. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -70,6 +80,14 @@ pub fn digest_file(path: &Path) -> Result<(u64, String)> { Ok((size, hex::encode(hasher.finalize()))) } +/// The HMAC key for manifests: `HMAC-SHA256(instance key, MAC_LABEL)`, used as the key of the manifest MAC. +/// Using a derived subkey means the instance key itself is never the MAC key. +pub fn manifest_key(instance_key: &[u8; 32]) -> hmac::Key { + let master = hmac::Key::new(hmac::HMAC_SHA256, instance_key); + let subkey = hmac::sign(&master, MAC_LABEL); + hmac::Key::new(hmac::HMAC_SHA256, subkey.as_ref()) +} + /// Whether `path` is a safe relative set path: non-empty, no leading `/`, no `..`, no `.`, no empty /// component, no NUL or backslash. pub fn is_safe_relative(path: &str) -> bool { @@ -82,11 +100,13 @@ pub fn is_safe_relative(path: &str) -> bool { .all(|component| matches!(component, Component::Normal(_))) } -/// Writes `manifest.json` into `dir` with the given files. Each listed file must already exist in -/// `dir` and is hashed here, so the manifest describes what is on disk. The manifest is written to a -/// temporary name and renamed into place, so a crash leaves either no manifest or a whole one. +/// Writes `manifest.json` and `manifest.mac` into `dir` with the given files. Each listed file must already +/// exist in `dir` and is hashed here, so the manifest describes what is on disk. Both files are written to +/// a temporary name and renamed into place, the manifest first and the MAC last, so a crash leaves a set +/// without a MAC, which the verifier refuses. pub fn write_manifest( dir: &Path, + instance_key: &[u8; 32], created_at: &str, build: &str, paths: &[String], @@ -113,17 +133,25 @@ pub fn write_manifest( }; let json = serde_json::to_vec_pretty(&manifest) .map_err(|e| Error::Invalid(format!("encoding the manifest: {e}")))?; - let tmp = dir.join(format!("{MANIFEST_NAME}.tmp")); - std::fs::write(&tmp, json)?; - File::open(&tmp)?.sync_all()?; - std::fs::rename(&tmp, dir.join(MANIFEST_NAME))?; + let tag = hmac::sign(&manifest_key(instance_key), &json); + write_synced(dir, MANIFEST_NAME, &json)?; + write_synced(dir, MAC_NAME, hex::encode(tag.as_ref()).as_bytes())?; Ok(manifest) } -/// Reads and checks a set. Returns the manifest when every listed file matches its size and digest and -/// no other file sits in the set. Errors name the first problem found. -pub fn verify_set(dir: &Path) -> Result { - let manifest = read_manifest(&dir.join(MANIFEST_NAME))?; +/// Writes `bytes` to `dir/name` through a temporary name, fsynced, then renamed into place. +fn write_synced(dir: &Path, name: &str, bytes: &[u8]) -> Result<()> { + let tmp = dir.join(format!("{name}.tmp")); + std::fs::write(&tmp, bytes)?; + File::open(&tmp)?.sync_all()?; + std::fs::rename(&tmp, dir.join(name))?; + Ok(()) +} + +/// Reads and checks a set. The manifest's MAC is checked first; then every listed file must match its +/// size and digest, and no other file may sit in the set. Errors name the first problem found. +pub fn verify_set(dir: &Path, instance_key: &[u8; 32]) -> Result { + let manifest = read_manifest(dir, instance_key)?; let mut listed = BTreeSet::new(); for file in &manifest.files { if !is_safe_relative(&file.path) { @@ -152,22 +180,26 @@ pub fn verify_set(dir: &Path) -> Result { let mut on_disk = BTreeSet::new(); collect_files(dir, dir, &mut on_disk)?; on_disk.remove(MANIFEST_NAME); + on_disk.remove(MAC_NAME); if let Some(extra) = on_disk.difference(&listed).next() { return Err(refused(format!("not listed in the manifest: {extra}"))); } Ok(manifest) } -/// Reads the manifest with its size limit and checks its version. -pub fn read_manifest(path: &Path) -> Result { - let meta = std::fs::symlink_metadata(path) +/// Reads the manifest of the set in `dir`. The MAC is checked against the exact bytes read, in constant +/// time, before those bytes are parsed. Then the version is checked. +pub fn read_manifest(dir: &Path, instance_key: &[u8; 32]) -> Result { + let bytes = read_regular(&dir.join(MANIFEST_NAME), MANIFEST_MAX_BYTES) .map_err(|_| refused("the set has no manifest".to_owned()))?; - if !meta.file_type().is_file() || meta.len() > MANIFEST_MAX_BYTES { - return Err(refused( - "the manifest is not a regular file of a sane size".to_owned(), - )); - } - let bytes = std::fs::read(path)?; + let mac = read_regular(&dir.join(MAC_NAME), MAC_MAX_BYTES) + .map_err(|_| refused("the manifest has no MAC".to_owned()))?; + let tag = std::str::from_utf8(&mac) + .ok() + .and_then(|text| hex::decode(text.trim_end()).ok()) + .ok_or_else(|| refused("the manifest MAC is not valid hex".to_owned()))?; + hmac::verify(&manifest_key(instance_key), &bytes, &tag) + .map_err(|_| refused("the manifest does not match its MAC".to_owned()))?; let manifest: Manifest = serde_json::from_slice(&bytes) .map_err(|e| refused(format!("the manifest is not valid: {e}")))?; if manifest.version != MANIFEST_VERSION { @@ -179,6 +211,18 @@ pub fn read_manifest(path: &Path) -> Result { Ok(manifest) } +/// The bytes of a regular file that is not a link and is at most `max` bytes long. +fn read_regular(path: &Path, max: u64) -> Result> { + let meta = std::fs::symlink_metadata(path)?; + if !meta.file_type().is_file() || meta.len() > max { + return Err(Error::Invalid(format!( + "not a regular file of a sane size: {}", + path.display() + ))); + } + Ok(std::fs::read(path)?) +} + /// Every regular file below `root` as a `/`-separated path relative to `base`. Links and other /// non-regular entries are refused, so a set cannot hide a file behind a link. fn collect_files(base: &Path, dir: &Path, out: &mut BTreeSet) -> Result<()> { @@ -236,20 +280,26 @@ mod tests { #[test] fn a_tampered_file_or_an_extra_file_is_refused() { let dir = tempfile::tempdir().expect("temp dir"); + let key = [3u8; 32]; std::fs::write(dir.path().join("iz.db"), b"one").expect("write"); write_manifest( dir.path(), + &key, "2026-10-28T00:00:00.000000000Z", "t", &["iz.db".into()], ) .expect("manifest"); - verify_set(dir.path()).expect("a fresh set verifies"); + verify_set(dir.path(), &key).expect("a fresh set verifies"); + assert!( + verify_set(dir.path(), &[4u8; 32]).is_err(), + "another key is refused" + ); std::fs::write(dir.path().join("iz.db"), b"two").expect("tamper"); - assert!(verify_set(dir.path()).is_err()); + assert!(verify_set(dir.path(), &key).is_err()); std::fs::write(dir.path().join("iz.db"), b"one").expect("restore"); std::fs::write(dir.path().join("extra"), b"x").expect("extra"); - assert!(verify_set(dir.path()).is_err()); + assert!(verify_set(dir.path(), &key).is_err()); } } diff --git a/crates/iz-core/src/secret.rs b/crates/iz-core/src/secret.rs index 82f0eae..405f15a 100644 --- a/crates/iz-core/src/secret.rs +++ b/crates/iz-core/src/secret.rs @@ -49,7 +49,9 @@ fn create_key(path: &Path) -> std::io::Result<[u8; 32]> { Ok(key) } -fn read_key(path: &Path) -> Result<[u8; 32]> { +/// Reads an existing instance key at `path` without creating it. Refused like [`load_or_create_key`] +/// when the file is group or world accessible or has the wrong length. +pub fn read_key(path: &Path) -> Result<[u8; 32]> { #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; diff --git a/crates/iz-web/src/backup.rs b/crates/iz-web/src/backup.rs index b214e40..7746c28 100644 --- a/crates/iz-web/src/backup.rs +++ b/crates/iz-web/src/backup.rs @@ -4,7 +4,7 @@ //! //! A set is a directory named by its UTC stamp (for example `20261028T093000Z`). It holds `iz.db` (a //! `VACUUM INTO` snapshot), `attachments/` for every attachment whose bytes are local, and -//! `manifest.json` written last (`iz_core::manifest`). A set is built in `.tmp-` and renamed to its +//! `manifest.json` and `manifest.mac` written last (`iz_core::manifest`), the MAC keyed by the instance key. A set is built in `.tmp-` and renamed to its //! stamp only when complete, so a directory with a manifest is always a whole set. A failed set is removed. //! Only directories this worker created, or names that match the stamp pattern and hold a manifest, are ever //! deleted. Nothing is written in place. @@ -87,7 +87,7 @@ async fn run_once( }; let tmp = policy.dir.join(format!("{TMP_PREFIX}{}", new_id())); let outcome = tokio::select! { - result = write_set(&state.store, &state.config.data_dir, &tmp, &created_at) => result, + result = write_set(&state.store, &state.config.data_dir, &state.key, &tmp, &created_at) => result, _ = stop.wait_for(|stopped| *stopped) => { Err(Error::Io(std::io::Error::other("stopped before the set was finished"))) } @@ -114,9 +114,15 @@ async fn run_once( } } -/// Writes the files of one set into `tmp` and the manifest last. Returns the number of files listed, not -/// counting the manifest. The caller removes `tmp` on error. -async fn write_set(store: &Store, data_dir: &Path, tmp: &Path, created_at: &str) -> Result { +/// Writes the files of one set into `tmp` and the manifest and its MAC last. Returns the number of files +/// listed, not counting the manifest. The caller removes `tmp` on error. +async fn write_set( + store: &Store, + data_dir: &Path, + instance_key: &[u8; 32], + tmp: &Path, + created_at: &str, +) -> Result { create_dir(tmp, false)?; store.snapshot_to(&tmp.join(DB_FILE)).await?; let mut paths = vec![DB_FILE.to_owned()]; @@ -135,9 +141,12 @@ async fn write_set(store: &Store, data_dir: &Path, tmp: &Path, created_at: &str) let dir = tmp.to_owned(); let created = created_at.to_owned(); let build = env!("IZ_BUILD_SHA").to_owned(); - tokio::task::spawn_blocking(move || manifest::write_manifest(&dir, &created, &build, &paths)) - .await - .map_err(|error| Error::Io(std::io::Error::other(error)))??; + let key = *instance_key; + tokio::task::spawn_blocking(move || { + manifest::write_manifest(&dir, &key, &created, &build, &paths) + }) + .await + .map_err(|error| Error::Io(std::io::Error::other(error)))??; Ok(files) } @@ -235,12 +244,13 @@ mod tests { let store = Store::open(&dir.path().join("iz.db")).await.expect("store"); let tmp = dir.path().join(format!("{TMP_PREFIX}{}", new_id())); let created = "2026-10-28T09:30:00.000000000Z"; - write_set(&store, dir.path(), &tmp, created) + let key = [6u8; 32]; + write_set(&store, dir.path(), &key, &tmp, created) .await .expect("set written"); publish(&tmp, dir.path(), "20261028T093000Z").expect("published"); let published = dir.path().join("20261028T093000Z"); - let verified = manifest::verify_set(&published).expect("the set verifies"); + let verified = manifest::verify_set(&published, &key).expect("the set verifies"); assert_eq!(verified.created_at, created); assert!(verified.files.iter().any(|file| file.path == DB_FILE)); assert!(!tmp.exists(), "the temporary name is gone after the rename"); diff --git a/crates/iz-web/src/boot.rs b/crates/iz-web/src/boot.rs index ff5ccf8..9904fd6 100644 --- a/crates/iz-web/src/boot.rs +++ b/crates/iz-web/src/boot.rs @@ -29,7 +29,7 @@ use crate::security::{self, SecurityHeaders}; use crate::state::AppState; /// Name of the instance key file inside the data directory. -const KEY_FILE: &str = "iz.key"; +pub const KEY_FILE: &str = "iz.key"; /// The prefix of task keys (`IZ-42`) until the setting that changes it exists. Two to six capitals. const DEFAULT_KEY_PREFIX: &str = "IZ"; diff --git a/crates/iz-web/src/cli/export.rs b/crates/iz-web/src/cli/export.rs index 90c2b26..d2ab644 100644 --- a/crates/iz-web/src/cli/export.rs +++ b/crates/iz-web/src/cli/export.rs @@ -3,7 +3,7 @@ //! //! The directory holds `board.json` (the board, its tasks, assignees, dependencies, comments, activity, //! attachment metadata and the members named by those rows), `attachments/` for every attachment whose -//! bytes are on this disk, and `manifest.json` for all of them. An attachment whose bytes are elsewhere +//! bytes are on this disk, and `manifest.json` with its `manifest.mac` (HMAC under the instance key) for all of them. An attachment whose bytes are elsewhere //! (location `in`) or that is moving is listed with `"bytes": false`; the export then exits 1 after writing //! everything else, so an incomplete export is never silent. The output is refused unless `--out` is missing //! or an empty directory, and no path in it is built from anything but fixed names and validated ULIDs. No @@ -22,7 +22,7 @@ use iz_core::store::export::{AttachmentRow, ReadOnly}; use iz_core::time::now_stamp; use sha2::{Digest, Sha256}; -use super::{database_file, describe, existing_data_dir, fail, take_lock}; +use super::{database_file, describe, existing_data_dir, fail, instance_key, take_lock}; /// The file that holds the board. const BOARD_FILE: &str = "board.json"; @@ -45,10 +45,14 @@ pub async fn run(config_path: &Path, out: &Path) -> ExitCode { Ok(lock) => lock, Err(code) => return code, }; + let key = match instance_key(&data_dir) { + Ok(key) => key, + Err(message) => return fail(message), + }; if let Err(message) = prepare_out(out) { return fail(message); } - match write_export(&config, &data_dir, out).await { + match write_export(&config, &data_dir, out, &key).await { Ok(report) => { println!( "exported {} attachments with bytes and {} without to {}", @@ -104,7 +108,12 @@ fn prepare_out(out: &Path) -> Result<(), String> { /// Reads the database and writes the export. Every failure before the manifest leaves the directory /// partly written; the caller reports it and the operator removes it. -async fn write_export(config: &Config, data_dir: &Path, out: &Path) -> Result { +async fn write_export( + config: &Config, + data_dir: &Path, + out: &Path, + key: &[u8; 32], +) -> Result { let database = database_file(config)?; let db = ReadOnly::open(&database) .await @@ -187,7 +196,7 @@ async fn write_export(config: &Config, data_dir: &Path, out: &Path) -> Result Result { }) } +/// The instance key read from the data directory. It must exist: the commands that call this check or write +/// manifests under it, and never create a key on the way. +pub fn instance_key(data_dir: &Path) -> Result<[u8; 32], String> { + let path = data_dir.join(KEY_FILE); + secret::read_key(&path).map_err(|error| { + format!( + "the instance key {} cannot be used: {}", + path.display(), + describe(&error) + ) + }) +} + /// The database path, checked to be a regular file that is not a link. Nothing is created. pub fn database_file(config: &Config) -> Result { let meta = std::fs::symlink_metadata(&config.database).map_err(|error| { diff --git a/crates/iz-web/src/cli/restore.rs b/crates/iz-web/src/cli/restore.rs index 6b6ece3..873bd55 100644 --- a/crates/iz-web/src/cli/restore.rs +++ b/crates/iz-web/src/cli/restore.rs @@ -1,6 +1,7 @@ //! `iz restore --from `: replaces the database and the attachments with a verified backup set. //! -//! Order: verify the set with `manifest::verify_set`; check that the configured database is a regular file +//! Order: verify the set with `manifest::verify_set`, which checks the manifest's MAC under the instance key before +//! it trusts the manifest; check that the configured database is a regular file //! inside the data directory; copy the set's `iz.db` and attachments into a staging directory inside the data //! directory and check each copy against the manifest; run `integrity_check` and the migration check on the //! staged database. Nothing outside the staging directory changes until then. Only after that are the current @@ -21,7 +22,7 @@ use iz_core::staging::{ATTACHMENTS_DIR, blob_path}; use iz_core::store::export::{ReadOnly, migrations_problem}; use iz_core::store::new_id; -use super::{describe, existing_data_dir, fail, file_stamp, take_lock}; +use super::{describe, existing_data_dir, fail, file_stamp, instance_key, take_lock}; /// The database file name inside a backup set. Fixed: the set writer uses this name too. const SET_DB: &str = "iz.db"; @@ -50,7 +51,11 @@ pub async fn run(config_path: &Path, from: &Path) -> ExitCode { Ok(lock) => lock, Err(code) => return code, }; - match restore(&config, &data_dir, from).await { + let key = match instance_key(&data_dir) { + Ok(key) => key, + Err(message) => return fail(message), + }; + match restore(&config, &data_dir, from, &key).await { Ok(summary) => { println!("{summary}"); ExitCode::SUCCESS @@ -241,8 +246,13 @@ async fn check_staged(staged_db: &Path) -> Result<(), String> { } /// The whole restore. Returns the summary line on success. -async fn restore(config: &Config, data_dir: &Path, from: &Path) -> Result { - let manifest = manifest::verify_set(from).map_err(|error| describe(&error))?; +async fn restore( + config: &Config, + data_dir: &Path, + from: &Path, + key: &[u8; 32], +) -> Result { + let manifest = manifest::verify_set(from, key).map_err(|error| describe(&error))?; let attachment_ids = plan_set(&manifest)?; let db_target = database_target(config, data_dir)?; let attachments_dir = data_dir.join(ATTACHMENTS_DIR); @@ -416,11 +426,13 @@ mod tests { let data = root.path().join("data"); std::fs::create_dir_all(&set).expect("set dir"); std::fs::create_dir_all(&data).expect("data dir"); + let key = [5u8; 32]; let db = data.join("iz.db"); std::fs::write(&db, b"current database").expect("current db"); std::fs::write(set.join(SET_DB), b"backup database bytes").expect("set db"); write_manifest( &set, + &key, "2026-10-28T00:00:00.000000000Z", "test", &[SET_DB.to_owned()], @@ -437,9 +449,14 @@ mod tests { data.display(), )) .expect("config"); - let error = restore(&config, &data.canonicalize().expect("canonical"), &set) - .await - .expect_err("tampered set must be refused"); + let error = restore( + &config, + &data.canonicalize().expect("canonical"), + &set, + &key, + ) + .await + .expect_err("tampered set must be refused"); assert!( error.contains("changed since the set was written"), "got: {error}" diff --git a/docs/architecture.md b/docs/architecture.md index 8f5b0bf..875b1f8 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -218,7 +218,12 @@ manifest, and never writes outside `DIR`. `iz restore --from SET` verifies a bac database's `integrity_check` and contiguous migrations) before it replaces the database and attachments in the configured data directory, and keeps the files it replaces. `iz fsck` checks the database and the attachment bytes read-only. Every command except `export` refuses while a server holds `data_dir/iz.lock`. Backups are written by -the `[backup]` worker (`VACUUM INTO` plus attachment copies and `manifest.json`, see `iz_core::manifest`). +the `[backup]` worker (`VACUUM INTO` plus attachment copies, `manifest.json` and `manifest.mac`, see `iz_core::manifest`). +A set's manifest is authenticated: `manifest.mac` is the HMAC-SHA256 of the exact bytes of `manifest.json`, keyed by +`HMAC-SHA256(iz.key, "iz backup manifest v1")`. `verify_set` checks the MAC in constant time before it parses the +manifest or reads a listed file, so a set changed in place (file and manifest together) is refused. `export` writes +the same pair, and `restore` and `export` need the existing `iz.key` (they never create one). A set written before +the MAC existed is refused. ---