team-ljyzipelo

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