Backup manifest authenticated with HMAC keyed from iz.key
Browse files at this commit0982f5fecdc93d7a6297ad687ed2d98bd9c048e9Parent: 34f693b- fix
- backup manifest authenticated with HMAC keyed from iz.key
11 changed files +168 -55
- Cargo.lock +1 -0
- README.md +5 -3
- crates/iz-core/Cargo.toml +1 -0
- crates/iz-core/src/manifest.rs +76 -26
- crates/iz-core/src/secret.rs +3 -1
- crates/iz-web/src/backup.rs +20 -10
- crates/iz-web/src/boot.rs +1 -1
- crates/iz-web/src/cli/export.rs +14 -5
- crates/iz-web/src/cli/mod.rs +16 -0
- crates/iz-web/src/cli/restore.rs +25 -8
- docs/architecture.md +6 -1
Cargo.lockmodified+1 -0
| @@ -1877,6 +1877,7 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" | ||
| 1877 | 1877 | name = "iz-core" |
| 1878 | 1878 | version = "0.1.0" |
| 1879 | 1879 | dependencies = [ |
| 1880 | + "aws-lc-rs", | |
| 1880 | 1881 | "base64 0.23.1", |
| 1881 | 1882 | "bytes", |
| 1882 | 1883 | "calamine", |
README.mdmodified+5 -3
| @@ -139,9 +139,11 @@ With a `[backup]` section, iz writes a backup set into `dir` every `interval_hou | ||
| 139 | 139 | |
| 140 | 140 | - `iz.db`: a consistent copy of the database, |
| 141 | 141 | - `attachments/`: the local attachment files, |
| 142 | -- `manifest.json`: a SHA-256 for each file. | |
| 142 | +- `manifest.json`: a SHA-256 for each file, and | |
| 143 | +- `manifest.mac`: an HMAC-SHA256 of `manifest.json`, keyed from `iz.key`. | |
| 143 | 144 | |
| 144 | -Backups do not copy `iz.key`. Keep that copy separately, as described in First run. | |
| 145 | +Backups do not copy `iz.key`. Keep that copy separately, as described in First run. A set can only be checked | |
| 146 | +and restored with the same `iz.key` that wrote it; a set without a valid `manifest.mac` is refused. | |
| 145 | 147 | |
| 146 | 148 | Restore with the server stopped: |
| 147 | 149 | |
| @@ -151,7 +153,7 @@ iz restore --from /var/lib/iz/backups/<set dir> | ||
| 151 | 153 | sudo systemctl start iz |
| 152 | 154 | ``` |
| 153 | 155 | |
| 154 | -`iz restore` checks the set against `manifest.json` before it writes anything. A set that fails the | |
| 156 | +`iz restore` checks the set's `manifest.mac`, then the files against `manifest.json`, before it writes anything. A set that fails the | |
| 155 | 157 | check is not restored. Do not copy the live database file by hand: it is written while iz runs. |
| 156 | 158 | |
| 157 | 159 | ## Command line |
crates/iz-core/Cargo.tomlmodified+1 -0
| @@ -10,6 +10,7 @@ publish = false | ||
| 10 | 10 | workspace = true |
| 11 | 11 | |
| 12 | 12 | [dependencies] |
| 13 | +aws-lc-rs.workspace = true | |
| 13 | 14 | base64.workspace = true |
| 14 | 15 | bytes.workspace = true |
| 15 | 16 | calamine.workspace = true |
crates/iz-core/src/manifest.rsmodified+76 -26
| @@ -8,15 +8,18 @@ | ||
| 8 | 8 | //! file is in the directory that the manifest does not list. A manifest that is not valid JSON, or |
| 9 | 9 | //! names another version, is refused too. |
| 10 | 10 | //! |
| 11 | -//! The manifest only detects changes to the set: someone who rewrites files and the manifest together | |
| 12 | -//! is not caught. Keeping the backup directory readable only by the service user is the protection | |
| 13 | -//! against that. | |
| 11 | +//! The manifest is authenticated. `manifest.mac` next to it holds the HMAC-SHA256 of the exact bytes of | |
| 12 | +//! `manifest.json`, keyed by a subkey of the instance key (`iz.key`, which lives outside the set). The | |
| 13 | +//! MAC is checked before the manifest is parsed or any listed file is read, so someone who can write to | |
| 14 | +//! the backup directory cannot change a file and its manifest consistently. Without the instance key a | |
| 15 | +//! set is refused. A set written before the MAC existed is refused too. | |
| 14 | 16 | |
| 15 | 17 | use std::collections::BTreeSet; |
| 16 | 18 | use std::fs::File; |
| 17 | 19 | use std::io::Read; |
| 18 | 20 | use std::path::{Component, Path, PathBuf}; |
| 19 | 21 | |
| 22 | +use aws_lc_rs::hmac; | |
| 20 | 23 | use serde::{Deserialize, Serialize}; |
| 21 | 24 | use sha2::{Digest, Sha256}; |
| 22 | 25 | |
| @@ -24,10 +27,17 @@ use crate::error::{Error, Result}; | ||
| 24 | 27 | |
| 25 | 28 | /// The file name of the manifest inside a set. |
| 26 | 29 | pub const MANIFEST_NAME: &str = "manifest.json"; |
| 30 | +/// The file name of the MAC of the manifest inside a set: lowercase hex of the 32-byte HMAC-SHA256. | |
| 31 | +pub const MAC_NAME: &str = "manifest.mac"; | |
| 27 | 32 | /// The only manifest version this build reads and writes. |
| 28 | 33 | pub const MANIFEST_VERSION: u32 = 1; |
| 29 | 34 | /// Largest manifest read, in bytes. Reason: a manifest lists files; a huge one is not ours. |
| 30 | 35 | pub const MANIFEST_MAX_BYTES: u64 = 16 * 1024 * 1024; |
| 36 | +/// Largest MAC file read, in bytes. Reason: the MAC is 64 hex digits; anything larger is not ours. | |
| 37 | +pub const MAC_MAX_BYTES: u64 = 256; | |
| 38 | +/// The label that derives the manifest subkey from the instance key. Reason: a distinct label keeps this | |
| 39 | +/// key separate from any other use of the instance key. | |
| 40 | +const MAC_LABEL: &[u8] = b"iz backup manifest v1"; | |
| 31 | 41 | |
| 32 | 42 | /// One file of a set. |
| 33 | 43 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| @@ -70,6 +80,14 @@ pub fn digest_file(path: &Path) -> Result<(u64, String)> { | ||
| 70 | 80 | Ok((size, hex::encode(hasher.finalize()))) |
| 71 | 81 | } |
| 72 | 82 | |
| 83 | +/// The HMAC key for manifests: `HMAC-SHA256(instance key, MAC_LABEL)`, used as the key of the manifest MAC. | |
| 84 | +/// Using a derived subkey means the instance key itself is never the MAC key. | |
| 85 | +pub fn manifest_key(instance_key: &[u8; 32]) -> hmac::Key { | |
| 86 | + let master = hmac::Key::new(hmac::HMAC_SHA256, instance_key); | |
| 87 | + let subkey = hmac::sign(&master, MAC_LABEL); | |
| 88 | + hmac::Key::new(hmac::HMAC_SHA256, subkey.as_ref()) | |
| 89 | +} | |
| 90 | + | |
| 73 | 91 | /// Whether `path` is a safe relative set path: non-empty, no leading `/`, no `..`, no `.`, no empty |
| 74 | 92 | /// component, no NUL or backslash. |
| 75 | 93 | pub fn is_safe_relative(path: &str) -> bool { |
| @@ -82,11 +100,13 @@ pub fn is_safe_relative(path: &str) -> bool { | ||
| 82 | 100 | .all(|component| matches!(component, Component::Normal(_))) |
| 83 | 101 | } |
| 84 | 102 | |
| 85 | -/// Writes `manifest.json` into `dir` with the given files. Each listed file must already exist in | |
| 86 | -/// `dir` and is hashed here, so the manifest describes what is on disk. The manifest is written to a | |
| 87 | -/// temporary name and renamed into place, so a crash leaves either no manifest or a whole one. | |
| 103 | +/// Writes `manifest.json` and `manifest.mac` into `dir` with the given files. Each listed file must already | |
| 104 | +/// exist in `dir` and is hashed here, so the manifest describes what is on disk. Both files are written to | |
| 105 | +/// a temporary name and renamed into place, the manifest first and the MAC last, so a crash leaves a set | |
| 106 | +/// without a MAC, which the verifier refuses. | |
| 88 | 107 | pub fn write_manifest( |
| 89 | 108 | dir: &Path, |
| 109 | + instance_key: &[u8; 32], | |
| 90 | 110 | created_at: &str, |
| 91 | 111 | build: &str, |
| 92 | 112 | paths: &[String], |
| @@ -113,17 +133,25 @@ pub fn write_manifest( | ||
| 113 | 133 | }; |
| 114 | 134 | let json = serde_json::to_vec_pretty(&manifest) |
| 115 | 135 | .map_err(|e| Error::Invalid(format!("encoding the manifest: {e}")))?; |
| 116 | - let tmp = dir.join(format!("{MANIFEST_NAME}.tmp")); | |
| 117 | - std::fs::write(&tmp, json)?; | |
| 118 | - File::open(&tmp)?.sync_all()?; | |
| 119 | - std::fs::rename(&tmp, dir.join(MANIFEST_NAME))?; | |
| 136 | + let tag = hmac::sign(&manifest_key(instance_key), &json); | |
| 137 | + write_synced(dir, MANIFEST_NAME, &json)?; | |
| 138 | + write_synced(dir, MAC_NAME, hex::encode(tag.as_ref()).as_bytes())?; | |
| 120 | 139 | Ok(manifest) |
| 121 | 140 | } |
| 122 | 141 | |
| 123 | -/// Reads and checks a set. Returns the manifest when every listed file matches its size and digest and | |
| 124 | -/// no other file sits in the set. Errors name the first problem found. | |
| 125 | -pub fn verify_set(dir: &Path) -> Result<Manifest> { | |
| 126 | - let manifest = read_manifest(&dir.join(MANIFEST_NAME))?; | |
| 142 | +/// Writes `bytes` to `dir/name` through a temporary name, fsynced, then renamed into place. | |
| 143 | +fn write_synced(dir: &Path, name: &str, bytes: &[u8]) -> Result<()> { | |
| 144 | + let tmp = dir.join(format!("{name}.tmp")); | |
| 145 | + std::fs::write(&tmp, bytes)?; | |
| 146 | + File::open(&tmp)?.sync_all()?; | |
| 147 | + std::fs::rename(&tmp, dir.join(name))?; | |
| 148 | + Ok(()) | |
| 149 | +} | |
| 150 | + | |
| 151 | +/// Reads and checks a set. The manifest's MAC is checked first; then every listed file must match its | |
| 152 | +/// size and digest, and no other file may sit in the set. Errors name the first problem found. | |
| 153 | +pub fn verify_set(dir: &Path, instance_key: &[u8; 32]) -> Result<Manifest> { | |
| 154 | + let manifest = read_manifest(dir, instance_key)?; | |
| 127 | 155 | let mut listed = BTreeSet::new(); |
| 128 | 156 | for file in &manifest.files { |
| 129 | 157 | if !is_safe_relative(&file.path) { |
| @@ -152,22 +180,26 @@ pub fn verify_set(dir: &Path) -> Result<Manifest> { | ||
| 152 | 180 | let mut on_disk = BTreeSet::new(); |
| 153 | 181 | collect_files(dir, dir, &mut on_disk)?; |
| 154 | 182 | on_disk.remove(MANIFEST_NAME); |
| 183 | + on_disk.remove(MAC_NAME); | |
| 155 | 184 | if let Some(extra) = on_disk.difference(&listed).next() { |
| 156 | 185 | return Err(refused(format!("not listed in the manifest: {extra}"))); |
| 157 | 186 | } |
| 158 | 187 | Ok(manifest) |
| 159 | 188 | } |
| 160 | 189 | |
| 161 | -/// Reads the manifest with its size limit and checks its version. | |
| 162 | -pub fn read_manifest(path: &Path) -> Result<Manifest> { | |
| 163 | - let meta = std::fs::symlink_metadata(path) | |
| 190 | +/// Reads the manifest of the set in `dir`. The MAC is checked against the exact bytes read, in constant | |
| 191 | +/// time, before those bytes are parsed. Then the version is checked. | |
| 192 | +pub fn read_manifest(dir: &Path, instance_key: &[u8; 32]) -> Result<Manifest> { | |
| 193 | + let bytes = read_regular(&dir.join(MANIFEST_NAME), MANIFEST_MAX_BYTES) | |
| 164 | 194 | .map_err(|_| refused("the set has no manifest".to_owned()))?; |
| 165 | - if !meta.file_type().is_file() || meta.len() > MANIFEST_MAX_BYTES { | |
| 166 | - return Err(refused( | |
| 167 | - "the manifest is not a regular file of a sane size".to_owned(), | |
| 168 | - )); | |
| 169 | - } | |
| 170 | - let bytes = std::fs::read(path)?; | |
| 195 | + let mac = read_regular(&dir.join(MAC_NAME), MAC_MAX_BYTES) | |
| 196 | + .map_err(|_| refused("the manifest has no MAC".to_owned()))?; | |
| 197 | + let tag = std::str::from_utf8(&mac) | |
| 198 | + .ok() | |
| 199 | + .and_then(|text| hex::decode(text.trim_end()).ok()) | |
| 200 | + .ok_or_else(|| refused("the manifest MAC is not valid hex".to_owned()))?; | |
| 201 | + hmac::verify(&manifest_key(instance_key), &bytes, &tag) | |
| 202 | + .map_err(|_| refused("the manifest does not match its MAC".to_owned()))?; | |
| 171 | 203 | let manifest: Manifest = serde_json::from_slice(&bytes) |
| 172 | 204 | .map_err(|e| refused(format!("the manifest is not valid: {e}")))?; |
| 173 | 205 | if manifest.version != MANIFEST_VERSION { |
| @@ -179,6 +211,18 @@ pub fn read_manifest(path: &Path) -> Result<Manifest> { | ||
| 179 | 211 | Ok(manifest) |
| 180 | 212 | } |
| 181 | 213 | |
| 214 | +/// The bytes of a regular file that is not a link and is at most `max` bytes long. | |
| 215 | +fn read_regular(path: &Path, max: u64) -> Result<Vec<u8>> { | |
| 216 | + let meta = std::fs::symlink_metadata(path)?; | |
| 217 | + if !meta.file_type().is_file() || meta.len() > max { | |
| 218 | + return Err(Error::Invalid(format!( | |
| 219 | + "not a regular file of a sane size: {}", | |
| 220 | + path.display() | |
| 221 | + ))); | |
| 222 | + } | |
| 223 | + Ok(std::fs::read(path)?) | |
| 224 | +} | |
| 225 | + | |
| 182 | 226 | /// Every regular file below `root` as a `/`-separated path relative to `base`. Links and other |
| 183 | 227 | /// non-regular entries are refused, so a set cannot hide a file behind a link. |
| 184 | 228 | fn collect_files(base: &Path, dir: &Path, out: &mut BTreeSet<String>) -> Result<()> { |
| @@ -236,20 +280,26 @@ mod tests { | ||
| 236 | 280 | #[test] |
| 237 | 281 | fn a_tampered_file_or_an_extra_file_is_refused() { |
| 238 | 282 | let dir = tempfile::tempdir().expect("temp dir"); |
| 283 | + let key = [3u8; 32]; | |
| 239 | 284 | std::fs::write(dir.path().join("iz.db"), b"one").expect("write"); |
| 240 | 285 | write_manifest( |
| 241 | 286 | dir.path(), |
| 287 | + &key, | |
| 242 | 288 | "2026-10-28T00:00:00.000000000Z", |
| 243 | 289 | "t", |
| 244 | 290 | &["iz.db".into()], |
| 245 | 291 | ) |
| 246 | 292 | .expect("manifest"); |
| 247 | - verify_set(dir.path()).expect("a fresh set verifies"); | |
| 293 | + verify_set(dir.path(), &key).expect("a fresh set verifies"); | |
| 294 | + assert!( | |
| 295 | + verify_set(dir.path(), &[4u8; 32]).is_err(), | |
| 296 | + "another key is refused" | |
| 297 | + ); | |
| 248 | 298 | |
| 249 | 299 | std::fs::write(dir.path().join("iz.db"), b"two").expect("tamper"); |
| 250 | - assert!(verify_set(dir.path()).is_err()); | |
| 300 | + assert!(verify_set(dir.path(), &key).is_err()); | |
| 251 | 301 | std::fs::write(dir.path().join("iz.db"), b"one").expect("restore"); |
| 252 | 302 | std::fs::write(dir.path().join("extra"), b"x").expect("extra"); |
| 253 | - assert!(verify_set(dir.path()).is_err()); | |
| 303 | + assert!(verify_set(dir.path(), &key).is_err()); | |
| 254 | 304 | } |
| 255 | 305 | } |
crates/iz-core/src/secret.rsmodified+3 -1
| @@ -49,7 +49,9 @@ fn create_key(path: &Path) -> std::io::Result<[u8; 32]> { | ||
| 49 | 49 | Ok(key) |
| 50 | 50 | } |
| 51 | 51 | |
| 52 | -fn read_key(path: &Path) -> Result<[u8; 32]> { | |
| 52 | +/// Reads an existing instance key at `path` without creating it. Refused like [`load_or_create_key`] | |
| 53 | +/// when the file is group or world accessible or has the wrong length. | |
| 54 | +pub fn read_key(path: &Path) -> Result<[u8; 32]> { | |
| 53 | 55 | #[cfg(unix)] |
| 54 | 56 | { |
| 55 | 57 | use std::os::unix::fs::PermissionsExt; |
crates/iz-web/src/backup.rsmodified+20 -10
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | //! |
| 5 | 5 | //! A set is a directory named by its UTC stamp (for example `20261028T093000Z`). It holds `iz.db` (a |
| 6 | 6 | //! `VACUUM INTO` snapshot), `attachments/<id>` for every attachment whose bytes are local, and |
| 7 | -//! `manifest.json` written last (`iz_core::manifest`). A set is built in `.tmp-<ulid>` and renamed to its | |
| 7 | +//! `manifest.json` and `manifest.mac` written last (`iz_core::manifest`), the MAC keyed by the instance key. A set is built in `.tmp-<ulid>` and renamed to its | |
| 8 | 8 | //! stamp only when complete, so a directory with a manifest is always a whole set. A failed set is removed. |
| 9 | 9 | //! Only directories this worker created, or names that match the stamp pattern and hold a manifest, are ever |
| 10 | 10 | //! deleted. Nothing is written in place. |
| @@ -87,7 +87,7 @@ async fn run_once( | ||
| 87 | 87 | }; |
| 88 | 88 | let tmp = policy.dir.join(format!("{TMP_PREFIX}{}", new_id())); |
| 89 | 89 | let outcome = tokio::select! { |
| 90 | - result = write_set(&state.store, &state.config.data_dir, &tmp, &created_at) => result, | |
| 90 | + result = write_set(&state.store, &state.config.data_dir, &state.key, &tmp, &created_at) => result, | |
| 91 | 91 | _ = stop.wait_for(|stopped| *stopped) => { |
| 92 | 92 | Err(Error::Io(std::io::Error::other("stopped before the set was finished"))) |
| 93 | 93 | } |
| @@ -114,9 +114,15 @@ async fn run_once( | ||
| 114 | 114 | } |
| 115 | 115 | } |
| 116 | 116 | |
| 117 | -/// Writes the files of one set into `tmp` and the manifest last. Returns the number of files listed, not | |
| 118 | -/// counting the manifest. The caller removes `tmp` on error. | |
| 119 | -async fn write_set(store: &Store, data_dir: &Path, tmp: &Path, created_at: &str) -> Result<usize> { | |
| 117 | +/// Writes the files of one set into `tmp` and the manifest and its MAC last. Returns the number of files | |
| 118 | +/// listed, not counting the manifest. The caller removes `tmp` on error. | |
| 119 | +async fn write_set( | |
| 120 | + store: &Store, | |
| 121 | + data_dir: &Path, | |
| 122 | + instance_key: &[u8; 32], | |
| 123 | + tmp: &Path, | |
| 124 | + created_at: &str, | |
| 125 | +) -> Result<usize> { | |
| 120 | 126 | create_dir(tmp, false)?; |
| 121 | 127 | store.snapshot_to(&tmp.join(DB_FILE)).await?; |
| 122 | 128 | 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) | ||
| 135 | 141 | let dir = tmp.to_owned(); |
| 136 | 142 | let created = created_at.to_owned(); |
| 137 | 143 | let build = env!("IZ_BUILD_SHA").to_owned(); |
| 138 | - tokio::task::spawn_blocking(move || manifest::write_manifest(&dir, &created, &build, &paths)) | |
| 139 | - .await | |
| 140 | - .map_err(|error| Error::Io(std::io::Error::other(error)))??; | |
| 144 | + let key = *instance_key; | |
| 145 | + tokio::task::spawn_blocking(move || { | |
| 146 | + manifest::write_manifest(&dir, &key, &created, &build, &paths) | |
| 147 | + }) | |
| 148 | + .await | |
| 149 | + .map_err(|error| Error::Io(std::io::Error::other(error)))??; | |
| 141 | 150 | Ok(files) |
| 142 | 151 | } |
| 143 | 152 | |
| @@ -235,12 +244,13 @@ mod tests { | ||
| 235 | 244 | let store = Store::open(&dir.path().join("iz.db")).await.expect("store"); |
| 236 | 245 | let tmp = dir.path().join(format!("{TMP_PREFIX}{}", new_id())); |
| 237 | 246 | let created = "2026-10-28T09:30:00.000000000Z"; |
| 238 | - write_set(&store, dir.path(), &tmp, created) | |
| 247 | + let key = [6u8; 32]; | |
| 248 | + write_set(&store, dir.path(), &key, &tmp, created) | |
| 239 | 249 | .await |
| 240 | 250 | .expect("set written"); |
| 241 | 251 | publish(&tmp, dir.path(), "20261028T093000Z").expect("published"); |
| 242 | 252 | let published = dir.path().join("20261028T093000Z"); |
| 243 | - let verified = manifest::verify_set(&published).expect("the set verifies"); | |
| 253 | + let verified = manifest::verify_set(&published, &key).expect("the set verifies"); | |
| 244 | 254 | assert_eq!(verified.created_at, created); |
| 245 | 255 | assert!(verified.files.iter().any(|file| file.path == DB_FILE)); |
| 246 | 256 | assert!(!tmp.exists(), "the temporary name is gone after the rename"); |
crates/iz-web/src/boot.rsmodified+1 -1
| @@ -29,7 +29,7 @@ use crate::security::{self, SecurityHeaders}; | ||
| 29 | 29 | use crate::state::AppState; |
| 30 | 30 | |
| 31 | 31 | /// Name of the instance key file inside the data directory. |
| 32 | -const KEY_FILE: &str = "iz.key"; | |
| 32 | +pub const KEY_FILE: &str = "iz.key"; | |
| 33 | 33 | /// The prefix of task keys (`IZ-42`) until the setting that changes it exists. Two to six capitals. |
| 34 | 34 | const DEFAULT_KEY_PREFIX: &str = "IZ"; |
| 35 | 35 |
crates/iz-web/src/cli/export.rsmodified+14 -5
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | //! |
| 4 | 4 | //! The directory holds `board.json` (the board, its tasks, assignees, dependencies, comments, activity, |
| 5 | 5 | //! attachment metadata and the members named by those rows), `attachments/<id>` for every attachment whose |
| 6 | -//! bytes are on this disk, and `manifest.json` for all of them. An attachment whose bytes are elsewhere | |
| 6 | +//! 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 | |
| 7 | 7 | //! (location `in`) or that is moving is listed with `"bytes": false`; the export then exits 1 after writing |
| 8 | 8 | //! everything else, so an incomplete export is never silent. The output is refused unless `--out` is missing |
| 9 | 9 | //! 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}; | ||
| 22 | 22 | use iz_core::time::now_stamp; |
| 23 | 23 | use sha2::{Digest, Sha256}; |
| 24 | 24 | |
| 25 | -use super::{database_file, describe, existing_data_dir, fail, take_lock}; | |
| 25 | +use super::{database_file, describe, existing_data_dir, fail, instance_key, take_lock}; | |
| 26 | 26 | |
| 27 | 27 | /// The file that holds the board. |
| 28 | 28 | const BOARD_FILE: &str = "board.json"; |
| @@ -45,10 +45,14 @@ pub async fn run(config_path: &Path, out: &Path) -> ExitCode { | ||
| 45 | 45 | Ok(lock) => lock, |
| 46 | 46 | Err(code) => return code, |
| 47 | 47 | }; |
| 48 | + let key = match instance_key(&data_dir) { | |
| 49 | + Ok(key) => key, | |
| 50 | + Err(message) => return fail(message), | |
| 51 | + }; | |
| 48 | 52 | if let Err(message) = prepare_out(out) { |
| 49 | 53 | return fail(message); |
| 50 | 54 | } |
| 51 | - match write_export(&config, &data_dir, out).await { | |
| 55 | + match write_export(&config, &data_dir, out, &key).await { | |
| 52 | 56 | Ok(report) => { |
| 53 | 57 | println!( |
| 54 | 58 | "exported {} attachments with bytes and {} without to {}", |
| @@ -104,7 +108,12 @@ fn prepare_out(out: &Path) -> Result<(), String> { | ||
| 104 | 108 | |
| 105 | 109 | /// Reads the database and writes the export. Every failure before the manifest leaves the directory |
| 106 | 110 | /// partly written; the caller reports it and the operator removes it. |
| 107 | -async fn write_export(config: &Config, data_dir: &Path, out: &Path) -> Result<Report, String> { | |
| 111 | +async fn write_export( | |
| 112 | + config: &Config, | |
| 113 | + data_dir: &Path, | |
| 114 | + out: &Path, | |
| 115 | + key: &[u8; 32], | |
| 116 | +) -> Result<Report, String> { | |
| 108 | 117 | let database = database_file(config)?; |
| 109 | 118 | let db = ReadOnly::open(&database) |
| 110 | 119 | .await |
| @@ -187,7 +196,7 @@ async fn write_export(config: &Config, data_dir: &Path, out: &Path) -> Result<Re | ||
| 187 | 196 | .map_err(|error| format!("encoding {BOARD_FILE}: {error}"))?; |
| 188 | 197 | write_new(&out.join(BOARD_FILE), &bytes)?; |
| 189 | 198 | |
| 190 | - write_manifest(out, &now_stamp(), env!("IZ_BUILD_SHA"), &written) | |
| 199 | + write_manifest(out, key, &now_stamp(), env!("IZ_BUILD_SHA"), &written) | |
| 191 | 200 | .map_err(|error| describe(&error))?; |
| 192 | 201 | Ok(report) |
| 193 | 202 | } |
crates/iz-web/src/cli/mod.rsmodified+16 -0
| @@ -22,6 +22,9 @@ use std::process::ExitCode; | ||
| 22 | 22 | |
| 23 | 23 | use clap::{Parser, Subcommand}; |
| 24 | 24 | use iz_core::config::Config; |
| 25 | +use iz_core::secret; | |
| 26 | + | |
| 27 | +use crate::boot::KEY_FILE; | |
| 25 | 28 | |
| 26 | 29 | /// The file inside the data directory that carries the process lock. |
| 27 | 30 | pub const LOCK_FILE: &str = "iz.lock"; |
| @@ -133,6 +136,19 @@ pub fn existing_data_dir(config: &Config) -> Result<PathBuf, String> { | ||
| 133 | 136 | }) |
| 134 | 137 | } |
| 135 | 138 | |
| 139 | +/// The instance key read from the data directory. It must exist: the commands that call this check or write | |
| 140 | +/// manifests under it, and never create a key on the way. | |
| 141 | +pub fn instance_key(data_dir: &Path) -> Result<[u8; 32], String> { | |
| 142 | + let path = data_dir.join(KEY_FILE); | |
| 143 | + secret::read_key(&path).map_err(|error| { | |
| 144 | + format!( | |
| 145 | + "the instance key {} cannot be used: {}", | |
| 146 | + path.display(), | |
| 147 | + describe(&error) | |
| 148 | + ) | |
| 149 | + }) | |
| 150 | +} | |
| 151 | + | |
| 136 | 152 | /// The database path, checked to be a regular file that is not a link. Nothing is created. |
| 137 | 153 | pub fn database_file(config: &Config) -> Result<PathBuf, String> { |
| 138 | 154 | let meta = std::fs::symlink_metadata(&config.database).map_err(|error| { |
crates/iz-web/src/cli/restore.rsmodified+25 -8
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | //! `iz restore --from <set dir>`: replaces the database and the attachments with a verified backup set. |
| 2 | 2 | //! |
| 3 | -//! Order: verify the set with `manifest::verify_set`; check that the configured database is a regular file | |
| 3 | +//! Order: verify the set with `manifest::verify_set`, which checks the manifest's MAC under the instance key before | |
| 4 | +//! it trusts the manifest; check that the configured database is a regular file | |
| 4 | 5 | //! inside the data directory; copy the set's `iz.db` and attachments into a staging directory inside the data |
| 5 | 6 | //! directory and check each copy against the manifest; run `integrity_check` and the migration check on the |
| 6 | 7 | //! 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}; | ||
| 21 | 22 | use iz_core::store::export::{ReadOnly, migrations_problem}; |
| 22 | 23 | use iz_core::store::new_id; |
| 23 | 24 | |
| 24 | -use super::{describe, existing_data_dir, fail, file_stamp, take_lock}; | |
| 25 | +use super::{describe, existing_data_dir, fail, file_stamp, instance_key, take_lock}; | |
| 25 | 26 | |
| 26 | 27 | /// The database file name inside a backup set. Fixed: the set writer uses this name too. |
| 27 | 28 | const SET_DB: &str = "iz.db"; |
| @@ -50,7 +51,11 @@ pub async fn run(config_path: &Path, from: &Path) -> ExitCode { | ||
| 50 | 51 | Ok(lock) => lock, |
| 51 | 52 | Err(code) => return code, |
| 52 | 53 | }; |
| 53 | - match restore(&config, &data_dir, from).await { | |
| 54 | + let key = match instance_key(&data_dir) { | |
| 55 | + Ok(key) => key, | |
| 56 | + Err(message) => return fail(message), | |
| 57 | + }; | |
| 58 | + match restore(&config, &data_dir, from, &key).await { | |
| 54 | 59 | Ok(summary) => { |
| 55 | 60 | println!("{summary}"); |
| 56 | 61 | ExitCode::SUCCESS |
| @@ -241,8 +246,13 @@ async fn check_staged(staged_db: &Path) -> Result<(), String> { | ||
| 241 | 246 | } |
| 242 | 247 | |
| 243 | 248 | /// The whole restore. Returns the summary line on success. |
| 244 | -async fn restore(config: &Config, data_dir: &Path, from: &Path) -> Result<String, String> { | |
| 245 | - let manifest = manifest::verify_set(from).map_err(|error| describe(&error))?; | |
| 249 | +async fn restore( | |
| 250 | + config: &Config, | |
| 251 | + data_dir: &Path, | |
| 252 | + from: &Path, | |
| 253 | + key: &[u8; 32], | |
| 254 | +) -> Result<String, String> { | |
| 255 | + let manifest = manifest::verify_set(from, key).map_err(|error| describe(&error))?; | |
| 246 | 256 | let attachment_ids = plan_set(&manifest)?; |
| 247 | 257 | let db_target = database_target(config, data_dir)?; |
| 248 | 258 | let attachments_dir = data_dir.join(ATTACHMENTS_DIR); |
| @@ -416,11 +426,13 @@ mod tests { | ||
| 416 | 426 | let data = root.path().join("data"); |
| 417 | 427 | std::fs::create_dir_all(&set).expect("set dir"); |
| 418 | 428 | std::fs::create_dir_all(&data).expect("data dir"); |
| 429 | + let key = [5u8; 32]; | |
| 419 | 430 | let db = data.join("iz.db"); |
| 420 | 431 | std::fs::write(&db, b"current database").expect("current db"); |
| 421 | 432 | std::fs::write(set.join(SET_DB), b"backup database bytes").expect("set db"); |
| 422 | 433 | write_manifest( |
| 423 | 434 | &set, |
| 435 | + &key, | |
| 424 | 436 | "2026-10-28T00:00:00.000000000Z", |
| 425 | 437 | "test", |
| 426 | 438 | &[SET_DB.to_owned()], |
| @@ -437,9 +449,14 @@ mod tests { | ||
| 437 | 449 | data.display(), |
| 438 | 450 | )) |
| 439 | 451 | .expect("config"); |
| 440 | - let error = restore(&config, &data.canonicalize().expect("canonical"), &set) | |
| 441 | - .await | |
| 442 | - .expect_err("tampered set must be refused"); | |
| 452 | + let error = restore( | |
| 453 | + &config, | |
| 454 | + &data.canonicalize().expect("canonical"), | |
| 455 | + &set, | |
| 456 | + &key, | |
| 457 | + ) | |
| 458 | + .await | |
| 459 | + .expect_err("tampered set must be refused"); | |
| 443 | 460 | assert!( |
| 444 | 461 | error.contains("changed since the set was written"), |
| 445 | 462 | "got: {error}" |
docs/architecture.mdmodified+6 -1
| @@ -218,7 +218,12 @@ manifest, and never writes outside `DIR`. `iz restore --from SET` verifies a bac | ||
| 218 | 218 | database's `integrity_check` and contiguous migrations) before it replaces the database and attachments in the |
| 219 | 219 | configured data directory, and keeps the files it replaces. `iz fsck` checks the database and the attachment bytes |
| 220 | 220 | read-only. Every command except `export` refuses while a server holds `data_dir/iz.lock`. Backups are written by |
| 221 | -the `[backup]` worker (`VACUUM INTO` plus attachment copies and `manifest.json`, see `iz_core::manifest`). | |
| 221 | +the `[backup]` worker (`VACUUM INTO` plus attachment copies, `manifest.json` and `manifest.mac`, see `iz_core::manifest`). | |
| 222 | +A set's manifest is authenticated: `manifest.mac` is the HMAC-SHA256 of the exact bytes of `manifest.json`, keyed by | |
| 223 | +`HMAC-SHA256(iz.key, "iz backup manifest v1")`. `verify_set` checks the MAC in constant time before it parses the | |
| 224 | +manifest or reads a listed file, so a set changed in place (file and manifest together) is refused. `export` writes | |
| 225 | +the same pair, and `restore` and `export` need the existing `iz.key` (they never create one). A set written before | |
| 226 | +the MAC existed is refused. | |
| 222 | 227 | |
| 223 | 228 | --- |
| 224 | 229 |