capsule_core/backup/mod.rs
1//! The portable backup artifact and recovery mechanisms (SSoT: [Backup and Recovery]).
2//!
3//! Two distinct things are kept separate:
4//! - the **backup artifact** — a deterministic, self-describing, signed tar of a
5//! library's encrypted blobs, metadata blobs, provenance chains, the AMK ledger needed
6//! to decrypt them, and each album's public authority ledger needed to verify them;
7//! - the **[master-key escrow](escrow_master_key)** — a small passphrase-wrapped blob that
8//! reconstructs the key hierarchy.
9//!
10//! Recovery rests on one rule: holding the recovery secret restores every asset, even after
11//! every device is lost. The artifact carries its own AMK ledger, so it is self-sufficient.
12//!
13//! [Backup and Recovery]: https://docs/design/backup-recovery/
14
15mod artifact;
16
17pub use artifact::{
18 BackupArtifact, BackupAsset, BackupDoc, BackupDocKind, BackupInput, CiphertextSource,
19 RestoreMode, RestoreReport, RestoredAsset, WRAP_PARAMS, export, export_to, export_with_salt,
20};
21/// The caller-chosen-cost export entry points. Gated identically to their definitions: a weak
22/// Argon2id cost yields a brute-forceable artifact, so reaching one takes `cfg(test)` or an
23/// explicit `test-support` line in the consuming manifest.
24#[cfg(any(test, feature = "test-support"))]
25pub use artifact::{export_with_params, export_with_params_to, export_with_salt_and_params};
26use thiserror::Error;
27
28use crate::crypto::primitives::DeviceTier;
29use crate::crypto::pwkdf::{self, WrappedSecret};
30use crate::crypto::{CryptoError, kdf, rng};
31
32/// The backup artifact format version.
33///
34/// - `1` — blobs, metadata, provenance, receipts, and the sealed AMK ledger.
35/// - `2` — adds an `authority/{album_id}` entry per album: its public admin-signed epoch
36/// ledger, so a restored asset verifies (#468). A format-1 artifact still opens; its albums
37/// restore readable but unverifiable. A format newer than this build is refused.
38///
39/// Format 2 also carries optional `docs/{album|stack}/{id}` entries: each album's and stack's
40/// label record, sealed under its album's AMK (#667). Additive, so no bump: an older format-2
41/// reader verifies them as manifest entries and otherwise ignores them, restoring the album as
42/// `Recovered album` exactly as before.
43///
44/// Format 2 likewise carries an optional `attestations/{asset_id}` entry per asset: its signed
45/// storage-attestation log, verbatim, as `receipts/{asset_id}` carries its receipt log (#747).
46/// Additive for the same reason: an older reader hash-checks it as a manifest entry and
47/// restores the asset without it.
48///
49/// Format 2 likewise carries an optional `library/attestation-keys.cbor` entry: the library's
50/// pinned attestation-key history, verbatim (#805). Additive again: an older reader hash-checks
51/// it and ignores it, and an artifact without it restores as before.
52pub const ARTIFACT_FORMAT_VERSION: u16 = 2;
53
54/// Errors from backup export/restore and recovery.
55#[derive(Debug, Error, PartialEq, Eq)]
56pub enum BackupError {
57 /// A reader/writer or archive structural failure.
58 #[error("backup io/format error: {0}")]
59 Format(String),
60 /// MANIFEST HMAC or exporter signature failed (tamper).
61 #[error("backup authentication failed: {0}")]
62 Auth(&'static str),
63 /// An entry's content hash did not match the manifest (corruption).
64 #[error("backup entry corrupt: {0}")]
65 Corrupt(String),
66 /// The AMK ledger is missing an `amk_version` an included asset references.
67 #[error("backup AMK ledger incomplete: missing {0}")]
68 AmkIncomplete(String),
69 /// The artifact pins an attestation-key history for `origin` that diverges from the one the
70 /// target library pins: each holds a key the other lacks. Neither is overwritten, and the
71 /// restore is refused before it writes anything.
72 #[error(
73 "backup attestation-key pin for {origin} diverges from the library's: {only_carried} \
74 key(s) only in the backup, {only_local} only in the library"
75 )]
76 AttestationKeyPinsDiverge {
77 /// The canonical origin whose two pinned histories diverge.
78 origin: String,
79 /// How many keys only the artifact's pin holds.
80 only_carried: usize,
81 /// How many keys only the library's pin holds.
82 only_local: usize,
83 },
84 /// The artifact's pinned attestation-key history could not be read, decoded or restored.
85 #[error("backup attestation-key pin: {0}")]
86 AttestationKeyPins(String),
87 /// Underlying cryptographic failure.
88 #[error(transparent)]
89 Crypto(#[from] CryptoError),
90}
91
92// ── Master-key escrow ───────────────────────────────────────────────────────
93
94/// Escrow the account master key under a recovery passphrase (Argon2id + AES-256-GCM).
95pub fn escrow_master_key(
96 master: &[u8; 32],
97 passphrase: &[u8],
98 tier: DeviceTier,
99) -> Result<WrappedSecret, BackupError> {
100 Ok(pwkdf::wrap(master, passphrase, tier)?)
101}
102
103/// Recover the master key from its escrow blob and the recovery passphrase.
104pub fn recover_master_key(
105 blob: &WrappedSecret,
106 passphrase: &[u8],
107) -> Result<[u8; 32], BackupError> {
108 let bytes = pwkdf::unwrap(blob, passphrase)?;
109 bytes
110 .as_slice()
111 .try_into()
112 .map_err(|_| BackupError::Auth("escrowed master key wrong length"))
113}
114
115// ── Recovery verification cadence ───────────────────────────────────
116
117/// Domain-separation label for the recovery-verification derived-tag compare
118/// (SSoT: [Backup — Recovery Verification Cadence]).
119///
120/// [Backup — Recovery Verification Cadence]: https://docs/design/backup-recovery/#recovery-verification-cadence
121pub const RECOVERY_VERIFY_V1: &[u8] = b"capsule-recovery-verify/v1";
122
123/// Outcome of a local recovery-secret verification.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum VerifyOutcome {
126 /// The entered secret unwraps the (cached) escrow to the device-held master key.
127 Verified,
128 /// The entered secret does not open the blob — wrong secret, or the cached
129 /// blob is stale after a rotation. Per the stale-cache rule the caller
130 /// refreshes the blob and retries once before recording a failure.
131 NotVerified,
132}
133
134/// Local-only verification that the user still holds the recovery secret:
135/// unwrap the cached escrow blob, then compare an HKDF-derived tag against the
136/// tag derived from the device-held master key (derived-tag compare — raw key
137/// bytes are never compared or surfaced). Zero network I/O by construction; the
138/// cadence, snooze, and refresh-before-fail policy live in the client.
139pub fn verify_recovery_secret(
140 cached_escrow: &WrappedSecret,
141 passphrase: &[u8],
142 device_master: &[u8; 32],
143) -> VerifyOutcome {
144 let Ok(unwrapped) = recover_master_key(cached_escrow, passphrase) else {
145 return VerifyOutcome::NotVerified;
146 };
147 let tag_a = kdf::hkdf_sha512(&unwrapped, b"", RECOVERY_VERIFY_V1, 32);
148 let tag_b = kdf::hkdf_sha512(device_master, b"", RECOVERY_VERIFY_V1, 32);
149 if tag_a == tag_b {
150 VerifyOutcome::Verified
151 } else {
152 VerifyOutcome::NotVerified
153 }
154}
155
156// ── Opt-in Shamir 2-of-3 social recovery ────────────────────────────────────
157
158/// Split a 32-byte recovery seed into 3 Shamir shares; any 2 reconstruct it, 1 reveals
159/// nothing. The default scheme from [Backup — Opt-in: Shamir Secret Sharing].
160///
161/// Each share is `x ‖ y` ([`SHAMIR_SHARE_LEN`] bytes), the encoding fixed by
162/// [Backup — Share Wire Format]; shares issued before the `sharks` → `blahaj` swap use the
163/// same encoding and recover unchanged.
164///
165/// [Backup — Opt-in: Shamir Secret Sharing]: https://docs/design/backup-recovery/#opt-in-shamir-secret-sharing
166/// [Backup — Share Wire Format]: https://docs/design/backup-recovery/#share-wire-format
167pub fn split_seed_2of3(seed: &[u8; 32]) -> Vec<Vec<u8>> {
168 let dealer = blahaj::Sharks(SHAMIR_THRESHOLD).dealer(seed);
169 let shares: Vec<Vec<u8>> = dealer.take(3).map(|s| Vec::from(&s)).collect();
170 tracing::debug!(
171 threshold = SHAMIR_THRESHOLD,
172 shares = shares.len(),
173 "shamir: split recovery seed"
174 );
175 shares
176}
177
178/// Shares needed to reconstruct the seed.
179const SHAMIR_THRESHOLD: u8 = 2;
180
181/// Encoded length of one share of the 32-byte seed: the evaluation point `x`, then 32 `y` bytes.
182pub const SHAMIR_SHARE_LEN: usize = 33;
183
184/// Reconstruct a seed from a set of Shamir shares (≥ 2 of the 3).
185///
186/// Every share must be [`SHAMIR_SHARE_LEN`] bytes with a nonzero `x`; fewer than two distinct
187/// `x` values is below threshold. Each is a [`BackupError::Format`].
188pub fn recover_seed(shares: &[Vec<u8>]) -> Result<Vec<u8>, BackupError> {
189 let parsed = shares
190 .iter()
191 .map(|b| {
192 if b.len() != SHAMIR_SHARE_LEN {
193 return Err(BackupError::Format(format!(
194 "malformed Shamir share: {} bytes, expected {SHAMIR_SHARE_LEN}",
195 b.len()
196 )));
197 }
198 if b[0] == 0 {
199 return Err(BackupError::Format(
200 "malformed Shamir share: evaluation point 0".into(),
201 ));
202 }
203 blahaj::Share::try_from(b.as_slice())
204 .map_err(|e| BackupError::Format(format!("malformed Shamir share: {e}")))
205 })
206 .collect::<Result<Vec<_>, _>>()?;
207 // Two shares at the same `x` with different `y` would interpolate to a wrong seed rather
208 // than fail, so a repeated evaluation point is refused outright.
209 for (i, share) in shares.iter().enumerate() {
210 if shares[..i].iter().any(|prior| prior[0] == share[0]) {
211 return Err(BackupError::Format(format!(
212 "Shamir recover: duplicate evaluation point {}",
213 share[0]
214 )));
215 }
216 }
217 let seed = blahaj::Sharks(SHAMIR_THRESHOLD)
218 .recover(parsed.iter())
219 .map_err(|e| BackupError::Format(format!("Shamir recover: {e}")))?;
220 tracing::debug!(shares = parsed.len(), "shamir: recovered seed");
221 Ok(seed)
222}
223
224/// Draw a fresh random 32-byte recovery seed.
225pub fn new_recovery_seed() -> [u8; 32] {
226 rng::random_array::<32>()
227}
228
229#[cfg(test)]
230mod tests;