| 1 | use super::*; |
| 2 | use std::{fs::File, io::Read}; |
| 3 | |
| 4 | fn generate(s: &Scratch, kind: &str, size: u64) { |
| 5 | assert!( |
| 6 | Command::new("python3") |
| 7 | .arg( |
| 8 | PathBuf::from(env!("CARGO_MANIFEST_DIR")) |
| 9 | .join("../../tests/rust-archive-worker/hardening_cases.py") |
| 10 | ) |
| 11 | .arg(&s.0) |
| 12 | .arg(kind) |
| 13 | .arg(size.to_string()) |
| 14 | .status() |
| 15 | .unwrap() |
| 16 | .success() |
| 17 | ); |
| 18 | } |
| 19 | fn start(s: &Scratch, gzip: bool, output: u64) -> Start { |
| 20 | fs::DirBuilder::new().create(s.0.join("output")).unwrap(); |
| 21 | #[cfg(unix)] |
| 22 | { |
| 23 | use std::os::unix::fs::PermissionsExt; |
| 24 | fs::set_permissions(s.0.join("output"), fs::Permissions::from_mode(0o700)).unwrap(); |
| 25 | } |
| 26 | Start { |
| 27 | action: Action::Extract { |
| 28 | archive: s.path("input"), |
| 29 | destination: s.path("output"), |
| 30 | selection: Selection::All, |
| 31 | list_id: None, |
| 32 | gzip_output_name: gzip.then(|| "payload.bin".to_owned()), |
| 33 | }, |
| 34 | limits: Limits { |
| 35 | output, |
| 36 | ..Limits::default() |
| 37 | }, |
| 38 | } |
| 39 | } |
| 40 | fn assert_zero_file(path: &std::path::Path, length: u64) { |
| 41 | let mut file = File::open(path).unwrap(); |
| 42 | assert_eq!(file.metadata().unwrap().len(), length); |
| 43 | let mut buffer = [0; 65536]; |
| 44 | let mut total = 0; |
| 45 | loop { |
| 46 | let n = file.read(&mut buffer).unwrap(); |
| 47 | if n == 0 { |
| 48 | break; |
| 49 | } |
| 50 | assert!(buffer[..n].iter().all(|b| *b == 0)); |
| 51 | total += n as u64; |
| 52 | } |
| 53 | assert_eq!(total, length); |
| 54 | } |
| 55 | #[test] |
| 56 | fn streaming_defaults_and_legacy_seven_zip_caps() { |
| 57 | assert_eq!(Limits::default().input, u64::MAX); |
| 58 | assert_eq!(Limits::default().output, 16 * 1024 * 1024 * 1024); |
| 59 | assert!( |
| 60 | !Limits { |
| 61 | output: 16 * 1024 * 1024 * 1024 + 1, |
| 62 | ..Limits::default() |
| 63 | } |
| 64 | .valid() |
| 65 | ); |
| 66 | let s = Scratch::new(); |
| 67 | let file = File::create(s.0.join("input")).unwrap(); |
| 68 | (&file).write_all(b"7z\xbc\xaf\x27\x1c").unwrap(); |
| 69 | file.set_len(1024 * 1024 * 1024).unwrap(); |
| 70 | let events = execute(start(&s, false, Limits::default().output)); |
| 71 | assert_eq!(terminal(&events).error, ErrorCode::Limit); |
| 72 | assert_eq!(terminal(&events).created_count, 0); |
| 73 | } |
| 74 | #[test] |
| 75 | fn streaming_zip64_local_headers_and_chunk_boundaries() { |
| 76 | let s = Scratch::new(); |
| 77 | generate(&s, "zip64", 9 * 1024 * 1024 + 13); |
| 78 | let events = execute(start(&s, false, Limits::default().output)); |
| 79 | assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); |
| 80 | assert_zero_file(&s.0.join("output/payload.bin"), 9 * 1024 * 1024 + 13); |
| 81 | } |
| 82 | #[test] |
| 83 | fn streaming_ratio_rejects_bomb_without_publication() { |
| 84 | let s = Scratch::new(); |
| 85 | generate(&s, "bomb", 16 * 1024 * 1024); |
| 86 | let events = execute(start(&s, false, Limits::default().output)); |
| 87 | assert_eq!(terminal(&events).error, ErrorCode::Limit, "{events:?}"); |
| 88 | assert_eq!(terminal(&events).publication, Publication::None); |
| 89 | assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0); |
| 90 | } |
| 91 | #[test] |
| 92 | fn streaming_tar_and_gzip_truncation_never_publish() { |
| 93 | for kind in ["tar", "targz", "gzip"] { |
| 94 | let s = Scratch::new(); |
| 95 | generate(&s, kind, 1024 * 1024 + 1); |
| 96 | let file = fs::OpenOptions::new() |
| 97 | .write(true) |
| 98 | .open(s.0.join("input")) |
| 99 | .unwrap(); |
| 100 | file.set_len(file.metadata().unwrap().len() - 1).unwrap(); |
| 101 | let events = execute(start(&s, kind == "gzip", Limits::default().output)); |
| 102 | assert_eq!( |
| 103 | terminal(&events).outcome, |
| 104 | Outcome::Failed, |
| 105 | "{kind}: {events:?}" |
| 106 | ); |
| 107 | assert_eq!(terminal(&events).created_count, 0); |
| 108 | assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0); |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | #[test] |
| 113 | fn zip64_directory_and_descriptor_interoperate() { |
| 114 | for kind in ["central64", "descriptor64"] { |
| 115 | let s = Scratch::new(); |
| 116 | generate(&s, kind, 65536 + 19); |
| 117 | let events = execute(start(&s, false, Limits::default().output)); |
| 118 | assert_eq!( |
| 119 | terminal(&events).outcome, |
| 120 | Outcome::Completed, |
| 121 | "{kind}: {events:?}" |
| 122 | ); |
| 123 | assert_zero_file(&s.0.join("output/payload.bin"), 65536 + 19); |
| 124 | } |
| 125 | } |
| 126 | #[test] |
| 127 | fn untrusted_zip64_u64_sizes_and_offsets_never_allocate_or_publish() { |
| 128 | for (kind, error) in [ |
| 129 | ("central64-size-overflow", ErrorCode::Limit), |
| 130 | ("central64-offset-overflow", ErrorCode::Integrity), |
| 131 | ] { |
| 132 | let s = Scratch::new(); |
| 133 | generate(&s, kind, 1024); |
| 134 | let events = execute(start(&s, false, Limits::default().output)); |
| 135 | assert_eq!(terminal(&events).error, error, "{kind}: {events:?}"); |
| 136 | assert_eq!(terminal(&events).publication, Publication::None); |
| 137 | assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0); |
| 138 | } |
| 139 | } |
| 140 | #[test] |
| 141 | fn gzip_ratio_is_per_member_even_with_low_ratio_suffix() { |
| 142 | let s = Scratch::new(); |
| 143 | generate(&s, "gzip-bomb-joined", 16 * 1024 * 1024); |
| 144 | let events = execute(start(&s, true, Limits::default().output)); |
| 145 | assert_eq!(terminal(&events).error, ErrorCode::Limit, "{events:?}"); |
| 146 | assert_eq!(terminal(&events).created_count, 0); |
| 147 | assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0); |
| 148 | } |
| 149 | #[test] |
| 150 | fn streamed_aes_counter_survives_many_read_chunks() { |
| 151 | let s = Scratch::new(); |
| 152 | generate(&s, "store", 2 * 1024 * 1024 + 17); |
| 153 | fs::rename(s.0.join("input"), s.0.join("source")).unwrap(); |
| 154 | let events = interactive( |
| 155 | Start { |
| 156 | action: Action::CreateZip { |
| 157 | sources: vec![Source { |
| 158 | path: s.path("source"), |
| 159 | archive_name: "payload.bin".to_owned(), |
| 160 | }], |
| 161 | output_file: s.path("input"), |
| 162 | method: Method::Store, |
| 163 | encryption: Encryption::Aes256, |
| 164 | }, |
| 165 | limits: Limits::default(), |
| 166 | }, |
| 167 | |id, _, _| password_reply(id, TEST_PASSWORD), |
| 168 | ); |
| 169 | assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); |
| 170 | let events = interactive(start(&s, false, Limits::default().output), |id, _, _| { |
| 171 | password_reply(id, TEST_PASSWORD) |
| 172 | }); |
| 173 | assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); |
| 174 | let mut source = File::open(s.0.join("source")).unwrap(); |
| 175 | let mut output = File::open(s.0.join("output/payload.bin")).unwrap(); |
| 176 | let mut a = [0; 65536]; |
| 177 | let mut b = [0; 65536]; |
| 178 | loop { |
| 179 | let n = source.read(&mut a).unwrap(); |
| 180 | output.read_exact(&mut b[..n]).unwrap(); |
| 181 | assert_eq!(a[..n], b[..n]); |
| 182 | if n == 0 { |
| 183 | break; |
| 184 | } |
| 185 | } |
| 186 | assert_eq!( |
| 187 | source.metadata().unwrap().len(), |
| 188 | output.metadata().unwrap().len() |
| 189 | ); |
| 190 | } |
| 191 | |
| 192 | #[cfg(target_os = "linux")] |
| 193 | mod linux { |
| 194 | use super::*; |
| 195 | use std::{ |
| 196 | os::raw::c_long, |
| 197 | time::{Duration, Instant}, |
| 198 | }; |
| 199 | #[repr(C)] |
| 200 | #[derive(Default)] |
| 201 | struct Usage { |
| 202 | user: [c_long; 2], |
| 203 | system: [c_long; 2], |
| 204 | max_rss: c_long, |
| 205 | rest: [c_long; 13], |
| 206 | } |
| 207 | unsafe extern "C" { |
| 208 | fn wait4(pid: i32, status: *mut i32, options: i32, usage: *mut Usage) -> i32; |
| 209 | fn prctl(option: i32, ...) -> i32; |
| 210 | fn kill(pid: i32, signal: i32) -> i32; |
| 211 | } |
| 212 | fn command() -> Command { |
| 213 | let worker = std::env::var_os("ZIPELO_BASELINE_WORKER") |
| 214 | .map(PathBuf::from) |
| 215 | .unwrap_or_else(|| PathBuf::from(env!("CARGO_BIN_EXE_zipelo-archive-worker"))); |
| 216 | Command::new(worker) |
| 217 | } |
| 218 | fn staging(s: &Scratch) -> PathBuf { |
| 219 | use std::os::unix::fs::DirBuilderExt; |
| 220 | let path = s.0.join("staging"); |
| 221 | fs::DirBuilder::new().mode(0o700).create(&path).unwrap(); |
| 222 | path |
| 223 | } |
| 224 | fn spawn(s: &Scratch, mut start: Start, mode: Option<&str>) -> std::process::Child { |
| 225 | if std::env::var_os("ZIPELO_BASELINE_WORKER").is_some() { |
| 226 | start.limits = Limits { |
| 227 | input: 64 * 1024 * 1024, |
| 228 | output: 128 * 1024 * 1024, |
| 229 | entries: 10000, |
| 230 | }; |
| 231 | } |
| 232 | let mut cmd = command(); |
| 233 | cmd.env("TMPDIR", staging(s)) |
| 234 | .stdin(Stdio::piped()) |
| 235 | .stdout(File::create(s.0.join("events")).unwrap()) |
| 236 | .stderr(File::create(s.0.join("stderr")).unwrap()); |
| 237 | if let Some(mode) = mode { |
| 238 | cmd.env("LD_PRELOAD", shim(s)) |
| 239 | .env("ZIPELO_TEST_FAULT", mode) |
| 240 | .env("ZIPELO_TEST_MARKER", s.0.join("paused")) |
| 241 | .env("ZIPELO_TEST_RELEASE", s.0.join("release")); |
| 242 | } |
| 243 | let mut child = cmd.spawn().unwrap(); |
| 244 | Writer::new(child.stdin.take().unwrap(), 17) |
| 245 | .send(&Message::Start(start)) |
| 246 | .unwrap(); |
| 247 | child |
| 248 | } |
| 249 | fn wait(pid: u32) -> (i32, u64) { |
| 250 | let deadline = Instant::now() + Duration::from_secs(320); |
| 251 | loop { |
| 252 | let mut status = 0; |
| 253 | let mut usage = Usage::default(); |
| 254 | let r = unsafe { wait4(pid as i32, &mut status, 1, &mut usage) }; |
| 255 | if r == pid as i32 { |
| 256 | return (status, usage.max_rss as u64 * 1024); |
| 257 | } |
| 258 | assert!( |
| 259 | r >= 0 || std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted |
| 260 | ); |
| 261 | if Instant::now() > deadline { |
| 262 | unsafe { |
| 263 | kill(pid as i32, 9); |
| 264 | wait4(pid as i32, &mut status, 0, &mut usage); |
| 265 | } |
| 266 | panic!("worker timeout"); |
| 267 | } |
| 268 | std::thread::sleep(Duration::from_millis(10)); |
| 269 | } |
| 270 | } |
| 271 | fn events(s: &Scratch) -> Vec<Message> { |
| 272 | assert!(fs::read(s.0.join("stderr")).unwrap().is_empty()); |
| 273 | let mut reader = Reader::new(File::open(s.0.join("events")).unwrap()); |
| 274 | let mut result = Vec::new(); |
| 275 | while let Some((_, _, message)) = reader.read().unwrap() { |
| 276 | result.push(message); |
| 277 | } |
| 278 | result |
| 279 | } |
| 280 | fn shim(s: &Scratch) -> PathBuf { |
| 281 | let path = s.0.join("io_fault.so"); |
| 282 | assert!( |
| 283 | Command::new("cc") |
| 284 | .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"]) |
| 285 | .arg( |
| 286 | PathBuf::from(env!("CARGO_MANIFEST_DIR")) |
| 287 | .join("../../tests/rust-archive-worker/io_fault.c") |
| 288 | ) |
| 289 | .arg("-ldl") |
| 290 | .arg("-o") |
| 291 | .arg(&path) |
| 292 | .status() |
| 293 | .unwrap() |
| 294 | .success() |
| 295 | ); |
| 296 | path |
| 297 | } |
| 298 | #[test] |
| 299 | fn gigabyte_formats_stay_below_64_mib_peak_rss() { |
| 300 | let mut measurements = Vec::new(); |
| 301 | for kind in ["store", "deflate", "tar", "gzip", "targz"] { |
| 302 | let s = Scratch::new(); |
| 303 | generate(&s, kind, 1024 * 1024 * 1024); |
| 304 | let request = start(&s, kind == "gzip", Limits::default().output); |
| 305 | let child = spawn(&s, request, None); |
| 306 | let (status, rss) = wait(child.id()); |
| 307 | assert_eq!(status, 0, "{kind}"); |
| 308 | let events = events(&s); |
| 309 | assert_eq!( |
| 310 | terminal(&events).outcome, |
| 311 | Outcome::Completed, |
| 312 | "{kind}: {events:?}" |
| 313 | ); |
| 314 | assert_eq!(terminal(&events).publication, Publication::Complete); |
| 315 | assert!(rss <= 64 * 1024 * 1024, "{kind}: RSS {rss}"); |
| 316 | assert_zero_file(&s.0.join("output/payload.bin"), 1024 * 1024 * 1024); |
| 317 | measurements.push(format!("{kind}: {rss}")); |
| 318 | } |
| 319 | println!( |
| 320 | "1 GiB extraction peak RSS bytes: {}", |
| 321 | measurements.join(", ") |
| 322 | ); |
| 323 | fs::write( |
| 324 | PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/ci/streaming-rss.log"), |
| 325 | measurements.join("\n") + "\n", |
| 326 | ) |
| 327 | .unwrap(); |
| 328 | } |
| 329 | #[test] |
| 330 | fn enospc_at_create_or_after_partial_write_cleans_output() { |
| 331 | for mode in ["create-full", "full", "stage-full"] { |
| 332 | let s = Scratch::new(); |
| 333 | generate(&s, "store", 1024 * 1024); |
| 334 | fs::write(s.0.join("preserve"), b"original").unwrap(); |
| 335 | let request = start(&s, false, Limits::default().output); |
| 336 | let child = spawn(&s, request, Some(mode)); |
| 337 | assert_eq!(wait(child.id()).0, 0); |
| 338 | let events = events(&s); |
| 339 | let t = terminal(&events); |
| 340 | assert_eq!(t.error, ErrorCode::Io, "{mode}: {events:?}"); |
| 341 | assert_eq!(t.publication, Publication::None); |
| 342 | assert_eq!(t.retained_partial_count, 0); |
| 343 | assert_eq!(t.cleanup, Cleanup::Complete); |
| 344 | assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0); |
| 345 | assert_eq!(fs::read(s.0.join("preserve")).unwrap(), b"original"); |
| 346 | } |
| 347 | } |
| 348 | #[test] |
| 349 | fn anonymous_tempfile_fallback_unlinks_before_use() { |
| 350 | let s = Scratch::new(); |
| 351 | generate(&s, "store", 1024 * 1024); |
| 352 | let request = start(&s, false, Limits::default().output); |
| 353 | let child = spawn(&s, request, Some("fallback")); |
| 354 | assert_eq!(wait(child.id()).0, 0); |
| 355 | let events = events(&s); |
| 356 | assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); |
| 357 | assert!(s.0.join("paused").exists()); |
| 358 | assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0); |
| 359 | assert_zero_file(&s.0.join("output/payload.bin"), 1024 * 1024); |
| 360 | } |
| 361 | struct Subreaper(i32); |
| 362 | impl Subreaper { |
| 363 | fn new() -> Self { |
| 364 | let mut old = 0; |
| 365 | assert_eq!(unsafe { prctl(37, &mut old as *mut i32, 0, 0, 0) }, 0); |
| 366 | assert_eq!(unsafe { prctl(36, 1, 0, 0, 0) }, 0); |
| 367 | Self(old) |
| 368 | } |
| 369 | } |
| 370 | impl Drop for Subreaper { |
| 371 | fn drop(&mut self) { |
| 372 | assert_eq!(unsafe { prctl(36, self.0, 0, 0, 0) }, 0); |
| 373 | } |
| 374 | } |
| 375 | #[test] |
| 376 | fn orphan_app_helper() { |
| 377 | let Some(path) = std::env::var_os("ZIPELO_TEST_APP_HELPER") else { |
| 378 | return; |
| 379 | }; |
| 380 | let s = std::mem::ManuallyDrop::new(Scratch(PathBuf::from(path))); |
| 381 | let mut request = Start { |
| 382 | action: Action::Extract { |
| 383 | archive: s.path("input"), |
| 384 | destination: s.path("output"), |
| 385 | selection: Selection::All, |
| 386 | list_id: None, |
| 387 | gzip_output_name: None, |
| 388 | }, |
| 389 | limits: Limits::default(), |
| 390 | }; |
| 391 | if std::env::var_os("ZIPELO_BASELINE_WORKER").is_some() { |
| 392 | request.limits = Limits { |
| 393 | input: 64 * 1024 * 1024, |
| 394 | output: 128 * 1024 * 1024, |
| 395 | entries: 10000, |
| 396 | }; |
| 397 | } |
| 398 | let mut cmd = command(); |
| 399 | cmd.env("TMPDIR", staging(&s)) |
| 400 | .stdin(Stdio::piped()) |
| 401 | .stdout(File::create(s.0.join("events")).unwrap()) |
| 402 | .stderr(File::create(s.0.join("stderr")).unwrap()) |
| 403 | .env("LD_PRELOAD", s.0.join("io_fault.so")) |
| 404 | .env("ZIPELO_TEST_FAULT", "pause") |
| 405 | .env("ZIPELO_TEST_MARKER", s.0.join("paused")) |
| 406 | .env("ZIPELO_TEST_RELEASE", s.0.join("release")); |
| 407 | let mut child = cmd.spawn().unwrap(); |
| 408 | fs::write(s.0.join("worker.pid"), child.id().to_string()).unwrap(); |
| 409 | let mut writer = Writer::new(child.stdin.take().unwrap(), 17); |
| 410 | writer.send(&Message::Start(request)).unwrap(); |
| 411 | loop { |
| 412 | std::thread::sleep(Duration::from_millis(20)); |
| 413 | } |
| 414 | } |
| 415 | #[test] |
| 416 | fn app_death_stops_worker_and_removes_partial_temp() { |
| 417 | let _guard = Subreaper::new(); |
| 418 | let s = Scratch::new(); |
| 419 | generate(&s, "store", 1024 * 1024); |
| 420 | let _ = start(&s, false, Limits::default().output); |
| 421 | shim(&s); |
| 422 | let mut helper = Command::new(std::env::current_exe().unwrap()) |
| 423 | .args([ |
| 424 | "--exact", |
| 425 | "hardening::linux::orphan_app_helper", |
| 426 | "--nocapture", |
| 427 | ]) |
| 428 | .env("ZIPELO_TEST_APP_HELPER", &s.0) |
| 429 | .stdout(Stdio::null()) |
| 430 | .stderr(Stdio::null()) |
| 431 | .spawn() |
| 432 | .unwrap(); |
| 433 | let deadline = Instant::now() + Duration::from_secs(20); |
| 434 | while !s.0.join("paused").exists() { |
| 435 | if Instant::now() > deadline { |
| 436 | helper.kill().unwrap(); |
| 437 | helper.wait().unwrap(); |
| 438 | if let Ok(pid) = fs::read_to_string(s.0.join("worker.pid")) { |
| 439 | unsafe { |
| 440 | kill(pid.parse().unwrap(), 9); |
| 441 | } |
| 442 | wait(pid.trim().parse().unwrap()); |
| 443 | } |
| 444 | panic!("worker did not reach publication"); |
| 445 | } |
| 446 | std::thread::sleep(Duration::from_millis(10)); |
| 447 | } |
| 448 | let pid = fs::read_to_string(s.0.join("worker.pid")) |
| 449 | .unwrap() |
| 450 | .parse::<u32>() |
| 451 | .unwrap(); |
| 452 | helper.kill().unwrap(); |
| 453 | helper.wait().unwrap(); |
| 454 | fs::write(s.0.join("release"), b"").unwrap(); |
| 455 | assert_eq!(wait(pid).0, 0); |
| 456 | let events = events(&s); |
| 457 | assert_eq!(terminal(&events).error, ErrorCode::Io, "{events:?}"); |
| 458 | assert_eq!(terminal(&events).publication, Publication::None); |
| 459 | assert_eq!(terminal(&events).cleanup, Cleanup::Complete); |
| 460 | assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0); |
| 461 | } |
| 462 | } |