use anyhow::{bail, ensure, Context, Result}; use argon2::{Algorithm, Argon2, Params, Version}; use base64::Engine as _; use rand::{rngs::SysRng, TryRng}; use ring::aead::{Aad, LessSafeKey, Nonce, UnboundKey, AES_256_GCM}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::{ fs::{self, File, OpenOptions}, io::{Read, Write}, path::{Component, Path, PathBuf}, }; use zeroize::Zeroizing; const BACKUP_MAGIC: &[u8; 8] = b"RPROXYB1"; const ARCHIVE_MAGIC: &[u8; 8] = b"RPROXYA1"; const KEY_MAGIC: &[u8; 4] = b"RPK1"; const FORMAT_VERSION: u32 = 1; const ARCHIVE_VERSION: u32 = 2; const CHUNK_SIZE: usize = 1024 * 1024; const ARGON_MEMORY_KIB: u32 = 64 * 1024; const ARGON_ITERATIONS: u32 = 3; const ARGON_PARALLELISM: u32 = 1; const MAX_HEADER_BYTES: usize = 16 * 1024; const MAX_MANIFEST_BYTES: usize = 1024 * 1024; const KEY_AAD: &[u8] = b"rustproxy-secret-store-key-v1"; #[derive(Debug, Clone, Serialize, Deserialize)] struct CryptoHeader { format_version: u32, kdf: String, salt_b64: String, memory_kib: u32, iterations: u32, parallelism: u32, aead: String, nonce_prefix_b64: String, chunk_size: usize, } struct CryptoContext { header_bytes: Vec, key: Zeroizing<[u8; 32]>, nonce_prefix: [u8; 4], } #[derive(Debug, Clone, Serialize, Deserialize)] struct Manifest { archive_version: u32, rustproxy_version: String, schema_version: i64, configuration_revision: u64, created_at_unix: i64, secret_store_encryption_version: u32, backup_encryption: String, entries: Vec, } #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] enum EntryKind { #[default] File, Directory, Symlink, } #[derive(Debug, Clone, Serialize, Deserialize)] struct ManifestEntry { path: String, size: u64, sha256: String, #[serde(default, skip_serializing_if = "is_file_entry")] kind: EntryKind, } fn is_file_entry(kind: &EntryKind) -> bool { *kind == EntryKind::File } enum EntrySource { File(PathBuf), Bytes(Vec), } struct ArchiveEntry { manifest: ManifestEntry, source: EntrySource, } #[derive(Debug, Clone)] pub struct BackupSummary { pub path: PathBuf, pub files: usize, pub configuration_revision: u64, } struct TempRoot(PathBuf); impl Drop for TempRoot { fn drop(&mut self) { let _ = fs::remove_dir_all(&self.0); } } struct PartialFile(PathBuf, bool); impl Drop for PartialFile { fn drop(&mut self) { if !self.1 { let _ = fs::remove_file(&self.0); } } } fn parent_or_dot(path: &Path) -> &Path { path.parent() .filter(|parent| !parent.as_os_str().is_empty()) .unwrap_or_else(|| Path::new(".")) } fn validate_backup_version(version: &str) -> Result<()> { fn parse(value: &str) -> Result<(u64, u64, u64)> { let value = value.split_once('-').map_or(value, |(base, _)| base); let mut parts = value.split('.'); let major = parts.next().context("missing major version")?.parse()?; let minor = parts.next().context("missing minor version")?.parse()?; let patch = parts.next().context("missing patch version")?.parse()?; ensure!(parts.next().is_none(), "invalid RustProxy version"); Ok((major, minor, patch)) } let backup = parse(version).context("invalid RustProxy version in backup manifest")?; let current = parse(env!("CARGO_PKG_VERSION")).context("invalid running RustProxy version")?; ensure!( backup <= current, "backup was created by newer RustProxy version {version}; current version is {}", env!("CARGO_PKG_VERSION") ); Ok(()) } fn harden_tree(root: &Path, path: &Path) -> Result<()> { let metadata = fs::symlink_metadata(path)?; if metadata.file_type().is_symlink() { let resolved = fs::canonicalize(path).context("restored symlink target is missing")?; let canonical_root = fs::canonicalize(root)?; ensure!( resolved.starts_with(&canonical_root), "restored symlink escapes the data directory" ); return Ok(()); } #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let mode = if metadata.is_dir() { 0o700 } else { 0o600 }; fs::set_permissions(path, fs::Permissions::from_mode(mode))?; } if metadata.is_dir() { for entry in fs::read_dir(path)? { harden_tree(root, &entry?.path())?; } } Ok(()) } fn private_dir(path: &Path) -> Result<()> { fs::create_dir_all(path)?; let meta = fs::symlink_metadata(path)?; ensure!( meta.is_dir() && !meta.file_type().is_symlink(), "backup directory must not be a symlink" ); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; fs::set_permissions(path, fs::Permissions::from_mode(0o700))?; } Ok(()) } fn private_file_options() -> OpenOptions { let mut options = OpenOptions::new(); options.write(true).read(true); #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; options.mode(0o600).custom_flags(libc::O_NOFOLLOW); } options } fn create_temp_root(parent: &Path, prefix: &str) -> Result { ensure!(parent.is_dir(), "backup parent directory does not exist"); for _ in 0..32 { let name = format!(".{prefix}-{:016x}", rand::random::()); let path = parent.join(name); match fs::create_dir(&path) { Ok(()) => { #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; fs::set_permissions(&path, fs::Permissions::from_mode(0o700))?; } return Ok(TempRoot(path)); } Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, Err(error) => return Err(error.into()), } } bail!("could not allocate private backup staging directory") } fn derive_key(password: &str, salt: &[u8]) -> Result> { ensure!(!password.is_empty(), "backup password cannot be empty"); let params = Params::new( ARGON_MEMORY_KIB, ARGON_ITERATIONS, ARGON_PARALLELISM, Some(32), ) .map_err(|_| anyhow::anyhow!("invalid backup KDF parameters"))?; let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params); let mut key = Zeroizing::new([0u8; 32]); argon .hash_password_into(password.as_bytes(), salt, key.as_mut()) .map_err(|_| anyhow::anyhow!("backup key derivation failed"))?; Ok(key) } fn new_crypto(password: &str) -> Result { let mut salt = [0u8; 16]; let mut nonce_prefix = [0u8; 4]; SysRng .try_fill_bytes(&mut salt) .expect("secure operating system random source unavailable"); SysRng .try_fill_bytes(&mut nonce_prefix) .expect("secure operating system random source unavailable"); let header = CryptoHeader { format_version: FORMAT_VERSION, kdf: "Argon2id".into(), salt_b64: base64::engine::general_purpose::STANDARD.encode(salt), memory_kib: ARGON_MEMORY_KIB, iterations: ARGON_ITERATIONS, parallelism: ARGON_PARALLELISM, aead: "AES-256-GCM".into(), nonce_prefix_b64: base64::engine::general_purpose::STANDARD.encode(nonce_prefix), chunk_size: CHUNK_SIZE, }; let header_bytes = serde_json::to_vec(&header)?; let key = derive_key(password, &salt)?; Ok(CryptoContext { header_bytes, key, nonce_prefix, }) } fn parse_crypto_header(bytes: Vec, password: &str) -> Result { let header: CryptoHeader = serde_json::from_slice(&bytes).context("invalid backup header")?; ensure!( header.format_version == FORMAT_VERSION && header.kdf == "Argon2id" && header.memory_kib == ARGON_MEMORY_KIB && header.iterations == ARGON_ITERATIONS && header.parallelism == ARGON_PARALLELISM && header.aead == "AES-256-GCM" && header.chunk_size == CHUNK_SIZE, "unsupported backup cryptographic format" ); let salt = base64::engine::general_purpose::STANDARD .decode(&header.salt_b64) .context("invalid backup salt")?; ensure!(salt.len() == 16, "invalid backup salt"); let prefix = base64::engine::general_purpose::STANDARD .decode(&header.nonce_prefix_b64) .context("invalid backup nonce prefix")?; ensure!(prefix.len() == 4, "invalid backup nonce prefix"); let mut nonce_prefix = [0u8; 4]; nonce_prefix.copy_from_slice(&prefix); let key = derive_key(password, &salt)?; Ok(CryptoContext { header_bytes: bytes, key, nonce_prefix, }) } fn cipher(key: &[u8]) -> Result { Ok(LessSafeKey::new( UnboundKey::new(&AES_256_GCM, key) .map_err(|_| anyhow::anyhow!("cannot initialize backup cipher"))?, )) } fn nonce(prefix: [u8; 4], counter: u64) -> Nonce { let mut bytes = [0u8; 12]; bytes[..4].copy_from_slice(&prefix); bytes[4..].copy_from_slice(&counter.to_be_bytes()); Nonce::assume_unique_for_key(bytes) } fn chunk_aad(header: &[u8], counter: u64) -> Vec { let mut aad = Vec::with_capacity(BACKUP_MAGIC.len() + header.len() + 8); aad.extend_from_slice(BACKUP_MAGIC); aad.extend_from_slice(header); aad.extend_from_slice(&counter.to_be_bytes()); aad } fn encrypt_archive(input: &Path, output: &Path, crypto: &CryptoContext) -> Result<()> { ensure!(!output.exists(), "backup output already exists"); let mut source = File::open(input)?; let mut target = private_file_options().create_new(true).open(output)?; let mut guard = PartialFile(output.to_path_buf(), false); target.write_all(BACKUP_MAGIC)?; let header_len: u32 = crypto.header_bytes.len().try_into()?; target.write_all(&header_len.to_be_bytes())?; target.write_all(&crypto.header_bytes)?; let cipher = cipher(crypto.key.as_ref())?; let mut counter = 0u64; let mut buffer = vec![0u8; CHUNK_SIZE]; loop { let read = source.read(&mut buffer)?; if read == 0 { break; } let mut chunk = buffer[..read].to_vec(); cipher .seal_in_place_append_tag( nonce(crypto.nonce_prefix, counter), Aad::from(chunk_aad(&crypto.header_bytes, counter)), &mut chunk, ) .map_err(|_| anyhow::anyhow!("backup encryption failed"))?; let length: u32 = chunk.len().try_into()?; target.write_all(&length.to_be_bytes())?; target.write_all(&chunk)?; counter = counter.checked_add(1).context("backup is too large")?; } target.write_all(&0u32.to_be_bytes())?; target.sync_all()?; guard.1 = true; Ok(()) } fn decrypt_archive(input: &Path, output: &Path, password: &str) -> Result> { let metadata = fs::symlink_metadata(input)?; ensure!( metadata.is_file() && !metadata.file_type().is_symlink(), "backup must be a regular file" ); let mut source = File::open(input)?; let mut magic = [0u8; 8]; source.read_exact(&mut magic)?; ensure!(&magic == BACKUP_MAGIC, "not a RustProxy backup"); let header_len = read_u32(&mut source)? as usize; ensure!( header_len > 0 && header_len <= MAX_HEADER_BYTES, "invalid backup header length" ); let mut header_bytes = vec![0u8; header_len]; source.read_exact(&mut header_bytes)?; let crypto = parse_crypto_header(header_bytes, password)?; let cipher = cipher(crypto.key.as_ref())?; let mut target = private_file_options().create_new(true).open(output)?; let mut counter = 0u64; loop { let length = read_u32(&mut source)? as usize; if length == 0 { break; } ensure!( length >= AES_256_GCM.tag_len() && length <= CHUNK_SIZE + AES_256_GCM.tag_len(), "invalid encrypted backup chunk" ); let mut chunk = vec![0u8; length]; source.read_exact(&mut chunk)?; let plaintext = cipher .open_in_place( nonce(crypto.nonce_prefix, counter), Aad::from(chunk_aad(&crypto.header_bytes, counter)), &mut chunk, ) .map_err(|_| anyhow::anyhow!("incorrect backup password or corrupted archive"))?; target.write_all(plaintext)?; counter = counter.checked_add(1).context("backup is too large")?; } let mut extra = [0u8; 1]; ensure!( source.read(&mut extra)? == 0, "trailing data after encrypted backup" ); target.sync_all()?; Ok(crypto.key) } fn seal_master_key(master: &[u8], backup_key: &[u8]) -> Result> { ensure!(master.len() == 32, "invalid secret store master key"); let mut nonce_bytes = [0u8; 12]; SysRng .try_fill_bytes(&mut nonce_bytes) .expect("secure operating system random source unavailable"); let cipher = cipher(backup_key)?; let mut encrypted = Zeroizing::new(master.to_vec()); cipher .seal_in_place_append_tag( Nonce::assume_unique_for_key(nonce_bytes), Aad::from(KEY_AAD), &mut *encrypted, ) .map_err(|_| anyhow::anyhow!("could not wrap secret store key"))?; let mut output = Vec::with_capacity(4 + 12 + encrypted.len()); output.extend_from_slice(KEY_MAGIC); output.extend_from_slice(&nonce_bytes); output.extend_from_slice(encrypted.as_ref()); Ok(output) } fn open_master_key(blob: &[u8], backup_key: &[u8]) -> Result>> { ensure!( blob.len() == 4 + 12 + 32 + AES_256_GCM.tag_len(), "invalid wrapped secret store key" ); ensure!(&blob[..4] == KEY_MAGIC, "invalid wrapped secret store key"); let mut nonce_bytes = [0u8; 12]; nonce_bytes.copy_from_slice(&blob[4..16]); let mut encrypted = Zeroizing::new(blob[16..].to_vec()); let cipher = cipher(backup_key)?; let plaintext = cipher .open_in_place( Nonce::assume_unique_for_key(nonce_bytes), Aad::from(KEY_AAD), encrypted.as_mut(), ) .map_err(|_| anyhow::anyhow!("wrapped secret store key authentication failed"))?; Ok(Zeroizing::new(plaintext.to_vec())) } fn hash_file(path: &Path) -> Result<(u64, String)> { let metadata = fs::symlink_metadata(path)?; ensure!( metadata.is_file() && !metadata.file_type().is_symlink(), "backup input must be a regular file" ); let mut file = File::open(path)?; let mut hasher = Sha256::new(); let mut size = 0u64; let mut buffer = [0u8; 1024 * 1024]; loop { let read = file.read(&mut buffer)?; if read == 0 { break; } size = size .checked_add(read as u64) .context("backup input too large")?; hasher.update(&buffer[..read]); } Ok((size, crate::hex::encode_lower(&hasher.finalize()))) } fn hash_bytes(bytes: &[u8]) -> String { crate::hex::encode_lower(&Sha256::digest(bytes)) } fn excluded_directory(name: &str) -> bool { matches!( name, "cache" | "logs" | "tmp" | "temp" | "work" | "acme-http01" | "acme-python" | "acme_python" ) }