1use std::collections::BTreeMap;
4use std::fs::{self, File, OpenOptions};
5use std::io::{Read, Write};
6use std::os::unix::fs::OpenOptionsExt;
7use std::path::{Path, PathBuf};
8use std::time::{SystemTime, UNIX_EPOCH};
9
10use anyhow::{Context, Result, bail};
11use serde::{Deserialize, Serialize};
12use sha2::{Digest, Sha256};
13
14pub const BACKUP_FORMAT: &str = "org.knott.knottvm.backup";
16pub const BACKUP_VERSION: u32 = 2;
18pub const CONFIG_FILE: &str = "vm.toml";
20pub const DISK_FILE: &str = "disk.qcow2";
22pub const UEFI_VARS_FILE: &str = "uefi-vars.fd";
24pub const TPM_STATE_DIR: &str = "tpm-state";
26pub const MANIFEST_FILE: &str = "manifest.json";
28pub(crate) const MAX_TPM_STATE_FILES: usize = 128;
29pub(crate) const MAX_TPM_STATE_BYTES: u64 = 64 * 1024 * 1024;
30
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33#[serde(deny_unknown_fields)]
34pub struct FileDigest {
35 pub bytes: u64,
37 pub sha256: String,
39}
40
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43#[serde(deny_unknown_fields)]
44pub struct BackupManifest {
45 pub format: String,
47 pub version: u32,
49 pub source_name: String,
51 pub created_at_unix: u64,
53 pub config: FileDigest,
55 pub disk: FileDigest,
57 #[serde(default, skip_serializing_if = "Option::is_none")]
59 pub uefi_vars: Option<FileDigest>,
60 #[serde(default, skip_serializing_if = "Option::is_none")]
62 pub tpm_state: Option<BTreeMap<String, FileDigest>>,
63}
64
65impl BackupManifest {
66 pub fn build(root: &Path, source_name: String) -> Result<Self> {
68 let config = digest_file(&root.join(CONFIG_FILE))?;
69 let disk = digest_file(&root.join(DISK_FILE))?;
70 let vars_path = root.join(UEFI_VARS_FILE);
71 let uefi_vars = match fs::symlink_metadata(&vars_path) {
72 Ok(_) => Some(digest_file(&vars_path)?),
73 Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
74 Err(error) => return Err(error.into()),
75 };
76 let tpm_state_path = root.join(TPM_STATE_DIR);
77 let tpm_state = match fs::symlink_metadata(&tpm_state_path) {
78 Ok(metadata) if metadata.is_dir() => Some(digest_tpm_directory(&tpm_state_path)?),
79 Ok(_) => bail!(
80 "backup TPM state {} is not a directory",
81 tpm_state_path.display()
82 ),
83 Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
84 Err(error) => return Err(error.into()),
85 };
86 Ok(Self {
87 format: BACKUP_FORMAT.to_owned(),
88 version: BACKUP_VERSION,
89 source_name,
90 created_at_unix: SystemTime::now()
91 .duration_since(UNIX_EPOCH)
92 .unwrap_or_default()
93 .as_secs(),
94 config,
95 disk,
96 uefi_vars,
97 tpm_state,
98 })
99 }
100
101 pub fn load(root: &Path) -> Result<Self> {
103 const MAX_MANIFEST_BYTES: u64 = 64 * 1024;
104 let path = root.join(MANIFEST_FILE);
105 let file = File::open(&path)
106 .with_context(|| format!("failed to open backup manifest {}", path.display()))?;
107 let mut source = Vec::new();
108 file.take(MAX_MANIFEST_BYTES + 1).read_to_end(&mut source)?;
109 if source.len() as u64 > MAX_MANIFEST_BYTES {
110 bail!("backup manifest exceeded {MAX_MANIFEST_BYTES} bytes");
111 }
112 let manifest: Self = serde_json::from_slice(&source)
113 .with_context(|| format!("failed to parse backup manifest {}", path.display()))?;
114 manifest.validate_schema()?;
115 Ok(manifest)
116 }
117
118 pub fn save(&self, root: &Path) -> Result<PathBuf> {
120 self.validate_schema()?;
121 let path = root.join(MANIFEST_FILE);
122 let mut file = OpenOptions::new()
123 .write(true)
124 .create_new(true)
125 .open(&path)
126 .with_context(|| format!("failed to create backup manifest {}", path.display()))?;
127 serde_json::to_writer_pretty(&mut file, self)?;
128 file.write_all(b"\n")?;
129 file.sync_all()?;
130 Ok(path)
131 }
132
133 pub fn verify(&self, root: &Path) -> Result<()> {
135 self.validate_schema()?;
136 verify_digest(&root.join(CONFIG_FILE), &self.config)?;
137 verify_digest(&root.join(DISK_FILE), &self.disk)?;
138 let vars_path = root.join(UEFI_VARS_FILE);
139 match (&self.uefi_vars, fs::symlink_metadata(&vars_path)) {
140 (Some(expected), Ok(_)) => verify_digest(&vars_path, expected)?,
141 (Some(_), Err(error)) if error.kind() == std::io::ErrorKind::NotFound => {
142 bail!("backup is missing declared UEFI variables");
143 }
144 (None, Ok(_)) => bail!("backup contains undeclared UEFI variables"),
145 (None, Err(error)) if error.kind() == std::io::ErrorKind::NotFound => {}
146 (_, Err(error)) => return Err(error.into()),
147 }
148 let tpm_state_path = root.join(TPM_STATE_DIR);
149 match (&self.tpm_state, fs::symlink_metadata(&tpm_state_path)) {
150 (Some(expected), Ok(metadata)) if metadata.is_dir() => {
151 let actual = digest_tpm_directory(&tpm_state_path)?;
152 if &actual != expected {
153 bail!("backup TPM state failed integrity verification");
154 }
155 }
156 (Some(_), Ok(_)) => bail!("backup TPM state is not a directory"),
157 (Some(_), Err(error)) if error.kind() == std::io::ErrorKind::NotFound => {
158 bail!("backup is missing declared TPM state");
159 }
160 (None, Ok(_)) => bail!("backup contains undeclared TPM state"),
161 (None, Err(error)) if error.kind() == std::io::ErrorKind::NotFound => {}
162 (_, Err(error)) => return Err(error.into()),
163 }
164 Ok(())
165 }
166
167 fn validate_schema(&self) -> Result<()> {
168 if self.format != BACKUP_FORMAT {
169 bail!("unsupported backup format {}", self.format);
170 }
171 if !matches!(self.version, 1 | BACKUP_VERSION) {
172 bail!(
173 "unsupported backup version {}; expected 1 or {BACKUP_VERSION}",
174 self.version
175 );
176 }
177 if self.version == 1 && self.tpm_state.is_some() {
178 bail!("version-1 backups cannot contain software TPM state");
179 }
180 if self.source_name.is_empty() || self.source_name.len() > 64 {
181 bail!("backup source name is invalid");
182 }
183 Ok(())
184 }
185}
186
187fn digest_tpm_directory(path: &Path) -> Result<BTreeMap<String, FileDigest>> {
188 let metadata = fs::symlink_metadata(path)?;
189 if !metadata.is_dir() || metadata.file_type().is_symlink() {
190 bail!("TPM state {} is not a real directory", path.display());
191 }
192 let mut files = BTreeMap::new();
193 let mut total_bytes = 0_u64;
194 for entry in fs::read_dir(path)? {
195 let entry = entry?;
196 let name = entry.file_name();
197 let Some(name) = name.to_str() else {
198 bail!("TPM state contains a non-UTF-8 filename");
199 };
200 validate_tpm_state_name(name)?;
201 let entry_metadata = fs::symlink_metadata(entry.path())?;
202 if !entry_metadata.is_file() || entry_metadata.file_type().is_symlink() {
203 bail!(
204 "TPM state entry {} is not a regular file",
205 entry.path().display()
206 );
207 }
208 if files.len() >= MAX_TPM_STATE_FILES {
209 bail!("TPM state contains more than {MAX_TPM_STATE_FILES} files");
210 }
211 let digest = digest_tpm_file(&entry.path())?;
212 total_bytes = total_bytes
213 .checked_add(digest.bytes)
214 .context("TPM state size overflow")?;
215 if total_bytes > MAX_TPM_STATE_BYTES {
216 bail!("TPM state exceeds {MAX_TPM_STATE_BYTES} bytes");
217 }
218 files.insert(name.to_owned(), digest);
219 }
220 Ok(files)
221}
222
223fn digest_tpm_file(path: &Path) -> Result<FileDigest> {
224 let mut file = OpenOptions::new()
225 .read(true)
226 .custom_flags(libc::O_NOFOLLOW)
227 .open(path)
228 .with_context(|| format!("failed to open TPM state {}", path.display()))?;
229 let metadata = file.metadata()?;
230 if !metadata.is_file() || metadata.len() > MAX_TPM_STATE_BYTES {
231 bail!(
232 "TPM state file {} exceeds the managed size limit",
233 path.display()
234 );
235 }
236 let expected_bytes = metadata.len();
237 let mut bytes = 0_u64;
238 let mut hasher = Sha256::new();
239 let mut buffer = vec![0_u8; 128 * 1024];
240 loop {
241 let read = file.read(&mut buffer)?;
242 if read == 0 {
243 break;
244 }
245 bytes = bytes
246 .checked_add(u64::try_from(read)?)
247 .context("TPM state file size overflow")?;
248 if bytes > MAX_TPM_STATE_BYTES {
249 bail!(
250 "TPM state file {} exceeds the managed size limit",
251 path.display()
252 );
253 }
254 hasher.update(&buffer[..read]);
255 }
256 if bytes != expected_bytes || file.metadata()?.len() != expected_bytes {
257 bail!("TPM state file {} changed while being read", path.display());
258 }
259 Ok(FileDigest {
260 bytes,
261 sha256: format!("{:x}", hasher.finalize()),
262 })
263}
264
265pub(crate) fn validate_tpm_state_name(name: &str) -> Result<()> {
266 let safe_component = !name.is_empty()
267 && name.len() <= 128
268 && name != "."
269 && name != ".."
270 && name
271 .bytes()
272 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'));
273 let tpm_blob = name
274 .strip_prefix("tpm2-00.")
275 .is_some_and(|suffix| !suffix.is_empty());
276 let backend_lock = name == ".lock";
278 let context_blob = name
279 .strip_prefix('h')
280 .and_then(|value| value.strip_suffix(".bin"))
281 .is_some_and(|hex| hex.len() == 8 && hex.bytes().all(|byte| byte.is_ascii_hexdigit()));
282 if !safe_component || !(backend_lock || tpm_blob || context_blob) {
283 bail!("TPM state filename is not a safe single path component");
284 }
285 Ok(())
286}
287
288fn verify_digest(path: &Path, expected: &FileDigest) -> Result<()> {
289 let actual = digest_file(path)?;
290 if &actual != expected {
291 bail!(
292 "backup artifact {} failed integrity verification",
293 path.display()
294 );
295 }
296 Ok(())
297}
298
299fn digest_file(path: &Path) -> Result<FileDigest> {
300 let mut file = OpenOptions::new()
301 .read(true)
302 .custom_flags(libc::O_NOFOLLOW)
303 .open(path)
304 .with_context(|| format!("failed to open backup artifact {}", path.display()))?;
305 let metadata = file.metadata()?;
306 if !metadata.is_file() {
307 bail!("backup artifact {} is not a regular file", path.display());
308 }
309 let mut hasher = Sha256::new();
310 let mut buffer = vec![0_u8; 128 * 1024];
311 loop {
312 let read = file.read(&mut buffer)?;
313 if read == 0 {
314 break;
315 }
316 hasher.update(&buffer[..read]);
317 }
318 Ok(FileDigest {
319 bytes: metadata.len(),
320 sha256: format!("{:x}", hasher.finalize()),
321 })
322}
323
324#[cfg(test)]
325mod tests {
326 use super::{BackupManifest, CONFIG_FILE, DISK_FILE, TPM_STATE_DIR};
327 use std::fs;
328 use std::os::unix::fs::symlink;
329 use tempfile::tempdir;
330
331 #[test]
332 fn detects_tampered_backup_artifacts() {
333 let root = tempdir().unwrap();
334 fs::write(root.path().join(CONFIG_FILE), b"config").unwrap();
335 fs::write(root.path().join(DISK_FILE), b"disk").unwrap();
336 let manifest = BackupManifest::build(root.path(), "test".to_owned()).unwrap();
337 manifest.save(root.path()).unwrap();
338 let loaded = BackupManifest::load(root.path()).unwrap();
339 loaded.verify(root.path()).unwrap();
340 fs::write(root.path().join(DISK_FILE), b"changed").unwrap();
341 assert!(loaded.verify(root.path()).is_err());
342 }
343
344 #[test]
345 fn manifests_and_verifies_flat_tpm_state_files() {
346 let root = tempdir().unwrap();
347 fs::write(root.path().join(CONFIG_FILE), b"config").unwrap();
348 fs::write(root.path().join(DISK_FILE), b"disk").unwrap();
349 let tpm = root.path().join(TPM_STATE_DIR);
350 fs::create_dir(&tpm).unwrap();
351 fs::write(tpm.join("tpm2-00.permall"), b"permanent state").unwrap();
352 fs::write(tpm.join("h02000000.bin"), b"context").unwrap();
353 fs::write(tpm.join(".lock"), []).unwrap();
354 let manifest = BackupManifest::build(root.path(), "test".to_owned()).unwrap();
355 assert_eq!(manifest.version, 2);
356 assert_eq!(manifest.tpm_state.as_ref().unwrap().len(), 3);
357 manifest.save(root.path()).unwrap();
358 BackupManifest::load(root.path())
359 .unwrap()
360 .verify(root.path())
361 .unwrap();
362
363 fs::write(tpm.join("h02000000.bin"), b"tampered").unwrap();
364 assert!(manifest.verify(root.path()).is_err());
365 }
366
367 #[test]
368 fn tpm_manifest_rejects_unexpected_nodes_and_unmanifested_directories() {
369 let root = tempdir().unwrap();
370 fs::write(root.path().join(CONFIG_FILE), b"config").unwrap();
371 fs::write(root.path().join(DISK_FILE), b"disk").unwrap();
372 let tpm = root.path().join(TPM_STATE_DIR);
373 fs::create_dir(&tpm).unwrap();
374 fs::write(tpm.join("tpm2-00.permall"), b"state").unwrap();
375 let outside = root.path().join("outside");
376 fs::write(&outside, b"preserve").unwrap();
377 symlink(&outside, tpm.join("tpm2-00.volatilestate")).unwrap();
378 assert!(BackupManifest::build(root.path(), "test".to_owned()).is_err());
379
380 fs::remove_file(tpm.join("tpm2-00.volatilestate")).unwrap();
381 let mut manifest = BackupManifest::build(root.path(), "test".to_owned()).unwrap();
382 manifest.tpm_state = None;
383 assert!(manifest.verify(root.path()).is_err());
384 assert_eq!(fs::read(outside).unwrap(), b"preserve");
385 }
386
387 #[test]
388 fn continues_to_verify_version_one_backups() {
389 let root = tempdir().unwrap();
390 fs::write(root.path().join(CONFIG_FILE), b"config").unwrap();
391 fs::write(root.path().join(DISK_FILE), b"disk").unwrap();
392 let mut manifest = BackupManifest::build(root.path(), "test".to_owned()).unwrap();
393 manifest.version = 1;
394 manifest.save(root.path()).unwrap();
395 BackupManifest::load(root.path())
396 .unwrap()
397 .verify(root.path())
398 .unwrap();
399 }
400}