aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-kv-store / src / seal.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Encryption at rest of host record files (ADR 0003 section 20, #506). |
| 17 | //! |
| 18 | //! A sealed object is the same `header region (4096 B) || payload` file as |
| 19 | //! before, with two differences: the payload bytes are AES-256-GCM |
| 20 | //! ciphertext (same length: the cipher is a stream mode), and the last 32 |
| 21 | //! bytes of the header region, the **seal slot** at `SEAL_SLOT_OFFSET`, hold: |
| 22 | //! |
| 23 | //! | region offset | size | field | |
| 24 | //! |---|---|---| |
| 25 | //! | 4064 | 3 | magic `AKS` | |
| 26 | //! | 4067 | 1 | sealed format version = 2 (1 was the plaintext layout) | |
| 27 | //! | 4068 | 12 | nonce, fresh from the OS random source for every file | |
| 28 | //! | 4080 | 16 | AEAD tag | |
| 29 | //! |
| 30 | //! Associated data: region bytes `0..4068`, i.e. the 256-byte identity |
| 31 | //! header (namespace id, chunk key, parent, geometry, payload root, header |
| 32 | //! checksum), the segment digest table, the padding, and the magic and |
| 33 | //! version. Any change to any of them, a wrong key, or one flipped |
| 34 | //! ciphertext, nonce or tag bit makes `open_payload` refuse. The caller then |
| 35 | //! discards the object and recomputes; nothing is restored from it. |
| 36 | //! |
| 37 | //! The key: 32 bytes, given to the process as 64 hex digits in |
| 38 | //! `AIEN_KV_STORE_KEY` (`atlas-vault run AIEN_KV_STORE_KEY -- <daemon>`). It is |
| 39 | //! read once, removed from the environment, held in a buffer that is zeroed |
| 40 | //! on drop, and never printed: `Debug` is redacted and refusals carry no key |
| 41 | //! text. Key rotation: objects sealed under an old key fail to open and are |
| 42 | //! discarded like any other refused object. |
| 43 | //! |
| 44 | //! # Nonce source (#708) |
| 45 | //! |
| 46 | //! Production [`SealKey::seal_file`] fills the 96-bit nonce from |
| 47 | //! [`ring::rand::SystemRandom`] and from no other source. A failed fill |
| 48 | //! returns [`SealError::Random`] and leaves the caller's buffer unchanged. |
| 49 | //! There is no environment variable, no config field, and no fallback nonce. |
| 50 | //! |
| 51 | //! Crate unit tests may attach a source with `with_nonce_source`. That method |
| 52 | //! exists only when the crate is built for its own unit tests (`cfg(test)`). |
| 53 | //! Integration tests and production builds do not compile it. |
| 54 | //! |
| 55 | //! # Usage budget (#811) |
| 56 | //! |
| 57 | //! Nonces are independent uniform 96-bit draws. For `q` draws under one key |
| 58 | //! the probability of a collision is at most `q(q-1)/2^97` (NIST SP 800-38D, |
| 59 | //! section 8.3). [`RECOMMENDED_SEALS_PER_KEY`] is `2^20` (bound `2^-57`). |
| 60 | //! [`NIST_SP800_38D_RANDOM_NONCE_LIMIT`] is `2^32` (bound about `2^-33`). |
| 61 | //! A finite sample of distinct nonces is not a uniqueness proof. |
| 62 | //! |
| 63 | //! [`SealKey::seal_file`] enforces the `2^20` budget for one store directory. |
| 64 | //! The caller passes that directory's [`USAGE_DIR_NAME`] directory. The count |
| 65 | //! is a file named by the SHA-256 of the key bytes (the key itself is not |
| 66 | //! written). The file is read, and `count + 1` is made durable, before the |
| 67 | //! caller's buffer is modified. A stored count that is already `2^20` returns |
| 68 | //! [`SealError::Budget`] and leaves the buffer unchanged. A count that cannot |
| 69 | //! be read or persisted returns [`SealError::UsageStore`] and does not seal. |
| 70 | //! |
| 71 | //! Order, under an exclusive `flock` on `seal-usage/LOCK`: |
| 72 | //! |
| 73 | //! 1. A buffer shorter than a header region returns [`SealError::Short`]. The |
| 74 | //! count file is not touched. The nonce is not drawn. |
| 75 | //! 2. The nonce is drawn into a stack buffer. [`SealError::Random`] returns |
| 76 | //! here. The count file and the caller's buffer stay as they were. |
| 77 | //! 3. The fingerprint list is read before any count is written, so a corrupt |
| 78 | //! list does not consume a slot. The AKS v2 seal slot is magic, version, |
| 79 | //! nonce and tag (32 bytes) and has no key id. The store keeps an |
| 80 | //! append-only list of every key fingerprint it has sealed under, in |
| 81 | //! `seal-usage/key-fingerprints` ([`KEY_FINGERPRINTS_NAME`]). The key bytes |
| 82 | //! are not written. Each update rewrites the whole list with the same |
| 83 | //! durability as the count. The list holds at most 256 fingerprints. |
| 84 | //! Reaching that cap means rotating to a new store directory: another key |
| 85 | //! cannot be appended in this one. A missing count file is zero only in |
| 86 | //! two cases: the store has no sealed object and no list, or this key's |
| 87 | //! fingerprint has never been in the list (a genuinely new key). When |
| 88 | //! `seal-usage/key-fingerprints` is missing and the directory holds valid |
| 89 | //! counter files, the list is rebuilt under this lock from those 64-hex |
| 90 | //! filenames plus the current key, through the same durable write. A |
| 91 | //! counter filename that is not a valid count file this uid owns refuses |
| 92 | //! the seal and writes nothing. A directory that is not named |
| 93 | //! [`USAGE_DIR_NAME`] is a unit-test usage dir and has no list; a missing |
| 94 | //! file there is also zero. A missing file is [`SealError::UsageStore`] |
| 95 | //! when this key is already in the list, and when there is no list and no |
| 96 | //! counter file but a sealed object exists. That refusal appends the |
| 97 | //! fingerprint to the list already on disk. It does not replace that list |
| 98 | //! with only this key. When no list and no counter file exist, the refusal |
| 99 | //! creates the one-key list and does not write a counter. Do not put a |
| 100 | //! listed key back into `AIEN_KV_STORE_KEY` after its counter is gone: |
| 101 | //! never reuse a retired key. A short, long, duplicate, or unrecognized |
| 102 | //! file is [`SealError::UsageStore`]. At `2^20` the call returns |
| 103 | //! [`SealError::Budget`]. |
| 104 | //! 4. `count + 1` is written to `<fingerprint>.part`. A leftover part file |
| 105 | //! this uid owns is truncated and replaced. A part file this uid does not |
| 106 | //! own, or that is not a regular file, is [`SealError::UsageStore`] and is |
| 107 | //! left in place: remove it as the store owner, then seal again. The part |
| 108 | //! file is `fsync`ed, renamed onto the count file, and the directory is |
| 109 | //! `fsync`ed. The fingerprint list, when it gains this key, uses that same |
| 110 | //! sequence and is written after the count. A rebuilt list is the |
| 111 | //! exception: it is written before the count, and every fingerprint in it |
| 112 | //! already has a counter file except the current key when that counter is |
| 113 | //! missing. That key is included and the seal then refuses without writing |
| 114 | //! a counter. Any failure is [`SealError::UsageStore`]. |
| 115 | //! 5. Only then is the seal slot written and the payload encrypted. |
| 116 | //! |
| 117 | //! A crash before the directory `fsync` keeps the previous count when the |
| 118 | //! rename has not reached disk. A crash after that `fsync` and before the |
| 119 | //! sealed object is published has counted a seal that is not on disk. The |
| 120 | //! count is never decremented: the budget is a ceiling. A failed directory |
| 121 | //! `fsync` after a rename that did reach disk is the same direction (the |
| 122 | //! seal does not run, and a later open may observe the higher count). The |
| 123 | //! count file for a new key is durable before that key is appended to the |
| 124 | //! list, so a crash cannot list the key and then find no counter. Two |
| 125 | //! refusals write the list and no counter, on purpose: the legacy refusal, |
| 126 | //! and a rebuilt list that had to record the current key because its counter |
| 127 | //! file was already gone. |
| 128 | //! |
| 129 | //! The file is per store directory and per key fingerprint. Restarting that |
| 130 | //! directory sees it. Sealers that share the directory serialize on the lock. |
| 131 | //! The host adapter already refuses a second open of the same directory. |
| 132 | //! Another directory, including a copy on another host, has its own file and |
| 133 | //! is not included. A missing count is not filled in by counting objects: a |
| 134 | //! listing misses seals that were later deleted. `2^32` is not a second |
| 135 | //! refusal; the `2^20` check comes first. Rotation leaves objects sealed under |
| 136 | //! the previous key on disk until a read fails to open one. This crate does |
| 137 | //! not delete them at open and does not migrate them. |
| 138 | //! |
| 139 | //! `Nonce::assume_unique_for_key` does not search for an earlier nonce, and |
| 140 | //! neither does this module. A repeat under one key makes the CTR keystream |
| 141 | //! reusable: the XOR of the two ciphertexts equals the XOR of the two |
| 142 | //! plaintexts. Each tag still authenticates its own file. |
| 143 | //! |
| 144 | //! The nonce that was used is stored in the seal slot. Process exit does not |
| 145 | //! rewind the kernel CSPRNG, and copying the store directory back into place |
| 146 | //! does not rewind it either. A restored file opens because its nonce is in |
| 147 | //! the file. A snapshot of a running VM can include kernel entropy; this |
| 148 | //! crate does not detect that case and does not reseed. |
| 149 | //! |
| 150 | //! Restoring or rolling back an older `seal-usage/` directory, an older |
| 151 | //! `seal-usage/key-fingerprints` list, or an older copy of the whole store, |
| 152 | //! can lower the persisted count. Deleting or shortening |
| 153 | //! `seal-usage/key-fingerprints` drops keys from that list. A missing list is |
| 154 | //! rebuilt from the counter files still in `seal-usage/`. A key whose counter |
| 155 | //! file is also gone is recorded when that key seals while the list is |
| 156 | //! absent, and that seal is refused. The counter is local state and has no |
| 157 | //! external monotonic anchor. Sealing stays safe because each nonce is a |
| 158 | //! fresh random draw, but the `2^20` bound weakens by the seals the restored |
| 159 | //! count leaves out. An external or TPM-backed counter would keep the count |
| 160 | //! from moving backward. |
| 161 | |
| 162 | use crate::record::{HEADER_REGION_LEN, SEAL_SLOT_OFFSET}; |
| 163 | use core::sync::atomic::{AtomicU64, Ordering}; |
| 164 | use ring::aead::{Aad, LessSafeKey, Nonce, Tag, UnboundKey, AES_256_GCM}; |
| 165 | use ring::rand::{SecureRandom, SystemRandom}; |
| 166 | use sha2::{Digest, Sha256}; |
| 167 | use std::fs::{File, OpenOptions}; |
| 168 | use std::io::{Read, Seek, SeekFrom, Write}; |
| 169 | use std::os::unix::fs::MetadataExt; |
| 170 | use std::path::Path; |
| 171 | #[cfg(test)] |
| 172 | use std::path::PathBuf; |
| 173 | use zeroize::{Zeroize, Zeroizing}; |
| 174 | |
| 175 | /// The environment variable the key arrives in. |
| 176 | pub const KEY_ENV: &str = "AIEN_KV_STORE_KEY"; |
| 177 | pub const KEY_LEN: usize = 32; |
| 178 | pub const SEAL_MAGIC: [u8; 3] = *b"AKS"; |
| 179 | /// Host object format: 1 = plaintext payload (no longer read), 2 = sealed. |
| 180 | pub const SEALED_FORMAT_VERSION: u8 = 2; |
| 181 | pub const NONCE_LEN: usize = 12; |
| 182 | pub const TAG_LEN: usize = 16; |
| 183 | /// Operator rekey budget. [`SealKey::seal_file`] returns [`SealError::Budget`] |
| 184 | /// when the persisted count for this key in the given usage directory is |
| 185 | /// already this value. At this count the NIST SP 800-38D collision bound is |
| 186 | /// `2^-57`. |
| 187 | pub const RECOMMENDED_SEALS_PER_KEY: u64 = 1 << 20; |
| 188 | /// NIST SP 800-38D guidance for random 96-bit nonces: stay below this many |
| 189 | /// invocations per key. The enforced ceiling is [`RECOMMENDED_SEALS_PER_KEY`], |
| 190 | /// which is below this value, so `seal_file` does not consult this constant. |
| 191 | pub const NIST_SP800_38D_RANDOM_NONCE_LIMIT: u64 = 1 << 32; |
| 192 | /// Directory under the store root that holds one count file per key fingerprint. |
| 193 | pub const USAGE_DIR_NAME: &str = "seal-usage"; |
| 194 | /// Append-only list of every key fingerprint this store has sealed under. |
| 195 | /// Not a count file (those names are 64 hex digits). The key itself is not |
| 196 | /// stored. The unreleased single-file name `key-fingerprint` is not read and |
| 197 | /// not migrated: that file never shipped. |
| 198 | pub(crate) const KEY_FINGERPRINTS_NAME: &str = "key-fingerprints"; |
| 199 | const USAGE_MAGIC: [u8; 4] = *b"AKSU"; |
| 200 | const USAGE_VERSION: u8 = 1; |
| 201 | const USAGE_LEN: usize = 16; |
| 202 | const KEY_LIST_MAGIC: [u8; 4] = *b"AKSL"; |
| 203 | const KEY_LIST_VERSION: u8 = 1; |
| 204 | const KEY_LIST_HEADER: usize = 12; |
| 205 | /// At most this many key fingerprints in one store. A longer list, or a seal |
| 206 | /// that would append one more, is [`SealError::UsageStore`]. Reaching the cap |
| 207 | /// means rotating to a new store directory: this directory cannot record |
| 208 | /// another key. |
| 209 | const MAX_KEY_FINGERPRINTS: usize = 256; |
| 210 | const O_MAGIC: usize = SEAL_SLOT_OFFSET; |
| 211 | const O_VERSION: usize = SEAL_SLOT_OFFSET + 3; |
| 212 | const O_NONCE: usize = SEAL_SLOT_OFFSET + 4; |
| 213 | const O_TAG: usize = O_NONCE + NONCE_LEN; |
| 214 | /// Region bytes bound as associated data: everything before the nonce. |
| 215 | pub const AAD_LEN: usize = O_NONCE; |
| 216 | const _: () = assert!(O_TAG + TAG_LEN == HEADER_REGION_LEN); |
| 217 | /// AKS v2 fills the seal slot: magic, version, nonce, tag. No key id remains. |
| 218 | const _: () = assert!(3 + 1 + NONCE_LEN + TAG_LEN == 32); |
| 219 | |
| 220 | /// Fills the 96-bit nonce for one seal. |
| 221 | /// |
| 222 | /// [`OsNonceSource`] is the production implementation. A failed fill is |
| 223 | /// [`SealError::Random`]. Callers must not replace a failure with a fixed |
| 224 | /// nonce. |
| 225 | pub(crate) trait NonceSource { |
| 226 | fn fill_nonce(&self, out: &mut [u8; NONCE_LEN]) -> Result<(), SealError>; |
| 227 | } |
| 228 | |
| 229 | struct OsNonceSource; |
| 230 | |
| 231 | impl NonceSource for OsNonceSource { |
| 232 | fn fill_nonce(&self, out: &mut [u8; NONCE_LEN]) -> Result<(), SealError> { |
| 233 | SystemRandom::new() |
| 234 | .fill(&mut out[..]) |
| 235 | .map_err(|_| SealError::Random) |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | static OS_NONCE: OsNonceSource = OsNonceSource; |
| 240 | |
| 241 | /// Why no key could be loaded. Carries no key text. |
| 242 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 243 | pub enum KeyRefusal { |
| 244 | /// `AIEN_KV_STORE_KEY` is not set. |
| 245 | Missing, |
| 246 | /// Set, but not exactly 64 hex digits. |
| 247 | Malformed, |
| 248 | } |
| 249 | |
| 250 | impl KeyRefusal { |
| 251 | /// The status reason (`kv_store_refused_reason`). |
| 252 | pub fn reason(&self) -> &'static str { |
| 253 | match self { |
| 254 | Self::Missing => "key_missing", |
| 255 | Self::Malformed => "key_malformed", |
| 256 | } |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | impl core::fmt::Display for KeyRefusal { |
| 261 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { |
| 262 | match self { |
| 263 | Self::Missing => write!(f, "key_missing: {KEY_ENV} is not set"), |
| 264 | Self::Malformed => write!( |
| 265 | f, |
| 266 | "key_malformed: {KEY_ENV} is not exactly 64 hex digits (32 bytes)" |
| 267 | ), |
| 268 | } |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | /// Why an object was not sealed or not opened. |
| 273 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 274 | pub enum SealError { |
| 275 | /// Fewer bytes than a header region. |
| 276 | Short, |
| 277 | /// No seal magic: an old plaintext-format file (or not ours). |
| 278 | NotSealed, |
| 279 | /// Seal magic with another sealed format version. |
| 280 | UnsupportedVersion, |
| 281 | /// Authentication failed: wrong key, tampered bytes or swapped header. |
| 282 | Rejected, |
| 283 | /// The OS random source failed (sealing only). The buffer is unchanged. |
| 284 | Random, |
| 285 | /// The persisted seal count for this key in the usage directory is already |
| 286 | /// [`RECOMMENDED_SEALS_PER_KEY`]. The buffer is unchanged. |
| 287 | Budget, |
| 288 | /// The usage count could not be read or made durable. The buffer is unchanged |
| 289 | /// and the payload was not encrypted. |
| 290 | UsageStore, |
| 291 | } |
| 292 | |
| 293 | /// The store key. Zeroed on drop; never printed. |
| 294 | pub struct SealKey { |
| 295 | bytes: Zeroizing<[u8; KEY_LEN]>, |
| 296 | /// Unit-test override. Absent from non-test builds. `None` selects |
| 297 | /// [`OsNonceSource`]. |
| 298 | #[cfg(test)] |
| 299 | nonce_source: Option<std::sync::Arc<dyn NonceSource + Send + Sync>>, |
| 300 | /// Next `commit_usage` fails before it writes. The count file stays put. |
| 301 | #[cfg(test)] |
| 302 | fail_usage_persist: core::sync::atomic::AtomicBool, |
| 303 | } |
| 304 | |
| 305 | fn hex_val(c: u8) -> Option<u8> { |
| 306 | match c { |
| 307 | b'0'..=b'9' => Some(c - b'0'), |
| 308 | b'a'..=b'f' => Some(c - b'a' + 10), |
| 309 | b'A'..=b'F' => Some(c - b'A' + 10), |
| 310 | _ => None, |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | impl SealKey { |
| 315 | fn from_parts(bytes: Zeroizing<[u8; KEY_LEN]>) -> Self { |
| 316 | Self { |
| 317 | bytes, |
| 318 | #[cfg(test)] |
| 319 | nonce_source: None, |
| 320 | #[cfg(test)] |
| 321 | fail_usage_persist: core::sync::atomic::AtomicBool::new(false), |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | pub fn from_bytes(bytes: [u8; KEY_LEN]) -> Self { |
| 326 | let mut b = bytes; |
| 327 | let key = Self::from_parts(Zeroizing::new(b)); |
| 328 | b.zeroize(); |
| 329 | key |
| 330 | } |
| 331 | |
| 332 | /// Attach a nonce source. Compiled only for this crate's unit tests. |
| 333 | /// Production `seal_file` has no equivalent and reads no nonce setting. |
| 334 | #[cfg(test)] |
| 335 | pub(crate) fn with_nonce_source( |
| 336 | mut self, |
| 337 | source: std::sync::Arc<dyn NonceSource + Send + Sync>, |
| 338 | ) -> Self { |
| 339 | self.nonce_source = Some(source); |
| 340 | self |
| 341 | } |
| 342 | |
| 343 | /// A fresh random key (tests, benchmarks). The key bytes come from the OS |
| 344 | /// source. This is separate from the per-file nonce. |
| 345 | pub fn generate() -> Result<Self, SealError> { |
| 346 | let mut raw = [0u8; KEY_LEN]; |
| 347 | SystemRandom::new() |
| 348 | .fill(&mut raw) |
| 349 | .map_err(|_| SealError::Random)?; |
| 350 | let key = Self::from_bytes(raw); |
| 351 | raw.zeroize(); |
| 352 | Ok(key) |
| 353 | } |
| 354 | |
| 355 | /// Exactly 64 hex digits, either case; anything else is `Malformed` |
| 356 | /// (no trimming: a stray newline is a refusal, not a guess). |
| 357 | pub fn from_hex(hex: &str) -> Result<Self, KeyRefusal> { |
| 358 | let h = hex.as_bytes(); |
| 359 | if h.len() != 2 * KEY_LEN { |
| 360 | return Err(KeyRefusal::Malformed); |
| 361 | } |
| 362 | let mut raw = [0u8; KEY_LEN]; |
| 363 | for (i, [hi, lo]) in h.as_chunks::<2>().0.iter().enumerate() { |
| 364 | match (hex_val(*hi), hex_val(*lo)) { |
| 365 | (Some(a), Some(b)) => raw[i] = (a << 4) | b, |
| 366 | _ => { |
| 367 | raw.zeroize(); |
| 368 | return Err(KeyRefusal::Malformed); |
| 369 | } |
| 370 | } |
| 371 | } |
| 372 | let key = Self::from_bytes(raw); |
| 373 | raw.zeroize(); |
| 374 | Ok(key) |
| 375 | } |
| 376 | |
| 377 | /// The key from `KEY_ENV` through any lookup (tests pass a closure). The |
| 378 | /// looked-up text is zeroed after parsing. |
| 379 | pub fn from_lookup(get: impl Fn(&str) -> Option<String>) -> Result<Self, KeyRefusal> { |
| 380 | let Some(text) = get(KEY_ENV).map(Zeroizing::new) else { |
| 381 | return Err(KeyRefusal::Missing); |
| 382 | }; |
| 383 | Self::from_hex(&text) |
| 384 | } |
| 385 | |
| 386 | /// The key from the process environment, which no longer holds it |
| 387 | /// afterwards (whether or not it parsed), so child processes do not |
| 388 | /// inherit it. Call before other threads read the environment. |
| 389 | pub fn take_from_process_env() -> Result<Self, KeyRefusal> { |
| 390 | let got = Self::from_lookup(|n| std::env::var(n).ok()); |
| 391 | let malformed_os = std::env::var_os(KEY_ENV).is_some() && got.is_err(); |
| 392 | std::env::remove_var(KEY_ENV); |
| 393 | match got { |
| 394 | // Present but not valid UTF-8 reads as missing above. |
| 395 | Err(KeyRefusal::Missing) if malformed_os => Err(KeyRefusal::Malformed), |
| 396 | other => other, |
| 397 | } |
| 398 | } |
| 399 | |
| 400 | fn aead(&self) -> LessSafeKey { |
| 401 | LessSafeKey::new(UnboundKey::new(&AES_256_GCM, &self.bytes[..]).expect("32-byte key")) |
| 402 | } |
| 403 | |
| 404 | /// The next persisted count update fails before it writes. The following |
| 405 | /// `seal_file` returns [`SealError::UsageStore`] and leaves the buffer |
| 406 | /// unchanged. Compiled only for this crate's unit tests. |
| 407 | #[cfg(test)] |
| 408 | pub(crate) fn testing_fail_next_usage_persist(&self) { |
| 409 | self.fail_usage_persist |
| 410 | .store(true, core::sync::atomic::Ordering::SeqCst); |
| 411 | } |
| 412 | |
| 413 | /// Seal `file` = `region || payload` in place: writes the seal slot (magic, |
| 414 | /// version, fresh nonce, tag) and encrypts the payload. The file length is |
| 415 | /// unchanged. |
| 416 | /// |
| 417 | /// `usage_dir` is the store's [`USAGE_DIR_NAME`] directory. One use of this |
| 418 | /// key is recorded there, and that record is durable, before this modifies |
| 419 | /// `file`. [`SealError::Random`], [`SealError::Budget`] and |
| 420 | /// [`SealError::UsageStore`] leave the buffer as the caller passed it. |
| 421 | pub fn seal_file(&self, usage_dir: &Path, file: &mut [u8]) -> Result<(), SealError> { |
| 422 | let t0 = std::time::Instant::now(); |
| 423 | let got = self.seal_counted(usage_dir, file); |
| 424 | note_timing( |
| 425 | &SEAL_TIMING, |
| 426 | file.len().saturating_sub(HEADER_REGION_LEN), |
| 427 | t0, |
| 428 | ); |
| 429 | got |
| 430 | } |
| 431 | |
| 432 | fn active_source(&self) -> &dyn NonceSource { |
| 433 | #[cfg(test)] |
| 434 | if let Some(source) = self.nonce_source.as_deref() { |
| 435 | return source; |
| 436 | } |
| 437 | &OS_NONCE |
| 438 | } |
| 439 | |
| 440 | fn seal_counted(&self, usage_dir: &Path, file: &mut [u8]) -> Result<(), SealError> { |
| 441 | if file.len() < HEADER_REGION_LEN { |
| 442 | return Err(SealError::Short); |
| 443 | } |
| 444 | // Draw before the count is committed and before any write to `file`. |
| 445 | // A failed source must not mark the buffer as sealed, must not encrypt, |
| 446 | // and must not consume a budget slot. The AEAD call stays in this |
| 447 | // function: `fill_nonce` overwrites the stack buffer, and a helper |
| 448 | // parameter named `nonce` is a hard-coded-nonce sink for that zero |
| 449 | // fill (the query does not treat the trait write as a barrier). |
| 450 | let source = self.active_source(); |
| 451 | let mut nonce = [0u8; NONCE_LEN]; |
| 452 | source.fill_nonce(&mut nonce)?; |
| 453 | // The count is durable before `file` changes. A persist error returns |
| 454 | // with the plaintext still in the caller's buffer. |
| 455 | self.commit_usage(usage_dir)?; |
| 456 | let (region, payload) = file.split_at_mut(HEADER_REGION_LEN); |
| 457 | region[O_MAGIC..O_MAGIC + 3].copy_from_slice(&SEAL_MAGIC); |
| 458 | region[O_VERSION] = SEALED_FORMAT_VERSION; |
| 459 | region[O_NONCE..O_TAG].copy_from_slice(&nonce); |
| 460 | let tag = self |
| 461 | .aead() |
| 462 | .seal_in_place_separate_tag( |
| 463 | Nonce::assume_unique_for_key(nonce), |
| 464 | Aad::from(®ion[..AAD_LEN]), |
| 465 | payload, |
| 466 | ) |
| 467 | .map_err(|_| SealError::Rejected)?; |
| 468 | region[O_TAG..].copy_from_slice(tag.as_ref()); |
| 469 | Ok(()) |
| 470 | } |
| 471 | |
| 472 | fn commit_usage(&self, usage_dir: &Path) -> Result<(), SealError> { |
| 473 | require_usage_dir(usage_dir)?; |
| 474 | let _lock = lock_usage_dir(usage_dir)?; |
| 475 | let fp = key_fingerprint(&self.bytes); |
| 476 | let name = fingerprint_hex(&fp); |
| 477 | // Validate the list before any count write. A corrupt list must not |
| 478 | // consume a budget slot. |
| 479 | let mut listed = if tracks_store_objects(usage_dir) { |
| 480 | read_key_fingerprints(usage_dir)? |
| 481 | } else { |
| 482 | None |
| 483 | }; |
| 484 | // A missing list must not be replaced with only this key. Rebuild it |
| 485 | // from the counter files still in the directory, plus this key, before |
| 486 | // any count write. A counter file that fails validation refuses here |
| 487 | // and leaves the directory unchanged. |
| 488 | if tracks_store_objects(usage_dir) && listed.is_none() { |
| 489 | if let Some(rebuilt) = rebuild_missing_list(usage_dir, &fp)? { |
| 490 | listed = Some(rebuilt); |
| 491 | } |
| 492 | } |
| 493 | let count = match read_count_file(&usage_dir.join(&name))? { |
| 494 | Some(count) => count, |
| 495 | None => missing_count(usage_dir, &fp, listed.as_deref())?, |
| 496 | }; |
| 497 | if count >= RECOMMENDED_SEALS_PER_KEY { |
| 498 | return Err(SealError::Budget); |
| 499 | } |
| 500 | let already_listed = listed |
| 501 | .as_ref() |
| 502 | .is_some_and(|fps| fps.iter().any(|e| e == &fp)); |
| 503 | if tracks_store_objects(usage_dir) && !already_listed { |
| 504 | let n = listed.as_ref().map(|fps| fps.len()).unwrap_or(0); |
| 505 | if n >= MAX_KEY_FINGERPRINTS { |
| 506 | return Err(SealError::UsageStore); |
| 507 | } |
| 508 | // A foreign or linked list part must fail before the count write, |
| 509 | // or a retry would consume a slot on every attempt. |
| 510 | part_is_writable(usage_dir, KEY_FINGERPRINTS_NAME)?; |
| 511 | } |
| 512 | #[cfg(test)] |
| 513 | if self |
| 514 | .fail_usage_persist |
| 515 | .swap(false, core::sync::atomic::Ordering::SeqCst) |
| 516 | { |
| 517 | return Err(SealError::UsageStore); |
| 518 | } |
| 519 | // The incremented count is durable before this key is appended. A |
| 520 | // crash between them leaves the counter and the previous list. The |
| 521 | // next seal still has the counter and appends then. |
| 522 | write_count_file(usage_dir, &name, count + 1)?; |
| 523 | if tracks_store_objects(usage_dir) && !already_listed { |
| 524 | let mut next = listed.unwrap_or_default(); |
| 525 | next.push(fp); |
| 526 | write_key_fingerprints(usage_dir, &next)?; |
| 527 | } |
| 528 | Ok(()) |
| 529 | } |
| 530 | |
| 531 | /// Authenticate and decrypt `payload` (the bytes after `region` in a |
| 532 | /// sealed file) in place. On any error the payload buffer is zeroed and |
| 533 | /// must be discarded; nothing in it may be used. |
| 534 | pub fn open_payload(&self, region: &[u8], payload: &mut [u8]) -> Result<(), SealError> { |
| 535 | let t0 = std::time::Instant::now(); |
| 536 | let got = self.open_inner(region, payload); |
| 537 | note_timing(&OPEN_TIMING, payload.len(), t0); |
| 538 | if got.is_err() { |
| 539 | payload.fill(0); |
| 540 | if got == Err(SealError::Rejected) { |
| 541 | OPEN_REJECTED.fetch_add(1, Ordering::Relaxed); |
| 542 | } |
| 543 | } |
| 544 | got |
| 545 | } |
| 546 | |
| 547 | fn open_inner(&self, region: &[u8], payload: &mut [u8]) -> Result<(), SealError> { |
| 548 | if region.len() < HEADER_REGION_LEN { |
| 549 | return Err(SealError::Short); |
| 550 | } |
| 551 | check_marker(region)?; |
| 552 | let mut nonce = [0u8; NONCE_LEN]; |
| 553 | nonce.copy_from_slice(®ion[O_NONCE..O_TAG]); |
| 554 | let mut tag = [0u8; TAG_LEN]; |
| 555 | tag.copy_from_slice(®ion[O_TAG..HEADER_REGION_LEN]); |
| 556 | self.aead() |
| 557 | .open_in_place_separate_tag( |
| 558 | Nonce::assume_unique_for_key(nonce), |
| 559 | Aad::from(®ion[..AAD_LEN]), |
| 560 | Tag::from(tag), |
| 561 | payload, |
| 562 | 0.., |
| 563 | ) |
| 564 | .map(|_| ()) |
| 565 | .map_err(|_| SealError::Rejected) |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | /// Write `count` as this key's persisted usage, without the budget check. |
| 570 | /// Unit tests use it to stand at `2^20` without sealing that many files. |
| 571 | /// The bytes are the same encoding `commit_usage` writes. |
| 572 | #[cfg(test)] |
| 573 | pub(crate) fn testing_install_usage_count( |
| 574 | usage_dir: &Path, |
| 575 | key: &SealKey, |
| 576 | count: u64, |
| 577 | ) -> Result<(), SealError> { |
| 578 | require_usage_dir(usage_dir)?; |
| 579 | let _lock = lock_usage_dir(usage_dir)?; |
| 580 | write_count_file(usage_dir, &fingerprint_name(&key.bytes), count) |
| 581 | } |
| 582 | |
| 583 | /// The persisted count for `key` in `usage_dir`. A missing file is zero. |
| 584 | #[cfg(test)] |
| 585 | pub(crate) fn testing_read_usage_count(usage_dir: &Path, key: &SealKey) -> Result<u64, SealError> { |
| 586 | require_usage_dir(usage_dir)?; |
| 587 | let _lock = lock_usage_dir(usage_dir)?; |
| 588 | Ok(read_count_file(&usage_dir.join(fingerprint_name(&key.bytes)))?.unwrap_or(0)) |
| 589 | } |
| 590 | |
| 591 | /// The fingerprints in [`KEY_FINGERPRINTS_NAME`], if the file is present. |
| 592 | #[cfg(test)] |
| 593 | pub(crate) fn testing_read_key_fingerprints( |
| 594 | usage_dir: &Path, |
| 595 | ) -> Result<Option<Vec<[u8; 32]>>, SealError> { |
| 596 | require_usage_dir(usage_dir)?; |
| 597 | let _lock = lock_usage_dir(usage_dir)?; |
| 598 | read_key_fingerprints(usage_dir) |
| 599 | } |
| 600 | |
| 601 | /// Path of the count file. Tests check the fingerprint name independently |
| 602 | /// by hashing the key with SHA-256 themselves. |
| 603 | #[cfg(test)] |
| 604 | pub(crate) fn testing_usage_path(usage_dir: &Path, key: &SealKey) -> PathBuf { |
| 605 | usage_dir.join(fingerprint_name(&key.bytes)) |
| 606 | } |
| 607 | |
| 608 | fn key_fingerprint(key: &[u8; KEY_LEN]) -> [u8; 32] { |
| 609 | Sha256::digest(key).into() |
| 610 | } |
| 611 | |
| 612 | fn fingerprint_hex(fp: &[u8; 32]) -> String { |
| 613 | let mut hex = String::with_capacity(64); |
| 614 | const NIBBLE: &[u8; 16] = b"0123456789abcdef"; |
| 615 | for byte in fp { |
| 616 | hex.push(NIBBLE[(byte >> 4) as usize] as char); |
| 617 | hex.push(NIBBLE[(byte & 0x0f) as usize] as char); |
| 618 | } |
| 619 | hex |
| 620 | } |
| 621 | |
| 622 | #[cfg(test)] |
| 623 | fn fingerprint_name(key: &[u8; KEY_LEN]) -> String { |
| 624 | fingerprint_hex(&key_fingerprint(key)) |
| 625 | } |
| 626 | |
| 627 | /// Decide a missing counter. `listed` was already validated. |
| 628 | /// |
| 629 | /// A zero return means this seal may start at zero. The legacy refusal |
| 630 | /// appends `fp` to the list already on disk and writes no counter. It does |
| 631 | /// not replace that list with only this key. Any other |
| 632 | /// [`SealError::UsageStore`] writes nothing. |
| 633 | fn missing_count( |
| 634 | usage_dir: &Path, |
| 635 | fp: &[u8; 32], |
| 636 | listed: Option<&[[u8; 32]]>, |
| 637 | ) -> Result<u64, SealError> { |
| 638 | if !tracks_store_objects(usage_dir) { |
| 639 | return Ok(0); |
| 640 | } |
| 641 | match listed { |
| 642 | Some(fps) if fps.iter().any(|existing| existing == fp) => Err(SealError::UsageStore), |
| 643 | Some(_) => Ok(0), |
| 644 | None => { |
| 645 | if store_already_holds_sealed_object(usage_dir)? { |
| 646 | // No list and no counter file, but a sealed object exists. |
| 647 | // Record this key and refuse. Do not write a counter. |
| 648 | append_listed_key(usage_dir, fp)?; |
| 649 | Err(SealError::UsageStore) |
| 650 | } else { |
| 651 | Ok(0) |
| 652 | } |
| 653 | } |
| 654 | } |
| 655 | } |
| 656 | |
| 657 | /// When `seal-usage/key-fingerprints` is missing and at least one valid |
| 658 | /// counter file is present, write the list of those fingerprints plus `fp`. |
| 659 | /// `Ok(None)` means there was no counter file to recover. A filename that |
| 660 | /// looks like a counter but is not a valid count file this uid owns is |
| 661 | /// [`SealError::UsageStore`], and nothing is written. |
| 662 | fn rebuild_missing_list(dir: &Path, fp: &[u8; 32]) -> Result<Option<Vec<[u8; 32]>>, SealError> { |
| 663 | let recovered = counter_fingerprints(dir)?; |
| 664 | if recovered.is_empty() { |
| 665 | return Ok(None); |
| 666 | } |
| 667 | let mut fps = recovered; |
| 668 | if !fps.iter().any(|existing| existing == fp) { |
| 669 | if fps.len() >= MAX_KEY_FINGERPRINTS { |
| 670 | return Err(SealError::UsageStore); |
| 671 | } |
| 672 | fps.push(*fp); |
| 673 | } |
| 674 | part_is_writable(dir, KEY_FINGERPRINTS_NAME)?; |
| 675 | write_key_fingerprints(dir, &fps)?; |
| 676 | Ok(Some(fps)) |
| 677 | } |
| 678 | |
| 679 | /// Append `fp` to the list on disk. A missing list is filled from the counter |
| 680 | /// files first, so this never replaces a recovered history with only `fp`. |
| 681 | /// When there is no list and no counter file, the written list is `[fp]`. |
| 682 | fn append_listed_key(dir: &Path, fp: &[u8; 32]) -> Result<(), SealError> { |
| 683 | let mut fps = match read_key_fingerprints(dir)? { |
| 684 | Some(fps) => fps, |
| 685 | None => counter_fingerprints(dir)?, |
| 686 | }; |
| 687 | if fps.iter().any(|existing| existing == fp) { |
| 688 | return Ok(()); |
| 689 | } |
| 690 | if fps.len() >= MAX_KEY_FINGERPRINTS { |
| 691 | return Err(SealError::UsageStore); |
| 692 | } |
| 693 | part_is_writable(dir, KEY_FINGERPRINTS_NAME)?; |
| 694 | fps.push(*fp); |
| 695 | write_key_fingerprints(dir, &fps) |
| 696 | } |
| 697 | |
| 698 | /// Fingerprints named by valid counter files in `dir`, in ascending order. |
| 699 | /// Names that are not 64 lowercase hex digits are ignored, including `LOCK`, |
| 700 | /// `key-fingerprints`, `key-fingerprints.part`, and the unreleased |
| 701 | /// `key-fingerprint` marker. A 64-hex name that is not a regular count file |
| 702 | /// this uid owns refuses the scan. |
| 703 | fn counter_fingerprints(dir: &Path) -> Result<Vec<[u8; 32]>, SealError> { |
| 704 | let entries = std::fs::read_dir(dir).map_err(|_| SealError::UsageStore)?; |
| 705 | let mut fps = Vec::new(); |
| 706 | for entry in entries { |
| 707 | let entry = entry.map_err(|_| SealError::UsageStore)?; |
| 708 | let name = entry.file_name(); |
| 709 | let Some(name) = name.to_str() else { |
| 710 | return Err(SealError::UsageStore); |
| 711 | }; |
| 712 | if !is_counter_filename(name) { |
| 713 | continue; |
| 714 | } |
| 715 | let fp = decode_fingerprint_hex(name)?; |
| 716 | match read_count_file(&dir.join(name))? { |
| 717 | Some(_) => {} |
| 718 | None => return Err(SealError::UsageStore), |
| 719 | } |
| 720 | if fps.iter().any(|existing| existing == &fp) { |
| 721 | return Err(SealError::UsageStore); |
| 722 | } |
| 723 | fps.push(fp); |
| 724 | } |
| 725 | if fps.len() > MAX_KEY_FINGERPRINTS { |
| 726 | return Err(SealError::UsageStore); |
| 727 | } |
| 728 | fps.sort_unstable(); |
| 729 | Ok(fps) |
| 730 | } |
| 731 | |
| 732 | fn is_counter_filename(name: &str) -> bool { |
| 733 | let bytes = name.as_bytes(); |
| 734 | if bytes.len() != 64 { |
| 735 | return false; |
| 736 | } |
| 737 | bytes.iter().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) |
| 738 | } |
| 739 | |
| 740 | fn decode_fingerprint_hex(name: &str) -> Result<[u8; 32], SealError> { |
| 741 | let bytes = name.as_bytes(); |
| 742 | if bytes.len() != 64 { |
| 743 | return Err(SealError::UsageStore); |
| 744 | } |
| 745 | let mut fp = [0u8; 32]; |
| 746 | for i in 0..32 { |
| 747 | let hi = hex_nibble(bytes[i * 2])?; |
| 748 | let lo = hex_nibble(bytes[i * 2 + 1])?; |
| 749 | fp[i] = (hi << 4) | lo; |
| 750 | } |
| 751 | Ok(fp) |
| 752 | } |
| 753 | |
| 754 | fn hex_nibble(b: u8) -> Result<u8, SealError> { |
| 755 | match b { |
| 756 | b'0'..=b'9' => Ok(b - b'0'), |
| 757 | b'a'..=b'f' => Ok(b - b'a' + 10), |
| 758 | _ => Err(SealError::UsageStore), |
| 759 | } |
| 760 | } |
| 761 | |
| 762 | /// Production passes the store's `seal-usage` directory: `HostFsStore::open` |
| 763 | /// creates [`USAGE_DIR_NAME`] and every seal uses that path. Any other |
| 764 | /// directory name is a unit-test usage dir. It has no `objects/` tree and no |
| 765 | /// fingerprint list, and a missing counter there starts at zero. |
| 766 | fn tracks_store_objects(usage_dir: &Path) -> bool { |
| 767 | usage_dir.file_name() == Some(std::ffi::OsStr::new(USAGE_DIR_NAME)) |
| 768 | } |
| 769 | |
| 770 | fn require_usage_dir(dir: &Path) -> Result<(), SealError> { |
| 771 | match std::fs::symlink_metadata(dir) { |
| 772 | Ok(meta) if meta.file_type().is_dir() => Ok(()), |
| 773 | _ => Err(SealError::UsageStore), |
| 774 | } |
| 775 | } |
| 776 | |
| 777 | fn euid() -> u32 { |
| 778 | // SAFETY: geteuid has no preconditions and cannot fail. |
| 779 | unsafe { libc::geteuid() } |
| 780 | } |
| 781 | |
| 782 | fn lock_usage_dir(dir: &Path) -> Result<File, SealError> { |
| 783 | use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; |
| 784 | use std::os::unix::io::AsRawFd; |
| 785 | let path = dir.join("LOCK"); |
| 786 | let f = OpenOptions::new() |
| 787 | .read(true) |
| 788 | .write(true) |
| 789 | .create(true) |
| 790 | .mode(0o600) |
| 791 | .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC) |
| 792 | .open(&path) |
| 793 | .map_err(|_| SealError::UsageStore)?; |
| 794 | let meta = f.metadata().map_err(|_| SealError::UsageStore)?; |
| 795 | if !meta.is_file() || meta.uid() != euid() { |
| 796 | return Err(SealError::UsageStore); |
| 797 | } |
| 798 | if meta.mode() & 0o777 != 0o600 { |
| 799 | f.set_permissions(std::fs::Permissions::from_mode(0o600)) |
| 800 | .map_err(|_| SealError::UsageStore)?; |
| 801 | } |
| 802 | // SAFETY: flock takes an advisory lock on a descriptor we own. The lock |
| 803 | // ends when `f` is dropped, which is the end of the read-modify-write. |
| 804 | if unsafe { libc::flock(f.as_raw_fd(), libc::LOCK_EX) } != 0 { |
| 805 | return Err(SealError::UsageStore); |
| 806 | } |
| 807 | Ok(f) |
| 808 | } |
| 809 | |
| 810 | fn create_usage_file(path: &Path) -> Result<File, SealError> { |
| 811 | use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; |
| 812 | let f = OpenOptions::new() |
| 813 | .read(true) |
| 814 | .write(true) |
| 815 | .create(true) |
| 816 | .mode(0o600) |
| 817 | .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC) |
| 818 | .open(path) |
| 819 | .map_err(|_| SealError::UsageStore)?; |
| 820 | let meta = f.metadata().map_err(|_| SealError::UsageStore)?; |
| 821 | // Truncate only after the owner check, so a planted file we do not own |
| 822 | // is left as it was. |
| 823 | if !meta.is_file() || meta.uid() != euid() { |
| 824 | return Err(SealError::UsageStore); |
| 825 | } |
| 826 | f.set_len(0).map_err(|_| SealError::UsageStore)?; |
| 827 | if meta.mode() & 0o777 != 0o600 { |
| 828 | f.set_permissions(std::fs::Permissions::from_mode(0o600)) |
| 829 | .map_err(|_| SealError::UsageStore)?; |
| 830 | } |
| 831 | Ok(f) |
| 832 | } |
| 833 | |
| 834 | /// `Ok(None)` is a missing file. The caller decides whether that is zero. |
| 835 | fn read_count_file(path: &Path) -> Result<Option<u64>, SealError> { |
| 836 | use std::os::unix::fs::OpenOptionsExt; |
| 837 | let mut f = match OpenOptions::new() |
| 838 | .read(true) |
| 839 | .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC) |
| 840 | .open(path) |
| 841 | { |
| 842 | Ok(f) => f, |
| 843 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), |
| 844 | Err(_) => return Err(SealError::UsageStore), |
| 845 | }; |
| 846 | let meta = f.metadata().map_err(|_| SealError::UsageStore)?; |
| 847 | if !meta.is_file() || meta.uid() != euid() || meta.len() != USAGE_LEN as u64 { |
| 848 | return Err(SealError::UsageStore); |
| 849 | } |
| 850 | let mut buf = [0u8; USAGE_LEN]; |
| 851 | f.read_exact(&mut buf).map_err(|_| SealError::UsageStore)?; |
| 852 | if buf[0..4] != USAGE_MAGIC || buf[4] != USAGE_VERSION || buf[5..8] != [0, 0, 0] { |
| 853 | return Err(SealError::UsageStore); |
| 854 | } |
| 855 | let mut le = [0u8; 8]; |
| 856 | le.copy_from_slice(&buf[8..16]); |
| 857 | Ok(Some(u64::from_le_bytes(le))) |
| 858 | } |
| 859 | |
| 860 | /// `Ok(None)` is a missing list. A present file that is not the list encoding |
| 861 | /// is [`SealError::UsageStore`], not a fresh store. |
| 862 | fn read_key_fingerprints(dir: &Path) -> Result<Option<Vec<[u8; 32]>>, SealError> { |
| 863 | use std::os::unix::fs::OpenOptionsExt; |
| 864 | let mut f = match OpenOptions::new() |
| 865 | .read(true) |
| 866 | .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC) |
| 867 | .open(dir.join(KEY_FINGERPRINTS_NAME)) |
| 868 | { |
| 869 | Ok(f) => f, |
| 870 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), |
| 871 | Err(_) => return Err(SealError::UsageStore), |
| 872 | }; |
| 873 | let meta = f.metadata().map_err(|_| SealError::UsageStore)?; |
| 874 | let len = meta.len(); |
| 875 | let max = KEY_LIST_HEADER as u64 + (MAX_KEY_FINGERPRINTS as u64) * 32; |
| 876 | if !meta.is_file() |
| 877 | || meta.uid() != euid() |
| 878 | || len < KEY_LIST_HEADER as u64 |
| 879 | || len > max |
| 880 | || !(len - KEY_LIST_HEADER as u64).is_multiple_of(32) |
| 881 | { |
| 882 | return Err(SealError::UsageStore); |
| 883 | } |
| 884 | let mut buf = vec![0u8; len as usize]; |
| 885 | f.read_exact(&mut buf).map_err(|_| SealError::UsageStore)?; |
| 886 | if buf[0..4] != KEY_LIST_MAGIC || buf[4] != KEY_LIST_VERSION || buf[5..8] != [0, 0, 0] { |
| 887 | return Err(SealError::UsageStore); |
| 888 | } |
| 889 | let n = u32::from_le_bytes([buf[8], buf[9], buf[10], buf[11]]) as usize; |
| 890 | if n > MAX_KEY_FINGERPRINTS || KEY_LIST_HEADER + n * 32 != buf.len() { |
| 891 | return Err(SealError::UsageStore); |
| 892 | } |
| 893 | let mut fps = Vec::with_capacity(n); |
| 894 | for i in 0..n { |
| 895 | let start = KEY_LIST_HEADER + i * 32; |
| 896 | let mut fp = [0u8; 32]; |
| 897 | fp.copy_from_slice(&buf[start..start + 32]); |
| 898 | if fps.iter().any(|existing| existing == &fp) { |
| 899 | return Err(SealError::UsageStore); |
| 900 | } |
| 901 | fps.push(fp); |
| 902 | } |
| 903 | Ok(Some(fps)) |
| 904 | } |
| 905 | |
| 906 | /// Whether `objects/<shard>/*.kvc` holds an AKS v2 object. There is no |
| 907 | /// seeder: this does not count files, and it does not read a key id. The |
| 908 | /// v2 seal slot has none. |
| 909 | fn store_already_holds_sealed_object(usage_dir: &Path) -> Result<bool, SealError> { |
| 910 | if !tracks_store_objects(usage_dir) { |
| 911 | return Ok(false); |
| 912 | } |
| 913 | let Some(root) = usage_dir.parent() else { |
| 914 | return Err(SealError::UsageStore); |
| 915 | }; |
| 916 | if root.as_os_str().is_empty() { |
| 917 | return Err(SealError::UsageStore); |
| 918 | } |
| 919 | let objects = root.join("objects"); |
| 920 | match std::fs::symlink_metadata(&objects) { |
| 921 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false), |
| 922 | Err(_) => return Err(SealError::UsageStore), |
| 923 | Ok(meta) if meta.file_type().is_symlink() || !meta.is_dir() => { |
| 924 | return Err(SealError::UsageStore); |
| 925 | } |
| 926 | Ok(_) => {} |
| 927 | } |
| 928 | let shards = std::fs::read_dir(&objects).map_err(|_| SealError::UsageStore)?; |
| 929 | for shard in shards { |
| 930 | let shard = shard.map_err(|_| SealError::UsageStore)?; |
| 931 | let shard_meta = |
| 932 | std::fs::symlink_metadata(shard.path()).map_err(|_| SealError::UsageStore)?; |
| 933 | if shard_meta.file_type().is_symlink() { |
| 934 | return Err(SealError::UsageStore); |
| 935 | } |
| 936 | if !shard_meta.is_dir() { |
| 937 | continue; |
| 938 | } |
| 939 | let files = std::fs::read_dir(shard.path()).map_err(|_| SealError::UsageStore)?; |
| 940 | for file in files { |
| 941 | let file = file.map_err(|_| SealError::UsageStore)?; |
| 942 | let path = file.path(); |
| 943 | let meta = std::fs::symlink_metadata(&path).map_err(|_| SealError::UsageStore)?; |
| 944 | if meta.file_type().is_symlink() { |
| 945 | return Err(SealError::UsageStore); |
| 946 | } |
| 947 | if !meta.is_file() { |
| 948 | continue; |
| 949 | } |
| 950 | let name = file.file_name(); |
| 951 | let Some(name) = name.to_str() else { |
| 952 | continue; |
| 953 | }; |
| 954 | if !name.ends_with(".kvc") { |
| 955 | continue; |
| 956 | } |
| 957 | if region_is_sealed(&path)? { |
| 958 | return Ok(true); |
| 959 | } |
| 960 | } |
| 961 | } |
| 962 | Ok(false) |
| 963 | } |
| 964 | |
| 965 | fn region_is_sealed(path: &Path) -> Result<bool, SealError> { |
| 966 | use std::os::unix::fs::OpenOptionsExt; |
| 967 | let mut f = OpenOptions::new() |
| 968 | .read(true) |
| 969 | .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC) |
| 970 | .open(path) |
| 971 | .map_err(|_| SealError::UsageStore)?; |
| 972 | let meta = f.metadata().map_err(|_| SealError::UsageStore)?; |
| 973 | if !meta.is_file() || meta.len() < HEADER_REGION_LEN as u64 { |
| 974 | return Ok(false); |
| 975 | } |
| 976 | f.seek(SeekFrom::Start(O_MAGIC as u64)) |
| 977 | .map_err(|_| SealError::UsageStore)?; |
| 978 | let mut magic = [0u8; 3]; |
| 979 | f.read_exact(&mut magic) |
| 980 | .map_err(|_| SealError::UsageStore)?; |
| 981 | let mut version = [0u8; 1]; |
| 982 | f.read_exact(&mut version) |
| 983 | .map_err(|_| SealError::UsageStore)?; |
| 984 | Ok(magic == SEAL_MAGIC && version[0] == SEALED_FORMAT_VERSION) |
| 985 | } |
| 986 | |
| 987 | /// `Ok` when `name.part` is absent or a regular file this uid owns. |
| 988 | /// A symlink, a directory, or another uid's file is [`SealError::UsageStore`] |
| 989 | /// and is left in place. |
| 990 | fn part_is_writable(dir: &Path, name: &str) -> Result<(), SealError> { |
| 991 | let part = dir.join(format!("{name}.part")); |
| 992 | match std::fs::symlink_metadata(&part) { |
| 993 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), |
| 994 | Err(_) => Err(SealError::UsageStore), |
| 995 | Ok(meta) if meta.file_type().is_symlink() || !meta.is_file() || meta.uid() != euid() => { |
| 996 | Err(SealError::UsageStore) |
| 997 | } |
| 998 | Ok(_) => Ok(()), |
| 999 | } |
| 1000 | } |
| 1001 | |
| 1002 | fn write_count_file(dir: &Path, name: &str, count: u64) -> Result<(), SealError> { |
| 1003 | write_durable(dir, name, &encode_count(count)) |
| 1004 | } |
| 1005 | |
| 1006 | fn write_key_fingerprints(dir: &Path, fps: &[[u8; 32]]) -> Result<(), SealError> { |
| 1007 | let bytes = encode_key_fingerprints(fps)?; |
| 1008 | write_durable(dir, KEY_FINGERPRINTS_NAME, &bytes) |
| 1009 | } |
| 1010 | |
| 1011 | fn write_durable(dir: &Path, name: &str, bytes: &[u8]) -> Result<(), SealError> { |
| 1012 | let final_path = dir.join(name); |
| 1013 | let part_path = dir.join(format!("{name}.part")); |
| 1014 | { |
| 1015 | let mut f = create_usage_file(&part_path)?; |
| 1016 | f.write_all(bytes).map_err(|_| SealError::UsageStore)?; |
| 1017 | f.sync_all().map_err(|_| SealError::UsageStore)?; |
| 1018 | } |
| 1019 | std::fs::rename(&part_path, &final_path).map_err(|_| SealError::UsageStore)?; |
| 1020 | fsync_usage_dir(dir) |
| 1021 | } |
| 1022 | |
| 1023 | fn encode_count(count: u64) -> [u8; USAGE_LEN] { |
| 1024 | let mut buf = [0u8; USAGE_LEN]; |
| 1025 | buf[0..4].copy_from_slice(&USAGE_MAGIC); |
| 1026 | buf[4] = USAGE_VERSION; |
| 1027 | buf[8..16].copy_from_slice(&count.to_le_bytes()); |
| 1028 | buf |
| 1029 | } |
| 1030 | |
| 1031 | fn encode_key_fingerprints(fps: &[[u8; 32]]) -> Result<Vec<u8>, SealError> { |
| 1032 | if fps.len() > MAX_KEY_FINGERPRINTS { |
| 1033 | return Err(SealError::UsageStore); |
| 1034 | } |
| 1035 | let mut buf = Vec::with_capacity(KEY_LIST_HEADER + fps.len() * 32); |
| 1036 | buf.extend_from_slice(&KEY_LIST_MAGIC); |
| 1037 | buf.push(KEY_LIST_VERSION); |
| 1038 | buf.extend_from_slice(&[0, 0, 0]); |
| 1039 | buf.extend_from_slice(&(fps.len() as u32).to_le_bytes()); |
| 1040 | for fp in fps { |
| 1041 | buf.extend_from_slice(fp); |
| 1042 | } |
| 1043 | Ok(buf) |
| 1044 | } |
| 1045 | |
| 1046 | fn fsync_usage_dir(dir: &Path) -> Result<(), SealError> { |
| 1047 | use std::os::unix::fs::OpenOptionsExt; |
| 1048 | let f = OpenOptions::new() |
| 1049 | .read(true) |
| 1050 | .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_DIRECTORY) |
| 1051 | .open(dir) |
| 1052 | .map_err(|_| SealError::UsageStore)?; |
| 1053 | f.sync_all().map_err(|_| SealError::UsageStore) |
| 1054 | } |
| 1055 | |
| 1056 | fn check_marker(region: &[u8]) -> Result<(), SealError> { |
| 1057 | if region[O_MAGIC..O_MAGIC + 3] != SEAL_MAGIC { |
| 1058 | return Err(SealError::NotSealed); |
| 1059 | } |
| 1060 | if region[O_VERSION] != SEALED_FORMAT_VERSION { |
| 1061 | return Err(SealError::UnsupportedVersion); |
| 1062 | } |
| 1063 | Ok(()) |
| 1064 | } |
| 1065 | |
| 1066 | /// The region carries the sealed-format marker (magic and version 2). Checks |
| 1067 | /// no key: recovery uses it to discard old plaintext-format files without |
| 1068 | /// reading their payload. |
| 1069 | pub fn is_sealed_region(region: &[u8]) -> bool { |
| 1070 | region.len() >= HEADER_REGION_LEN && check_marker(region).is_ok() |
| 1071 | } |
| 1072 | |
| 1073 | impl core::fmt::Debug for SealKey { |
| 1074 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { |
| 1075 | f.write_str("SealKey(redacted)") |
| 1076 | } |
| 1077 | } |
| 1078 | |
| 1079 | impl PartialEq for SealKey { |
| 1080 | /// Constant time over the 32 bytes. |
| 1081 | fn eq(&self, other: &Self) -> bool { |
| 1082 | self.bytes |
| 1083 | .iter() |
| 1084 | .zip(other.bytes.iter()) |
| 1085 | .fold(0u8, |acc, (a, b)| acc | (a ^ b)) |
| 1086 | == 0 |
| 1087 | } |
| 1088 | } |
| 1089 | |
| 1090 | impl Eq for SealKey {} |
| 1091 | |
| 1092 | static KEY_REFUSALS: AtomicU64 = AtomicU64::new(0); |
| 1093 | static OPEN_REJECTED: AtomicU64 = AtomicU64::new(0); |
| 1094 | |
| 1095 | /// Count one store-key refusal (the runtime calls it when it refuses persistence). |
| 1096 | pub fn note_key_refusal() { |
| 1097 | KEY_REFUSALS.fetch_add(1, Ordering::Relaxed); |
| 1098 | } |
| 1099 | |
| 1100 | /// Store-key refusals in this process. |
| 1101 | pub fn key_refusals_total() -> u64 { |
| 1102 | KEY_REFUSALS.load(Ordering::Relaxed) |
| 1103 | } |
| 1104 | |
| 1105 | /// Objects whose authentication failed in this process (each was discarded). |
| 1106 | pub fn open_rejected_total() -> u64 { |
| 1107 | OPEN_REJECTED.load(Ordering::Relaxed) |
| 1108 | } |
| 1109 | |
| 1110 | /// Calls, payload bytes and wall nanoseconds of one seal operation (#508 encryption cost). |
| 1111 | struct Timing { |
| 1112 | calls: AtomicU64, |
| 1113 | bytes: AtomicU64, |
| 1114 | ns: AtomicU64, |
| 1115 | } |
| 1116 | |
| 1117 | static SEAL_TIMING: Timing = Timing { |
| 1118 | calls: AtomicU64::new(0), |
| 1119 | bytes: AtomicU64::new(0), |
| 1120 | ns: AtomicU64::new(0), |
| 1121 | }; |
| 1122 | static OPEN_TIMING: Timing = Timing { |
| 1123 | calls: AtomicU64::new(0), |
| 1124 | bytes: AtomicU64::new(0), |
| 1125 | ns: AtomicU64::new(0), |
| 1126 | }; |
| 1127 | |
| 1128 | fn note_timing(t: &Timing, bytes: usize, t0: std::time::Instant) { |
| 1129 | let ns = u64::try_from(t0.elapsed().as_nanos()).unwrap_or(u64::MAX); |
| 1130 | t.calls.fetch_add(1, Ordering::Relaxed); |
| 1131 | t.bytes.fetch_add(bytes as u64, Ordering::Relaxed); |
| 1132 | t.ns.fetch_add(ns, Ordering::Relaxed); |
| 1133 | } |
| 1134 | |
| 1135 | /// Totals of [`SealKey::seal_file`] and [`SealKey::open_payload`] in this process: every call |
| 1136 | /// (refused ones included), the payload bytes it covered and the wall time it took. The |
| 1137 | /// encryption cost of persistence is `seal_ns` per parked byte and `open_ns` per restored byte. |
| 1138 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 1139 | pub struct SealTiming { |
| 1140 | pub seal_calls: u64, |
| 1141 | pub seal_bytes: u64, |
| 1142 | pub seal_ns: u64, |
| 1143 | pub open_calls: u64, |
| 1144 | pub open_bytes: u64, |
| 1145 | pub open_ns: u64, |
| 1146 | } |
| 1147 | |
| 1148 | pub fn seal_timing() -> SealTiming { |
| 1149 | let r = |a: &AtomicU64| a.load(Ordering::Relaxed); |
| 1150 | SealTiming { |
| 1151 | seal_calls: r(&SEAL_TIMING.calls), |
| 1152 | seal_bytes: r(&SEAL_TIMING.bytes), |
| 1153 | seal_ns: r(&SEAL_TIMING.ns), |
| 1154 | open_calls: r(&OPEN_TIMING.calls), |
| 1155 | open_bytes: r(&OPEN_TIMING.bytes), |
| 1156 | open_ns: r(&OPEN_TIMING.ns), |
| 1157 | } |
| 1158 | } |