use std::collections::BTreeMap;
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Write};
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
pub const BACKUP_FORMAT: &str = "org.knott.knottvm.backup";
pub const BACKUP_VERSION: u32 = 2;
pub const CONFIG_FILE: &str = "vm.toml";
pub const DISK_FILE: &str = "disk.qcow2";
pub const UEFI_VARS_FILE: &str = "uefi-vars.fd";
pub const TPM_STATE_DIR: &str = "tpm-state";
pub const MANIFEST_FILE: &str = "manifest.json";
pub(crate) const MAX_TPM_STATE_FILES: usize = 128;
pub(crate) const MAX_TPM_STATE_BYTES: u64 = 64 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FileDigest {
pub bytes: u64,
pub sha256: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BackupManifest {
pub format: String,
pub version: u32,
pub source_name: String,
pub created_at_unix: u64,
pub config: FileDigest,
pub disk: FileDigest,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub uefi_vars: Option<FileDigest>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tpm_state: Option<BTreeMap<String, FileDigest>>,
}
impl BackupManifest {
pub fn build(root: &Path, source_name: String) -> Result<Self> {
let config = digest_file(&root.join(CONFIG_FILE))?;
let disk = digest_file(&root.join(DISK_FILE))?;
let vars_path = root.join(UEFI_VARS_FILE);
let uefi_vars = match fs::symlink_metadata(&vars_path) {
Ok(_) => Some(digest_file(&vars_path)?),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
Err(error) => return Err(error.into()),
};
let tpm_state_path = root.join(TPM_STATE_DIR);
let tpm_state = match fs::symlink_metadata(&tpm_state_path) {
Ok(metadata) if metadata.is_dir() => Some(digest_tpm_directory(&tpm_state_path)?),
Ok(_) => bail!(
"backup TPM state {} is not a directory",
tpm_state_path.display()
),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
Err(error) => return Err(error.into()),
};
Ok(Self {
format: BACKUP_FORMAT.to_owned(),
version: BACKUP_VERSION,
source_name,
created_at_unix: SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs(),
config,
disk,
uefi_vars,
tpm_state,
})
}
pub fn load(root: &Path) -> Result<Self> {
const MAX_MANIFEST_BYTES: u64 = 64 * 1024;
let path = root.join(MANIFEST_FILE);
let file = File::open(&path)
.with_context(|| format!("failed to open backup manifest {}", path.display()))?;
let mut source = Vec::new();
file.take(MAX_MANIFEST_BYTES + 1).read_to_end(&mut source)?;
if source.len() as u64 > MAX_MANIFEST_BYTES {
bail!("backup manifest exceeded {MAX_MANIFEST_BYTES} bytes");
}
let manifest: Self = serde_json::from_slice(&source)
.with_context(|| format!("failed to parse backup manifest {}", path.display()))?;
manifest.validate_schema()?;
Ok(manifest)
}
pub fn save(&self, root: &Path) -> Result<PathBuf> {
self.validate_schema()?;
let path = root.join(MANIFEST_FILE);
let mut file = OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
.with_context(|| format!("failed to create backup manifest {}", path.display()))?;
serde_json::to_writer_pretty(&mut file, self)?;
file.write_all(b"\n")?;
file.sync_all()?;
Ok(path)
}
pub fn verify(&self, root: &Path) -> Result<()> {
self.validate_schema()?;
verify_digest(&root.join(CONFIG_FILE), &self.config)?;
verify_digest(&root.join(DISK_FILE), &self.disk)?;
let vars_path = root.join(UEFI_VARS_FILE);
match (&self.uefi_vars, fs::symlink_metadata(&vars_path)) {
(Some(expected), Ok(_)) => verify_digest(&vars_path, expected)?,
(Some(_), Err(error)) if error.kind() == std::io::ErrorKind::NotFound => {
bail!("backup is missing declared UEFI variables");
}
(None, Ok(_)) => bail!("backup contains undeclared UEFI variables"),
(None, Err(error)) if error.kind() == std::io::ErrorKind::NotFound => {}
(_, Err(error)) => return Err(error.into()),
}
let tpm_state_path = root.join(TPM_STATE_DIR);
match (&self.tpm_state, fs::symlink_metadata(&tpm_state_path)) {
(Some(expected), Ok(metadata)) if metadata.is_dir() => {
let actual = digest_tpm_directory(&tpm_state_path)?;
if &actual != expected {
bail!("backup TPM state failed integrity verification");
}
}
(Some(_), Ok(_)) => bail!("backup TPM state is not a directory"),
(Some(_), Err(error)) if error.kind() == std::io::ErrorKind::NotFound => {
bail!("backup is missing declared TPM state");
}
(None, Ok(_)) => bail!("backup contains undeclared TPM state"),
(None, Err(error)) if error.kind() == std::io::ErrorKind::NotFound => {}
(_, Err(error)) => return Err(error.into()),
}
Ok(())
}
fn validate_schema(&self) -> Result<()> {
if self.format != BACKUP_FORMAT {
bail!("unsupported backup format {}", self.format);
}
if !matches!(self.version, 1 | BACKUP_VERSION) {
bail!(
"unsupported backup version {}; expected 1 or {BACKUP_VERSION}",
self.version
);
}
if self.version == 1 && self.tpm_state.is_some() {
bail!("version-1 backups cannot contain software TPM state");
}
if self.source_name.is_empty() || self.source_name.len() > 64 {
bail!("backup source name is invalid");
}
Ok(())
}
}
fn digest_tpm_directory(path: &Path) -> Result<BTreeMap<String, FileDigest>> {
let metadata = fs::symlink_metadata(path)?;
if !metadata.is_dir() || metadata.file_type().is_symlink() {
bail!("TPM state {} is not a real directory", path.display());
}
let mut files = BTreeMap::new();
let mut total_bytes = 0_u64;
for entry in fs::read_dir(path)? {
let entry = entry?;
let name = entry.file_name();
let Some(name) = name.to_str() else {
bail!("TPM state contains a non-UTF-8 filename");
};
validate_tpm_state_name(name)?;
let entry_metadata = fs::symlink_metadata(entry.path())?;
if !entry_metadata.is_file() || entry_metadata.file_type().is_symlink() {
bail!(
"TPM state entry {} is not a regular file",
entry.path().display()
);
}
if files.len() >= MAX_TPM_STATE_FILES {
bail!("TPM state contains more than {MAX_TPM_STATE_FILES} files");
}
let digest = digest_tpm_file(&entry.path())?;
total_bytes = total_bytes
.checked_add(digest.bytes)
.context("TPM state size overflow")?;
if total_bytes > MAX_TPM_STATE_BYTES {
bail!("TPM state exceeds {MAX_TPM_STATE_BYTES} bytes");
}
files.insert(name.to_owned(), digest);
}
Ok(files)
}
fn digest_tpm_file(path: &Path) -> Result<FileDigest> {
let mut file = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW)
.open(path)
.with_context(|| format!("failed to open TPM state {}", path.display()))?;
let metadata = file.metadata()?;
if !metadata.is_file() || metadata.len() > MAX_TPM_STATE_BYTES {
bail!(
"TPM state file {} exceeds the managed size limit",
path.display()
);
}
let expected_bytes = metadata.len();
let mut bytes = 0_u64;
let mut hasher = Sha256::new();
let mut buffer = vec![0_u8; 128 * 1024];
loop {
let read = file.read(&mut buffer)?;
if read == 0 {
break;
}
bytes = bytes
.checked_add(u64::try_from(read)?)
.context("TPM state file size overflow")?;
if bytes > MAX_TPM_STATE_BYTES {
bail!(
"TPM state file {} exceeds the managed size limit",
path.display()
);
}
hasher.update(&buffer[..read]);
}
if bytes != expected_bytes || file.metadata()?.len() != expected_bytes {
bail!("TPM state file {} changed while being read", path.display());
}
Ok(FileDigest {
bytes,
sha256: format!("{:x}", hasher.finalize()),
})
}
pub(crate) fn validate_tpm_state_name(name: &str) -> Result<()> {
let safe_component = !name.is_empty()
&& name.len() <= 128
&& name != "."
&& name != ".."
&& name
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'));
let tpm_blob = name
.strip_prefix("tpm2-00.")
.is_some_and(|suffix| !suffix.is_empty());
let backend_lock = name == ".lock";
let context_blob = name
.strip_prefix('h')
.and_then(|value| value.strip_suffix(".bin"))
.is_some_and(|hex| hex.len() == 8 && hex.bytes().all(|byte| byte.is_ascii_hexdigit()));
if !safe_component || !(backend_lock || tpm_blob || context_blob) {
bail!("TPM state filename is not a safe single path component");
}
Ok(())
}
fn verify_digest(path: &Path, expected: &FileDigest) -> Result<()> {
let actual = digest_file(path)?;
if &actual != expected {
bail!(
"backup artifact {} failed integrity verification",
path.display()
);
}
Ok(())
}
fn digest_file(path: &Path) -> Result<FileDigest> {
let mut file = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW)
.open(path)
.with_context(|| format!("failed to open backup artifact {}", path.display()))?;
let metadata = file.metadata()?;
if !metadata.is_file() {
bail!("backup artifact {} is not a regular file", path.display());
}
let mut hasher = Sha256::new();
let mut buffer = vec![0_u8; 128 * 1024];
loop {
let read = file.read(&mut buffer)?;
if read == 0 {
break;
}
hasher.update(&buffer[..read]);
}
Ok(FileDigest {
bytes: metadata.len(),
sha256: format!("{:x}", hasher.finalize()),
})
}
#[cfg(test)]
mod tests {
use super::{BackupManifest, CONFIG_FILE, DISK_FILE, TPM_STATE_DIR};
use std::fs;
use std::os::unix::fs::symlink;
use tempfile::tempdir;
#[test]
fn detects_tampered_backup_artifacts() {
let root = tempdir().unwrap();
fs::write(root.path().join(CONFIG_FILE), b"config").unwrap();
fs::write(root.path().join(DISK_FILE), b"disk").unwrap();
let manifest = BackupManifest::build(root.path(), "test".to_owned()).unwrap();
manifest.save(root.path()).unwrap();
let loaded = BackupManifest::load(root.path()).unwrap();
loaded.verify(root.path()).unwrap();
fs::write(root.path().join(DISK_FILE), b"changed").unwrap();
assert!(loaded.verify(root.path()).is_err());
}
#[test]
fn manifests_and_verifies_flat_tpm_state_files() {
let root = tempdir().unwrap();
fs::write(root.path().join(CONFIG_FILE), b"config").unwrap();
fs::write(root.path().join(DISK_FILE), b"disk").unwrap();
let tpm = root.path().join(TPM_STATE_DIR);
fs::create_dir(&tpm).unwrap();
fs::write(tpm.join("tpm2-00.permall"), b"permanent state").unwrap();
fs::write(tpm.join("h02000000.bin"), b"context").unwrap();
fs::write(tpm.join(".lock"), []).unwrap();
let manifest = BackupManifest::build(root.path(), "test".to_owned()).unwrap();
assert_eq!(manifest.version, 2);
assert_eq!(manifest.tpm_state.as_ref().unwrap().len(), 3);
manifest.save(root.path()).unwrap();
BackupManifest::load(root.path())
.unwrap()
.verify(root.path())
.unwrap();
fs::write(tpm.join("h02000000.bin"), b"tampered").unwrap();
assert!(manifest.verify(root.path()).is_err());
}
#[test]
fn tpm_manifest_rejects_unexpected_nodes_and_unmanifested_directories() {
let root = tempdir().unwrap();
fs::write(root.path().join(CONFIG_FILE), b"config").unwrap();
fs::write(root.path().join(DISK_FILE), b"disk").unwrap();
let tpm = root.path().join(TPM_STATE_DIR);
fs::create_dir(&tpm).unwrap();
fs::write(tpm.join("tpm2-00.permall"), b"state").unwrap();
let outside = root.path().join("outside");
fs::write(&outside, b"preserve").unwrap();
symlink(&outside, tpm.join("tpm2-00.volatilestate")).unwrap();
assert!(BackupManifest::build(root.path(), "test".to_owned()).is_err());
fs::remove_file(tpm.join("tpm2-00.volatilestate")).unwrap();
let mut manifest = BackupManifest::build(root.path(), "test".to_owned()).unwrap();
manifest.tpm_state = None;
assert!(manifest.verify(root.path()).is_err());
assert_eq!(fs::read(outside).unwrap(), b"preserve");
}
#[test]
fn continues_to_verify_version_one_backups() {
let root = tempdir().unwrap();
fs::write(root.path().join(CONFIG_FILE), b"config").unwrap();
fs::write(root.path().join(DISK_FILE), b"disk").unwrap();
let mut manifest = BackupManifest::build(root.path(), "test".to_owned()).unwrap();
manifest.version = 1;
manifest.save(root.path()).unwrap();
BackupManifest::load(root.path())
.unwrap()
.verify(root.path())
.unwrap();
}
}