team-ljyzipelo

공개
528줄19 KB
1use super::*;
2use std::{fs::File, io::Read};
3
4fn 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}
19fn 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}
40fn 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]
56fn 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]
75fn 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]
83fn 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]
92fn 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]
113fn 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]
127fn zip64_offset_only_keeps_32_bit_descriptors() {
128 for kind in ["offset64-descriptor-signed", "offset64-descriptor-unsigned"] {
129 let s = Scratch::new();
130 generate(&s, kind, 65536 + 19);
131 let events = execute(Start {
132 action: Action::List {
133 archive: s.path("input"),
134 },
135 limits: Limits::default(),
136 });
137 assert_eq!(
138 terminal(&events).outcome,
139 Outcome::Completed,
140 "{kind}: {events:?}"
141 );
142 let events = execute(start(&s, false, Limits::default().output));
143 assert_eq!(
144 terminal(&events).outcome,
145 Outcome::Completed,
146 "{kind}: {events:?}"
147 );
148 assert_zero_file(&s.0.join("output/payload.bin"), 65536 + 19);
149 }
150}
151#[test]
152fn zip64_locator_with_ordinary_eocd_fields_interoperates() {
153 let s = Scratch::new();
154 generate(&s, "locator64", 20);
155 assert_eq!(fs::metadata(s.0.join("input")).unwrap().len(), 260);
156 let events = execute(Start {
157 action: Action::List {
158 archive: s.path("input"),
159 },
160 limits: Limits::default(),
161 });
162 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
163 let events = execute(start(&s, false, Limits::default().output));
164 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
165 assert_zero_file(&s.0.join("output/payload.bin"), 20);
166}
167#[test]
168fn zip64_locator_corruption_never_publishes() {
169 for (kind, error) in [
170 ("locator64-bad-offset", ErrorCode::Integrity),
171 ("locator64-bad-size", ErrorCode::Integrity),
172 ("locator64-conflicting-count", ErrorCode::Integrity),
173 ("locator64-multidisk", ErrorCode::UnsupportedFeature),
174 ] {
175 let s = Scratch::new();
176 generate(&s, kind, 20);
177 let events = execute(start(&s, false, Limits::default().output));
178 assert_eq!(terminal(&events).error, error, "{kind}: {events:?}");
179 assert_eq!(terminal(&events).publication, Publication::None);
180 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
181 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
182 }
183}
184#[test]
185fn classic_directory_comment_is_not_a_zip64_locator() {
186 let s = Scratch::new();
187 generate(&s, "classic-locator-decoy", 20);
188 let events = execute(start(&s, false, Limits::default().output));
189 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
190 assert_zero_file(&s.0.join("output/payload.bin"), 20);
191}
192#[test]
193fn untrusted_zip64_u64_sizes_and_offsets_never_allocate_or_publish() {
194 for (kind, error) in [
195 ("central64-size-overflow", ErrorCode::Limit),
196 ("central64-offset-overflow", ErrorCode::Integrity),
197 ] {
198 let s = Scratch::new();
199 generate(&s, kind, 1024);
200 let events = execute(start(&s, false, Limits::default().output));
201 assert_eq!(terminal(&events).error, error, "{kind}: {events:?}");
202 assert_eq!(terminal(&events).publication, Publication::None);
203 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
204 }
205}
206#[test]
207fn gzip_ratio_is_per_member_even_with_low_ratio_suffix() {
208 let s = Scratch::new();
209 generate(&s, "gzip-bomb-joined", 16 * 1024 * 1024);
210 let events = execute(start(&s, true, Limits::default().output));
211 assert_eq!(terminal(&events).error, ErrorCode::Limit, "{events:?}");
212 assert_eq!(terminal(&events).created_count, 0);
213 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
214}
215#[test]
216fn streamed_aes_counter_survives_many_read_chunks() {
217 let s = Scratch::new();
218 generate(&s, "store", 2 * 1024 * 1024 + 17);
219 fs::rename(s.0.join("input"), s.0.join("source")).unwrap();
220 let events = interactive(
221 Start {
222 action: Action::CreateZip {
223 sources: vec![Source {
224 path: s.path("source"),
225 archive_name: "payload.bin".to_owned(),
226 }],
227 output_file: s.path("input"),
228 method: Method::Store,
229 encryption: Encryption::Aes256,
230 },
231 limits: Limits::default(),
232 },
233 |id, _, _| password_reply(id, TEST_PASSWORD),
234 );
235 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
236 let events = interactive(start(&s, false, Limits::default().output), |id, _, _| {
237 password_reply(id, TEST_PASSWORD)
238 });
239 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
240 let mut source = File::open(s.0.join("source")).unwrap();
241 let mut output = File::open(s.0.join("output/payload.bin")).unwrap();
242 let mut a = [0; 65536];
243 let mut b = [0; 65536];
244 loop {
245 let n = source.read(&mut a).unwrap();
246 output.read_exact(&mut b[..n]).unwrap();
247 assert_eq!(a[..n], b[..n]);
248 if n == 0 {
249 break;
250 }
251 }
252 assert_eq!(
253 source.metadata().unwrap().len(),
254 output.metadata().unwrap().len()
255 );
256}
257
258#[cfg(target_os = "linux")]
259mod linux {
260 use super::*;
261 use std::{
262 os::raw::c_long,
263 time::{Duration, Instant},
264 };
265 #[repr(C)]
266 #[derive(Default)]
267 struct Usage {
268 user: [c_long; 2],
269 system: [c_long; 2],
270 max_rss: c_long,
271 rest: [c_long; 13],
272 }
273 unsafe extern "C" {
274 fn wait4(pid: i32, status: *mut i32, options: i32, usage: *mut Usage) -> i32;
275 fn prctl(option: i32, ...) -> i32;
276 fn kill(pid: i32, signal: i32) -> i32;
277 }
278 fn command() -> Command {
279 let worker = std::env::var_os("ZIPELO_BASELINE_WORKER")
280 .map(PathBuf::from)
281 .unwrap_or_else(|| PathBuf::from(env!("CARGO_BIN_EXE_zipelo-archive-worker")));
282 Command::new(worker)
283 }
284 fn staging(s: &Scratch) -> PathBuf {
285 use std::os::unix::fs::DirBuilderExt;
286 let path = s.0.join("staging");
287 fs::DirBuilder::new().mode(0o700).create(&path).unwrap();
288 path
289 }
290 fn spawn(s: &Scratch, mut start: Start, mode: Option<&str>) -> std::process::Child {
291 if std::env::var_os("ZIPELO_BASELINE_WORKER").is_some() {
292 start.limits = Limits {
293 input: 64 * 1024 * 1024,
294 output: 128 * 1024 * 1024,
295 entries: 10000,
296 };
297 }
298 let mut cmd = command();
299 cmd.env("TMPDIR", staging(s))
300 .stdin(Stdio::piped())
301 .stdout(File::create(s.0.join("events")).unwrap())
302 .stderr(File::create(s.0.join("stderr")).unwrap());
303 if let Some(mode) = mode {
304 cmd.env("LD_PRELOAD", shim(s))
305 .env("ZIPELO_TEST_FAULT", mode)
306 .env("ZIPELO_TEST_MARKER", s.0.join("paused"))
307 .env("ZIPELO_TEST_RELEASE", s.0.join("release"));
308 }
309 let mut child = cmd.spawn().unwrap();
310 Writer::new(child.stdin.take().unwrap(), 17)
311 .send(&Message::Start(start))
312 .unwrap();
313 child
314 }
315 fn wait(pid: u32) -> (i32, u64) {
316 let deadline = Instant::now() + Duration::from_secs(320);
317 loop {
318 let mut status = 0;
319 let mut usage = Usage::default();
320 let r = unsafe { wait4(pid as i32, &mut status, 1, &mut usage) };
321 if r == pid as i32 {
322 return (status, usage.max_rss as u64 * 1024);
323 }
324 assert!(
325 r >= 0 || std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted
326 );
327 if Instant::now() > deadline {
328 unsafe {
329 kill(pid as i32, 9);
330 wait4(pid as i32, &mut status, 0, &mut usage);
331 }
332 panic!("worker timeout");
333 }
334 std::thread::sleep(Duration::from_millis(10));
335 }
336 }
337 fn events(s: &Scratch) -> Vec<Message> {
338 assert!(fs::read(s.0.join("stderr")).unwrap().is_empty());
339 let mut reader = Reader::new(File::open(s.0.join("events")).unwrap());
340 let mut result = Vec::new();
341 while let Some((_, _, message)) = reader.read().unwrap() {
342 result.push(message);
343 }
344 result
345 }
346 fn shim(s: &Scratch) -> PathBuf {
347 let path = s.0.join("io_fault.so");
348 assert!(
349 Command::new("cc")
350 .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"])
351 .arg(
352 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
353 .join("../../tests/rust-archive-worker/io_fault.c")
354 )
355 .arg("-ldl")
356 .arg("-o")
357 .arg(&path)
358 .status()
359 .unwrap()
360 .success()
361 );
362 path
363 }
364 #[test]
365 fn gigabyte_formats_stay_below_64_mib_peak_rss() {
366 let mut measurements = Vec::new();
367 for kind in ["store", "deflate", "tar", "gzip", "targz"] {
368 let s = Scratch::new();
369 generate(&s, kind, 1024 * 1024 * 1024);
370 let request = start(&s, kind == "gzip", Limits::default().output);
371 let child = spawn(&s, request, None);
372 let (status, rss) = wait(child.id());
373 assert_eq!(status, 0, "{kind}");
374 let events = events(&s);
375 assert_eq!(
376 terminal(&events).outcome,
377 Outcome::Completed,
378 "{kind}: {events:?}"
379 );
380 assert_eq!(terminal(&events).publication, Publication::Complete);
381 assert!(rss <= 64 * 1024 * 1024, "{kind}: RSS {rss}");
382 assert_zero_file(&s.0.join("output/payload.bin"), 1024 * 1024 * 1024);
383 measurements.push(format!("{kind}: {rss}"));
384 }
385 println!(
386 "1 GiB extraction peak RSS bytes: {}",
387 measurements.join(", ")
388 );
389 fs::write(
390 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/ci/streaming-rss.log"),
391 measurements.join("\n") + "\n",
392 )
393 .unwrap();
394 }
395 #[test]
396 fn enospc_at_create_or_after_partial_write_cleans_output() {
397 for mode in ["create-full", "full", "stage-full"] {
398 let s = Scratch::new();
399 generate(&s, "store", 1024 * 1024);
400 fs::write(s.0.join("preserve"), b"original").unwrap();
401 let request = start(&s, false, Limits::default().output);
402 let child = spawn(&s, request, Some(mode));
403 assert_eq!(wait(child.id()).0, 0);
404 let events = events(&s);
405 let t = terminal(&events);
406 assert_eq!(t.error, ErrorCode::Io, "{mode}: {events:?}");
407 assert_eq!(t.publication, Publication::None);
408 assert_eq!(t.retained_partial_count, 0);
409 assert_eq!(t.cleanup, Cleanup::Complete);
410 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
411 assert_eq!(fs::read(s.0.join("preserve")).unwrap(), b"original");
412 }
413 }
414 #[test]
415 fn anonymous_tempfile_fallback_unlinks_before_use() {
416 let s = Scratch::new();
417 generate(&s, "store", 1024 * 1024);
418 let request = start(&s, false, Limits::default().output);
419 let child = spawn(&s, request, Some("fallback"));
420 assert_eq!(wait(child.id()).0, 0);
421 let events = events(&s);
422 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
423 assert!(s.0.join("paused").exists());
424 assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
425 assert_zero_file(&s.0.join("output/payload.bin"), 1024 * 1024);
426 }
427 struct Subreaper(i32);
428 impl Subreaper {
429 fn new() -> Self {
430 let mut old = 0;
431 assert_eq!(unsafe { prctl(37, &mut old as *mut i32, 0, 0, 0) }, 0);
432 assert_eq!(unsafe { prctl(36, 1, 0, 0, 0) }, 0);
433 Self(old)
434 }
435 }
436 impl Drop for Subreaper {
437 fn drop(&mut self) {
438 assert_eq!(unsafe { prctl(36, self.0, 0, 0, 0) }, 0);
439 }
440 }
441 #[test]
442 fn orphan_app_helper() {
443 let Some(path) = std::env::var_os("ZIPELO_TEST_APP_HELPER") else {
444 return;
445 };
446 let s = std::mem::ManuallyDrop::new(Scratch(PathBuf::from(path)));
447 let mut request = Start {
448 action: Action::Extract {
449 archive: s.path("input"),
450 destination: s.path("output"),
451 selection: Selection::All,
452 list_id: None,
453 gzip_output_name: None,
454 },
455 limits: Limits::default(),
456 };
457 if std::env::var_os("ZIPELO_BASELINE_WORKER").is_some() {
458 request.limits = Limits {
459 input: 64 * 1024 * 1024,
460 output: 128 * 1024 * 1024,
461 entries: 10000,
462 };
463 }
464 let mut cmd = command();
465 cmd.env("TMPDIR", staging(&s))
466 .stdin(Stdio::piped())
467 .stdout(File::create(s.0.join("events")).unwrap())
468 .stderr(File::create(s.0.join("stderr")).unwrap())
469 .env("LD_PRELOAD", s.0.join("io_fault.so"))
470 .env("ZIPELO_TEST_FAULT", "pause")
471 .env("ZIPELO_TEST_MARKER", s.0.join("paused"))
472 .env("ZIPELO_TEST_RELEASE", s.0.join("release"));
473 let mut child = cmd.spawn().unwrap();
474 fs::write(s.0.join("worker.pid"), child.id().to_string()).unwrap();
475 let mut writer = Writer::new(child.stdin.take().unwrap(), 17);
476 writer.send(&Message::Start(request)).unwrap();
477 loop {
478 std::thread::sleep(Duration::from_millis(20));
479 }
480 }
481 #[test]
482 fn app_death_stops_worker_and_removes_partial_temp() {
483 let _guard = Subreaper::new();
484 let s = Scratch::new();
485 generate(&s, "store", 1024 * 1024);
486 let _ = start(&s, false, Limits::default().output);
487 shim(&s);
488 let mut helper = Command::new(std::env::current_exe().unwrap())
489 .args([
490 "--exact",
491 "hardening::linux::orphan_app_helper",
492 "--nocapture",
493 ])
494 .env("ZIPELO_TEST_APP_HELPER", &s.0)
495 .stdout(Stdio::null())
496 .stderr(Stdio::null())
497 .spawn()
498 .unwrap();
499 let deadline = Instant::now() + Duration::from_secs(20);
500 while !s.0.join("paused").exists() {
501 if Instant::now() > deadline {
502 helper.kill().unwrap();
503 helper.wait().unwrap();
504 if let Ok(pid) = fs::read_to_string(s.0.join("worker.pid")) {
505 unsafe {
506 kill(pid.parse().unwrap(), 9);
507 }
508 wait(pid.trim().parse().unwrap());
509 }
510 panic!("worker did not reach publication");
511 }
512 std::thread::sleep(Duration::from_millis(10));
513 }
514 let pid = fs::read_to_string(s.0.join("worker.pid"))
515 .unwrap()
516 .parse::<u32>()
517 .unwrap();
518 helper.kill().unwrap();
519 helper.wait().unwrap();
520 fs::write(s.0.join("release"), b"").unwrap();
521 assert_eq!(wait(pid).0, 0);
522 let events = events(&s);
523 assert_eq!(terminal(&events).error, ErrorCode::Io, "{events:?}");
524 assert_eq!(terminal(&events).publication, Publication::None);
525 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
526 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
527 }
528}