Repository Public
1//! ORIX Sonata2//! File: crates/sonata-pkg/src/archive.rs3//! Description: The .sonatapkg container: a plain ustar archive read and written here with strict4//! validation. Only regular files with safe relative names are accepted; links, devices, absolute5//! paths, `..`, duplicates and oversized content are refused before anything touches the disk.6//!7//! Author: Simon-Pierre Boucher8//! Contact: contact@spboucher.ai910use std::collections::BTreeMap;1112pub const MAX_ARCHIVE_BYTES: usize = 64 * 1024 * 1024;13pub const MAX_FILE_BYTES: usize = 4 * 1024 * 1024;14pub const MAX_ENTRIES: usize = 2000;1516/// A file name allowed inside a package: relative, `/`-separated, no empty, `.` or `..`17/// component, ASCII letters, digits, `-`, `_`, `.` only, at most 200 bytes, not hidden.18pub fn safe_name(name: &str) -> bool {19 if name.is_empty() || name.len() > 200 || name.starts_with('/') || name.ends_with('/') {20 return false;21 }22 name.split('/').all(|c| {23 !c.is_empty() && c != "." && c != ".." && !c.starts_with('.') && c.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.')24 })25}2627/// What a package may contain: its manifest, sources, examples, tests and plain documentation.28pub fn allowed_in_package(name: &str) -> bool {29 if !safe_name(name) {30 return false;31 }32 let top_level = !name.contains('/');33 if top_level {34 return name == "package.json" || name == "MANIFEST.sha256" || name.starts_with("LICENSE") || name.starts_with("README") || name == "CHANGELOG.md";35 }36 let dir = name.split('/').next().unwrap_or("");37 let ext = name.rsplit('.').next().unwrap_or("");38 match dir {39 "src" => ext == "sonata",40 "examples" | "tests" => ext == "sonata" || ext == "md",41 "docs" => ext == "md" || ext == "txt",42 _ => false,43 }44}4546fn octal(field: &[u8]) -> Option<u64> {47 let text: String = field.iter().take_while(|b| **b != 0 && **b != b' ').map(|b| *b as char).collect();48 if text.is_empty() {49 return Some(0);50 }51 u64::from_str_radix(text.trim(), 8).ok()52}5354/// Reads an archive into a map of file name to content. Any entry that is not a plain, allowed,55/// unique file makes the whole archive invalid.56pub fn read(data: &[u8]) -> Result<BTreeMap<String, Vec<u8>>, String> {57 if data.len() > MAX_ARCHIVE_BYTES {58 return Err(format!("the archive is larger than {} MiB", MAX_ARCHIVE_BYTES >> 20));59 }60 if !data.len().is_multiple_of(512) || data.len() < 1024 {61 return Err("not a package archive (bad length)".into());62 }63 let mut files = BTreeMap::new();64 let mut pos = 0usize;65 let mut total = 0usize;66 loop {67 let Some(header) = data.get(pos..pos + 512) else { return Err("the archive ends without its terminator".into()) };68 if header.iter().all(|b| *b == 0) {69 break;70 }71 if &header[257..262] != b"ustar" {72 return Err("not a package archive (not ustar)".into());73 }74 let stored = octal(&header[148..156]).ok_or("corrupt header checksum")?;75 let computed: u64 = header.iter().enumerate().map(|(i, b)| if (148..156).contains(&i) { 32u64 } else { *b as u64 }).sum();76 if stored != computed {77 return Err("corrupt header (checksum mismatch)".into());78 }79 let name_part: String = header[..100].iter().take_while(|b| **b != 0).map(|b| *b as char).collect();80 let prefix: String = header[345..500].iter().take_while(|b| **b != 0).map(|b| *b as char).collect();81 let name = if prefix.is_empty() { name_part } else { format!("{prefix}/{name_part}") };82 let size = octal(&header[124..136]).ok_or("corrupt size")? as usize;83 let kind = header[156];84 pos += 512;85 match kind {86 // Directory entries carry no data and are implied by the files; they must still be safe.87 b'5' => {88 if !safe_name(name.trim_end_matches('/')) || size != 0 {89 return Err(format!("unsafe directory entry '{name}'"));90 }91 continue;92 }93 b'0' | 0 => {}94 b'1' | b'2' => return Err(format!("'{name}' is a link; packages may not contain links")),95 other => return Err(format!("'{name}' has an entry type that packages may not contain ({})", other as char)),96 }97 if !allowed_in_package(&name) {98 return Err(format!("'{name}' is not allowed in a package"));99 }100 if size > MAX_FILE_BYTES {101 return Err(format!("'{name}' is larger than {} MiB", MAX_FILE_BYTES >> 20));102 }103 total += size;104 if total > MAX_ARCHIVE_BYTES || files.len() >= MAX_ENTRIES {105 return Err("the package has too many or too large files".into());106 }107 let content = data.get(pos..pos + size).ok_or("the archive is truncated")?.to_vec();108 if files.insert(name.clone(), content).is_some() {109 return Err(format!("'{name}' appears twice"));110 }111 pos += size.div_ceil(512) * 512;112 }113 Ok(files)114}115116/// Writes a deterministic archive: files sorted by name, fixed metadata (mode 644, no owner, time 0).117pub fn write(files: &BTreeMap<String, Vec<u8>>) -> Result<Vec<u8>, String> {118 let mut out = Vec::new();119 if files.len() > MAX_ENTRIES {120 return Err("the package has too many files".into());121 }122 for (name, content) in files {123 if !allowed_in_package(name) {124 return Err(format!("'{name}' is not allowed in a package"));125 }126 if content.len() > MAX_FILE_BYTES {127 return Err(format!("'{name}' is larger than {} MiB", MAX_FILE_BYTES >> 20));128 }129 let (prefix, short) = if name.len() <= 100 {130 ("", name.as_str())131 } else {132 // Split at a '/' so that the name fits in 100 bytes and the prefix in 155.133 let cut = name134 .char_indices()135 .filter(|(i, c)| *c == '/' && name.len() - i - 1 <= 100 && *i <= 155)136 .map(|(i, _)| i)137 .next()138 .ok_or(format!("'{name}' is too long"))?;139 (&name[..cut], &name[cut + 1..])140 };141 let mut h = [0u8; 512];142 h[..short.len()].copy_from_slice(short.as_bytes());143 h[100..108].copy_from_slice(b"0000644\0");144 h[108..116].copy_from_slice(b"0000000\0");145 h[116..124].copy_from_slice(b"0000000\0");146 h[124..136].copy_from_slice(format!("{:011o}\0", content.len()).as_bytes());147 h[136..148].copy_from_slice(b"00000000000\0");148 h[148..156].copy_from_slice(b" ");149 h[156] = b'0';150 h[257..263].copy_from_slice(b"ustar\0");151 h[263..265].copy_from_slice(b"00");152 h[345..345 + prefix.len()].copy_from_slice(prefix.as_bytes());153 let sum: u64 = h.iter().map(|b| *b as u64).sum();154 h[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes());155 out.extend_from_slice(&h);156 out.extend_from_slice(content);157 out.resize(out.len().div_ceil(512) * 512, 0);158 }159 out.extend_from_slice(&[0u8; 1024]);160 if out.len() > MAX_ARCHIVE_BYTES {161 return Err(format!("the package is larger than {} MiB", MAX_ARCHIVE_BYTES >> 20));162 }163 Ok(out)164}165166#[cfg(test)]167mod tests {168 use super::*;169170 fn sample() -> BTreeMap<String, Vec<u8>> {171 BTreeMap::from([172 ("package.json".to_string(), b"{}".to_vec()),173 ("src/motifs.sonata".to_string(), b"const a = 1\n".to_vec()),174 ("LICENSE".to_string(), vec![b'x'; 700]),175 ])176 }177178 /// A raw header for hostile entries the writer refuses to produce.179 fn raw_entry(name: &str, kind: u8, content: &[u8], link: &str) -> Vec<u8> {180 let mut h = [0u8; 512];181 h[..name.len()].copy_from_slice(name.as_bytes());182 h[100..108].copy_from_slice(b"0000644\0");183 h[124..136].copy_from_slice(format!("{:011o}\0", content.len()).as_bytes());184 h[148..156].copy_from_slice(b" ");185 h[156] = kind;186 h[157..157 + link.len()].copy_from_slice(link.as_bytes());187 h[257..263].copy_from_slice(b"ustar\0");188 let sum: u64 = h.iter().map(|b| *b as u64).sum();189 h[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes());190 let mut out = h.to_vec();191 out.extend_from_slice(content);192 out.resize(out.len().div_ceil(512) * 512, 0);193 out194 }195196 fn archive(entries: Vec<Vec<u8>>) -> Vec<u8> {197 let mut out: Vec<u8> = entries.concat();198 out.extend_from_slice(&[0u8; 1024]);199 out200 }201202 #[test]203 fn round_trip_is_deterministic() {204 let a = write(&sample()).unwrap();205 assert_eq!(a, write(&sample()).unwrap());206 assert_eq!(read(&a).unwrap(), sample());207 // The system tar agrees on the listing (when available).208 let dir = std::env::temp_dir().join(format!("sonata-pkg-tar-{}", std::process::id()));209 std::fs::create_dir_all(&dir).unwrap();210 let path = dir.join("p.sonatapkg");211 std::fs::write(&path, &a).unwrap();212 if let Ok(o) = std::process::Command::new("/usr/bin/tar").arg("-tf").arg(&path).output() {213 if o.status.success() {214 let listing = String::from_utf8_lossy(&o.stdout).to_string();215 assert_eq!(listing.lines().collect::<Vec<_>>(), vec!["LICENSE", "package.json", "src/motifs.sonata"]);216 }217 }218 let _ = std::fs::remove_dir_all(&dir);219 }220221 #[test]222 fn hostile_archives_are_refused() {223 let ok = raw_entry("src/a.sonata", b'0', b"x", "");224 for (what, data) in [225 ("parent traversal", archive(vec![raw_entry("../evil.sonata", b'0', b"x", "")])),226 ("nested traversal", archive(vec![raw_entry("src/../../evil.sonata", b'0', b"x", "")])),227 ("absolute path", archive(vec![raw_entry("/etc/passwd", b'0', b"x", "")])),228 ("symlink", archive(vec![raw_entry("src/link.sonata", b'2', b"", "/etc/passwd")])),229 ("hard link", archive(vec![raw_entry("src/link.sonata", b'1', b"", "package.json")])),230 ("device", archive(vec![raw_entry("src/dev.sonata", b'3', b"", "")])),231 ("script", archive(vec![raw_entry("install.sh", b'0', b"rm -rf ~", "")])),232 ("hidden file", archive(vec![raw_entry("src/.hidden.sonata", b'0', b"x", "")])),233 ("unknown directory", archive(vec![raw_entry("bin/tool", b'0', b"x", "")])),234 ("duplicate", archive(vec![ok.clone(), ok.clone()])),235 ("backslash", archive(vec![raw_entry("src\\a.sonata", b'0', b"x", "")])),236 ] {237 assert!(read(&data).is_err(), "{what} must be refused");238 }239 // Truncated, corrupted and oversized.240 let good = write(&sample()).unwrap();241 assert!(read(&good[..good.len() - 1024]).is_err(), "missing terminator");242 let mut bad = good.clone();243 bad[0] ^= 0x01;244 assert!(read(&bad).unwrap_err().contains("checksum"));245 let mut huge = raw_entry("src/a.sonata", b'0', b"", "");246 huge[124..136].copy_from_slice(b"77777777777\0");247 let sum: u64 = huge[..512].iter().enumerate().map(|(i, b)| if (148..156).contains(&i) { 32u64 } else { *b as u64 }).sum();248 huge[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes());249 assert!(read(&archive(vec![huge])).unwrap_err().contains("larger than"));250 assert!(read(b"not an archive").is_err());251 assert!(write(&BTreeMap::from([("../x.sonata".to_string(), vec![])])).is_err());252 // Deterministic pseudo-random corruption never panics.253 let mut s = 0x243f6a8885a308d3u64;254 for _ in 0..3000 {255 let mut m = good.clone();256 for _ in 0..4 {257 s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);258 let i = (s >> 33) as usize % m.len();259 m[i] = (s >> 20) as u8;260 }261 let _ = read(&m);262 }263 }264}265