Backup manifest authenticated with HMAC keyed from in.key
Browse files at this commitdd97953cd181712657ccb38a112ea5d6b7d6ea68Parent: 6e8ecae- fix
- backup manifest authenticated with HMAC keyed from in.key
7 changed files +165 -46
- README.md +7 -2
- crates/in-core/src/backup.rs +117 -34
- crates/in-core/src/secret.rs +14 -1
- crates/in-web/src/backup.rs +9 -2
- crates/in-web/src/boot.rs +1 -1
- crates/in-web/src/cli.rs +15 -5
- docs/architecture.md +2 -1
README.mdmodified+7 -2
| @@ -103,6 +103,10 @@ A set is a directory `set-<time>` in `dir`, holding: | |||
| 103 | 103 | ||
| 104 | - `in.db`: a consistent snapshot of the database (`VACUUM INTO`, checkpointed to one file). | 104 | - `in.db`: a consistent snapshot of the database (`VACUUM INTO`, checkpointed to one file). |
| 105 | - `manifest.json`: the snapshot's size and SHA-256, and every blob with its key, size and SHA-256. | 105 | - `manifest.json`: the snapshot's size and SHA-256, and every blob with its key, size and SHA-256. |
| 106 | +- `manifest.mac`: an HMAC-SHA256 of the exact bytes of `manifest.json`, keyed with a subkey of the instance key | ||
| 107 | + (`in.key`, in the data directory). Anyone who can write to the backup directory can rewrite a set, but cannot | ||
| 108 | + make an edited manifest pass without `in.key`. Keep `in.key` with the rest of the server's secrets, and back it | ||
| 109 | + up separately from the backup directory. | ||
| 106 | 110 | ||
| 107 | Blob bytes are not copied. Keep the blob tree (`data_dir/blobs`) under its own backup, or use an S3 bucket | 111 | Blob bytes are not copied. Keep the blob tree (`data_dir/blobs`) under its own backup, or use an S3 bucket |
| 108 | with its own versioning. The manifest is what lets `in fsck --hash` and a restore check what should be there. | 112 | with its own versioning. The manifest is what lets `in fsck --hash` and a restore check what should be there. |
| @@ -116,8 +120,9 @@ with its own versioning. The manifest is what lets `in fsck --hash` and a restor | |||
| 116 | in --config /etc/in/in.toml restore --from /var/lib/in/backups/set-2026-10-28T09-00-00-000000000Z | 120 | in --config /etc/in/in.toml restore --from /var/lib/in/backups/set-2026-10-28T09-00-00-000000000Z |
| 117 | ``` | 121 | ``` |
| 118 | 122 | ||
| 119 | - It checks the manifest format, the snapshot's size and hash, and the snapshot's integrity before it changes | 123 | + It checks the manifest's MAC against `in.key` first (a set without that key, or one that was edited, is |
| 120 | - anything. A set that fails a check is refused and nothing is replaced. The database it replaces is moved to | 124 | + refused), then the manifest format, the snapshot's size and hash, and the snapshot's integrity before it |
| 125 | + changes anything. A set that fails a check is refused and nothing is replaced. The database it replaces is moved to | ||
| 121 | `data_dir/restore-<time>/` and is not deleted. | 126 | `data_dir/restore-<time>/` and is not deleted. |
| 122 | 3. Run `in fsck` to see whether every row has its blob. Blobs listed in the manifest but missing from the blob | 127 | 3. Run `in fsck` to see whether every row has its blob. Blobs listed in the manifest but missing from the blob |
| 123 | tree are reported by the restore; they were deleted after the set was written. | 128 | tree are reported by the restore; they were deleted after the set was written. |
crates/in-core/src/backup.rsmodified+117 -34
| @@ -1,37 +1,49 @@ | |||
| 1 | //! Backup sets and restore. | 1 | //! Backup sets and restore. |
| 2 | //! | 2 | //! |
| 3 | //! A set is a directory `set-<stamp>` under the backup root, made of `in.db` (a consistent snapshot of the | 3 | //! A set is a directory `set-<stamp>` under the backup root, made of `in.db` (a consistent snapshot of the |
| 4 | -//! database, see `store/snapshot.rs`) and `manifest.json`. The manifest names the snapshot with its size | 4 | +//! database, see `store/snapshot.rs`), `manifest.json` and `manifest.mac`. The manifest names the snapshot |
| 5 | -//! and SHA-256, and lists every blob with its size and SHA-256. Blob bytes are not copied: the blob tree | 5 | +//! with its size and SHA-256, and lists every blob with its size and SHA-256. The MAC file holds an |
| 6 | -//! stays where it is, and the manifest is how a later check knows what should be there. A set is written | 6 | +//! HMAC-SHA256 over the exact manifest bytes, keyed with a subkey of the instance key (`in.key`, which lives |
| 7 | -//! under a temporary name and renamed into place only when its manifest is complete, so a half-written | 7 | +//! in the data directory, not in the backup set). Someone who can write to the backup directory can |
| 8 | -//! set is never mistaken for a good one. | 8 | +//! rewrite the snapshot and the manifest, but cannot make a changed manifest pass the MAC without the key. |
| 9 | +//! Blob bytes are not copied: the blob tree stays where it is, and the manifest is how a later check knows | ||
| 10 | +//! what should be there. A set is written under a temporary name and renamed into place only when its | ||
| 11 | +//! manifest and MAC are complete, so a half-written set is never mistaken for a good one. | ||
| 9 | //! | 12 | //! |
| 10 | -//! Restore verifies before it changes anything: the manifest format, the snapshot's size and hash, and | 13 | +//! Restore verifies before it changes anything: the MAC first, in constant time, before the manifest is |
| 11 | -//! the snapshot's `integrity_check` on a scratch copy. Only then does it move the current database aside | 14 | +//! parsed or trusted; then the manifest format, the snapshot's size and hash, and the snapshot's |
| 12 | -//! (into `data_dir/restore-<stamp>/`, not deleted) and put the snapshot in its place. It only replaces a | 15 | +//! `integrity_check` on a scratch copy. Only then does it move the current database aside (into |
| 13 | -//! database that lies inside the data directory. Restore must run with the server stopped; the CLI takes | 16 | +//! `data_dir/restore-<stamp>/`, not deleted) and put the snapshot in its place. It only replaces a database |
| 14 | -//! the data-directory lock first. | 17 | +//! that lies inside the data directory. Restore must run with the server stopped; the CLI takes the |
| 18 | +//! data-directory lock first. | ||
| 15 | 19 | ||
| 16 | use std::fs::OpenOptions; | 20 | use std::fs::OpenOptions; |
| 17 | use std::io::Write; | 21 | use std::io::Write; |
| 18 | use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; | 22 | use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; |
| 19 | use std::path::{Path, PathBuf}; | 23 | use std::path::{Path, PathBuf}; |
| 20 | 24 | ||
| 25 | +use hmac::{Hmac, KeyInit, Mac}; | ||
| 21 | use serde::{Deserialize, Serialize}; | 26 | use serde::{Deserialize, Serialize}; |
| 22 | use sha2::{Digest, Sha256}; | 27 | use sha2::{Digest, Sha256}; |
| 28 | +use subtle::ConstantTimeEq; | ||
| 23 | use turso::Builder; | 29 | use turso::Builder; |
| 24 | 30 | ||
| 25 | use crate::blob::{self, BlobStore}; | 31 | use crate::blob::{self, BlobStore}; |
| 26 | use crate::error::{Error, Result}; | 32 | use crate::error::{Error, Result}; |
| 33 | +use crate::secret; | ||
| 27 | use crate::store::{Store, col_text, db_err, fetch_all}; | 34 | use crate::store::{Store, col_text, db_err, fetch_all}; |
| 28 | 35 | ||
| 29 | -/// The only manifest format this build reads and writes. | 36 | +/// The only manifest format this build reads and writes. Format 1 had no MAC, so it is refused. |
| 30 | -pub const FORMAT: u32 = 1; | 37 | +pub const FORMAT: u32 = 2; |
| 31 | /// Name of the snapshot file inside a set. | 38 | /// Name of the snapshot file inside a set. |
| 32 | pub const DB_FILE: &str = "in.db"; | 39 | pub const DB_FILE: &str = "in.db"; |
| 33 | /// Name of the manifest file inside a set. | 40 | /// Name of the manifest file inside a set. |
| 34 | pub const MANIFEST_FILE: &str = "manifest.json"; | 41 | pub const MANIFEST_FILE: &str = "manifest.json"; |
| 42 | +/// Name of the MAC file inside a set: lower-case hex HMAC-SHA256 of the exact bytes of [`MANIFEST_FILE`]. | ||
| 43 | +pub const MAC_FILE: &str = "manifest.mac"; | ||
| 44 | +/// Label that derives the manifest MAC key from the instance key. Distinct from every other use of the | ||
| 45 | +/// instance key, so a MAC made for one purpose is never valid for another. | ||
| 46 | +const MAC_LABEL: &[u8] = b"in backup manifest v1"; | ||
| 35 | /// Prefix of a finished set's directory name. Pruning only ever removes directories with this prefix. | 47 | /// Prefix of a finished set's directory name. Pruning only ever removes directories with this prefix. |
| 36 | pub const SET_PREFIX: &str = "set-"; | 48 | pub const SET_PREFIX: &str = "set-"; |
| 37 | 49 | ||
| @@ -89,13 +101,24 @@ fn private_dir(path: &Path) -> Result<()> { | |||
| 89 | .map_err(Error::from) | 101 | .map_err(Error::from) |
| 90 | } | 102 | } |
| 91 | 103 | ||
| 104 | +/// The lower-case hex HMAC-SHA256 of `bytes` under the manifest subkey of `key`. | ||
| 105 | +fn manifest_mac(key: &[u8; 32], bytes: &[u8]) -> String { | ||
| 106 | + let subkey = secret::derive_subkey(key, MAC_LABEL); | ||
| 107 | + let mut mac = <Hmac<Sha256> as KeyInit>::new_from_slice(&subkey) | ||
| 108 | + .expect("HMAC accepts a key of any length"); | ||
| 109 | + mac.update(bytes); | ||
| 110 | + hex::encode(mac.finalize().into_bytes()) | ||
| 111 | +} | ||
| 112 | + | ||
| 92 | /// Writes a complete set under `root` and returns its directory. `stamp` names it, and must be safe in a | 113 | /// Writes a complete set under `root` and returns its directory. `stamp` names it, and must be safe in a |
| 93 | -/// file name: callers pass a time stamp with `:` and `.` replaced. | 114 | +/// file name: callers pass a time stamp with `:` and `.` replaced. `key` is the instance key that signs the |
| 115 | +/// manifest. | ||
| 94 | pub async fn write_set( | 116 | pub async fn write_set( |
| 95 | store: &Store, | 117 | store: &Store, |
| 96 | blobs: &dyn BlobStore, | 118 | blobs: &dyn BlobStore, |
| 97 | root: &Path, | 119 | root: &Path, |
| 98 | stamp: &str, | 120 | stamp: &str, |
| 121 | + key: &[u8; 32], | ||
| 99 | ) -> Result<PathBuf> { | 122 | ) -> Result<PathBuf> { |
| 100 | std::fs::create_dir_all(root)?; | 123 | std::fs::create_dir_all(root)?; |
| 101 | let tmp = root.join(format!(".tmp-{stamp}")); | 124 | let tmp = root.join(format!(".tmp-{stamp}")); |
| @@ -104,7 +127,7 @@ pub async fn write_set( | |||
| 104 | return Err(Error::Conflict(format!("set {stamp} already exists"))); | 127 | return Err(Error::Conflict(format!("set {stamp} already exists"))); |
| 105 | } | 128 | } |
| 106 | private_dir(&tmp)?; | 129 | private_dir(&tmp)?; |
| 107 | - let outcome = write_into(store, blobs, &tmp).await; | 130 | + let outcome = write_into(store, blobs, &tmp, key).await; |
| 108 | match outcome { | 131 | match outcome { |
| 109 | Ok(()) => { | 132 | Ok(()) => { |
| 110 | std::fs::rename(&tmp, &final_dir)?; | 133 | std::fs::rename(&tmp, &final_dir)?; |
| @@ -118,8 +141,13 @@ pub async fn write_set( | |||
| 118 | } | 141 | } |
| 119 | } | 142 | } |
| 120 | 143 | ||
| 121 | -/// Fills `dir` with the snapshot and the manifest, then fsyncs the directory. | 144 | +/// Fills `dir` with the snapshot, the manifest and its MAC, then fsyncs the directory. |
| 122 | -async fn write_into(store: &Store, blobs: &dyn BlobStore, dir: &Path) -> Result<()> { | 145 | +async fn write_into( |
| 146 | + store: &Store, | ||
| 147 | + blobs: &dyn BlobStore, | ||
| 148 | + dir: &Path, | ||
| 149 | + key: &[u8; 32], | ||
| 150 | +) -> Result<()> { | ||
| 123 | let db_path = dir.join(DB_FILE); | 151 | let db_path = dir.join(DB_FILE); |
| 124 | store.snapshot_to(&db_path).await?; | 152 | store.snapshot_to(&db_path).await?; |
| 125 | let (db_size, db_sha) = file_digest(&db_path)?; | 153 | let (db_size, db_sha) = file_digest(&db_path)?; |
| @@ -142,14 +170,24 @@ async fn write_into(store: &Store, blobs: &dyn BlobStore, dir: &Path) -> Result< | |||
| 142 | }; | 170 | }; |
| 143 | let text = serde_json::to_string_pretty(&manifest) | 171 | let text = serde_json::to_string_pretty(&manifest) |
| 144 | .map_err(|e| Error::Invalid(format!("manifest: {e}")))?; | 172 | .map_err(|e| Error::Invalid(format!("manifest: {e}")))?; |
| 173 | + write_private(&dir.join(MANIFEST_FILE), text.as_bytes())?; | ||
| 174 | + write_private( | ||
| 175 | + &dir.join(MAC_FILE), | ||
| 176 | + manifest_mac(key, text.as_bytes()).as_bytes(), | ||
| 177 | + )?; | ||
| 178 | + std::fs::File::open(dir)?.sync_all()?; | ||
| 179 | + Ok(()) | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +/// Creates a new file that only this user may read, with `bytes`, and syncs it. | ||
| 183 | +fn write_private(path: &Path, bytes: &[u8]) -> Result<()> { | ||
| 145 | let mut file = OpenOptions::new() | 184 | let mut file = OpenOptions::new() |
| 146 | .write(true) | 185 | .write(true) |
| 147 | .create_new(true) | 186 | .create_new(true) |
| 148 | .mode(0o600) | 187 | .mode(0o600) |
| 149 | - .open(dir.join(MANIFEST_FILE))?; | 188 | + .open(path)?; |
| 150 | - file.write_all(text.as_bytes())?; | 189 | + file.write_all(bytes)?; |
| 151 | file.sync_all()?; | 190 | file.sync_all()?; |
| 152 | - std::fs::File::open(dir)?.sync_all()?; | ||
| 153 | Ok(()) | 191 | Ok(()) |
| 154 | } | 192 | } |
| 155 | 193 | ||
| @@ -201,13 +239,20 @@ pub fn prune(root: &Path, keep: usize) -> Result<usize> { | |||
| 201 | Ok(excess) | 239 | Ok(excess) |
| 202 | } | 240 | } |
| 203 | 241 | ||
| 204 | -/// Reads and checks the manifest of a set: parses it, and refuses a format it does not know or a snapshot | 242 | +/// Reads and checks the manifest of a set. The MAC is compared first, in constant time, against the bytes |
| 243 | +/// on disk; only a manifest that passes is parsed. Then it refuses a format it does not know or a snapshot | ||
| 205 | /// name that is not [`DB_FILE`]. | 244 | /// name that is not [`DB_FILE`]. |
| 206 | -pub fn read_manifest(set: &Path) -> Result<Manifest> { | 245 | +pub fn read_manifest(set: &Path, key: &[u8; 32]) -> Result<Manifest> { |
| 207 | - let text = std::fs::read_to_string(set.join(MANIFEST_FILE)) | 246 | + let bytes = std::fs::read(set.join(MANIFEST_FILE)) |
| 208 | .map_err(|_| Error::Invalid("backup_manifest_missing".into()))?; | 247 | .map_err(|_| Error::Invalid("backup_manifest_missing".into()))?; |
| 248 | + let stored = std::fs::read_to_string(set.join(MAC_FILE)) | ||
| 249 | + .map_err(|_| Error::Invalid("backup_mac_missing".into()))?; | ||
| 250 | + let expected = manifest_mac(key, &bytes); | ||
| 251 | + if !bool::from(expected.as_bytes().ct_eq(stored.trim().as_bytes())) { | ||
| 252 | + return Err(Error::Invalid("backup_mac_bad".into())); | ||
| 253 | + } | ||
| 209 | let manifest: Manifest = | 254 | let manifest: Manifest = |
| 210 | - serde_json::from_str(&text).map_err(|_| Error::Invalid("backup_manifest_bad".into()))?; | 255 | + serde_json::from_slice(&bytes).map_err(|_| Error::Invalid("backup_manifest_bad".into()))?; |
| 211 | if manifest.format != FORMAT || manifest.database.file != DB_FILE { | 256 | if manifest.format != FORMAT || manifest.database.file != DB_FILE { |
| 212 | return Err(Error::Invalid("backup_manifest_bad".into())); | 257 | return Err(Error::Invalid("backup_manifest_bad".into())); |
| 213 | } | 258 | } |
| @@ -215,16 +260,18 @@ pub fn read_manifest(set: &Path) -> Result<Manifest> { | |||
| 215 | } | 260 | } |
| 216 | 261 | ||
| 217 | /// Restores the database from `set` into `database`, which must lie inside `data_dir`. Verifies the | 262 | /// Restores the database from `set` into `database`, which must lie inside `data_dir`. Verifies the |
| 218 | -/// manifest, the snapshot's size and hash, and its integrity before replacing anything. The previous | 263 | +/// manifest's MAC under `key`, then the manifest, the snapshot's size and hash, and its integrity before |
| 219 | -/// database, with its sidecar files, is moved into `data_dir/restore-<stamp>/`. | 264 | +/// replacing anything. The previous database, with its sidecar files, is moved into |
| 265 | +/// `data_dir/restore-<stamp>/`. | ||
| 220 | pub async fn restore( | 266 | pub async fn restore( |
| 221 | data_dir: &Path, | 267 | data_dir: &Path, |
| 222 | database: &Path, | 268 | database: &Path, |
| 223 | set: &Path, | 269 | set: &Path, |
| 224 | blobs: &dyn BlobStore, | 270 | blobs: &dyn BlobStore, |
| 271 | + key: &[u8; 32], | ||
| 225 | stamp: &str, | 272 | stamp: &str, |
| 226 | ) -> Result<RestoreOutcome> { | 273 | ) -> Result<RestoreOutcome> { |
| 227 | - let manifest = read_manifest(set)?; | 274 | + let manifest = read_manifest(set, key)?; |
| 228 | let source = set.join(DB_FILE); | 275 | let source = set.join(DB_FILE); |
| 229 | let (size, sha256) = | 276 | let (size, sha256) = |
| 230 | file_digest(&source).map_err(|_| Error::Invalid("backup_snapshot_missing".into()))?; | 277 | file_digest(&source).map_err(|_| Error::Invalid("backup_snapshot_missing".into()))?; |
| @@ -327,6 +374,16 @@ mod tests { | |||
| 327 | use crate::blob::local::LocalBlobs; | 374 | use crate::blob::local::LocalBlobs; |
| 328 | use crate::store::test_support::store_with_member; | 375 | use crate::store::test_support::store_with_member; |
| 329 | 376 | ||
| 377 | + /// Stands in for the instance key in these tests. | ||
| 378 | + const KEY: [u8; 32] = [9u8; 32]; | ||
| 379 | + | ||
| 380 | + /// Writes `manifest` into `set` and signs it with [`KEY`], as the writer would. | ||
| 381 | + fn sign_manifest(set: &Path, manifest: &Manifest) { | ||
| 382 | + let text = serde_json::to_string_pretty(manifest).unwrap(); | ||
| 383 | + std::fs::write(set.join(MANIFEST_FILE), &text).unwrap(); | ||
| 384 | + std::fs::write(set.join(MAC_FILE), manifest_mac(&KEY, text.as_bytes())).unwrap(); | ||
| 385 | + } | ||
| 386 | + | ||
| 330 | /// A store with one setting and one blob, a backup set of it, and the blob store. | 387 | /// A store with one setting and one blob, a backup set of it, and the blob store. |
| 331 | async fn source_with_set() -> (tempfile::TempDir, Store, LocalBlobs, PathBuf) { | 388 | async fn source_with_set() -> (tempfile::TempDir, Store, LocalBlobs, PathBuf) { |
| 332 | let (dir, store) = store_with_member("ann").await; | 389 | let (dir, store) = store_with_member("ann").await; |
| @@ -336,24 +393,30 @@ mod tests { | |||
| 336 | std::fs::write(&src, b"bytes").unwrap(); | 393 | std::fs::write(&src, b"bytes").unwrap(); |
| 337 | blobs.put_file("files/ab/one", &src).await.unwrap(); | 394 | blobs.put_file("files/ab/one", &src).await.unwrap(); |
| 338 | let root = dir.path().join("backups"); | 395 | let root = dir.path().join("backups"); |
| 339 | - let set = write_set(&store, &blobs, &root, "2026-10-28T00-00-00-000000000Z") | 396 | + let set = write_set( |
| 340 | - .await | 397 | + &store, |
| 341 | - .unwrap(); | 398 | + &blobs, |
| 399 | + &root, | ||
| 400 | + "2026-10-28T00-00-00-000000000Z", | ||
| 401 | + &KEY, | ||
| 402 | + ) | ||
| 403 | + .await | ||
| 404 | + .unwrap(); | ||
| 342 | (dir, store, blobs, set) | 405 | (dir, store, blobs, set) |
| 343 | } | 406 | } |
| 344 | 407 | ||
| 345 | #[tokio::test] | 408 | #[tokio::test] |
| 346 | async fn restore_refuses_a_manifest_with_a_wrong_hash() { | 409 | async fn restore_refuses_a_manifest_with_a_wrong_hash() { |
| 347 | let (dir, _store, blobs, set) = source_with_set().await; | 410 | let (dir, _store, blobs, set) = source_with_set().await; |
| 348 | - let manifest_path = set.join(MANIFEST_FILE); | 411 | + let mut manifest = read_manifest(&set, &KEY).unwrap(); |
| 349 | - let mut manifest = read_manifest(&set).unwrap(); | ||
| 350 | manifest.database.sha256 = "0".repeat(64); | 412 | manifest.database.sha256 = "0".repeat(64); |
| 351 | - std::fs::write(&manifest_path, serde_json::to_string(&manifest).unwrap()).unwrap(); | 413 | + // Signed with the right key, so only the snapshot hash check can refuse it. |
| 414 | + sign_manifest(&set, &manifest); | ||
| 352 | 415 | ||
| 353 | let data = dir.path().join("data"); | 416 | let data = dir.path().join("data"); |
| 354 | std::fs::create_dir_all(&data).unwrap(); | 417 | std::fs::create_dir_all(&data).unwrap(); |
| 355 | let database = data.join("in.db"); | 418 | let database = data.join("in.db"); |
| 356 | - let refused = restore(&data, &database, &set, &blobs, "20261028T000000Z").await; | 419 | + let refused = restore(&data, &database, &set, &blobs, &KEY, "20261028T000000Z").await; |
| 357 | assert!(matches!(refused, Err(Error::Invalid(ref w)) if w == "backup_hash")); | 420 | assert!(matches!(refused, Err(Error::Invalid(ref w)) if w == "backup_hash")); |
| 358 | assert!( | 421 | assert!( |
| 359 | !database.exists(), | 422 | !database.exists(), |
| @@ -361,6 +424,26 @@ mod tests { | |||
| 361 | ); | 424 | ); |
| 362 | } | 425 | } |
| 363 | 426 | ||
| 427 | + #[tokio::test] | ||
| 428 | + async fn restore_refuses_a_manifest_changed_without_the_key() { | ||
| 429 | + let (dir, _store, blobs, set) = source_with_set().await; | ||
| 430 | + // Someone with write access edits the manifest and fixes the snapshot hash, but cannot re-sign it. | ||
| 431 | + let mut manifest = read_manifest(&set, &KEY).unwrap(); | ||
| 432 | + manifest.database.sha256 = "0".repeat(64); | ||
| 433 | + std::fs::write( | ||
| 434 | + set.join(MANIFEST_FILE), | ||
| 435 | + serde_json::to_string_pretty(&manifest).unwrap(), | ||
| 436 | + ) | ||
| 437 | + .unwrap(); | ||
| 438 | + | ||
| 439 | + let data = dir.path().join("data"); | ||
| 440 | + std::fs::create_dir_all(&data).unwrap(); | ||
| 441 | + let database = data.join("in.db"); | ||
| 442 | + let refused = restore(&data, &database, &set, &blobs, &KEY, "20261028T000002Z").await; | ||
| 443 | + assert!(matches!(refused, Err(Error::Invalid(ref w)) if w == "backup_mac_bad")); | ||
| 444 | + assert!(!database.exists()); | ||
| 445 | + } | ||
| 446 | + | ||
| 364 | #[tokio::test] | 447 | #[tokio::test] |
| 365 | async fn restore_replaces_the_database_and_keeps_the_old_one() { | 448 | async fn restore_replaces_the_database_and_keeps_the_old_one() { |
| 366 | let (dir, store, blobs, set) = source_with_set().await; | 449 | let (dir, store, blobs, set) = source_with_set().await; |
| @@ -370,7 +453,7 @@ mod tests { | |||
| 370 | let database = data.join("in.db"); | 453 | let database = data.join("in.db"); |
| 371 | std::fs::write(&database, b"not a database").unwrap(); | 454 | std::fs::write(&database, b"not a database").unwrap(); |
| 372 | 455 | ||
| 373 | - let outcome = restore(&data, &database, &set, &blobs, "20261028T000001Z") | 456 | + let outcome = restore(&data, &database, &set, &blobs, &KEY, "20261028T000001Z") |
| 374 | .await | 457 | .await |
| 375 | .unwrap(); | 458 | .unwrap(); |
| 376 | assert_eq!(outcome.blobs_listed, 1); | 459 | assert_eq!(outcome.blobs_listed, 1); |
crates/in-core/src/secret.rsmodified+14 -1
| @@ -58,7 +58,9 @@ fn create_key(path: &Path) -> std::io::Result<[u8; 32]> { | |||
| 58 | Ok(key) | 58 | Ok(key) |
| 59 | } | 59 | } |
| 60 | 60 | ||
| 61 | -fn read_key(path: &Path) -> Result<[u8; 32]> { | 61 | +/// Reads an existing instance key without creating one. A key with group or world access, or of the wrong |
| 62 | +/// length, is refused. | ||
| 63 | +pub fn read_key(path: &Path) -> Result<[u8; 32]> { | ||
| 62 | #[cfg(unix)] | 64 | #[cfg(unix)] |
| 63 | { | 65 | { |
| 64 | use std::os::unix::fs::PermissionsExt; | 66 | use std::os::unix::fs::PermissionsExt; |
| @@ -110,6 +112,17 @@ pub fn unlock_proof(key: &[u8; 32], link_id: &str, password_hash: &str) -> Strin | |||
| 110 | hex::encode(mac.finalize().into_bytes()) | 112 | hex::encode(mac.finalize().into_bytes()) |
| 111 | } | 113 | } |
| 112 | 114 | ||
| 115 | +/// A 32-byte subkey for one purpose: HMAC-SHA256 of `label` under the instance key. Different labels give | ||
| 116 | +/// unrelated subkeys, so a key derived for one use cannot be replayed as the key of another. | ||
| 117 | +pub fn derive_subkey(master: &[u8; 32], label: &[u8]) -> [u8; 32] { | ||
| 118 | + let mut mac = <Hmac<Sha256> as hmac::KeyInit>::new_from_slice(master) | ||
| 119 | + .expect("HMAC accepts a key of any length"); | ||
| 120 | + mac.update(label); | ||
| 121 | + let mut subkey = [0u8; 32]; | ||
| 122 | + subkey.copy_from_slice(&mac.finalize().into_bytes()); | ||
| 123 | + subkey | ||
| 124 | +} | ||
| 125 | + | ||
| 113 | /// Opens a value produced by [`seal`]. A wrong key, a changed byte or a malformed value is an error. | 126 | /// Opens a value produced by [`seal`]. A wrong key, a changed byte or a malformed value is an error. |
| 114 | pub fn open(key: &[u8; 32], sealed: &str) -> Result<Vec<u8>> { | 127 | pub fn open(key: &[u8; 32], sealed: &str) -> Result<Vec<u8>> { |
| 115 | let encoded = sealed | 128 | let encoded = sealed |
crates/in-web/src/backup.rsmodified+9 -2
| @@ -1,4 +1,4 @@ | |||
| 1 | -//! The scheduled backup worker: writes a backup set (snapshot and blob manifest, see `in-core` `backup.rs`) | 1 | +//! The scheduled backup worker: writes a backup set (snapshot, blob manifest and its MAC, see `in-core` `backup.rs`) |
| 2 | //! every `interval_hours`, keeps the newest `keep` sets, and pings the dead-man URL after each good run. | 2 | //! every `interval_hours`, keeps the newest `keep` sets, and pings the dead-man URL after each good run. |
| 3 | //! | 3 | //! |
| 4 | //! A failed run is logged and the next one is tried at the next interval; a failed ping is logged and nothing | 4 | //! A failed run is logged and the next one is tried at the next interval; a failed ping is logged and nothing |
| @@ -21,7 +21,14 @@ pub const PING_TIMEOUT: Duration = Duration::from_secs(10); | |||
| 21 | async fn run_once(state: &AppState, config: &Backup) -> in_core::error::Result<std::path::PathBuf> { | 21 | async fn run_once(state: &AppState, config: &Backup) -> in_core::error::Result<std::path::PathBuf> { |
| 22 | // The stamp names the set; `:` and `.` are not wanted in file names. | 22 | // The stamp names the set; `:` and `.` are not wanted in file names. |
| 23 | let stamp = now_stamp().replace([':', '.'], "-"); | 23 | let stamp = now_stamp().replace([':', '.'], "-"); |
| 24 | - let set = backup::write_set(&state.store, state.blobs.as_ref(), &config.dir, &stamp).await?; | 24 | + let set = backup::write_set( |
| 25 | + &state.store, | ||
| 26 | + state.blobs.as_ref(), | ||
| 27 | + &config.dir, | ||
| 28 | + &stamp, | ||
| 29 | + &state.key, | ||
| 30 | + ) | ||
| 31 | + .await?; | ||
| 25 | let removed = backup::prune(&config.dir, config.keep as usize)?; | 32 | let removed = backup::prune(&config.dir, config.keep as usize)?; |
| 26 | tracing::info!(set = %set.display(), pruned = removed, "backup: set written"); | 33 | tracing::info!(set = %set.display(), pruned = removed, "backup: set written"); |
| 27 | Ok(set) | 34 | Ok(set) |
crates/in-web/src/boot.rsmodified+1 -1
| @@ -38,7 +38,7 @@ use crate::throttle::ShareThrottles; | |||
| 38 | use crate::thumbs_worker; | 38 | use crate::thumbs_worker; |
| 39 | 39 | ||
| 40 | /// Name of the instance key file inside the data directory. | 40 | /// Name of the instance key file inside the data directory. |
| 41 | -const KEY_FILE: &str = "in.key"; | 41 | +pub const KEY_FILE: &str = "in.key"; |
| 42 | 42 | ||
| 43 | /// Name of the lock file inside the data directory. A running server holds it; the operator commands take it | 43 | /// Name of the lock file inside the data directory. A running server holds it; the operator commands take it |
| 44 | /// too, so they refuse to run beside a server. | 44 | /// too, so they refuse to run beside a server. |
crates/in-web/src/cli.rsmodified+15 -5
| @@ -52,7 +52,7 @@ pub enum Command { | |||
| 52 | }, | 52 | }, |
| 53 | /// Replace the database with the one in a backup set. The server must be stopped. | 53 | /// Replace the database with the one in a backup set. The server must be stopped. |
| 54 | Restore { | 54 | Restore { |
| 55 | - /// The backup set directory (the one holding `in.db` and `manifest.json`). | 55 | + /// The backup set directory (the one holding `in.db`, `manifest.json` and `manifest.mac`). |
| 56 | #[arg(long, value_name = "SET")] | 56 | #[arg(long, value_name = "SET")] |
| 57 | from: PathBuf, | 57 | from: PathBuf, |
| 58 | }, | 58 | }, |
| @@ -173,16 +173,26 @@ async fn fsck_cmd(config: &Path, hash: bool) -> Result<bool, Error> { | |||
| 173 | Ok(report.is_clean()) | 173 | Ok(report.is_clean()) |
| 174 | } | 174 | } |
| 175 | 175 | ||
| 176 | -/// `in restore`. Opens nothing of the database itself: the snapshot is verified first, and only then is the | 176 | +/// `in restore`. Opens nothing of the database itself: the manifest's MAC is checked first (with the instance |
| 177 | -/// file replaced. True when the restore completed. | 177 | +/// key, which must already exist), then the snapshot is verified, and only then is the file replaced. True |
| 178 | +/// when the restore completed. | ||
| 178 | async fn restore(config_path: &Path, from: &Path) -> Result<bool, Error> { | 179 | async fn restore(config_path: &Path, from: &Path) -> Result<bool, Error> { |
| 179 | let config = in_core::config::Config::load(config_path)?; | 180 | let config = in_core::config::Config::load(config_path)?; |
| 180 | let _lock = boot::lock_data_dir(&config.data_dir)?; | 181 | let _lock = boot::lock_data_dir(&config.data_dir)?; |
| 181 | let data_dir = config.data_dir.canonicalize()?; | 182 | let data_dir = config.data_dir.canonicalize()?; |
| 183 | + // Read, never create: a missing key would make every set fail its MAC, and creating one here would hide that. | ||
| 184 | + let key = in_core::secret::read_key(&data_dir.join(boot::KEY_FILE))?; | ||
| 182 | let blobs = boot::open_blobs(&config, &data_dir)?; | 185 | let blobs = boot::open_blobs(&config, &data_dir)?; |
| 183 | let stamp = now_stamp().replace([':', '.'], "-"); | 186 | let stamp = now_stamp().replace([':', '.'], "-"); |
| 184 | - let outcome = | 187 | + let outcome = backup::restore( |
| 185 | - backup::restore(&data_dir, &config.database, from, blobs.as_ref(), &stamp).await?; | 188 | + &data_dir, |
| 189 | + &config.database, | ||
| 190 | + from, | ||
| 191 | + blobs.as_ref(), | ||
| 192 | + &key, | ||
| 193 | + &stamp, | ||
| 194 | + ) | ||
| 195 | + .await?; | ||
| 186 | println!( | 196 | println!( |
| 187 | "restored from {}: {} blobs listed, {} not in the blob tree", | 197 | "restored from {}: {} blobs listed, {} not in the blob tree", |
| 188 | from.display(), | 198 | from.display(), |
docs/architecture.mdmodified+2 -1
| @@ -218,7 +218,8 @@ and has no sessions. | |||
| 218 | - **thumbs**: picks `pending` files, generates thumbnails with bounded concurrency (2), marks ready/failed. | 218 | - **thumbs**: picks `pending` files, generates thumbnails with bounded concurrency (2), marks ready/failed. |
| 219 | - **sweeper** (hourly): expired sessions, expired uploads (staging removed), seen JTIs, trash past | 219 | - **sweeper** (hourly): expired sessions, expired uploads (staging removed), seen JTIs, trash past |
| 220 | `purge_after_days`, unreferenced blobs older than 24 h, quota drift check (nightly). | 220 | `purge_after_days`, unreferenced blobs older than 24 h, quota drift check (nightly). |
| 221 | -- **backup** (optional): snapshot + blob tree manifest, keep N, dead-man pings. | 221 | +- **backup** (optional): snapshot + blob tree manifest, HMAC-SHA256 over the manifest (`manifest.mac`, keyed from |
| 222 | + `in.key`, checked before a restore parses anything), keep N, dead-man pings. | ||
| 222 | 223 | ||
| 223 | --- | 224 | --- |
| 224 | 225 | ||