From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [45.144.208.40]) by lore.proxmox.com (Postfix) with ESMTPS id 0463F1FF0C2 for ; Thu, 03 Dec 2026 16:05:33 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id C7F1A2182F; Thu, 03 Dec 2026 16:05:12 +0100 (CET) From: Christian Ebner To: pbs-devel@lists.proxmox.com Subject: [PATCH v2 proxmox-backup 5/9] server: pull: decouple decryption key gathering from logging Date: Thu, 3 Dec 2026 16:04:44 +0100 Message-ID: <20261203150448.412515-6-c.ebner@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261203150448.412515-1-c.ebner@proxmox.com> References: <20261203150448.412515-1-c.ebner@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1796310301483 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.329 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: C3W3Z2C6ZCGDHBGVWHP7TNW6UIQD7BZF X-Message-ID-Hash: C3W3Z2C6ZCGDHBGVWHP7TNW6UIQD7BZF X-MailFrom: c.ebner@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox Backup Server development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: optionally_use_decryption_key() decides which decryption key to use (if any), checking for matching fingerprint and signature and checks if the snapshot can be resynced or not if already existing on the target. In an effort to make the key gathering and chosen pull variant more transparent/readable and decouple it from the logging, make the helper a method of PullParameters so decryption key configs need not be passed as parameter, introduce intrinsically more descriptive enum variants as return values instead of plain types, and pull the logging completely out of the helper. No functional changes apart from not logging decryption key match in case of no resync since no data changes, which is in preparation for state checking under shared lock. Signed-off-by: Christian Ebner --- src/server/pull.rs | 360 ++++++++++++++++++++++++--------------------- 1 file changed, 196 insertions(+), 164 deletions(-) diff --git a/src/server/pull.rs b/src/server/pull.rs index 308ac752b..52be2edda 100644 --- a/src/server/pull.rs +++ b/src/server/pull.rs @@ -168,6 +168,159 @@ impl PullParameters { crypt_configs, }) } + + /// Decide whether a configured decryption key should be used to decrypt the snapshot during + /// pull based on the source manifest and an optional pre-existing target manifest. + fn optionally_use_decryption_key( + &self, + manifest: &BackupManifest, + existing_target_manifest: Option<&BackupManifest>, + prefix: &str, + ) -> Result { + let Some(key_fp) = manifest.fingerprint().with_context(|| prefix.to_owned())? else { + if let Some(existing_manifest) = existing_target_manifest { + if existing_manifest.fingerprint()?.is_some() { + bail!("refusing to overwrite local encrypted snapshot from unencrypted source"); + } else { + // Use a zero key to produce a deterministic content hash over the canonical, + // signature- and unprotected-stripped manifest. Equal output means equal + // protected content (files, csums, backup-time, ...). + let dummy = CryptConfig::new([0u8; 32])?; + if existing_manifest.signature(&dummy)? != manifest.signature(&dummy)? { + // neither source nor target encrypted, but manifests differ + bail!("refusing to overwrite local snapshot: content differs from source"); + } + } + } + + return Ok(PullVariant::Plain); + }; + + // check if source is encrypted or contents signed + let encrypted = manifest + .files() + .iter() + .all(|f| f.chunk_crypt_mode() == CryptMode::Encrypt); + + if let Some(existing_manifest) = existing_target_manifest { + if let Some(existing_fingerprint) = existing_manifest.fingerprint()? { + if existing_fingerprint == key_fp { + let target_encrypted = existing_manifest + .files() + .iter() + .all(|f| f.chunk_crypt_mode() == CryptMode::Encrypt); + if encrypted == target_encrypted { + // both sides are signed or encrypted with the same key, just resync + return Ok(PullVariant::Plain); + } + } else { + // pre-existing local manifest for encrypted snapshot with key mismatch + bail!( + "Local encrypted or signed snapshot with different key detected, \ + refuse to sync" + ); + } + } + }; + + // source got key fingerprint, expect contents to be signed or encrypted + let Some((key_id, config)) = self + .crypt_configs + .iter() + .find(|(_id, crypt_conf)| crypt_conf.fingerprint() == *key_fp.bytes()) + else { + // all the other cases are handled above + if encrypted && existing_target_manifest.is_some() { + bail!("No matching key found, refusing sync"); + } + + return Ok(if !self.crypt_configs.is_empty() { + PullVariant::NoMatchingKey + } else { + PullVariant::Plain + }); + }; + + // check if source is encrypted or contents signed + if !encrypted { + return Ok(PullVariant::NotFullyEncrypted { + key_id: key_id.clone(), + key_fp, + }); + } + + manifest + .check_signature(config, false) + .context("failed to check source manifest signature") + .with_context(|| prefix.to_owned())?; + + let mut skip_resync = false; + + // avoid overwriting pre-existing target manifest + if let Some(existing_manifest) = existing_target_manifest { + let source_fp = manifest + .get_sync_source_signature() + .context("failed to parse sync-source-signature of source manifest") + .with_context(|| prefix.to_owned())?; + let stored_source_fp = existing_manifest + .get_sync_source_signature() + .context("failed to parse sync-source-signature of existing target manifest") + .with_context(|| prefix.to_owned())?; + + if source_fp.is_none() && stored_source_fp.is_none() { + bail!("No sync-source-signature found, refuse to continue!"); + } + + if let Some(source_fp) = source_fp { + // Stored fp is HMAC over the unencrypted source's protected fields; recompute + // over the locally decrypted manifest, not the fresh encrypted remote one. + let target_fp = existing_manifest + .signature(config) + .with_context(|| prefix.to_owned())?; + skip_resync = skip_resync || target_fp == *source_fp.bytes(); + } + + if let Some(stored_source_fp) = stored_source_fp { + // Stored sync-source-signature is the source's prior signature on decrypt-pull + // (the flow this fallback handles); values set by encrypt-push hold a different + // HMAC input and fall through to the mismatch bail. + let Some(current) = &manifest.signature else { + bail!("No signature on source manifest."); + }; + let current: Fingerprint = current.parse().with_context(|| prefix.to_owned())?; + skip_resync = skip_resync || current == stored_source_fp; + } + + if !skip_resync { + bail!("sync-source-signature mismatch, refuse to continue!"); + } + } + + Ok(PullVariant::Decrypt { + key_id: key_id.clone(), + key_fp, + crypt_config: Arc::clone(config), + skip_resync, + }) + } +} + +/// Variant of pull sync specifying whether and how to decrypt a snapshot during pull. +enum PullVariant { + /// Pull without decryption + Plain, + /// Pull as-is, since configured decryption keys did not match the source snapshot's key + /// fingerprint. + NoMatchingKey, + /// Pull as-is, a matching key exists, but the snapshot is not fully encrypted. + NotFullyEncrypted { key_id: String, key_fp: Fingerprint }, + /// Decrypt archives on pull with the matching key or skip resync if target is already synced. + Decrypt { + key_id: String, + key_fp: Fingerprint, + crypt_config: Arc, + skip_resync: bool, + }, } async fn pull_index_chunks( @@ -744,24 +897,54 @@ async fn pull_snapshot<'a>( return Ok(None); } - let (crypt_config, new_manifest) = match optionally_use_decryption_key( - Arc::clone(¶ms), + let (crypt_config, new_manifest) = match params.optionally_use_decryption_key( &manifest, existing_target_manifest.as_ref(), - prefix.clone(), - Arc::clone(&log_sender), - ) - .await? - { - (None, false) => (None, None), // regular pull without decryption - (Some(crypt_config), false) => { - // decrypt while pull + &prefix, + )? { + PullVariant::Plain => (None, None), + PullVariant::NoMatchingKey => { + log_sender + .log( + Level::INFO, + format!("{prefix}: No matching key found, sync without decryption"), + ) + .await?; + (None, None) + } + PullVariant::NotFullyEncrypted { key_id, key_fp } => { + log_sender.log( + Level::WARN, + format!( + "Snapshot not fully encrypted, sync as is despite matching key '{key_id}' with \ + fingerprint {key_fp}" + ), + ).await?; + (None, None) + } + PullVariant::Decrypt { + crypt_config, + key_id, + key_fp, + skip_resync: false, + } => { + log_sender + .log( + Level::INFO, + format!( + "Found matching key '{key_id}' with fingerprint {key_fp}, decrypt on pull" + ), + ) + .await?; let new_manifest = Arc::new(Mutex::new(BackupManifest::new(snapshot.into()))); (Some(crypt_config), Some(new_manifest)) } - (crypt_config, true) => { - // nothing changed - fetch_log(crypt_config).await?; + PullVariant::Decrypt { + crypt_config, + skip_resync: true, + .. + } => { + fetch_log(Some(crypt_config)).await?; log_sender .log(Level::INFO, format!("{prefix}: no data changes")) .await?; @@ -933,157 +1116,6 @@ async fn pull_snapshot<'a>( Ok(Some(sync_stats)) } -/// Check if the decryption key should be used to decrypt the snapshot during -/// pull based on given pull parameter, source and optionally already present -/// target manifest. -/// -/// The boolean flag in the returned tuple indicates whether the pull can be -/// skipped altogether, since the already existing target is unchanged. -/// If decryption should happen, the matching decryption key is returned. -async fn optionally_use_decryption_key( - params: Arc, - manifest: &BackupManifest, - existing_target_manifest: Option<&BackupManifest>, - prefix: String, - log_sender: Arc, -) -> Result<(Option>, bool), Error> { - let Some(key_fp) = manifest.fingerprint().with_context(|| prefix.clone())? else { - if let Some(existing_manifest) = existing_target_manifest { - if existing_manifest.fingerprint()?.is_some() { - bail!("refusing to overwrite local encrypted snapshot from unencrypted source"); - } else { - // Use a zero key to produce a deterministic content hash over the canonical, - // signature- and unprotected-stripped manifest. Equal output means equal - // protected content (files, csums, backup-time, ...). - let dummy = CryptConfig::new([0u8; 32])?; - if existing_manifest.signature(&dummy)? != manifest.signature(&dummy)? { - // neither source nor target encrypted, but manifests differ - bail!("refusing to overwrite local snapshot: content differs from source"); - } - } - } - - return Ok((None, false)); // no fingerprint on source, regular pull - }; - - // check if source is encrypted or contents signed - let encrypted = manifest - .files() - .iter() - .all(|f| f.chunk_crypt_mode() == CryptMode::Encrypt); - - if let Some(existing_manifest) = existing_target_manifest { - if let Some(existing_fingerprint) = existing_manifest.fingerprint()? { - if existing_fingerprint == key_fp { - let target_encrypted = existing_manifest - .files() - .iter() - .all(|f| f.chunk_crypt_mode() == CryptMode::Encrypt); - if encrypted == target_encrypted { - // both sides are signed or encrypted with the same key, just resync - return Ok((None, false)); - } - } else { - // pre-existing local manifest for encrypted snapshot with key mismatch - bail!( - "Local encrypted or signed snapshot with different key detected, refuse to sync" - ); - } - } - }; - - // source got key fingerprint, expect contents to be signed or encrypted - let Some((key_id, config)) = params - .crypt_configs - .iter() - .find(|(_id, crypt_conf)| crypt_conf.fingerprint() == *key_fp.bytes()) - else { - // all the other cases are handled above - if encrypted && existing_target_manifest.is_some() { - bail!("No matching key found, refusing sync"); - } - - // regular sync - if !params.crypt_configs.is_empty() { - log_sender - .log( - Level::INFO, - format!("{prefix}: No matching key found, sync without decryption"), - ) - .await?; - } - - return Ok((None, false)); - }; - - // check if source is encrypted or contents signed - if !encrypted { - log_sender - .log( - Level::WARN, - format!("Snapshot not fully encrypted, sync as is despite matching key '{key_id}' with fingerprint {key_fp}"), - ) - .await?; - return Ok((None, false)); - } - - manifest - .check_signature(config, false) - .context("failed to check source manifest signature") - .with_context(|| prefix.clone())?; - - let mut skip_resync = false; - - // avoid overwriting pre-existing target manifest - if let Some(existing_manifest) = existing_target_manifest { - let source_fp = manifest - .get_sync_source_signature() - .context("failed to parse sync-source-signature of source manifest") - .with_context(|| prefix.clone())?; - let stored_source_fp = existing_manifest - .get_sync_source_signature() - .context("failed to parse sync-source-signature of existing target manifest") - .with_context(|| prefix.clone())?; - - if source_fp.is_none() && stored_source_fp.is_none() { - bail!("No sync-source-signature found, refuse to continue!"); - } - - if let Some(source_fp) = source_fp { - // Stored fp is HMAC over the unencrypted source's protected fields; recompute - // over the locally decrypted manifest, not the fresh encrypted remote one. - let target_fp = existing_manifest - .signature(config) - .with_context(|| prefix.clone())?; - skip_resync = skip_resync || target_fp == *source_fp.bytes(); - } - - if let Some(stored_source_fp) = stored_source_fp { - // Stored sync-source-signature is the source's prior signature on decrypt-pull - // (the flow this fallback handles); values set by encrypt-push hold a different - // HMAC input and fall through to the mismatch bail. - let Some(current) = &manifest.signature else { - bail!("No signature on source manifest."); - }; - let current: Fingerprint = current.parse().with_context(|| prefix.clone())?; - skip_resync = skip_resync || current == stored_source_fp; - } - - if !skip_resync { - bail!("sync-source-signature mismatch, refuse to continue!"); - } - } - - log_sender - .log( - Level::INFO, - format!("Found matching key '{key_id}' with fingerprint {key_fp}, decrypt on pull"), - ) - .await?; - - Ok((Some(Arc::clone(config)), skip_resync)) -} - /// Pulls a `snapshot`, removing newly created ones on error, but keeping existing ones in any case. /// /// The `reader` is configured to read from the source backup directory, while the -- 2.47.3