|
| 1 | +use std::fs::File; |
| 2 | +use std::io::{self, Read as _}; |
| 3 | +use std::path::Path; |
| 4 | + |
| 5 | +use ring::{digest, hmac}; |
| 6 | +use sanitization::SecretVec; |
| 7 | +use serde::{Deserialize, Serialize}; |
| 8 | + |
| 9 | +use crate::store::SnapshotError; |
| 10 | + |
| 11 | +pub(crate) const MAX_INTEGRITY_KEY_BYTES: u64 = 4096; |
| 12 | +const MIN_INTEGRITY_KEY_BYTES: usize = 32; |
| 13 | +const SNAPSHOT_MAC_LABEL: &[u8] = b"fluxheim-snapshot-v1\0"; |
| 14 | +const RECOVERY_MAC_LABEL: &[u8] = b"fluxheim-snapshot-recovery-v1\0"; |
| 15 | + |
| 16 | +#[derive(Debug)] |
| 17 | +pub(crate) struct SnapshotIntegrityKey { |
| 18 | + secret: SecretVec, |
| 19 | + key_id: String, |
| 20 | +} |
| 21 | + |
| 22 | +#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize)] |
| 23 | +#[serde(deny_unknown_fields)] |
| 24 | +pub(crate) struct SnapshotIntegrityManifest { |
| 25 | + pub algorithm: String, |
| 26 | + pub key_id: String, |
| 27 | + pub config_sha256: String, |
| 28 | + pub metadata_hmac_sha256: String, |
| 29 | +} |
| 30 | + |
| 31 | +impl SnapshotIntegrityKey { |
| 32 | + pub(crate) fn load(path: &Path) -> Result<Self, SnapshotError> { |
| 33 | + if fluxheim_config::fs_trust::existing_path_or_parent_has_insecure_write_permissions(path) |
| 34 | + .unwrap_or(true) |
| 35 | + { |
| 36 | + return Err(SnapshotError::UnsafeIntegrityKey { |
| 37 | + path: path.to_path_buf(), |
| 38 | + }); |
| 39 | + } |
| 40 | + let mut file = open_secret_file(path)?; |
| 41 | + let metadata = file.metadata().map_err(SnapshotError::Io)?; |
| 42 | + if !metadata.is_file() || metadata.len() > MAX_INTEGRITY_KEY_BYTES { |
| 43 | + return Err(SnapshotError::InvalidIntegrityKey); |
| 44 | + } |
| 45 | + let admitted = |
| 46 | + usize::try_from(metadata.len()).map_err(|_| SnapshotError::InvalidIntegrityKey)?; |
| 47 | + let mut secret = SecretVec::from_fn(admitted, |_| 0); |
| 48 | + secret |
| 49 | + .with_secret_mut(|bytes| file.read_exact(bytes)) |
| 50 | + .map_err(SnapshotError::Io)?; |
| 51 | + let mut growth_probe = [0u8; 1]; |
| 52 | + let grew = file.read(&mut growth_probe).map_err(SnapshotError::Io)? != 0; |
| 53 | + sanitization::sanitize_bytes(&mut growth_probe); |
| 54 | + if grew || secret.with_secret(|bytes| bytes.len()) < MIN_INTEGRITY_KEY_BYTES { |
| 55 | + return Err(SnapshotError::InvalidIntegrityKey); |
| 56 | + } |
| 57 | + let key_id = |
| 58 | + secret.with_secret(|bytes| hex(digest::digest(&digest::SHA256, bytes).as_ref())); |
| 59 | + Ok(Self { secret, key_id }) |
| 60 | + } |
| 61 | + |
| 62 | + pub(crate) fn manifest( |
| 63 | + &self, |
| 64 | + id: &str, |
| 65 | + config: &[u8], |
| 66 | + metadata: &[u8], |
| 67 | + ) -> SnapshotIntegrityManifest { |
| 68 | + SnapshotIntegrityManifest { |
| 69 | + algorithm: "hmac-sha256".to_owned(), |
| 70 | + key_id: self.key_id.clone(), |
| 71 | + config_sha256: hex(digest::digest(&digest::SHA256, config).as_ref()), |
| 72 | + metadata_hmac_sha256: hex(self.sign(id, config, metadata).as_ref()), |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + pub(crate) fn key_id(&self) -> &str { |
| 77 | + &self.key_id |
| 78 | + } |
| 79 | + |
| 80 | + pub(crate) fn sign_recovery(&self, state: &[u8]) -> String { |
| 81 | + self.secret.with_secret(|secret| { |
| 82 | + let key = hmac::Key::new(hmac::HMAC_SHA256, secret); |
| 83 | + let mut context = hmac::Context::with_key(&key); |
| 84 | + context.update(RECOVERY_MAC_LABEL); |
| 85 | + context.update(&(state.len() as u64).to_be_bytes()); |
| 86 | + context.update(state); |
| 87 | + hex(context.sign().as_ref()) |
| 88 | + }) |
| 89 | + } |
| 90 | + |
| 91 | + pub(crate) fn verify_recovery(&self, state: &[u8], signature: &str) -> bool { |
| 92 | + let Some(signature) = decode_hex_32(signature) else { |
| 93 | + return false; |
| 94 | + }; |
| 95 | + self.secret.with_secret(|secret| { |
| 96 | + let key = hmac::Key::new(hmac::HMAC_SHA256, secret); |
| 97 | + let mut input = Vec::with_capacity(RECOVERY_MAC_LABEL.len() + state.len() + 8); |
| 98 | + input.extend_from_slice(RECOVERY_MAC_LABEL); |
| 99 | + input.extend_from_slice(&(state.len() as u64).to_be_bytes()); |
| 100 | + input.extend_from_slice(state); |
| 101 | + hmac::verify(&key, &input, &signature).is_ok() |
| 102 | + }) |
| 103 | + } |
| 104 | + |
| 105 | + pub(crate) fn verify( |
| 106 | + &self, |
| 107 | + id: &str, |
| 108 | + config: &[u8], |
| 109 | + metadata: &[u8], |
| 110 | + manifest: &SnapshotIntegrityManifest, |
| 111 | + ) -> Result<(), SnapshotError> { |
| 112 | + if manifest.algorithm != "hmac-sha256" || manifest.key_id != self.key_id { |
| 113 | + return Err(SnapshotError::IntegrityVerificationFailed { id: id.to_owned() }); |
| 114 | + } |
| 115 | + let config_digest = hex(digest::digest(&digest::SHA256, config).as_ref()); |
| 116 | + if config_digest != manifest.config_sha256 { |
| 117 | + return Err(SnapshotError::IntegrityVerificationFailed { id: id.to_owned() }); |
| 118 | + } |
| 119 | + let expected = decode_hex_32(&manifest.metadata_hmac_sha256) |
| 120 | + .ok_or_else(|| SnapshotError::IntegrityVerificationFailed { id: id.to_owned() })?; |
| 121 | + self.secret |
| 122 | + .with_secret(|secret| { |
| 123 | + hmac::verify( |
| 124 | + &hmac::Key::new(hmac::HMAC_SHA256, secret), |
| 125 | + &mac_input(id, config, metadata), |
| 126 | + &expected, |
| 127 | + ) |
| 128 | + }) |
| 129 | + .map_err(|_| SnapshotError::IntegrityVerificationFailed { id: id.to_owned() }) |
| 130 | + } |
| 131 | + |
| 132 | + fn sign(&self, id: &str, config: &[u8], metadata: &[u8]) -> hmac::Tag { |
| 133 | + self.secret.with_secret(|secret| { |
| 134 | + hmac::sign( |
| 135 | + &hmac::Key::new(hmac::HMAC_SHA256, secret), |
| 136 | + &mac_input(id, config, metadata), |
| 137 | + ) |
| 138 | + }) |
| 139 | + } |
| 140 | +} |
| 141 | + |
| 142 | +fn mac_input(id: &str, config: &[u8], metadata: &[u8]) -> Vec<u8> { |
| 143 | + let mut input = Vec::with_capacity( |
| 144 | + SNAPSHOT_MAC_LABEL.len() + id.len() + config.len() + metadata.len() + 24, |
| 145 | + ); |
| 146 | + input.extend_from_slice(SNAPSHOT_MAC_LABEL); |
| 147 | + append_field(&mut input, id.as_bytes()); |
| 148 | + append_field(&mut input, config); |
| 149 | + append_field(&mut input, metadata); |
| 150 | + input |
| 151 | +} |
| 152 | + |
| 153 | +fn append_field(output: &mut Vec<u8>, value: &[u8]) { |
| 154 | + output.extend_from_slice(&(value.len() as u64).to_be_bytes()); |
| 155 | + output.extend_from_slice(value); |
| 156 | +} |
| 157 | + |
| 158 | +fn hex(bytes: &[u8]) -> String { |
| 159 | + const DIGITS: &[u8; 16] = b"0123456789abcdef"; |
| 160 | + let mut output = String::with_capacity(bytes.len() * 2); |
| 161 | + for byte in bytes { |
| 162 | + output.push(char::from(DIGITS[usize::from(byte >> 4)])); |
| 163 | + output.push(char::from(DIGITS[usize::from(byte & 0x0f)])); |
| 164 | + } |
| 165 | + output |
| 166 | +} |
| 167 | + |
| 168 | +fn decode_hex_32(value: &str) -> Option<[u8; 32]> { |
| 169 | + if value.len() != 64 { |
| 170 | + return None; |
| 171 | + } |
| 172 | + let mut output = [0u8; 32]; |
| 173 | + for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() { |
| 174 | + output[index] = hex_nibble(pair[0])?.checked_mul(16)? | hex_nibble(pair[1])?; |
| 175 | + } |
| 176 | + Some(output) |
| 177 | +} |
| 178 | + |
| 179 | +fn hex_nibble(value: u8) -> Option<u8> { |
| 180 | + match value { |
| 181 | + b'0'..=b'9' => Some(value - b'0'), |
| 182 | + b'a'..=b'f' => Some(value - b'a' + 10), |
| 183 | + b'A'..=b'F' => Some(value - b'A' + 10), |
| 184 | + _ => None, |
| 185 | + } |
| 186 | +} |
| 187 | + |
| 188 | +#[cfg(unix)] |
| 189 | +fn open_secret_file(path: &Path) -> Result<File, SnapshotError> { |
| 190 | + let fd = rustix::fs::open( |
| 191 | + path, |
| 192 | + rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::CLOEXEC | rustix::fs::OFlags::NOFOLLOW, |
| 193 | + rustix::fs::Mode::empty(), |
| 194 | + ) |
| 195 | + .map_err(|error| SnapshotError::Io(io::Error::from_raw_os_error(error.raw_os_error())))?; |
| 196 | + Ok(fd.into()) |
| 197 | +} |
| 198 | + |
| 199 | +#[cfg(not(unix))] |
| 200 | +fn open_secret_file(path: &Path) -> Result<File, SnapshotError> { |
| 201 | + File::open(path).map_err(SnapshotError::Io) |
| 202 | +} |
0 commit comments