team-ljyzipelo

공개
592줄22 KB
1use super::*;
2use std::os::unix::fs::{MetadataExt, PermissionsExt};
3
4fn check_case(case: &str, safe: bool) {
5 run_case(case, safe, false);
6}
7
8pub(super) fn check_extraction(case: &str, safe: bool) {
9 run_case(case, safe, true);
10}
11
12fn run_case(case: &str, safe: bool, extraction: bool) {
13 let scratch = Scratch::new();
14 let output = scratch.0.join("output");
15 fs::create_dir(&output).unwrap();
16 let mode = if case == "world-writable" {
17 0o777
18 } else {
19 0o775
20 };
21 fs::set_permissions(&output, fs::Permissions::from_mode(mode)).unwrap();
22 if extraction {
23 fs::write(
24 scratch.0.join("input"),
25 include_bytes!("fixtures/store.zip"),
26 )
27 .unwrap();
28 }
29 let metadata = fs::metadata(&output).unwrap();
30 let uid = metadata.uid();
31 let gid = metadata.gid();
32 let mut passwd = format!("owner:x:{uid}:{gid}::/:/bin/sh\n");
33 match case {
34 "shared-primary" => passwd.push_str(&format!(
35 "other:x:{}:{gid}::/:/bin/sh\n",
36 uid.wrapping_add(1)
37 )),
38 "unrelated-primary" => passwd.push_str(&format!(
39 "other:x:{}:{}::/:/bin/sh\n",
40 uid.wrapping_add(1),
41 gid.wrapping_add(1)
42 )),
43 "missing-owner" => passwd.clear(),
44 "malformed-passwd" => passwd.push_str("broken:x:not-a-uid:1000::/:/bin/sh\n"),
45 "nis-passwd" => passwd.push_str("+::::::\n"),
46 _ => {}
47 }
48 let passwd_path = scratch.0.join("passwd");
49 fs::write(&passwd_path, passwd).unwrap();
50 if case == "passwd-unavailable" {
51 fs::remove_file(&passwd_path).unwrap();
52 }
53 let nss = match case {
54 "remote-accounts" | "sss-files-only" => "passwd: files sss\n",
55 "ldap-accounts" => "passwd: files ldap\n",
56 "winbind-accounts" => "passwd: files winbind\n",
57 "unknown-accounts" => "passwd: files unknown\n",
58 "short-circuit-policy" => "passwd: files [SUCCESS=return] systemd\n",
59 "duplicate-policy" => "passwd: files\npasswd: files\n",
60 "missing-policy" => "group: files\n",
61 _ if case.starts_with("sss-") || case == "systemd-remote" => "passwd: files systemd sss\n",
62 _ if case.starts_with("systemd-") || case.starts_with("userdb-") => {
63 "passwd: files systemd\n"
64 }
65 _ => "# fixture\npasswd: files # local accounts\n",
66 };
67 let nss_path = scratch.0.join("nsswitch.conf");
68 fs::write(&nss_path, nss).unwrap();
69 if case == "nss-unavailable" {
70 fs::remove_file(&nss_path).unwrap();
71 }
72 let sss = scratch.0.join("sss");
73 fs::create_dir_all(sss.join("pipes")).unwrap();
74 fs::create_dir_all(sss.join("mc")).unwrap();
75 let _socket = match case {
76 "sss-socket" | "remote-accounts" | "systemd-remote" => {
77 use std::os::fd::AsRawFd;
78 let pipes = fs::File::open(sss.join("pipes")).unwrap();
79 let path = format!("/proc/self/fd/{}/nss", pipes.as_raw_fd());
80 Some(std::os::unix::net::UnixListener::bind(path).unwrap())
81 }
82 _ => None,
83 };
84 match case {
85 "sss-passwd-cache" => fs::write(sss.join("mc/passwd"), b"").unwrap(),
86 "sss-group-cache" => fs::write(sss.join("mc/group"), b"").unwrap(),
87 "sss-initgr-cache" => fs::write(sss.join("mc/initgr"), b"").unwrap(),
88 "sss-dangling-socket" => {
89 std::os::unix::fs::symlink("missing", sss.join("pipes/nss")).unwrap();
90 }
91 "sss-dangling-cache" => {
92 std::os::unix::fs::symlink("missing", sss.join("mc/passwd")).unwrap();
93 }
94 "sss-cache-symlink" => {
95 fs::remove_dir(sss.join("mc")).unwrap();
96 std::os::unix::fs::symlink("missing", sss.join("mc")).unwrap();
97 }
98 "sss-invalid-parent" => {
99 fs::remove_dir(sss.join("mc")).unwrap();
100 fs::write(sss.join("mc"), b"").unwrap();
101 }
102 "sss-missing-directories" => fs::remove_dir_all(&sss).unwrap(),
103 _ => {}
104 }
105 let userdb = scratch.0.join("userdb");
106 let _services = FakeUserdb::new(&userdb, case, uid, gid);
107 let library = shim();
108 let result = Command::new(std::env::current_exe().unwrap())
109 .args([
110 "--exact",
111 "private_group::probe_child",
112 "--test-threads=1",
113 "--nocapture",
114 ])
115 .env("LD_PRELOAD", library)
116 .env("ZIPELO_GROUP_CASE", case)
117 .env("ZIPELO_GROUP_PASSWD", passwd_path)
118 .env("ZIPELO_GROUP_NSS", nss_path)
119 .env("ZIPELO_GROUP_SSS", sss)
120 .env("ZIPELO_GROUP_USERDB", &userdb)
121 .env("ZIPELO_GROUP_OUTPUT", &output)
122 .env("ZIPELO_GROUP_SAFE", if safe { "1" } else { "0" })
123 .env("ZIPELO_GROUP_EXTRACT", if extraction { "1" } else { "0" })
124 .output()
125 .unwrap();
126 assert!(
127 result.status.success(),
128 "{case}: {} {}",
129 String::from_utf8_lossy(&result.stdout),
130 String::from_utf8_lossy(&result.stderr)
131 );
132 if extraction && safe {
133 assert_eq!(fs::read(output.join("folder/hello.txt")).unwrap(), PAYLOAD);
134 } else {
135 assert_eq!(fs::read_dir(&output).unwrap().count(), 0);
136 }
137 assert_eq!(fs::metadata(&output).unwrap().mode() & 0o777, mode);
138}
139
140#[test]
141fn probe_child() {
142 let Some(path) = std::env::var_os("ZIPELO_GROUP_OUTPUT") else {
143 return;
144 };
145 let path = std::path::Path::new(&path);
146 let actual = zipelo_archive_worker::filesystem::Dir::root(path);
147 if std::env::var("ZIPELO_GROUP_SAFE").unwrap() == "1" {
148 assert!(actual.is_ok());
149 } else {
150 assert!(matches!(actual, Err(ErrorCode::UnsafePath)));
151 }
152 if std::env::var("ZIPELO_GROUP_EXTRACT").unwrap() == "1" {
153 let events = execute(Start {
154 action: Action::Extract {
155 archive: NativePath::from_path(&path.parent().unwrap().join("input")),
156 destination: NativePath::from_path(path),
157 selection: Selection::All,
158 list_id: None,
159 gzip_output_name: None,
160 },
161 limits: Limits::default(),
162 });
163 if std::env::var("ZIPELO_GROUP_SAFE").unwrap() == "1" {
164 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
165 } else {
166 assert_eq!(terminal(&events).error, ErrorCode::UnsafePath, "{events:?}");
167 }
168 }
169}
170
171#[test]
172fn private_group_accepts_only_current_primary_member() {
173 for case in ["personal", "unrelated-primary"] {
174 check_case(case, true);
175 }
176}
177
178#[test]
179fn private_group_rejects_another_primary_member() {
180 check_case("shared-primary", false);
181}
182
183#[test]
184fn private_group_rejects_incomplete_account_information() {
185 for case in [
186 "missing-owner",
187 "malformed-passwd",
188 "nis-passwd",
189 "passwd-unavailable",
190 "nss-unavailable",
191 "remote-accounts",
192 "unknown-accounts",
193 "ldap-accounts",
194 "winbind-accounts",
195 "systemd-remote",
196 "short-circuit-policy",
197 "duplicate-policy",
198 "missing-policy",
199 "group-error",
200 "group-missing",
201 "group-null-members",
202 "group-wrong-gid",
203 "supplementary-member",
204 ] {
205 check_case(case, false);
206 }
207}
208
209#[test]
210fn private_group_checks_varlink_records_and_completion() {
211 for case in [
212 "systemd-personal",
213 "systemd-unrelated",
214 "systemd-large-record",
215 "systemd-ignored-relays",
216 "systemd-multipart-empty",
217 "systemd-fragmented",
218 ] {
219 check_extraction(case, true);
220 }
221 for case in [
222 "systemd-dynamic-shared",
223 "systemd-homed-shared",
224 "systemd-large-shared",
225 "systemd-partial-error",
226 "systemd-group-error",
227 "systemd-membership-error",
228 "systemd-enumeration-error",
229 "systemd-disconnect",
230 "systemd-invalid-json",
231 "systemd-duplicate-key",
232 "systemd-missing-gid",
233 "systemd-wrong-type",
234 "systemd-group-member",
235 "systemd-membership-member",
236 "systemd-user-member",
237 "systemd-incomplete",
238 "systemd-overrides",
239 "systemd-non-socket",
240 "systemd-connect-error",
241 "systemd-buffer-limit",
242 "systemd-final-shared",
243 "systemd-unknown-membership",
244 "systemd-malformed-membership",
245 "systemd-second-service-error",
246 "systemd-socket-symlink",
247 "systemd-deep-json",
248 "systemd-invalid-utf8",
249 "systemd-negative-gid",
250 "systemd-float-gid",
251 "systemd-nested-duplicate",
252 "systemd-bad-continues",
253 ] {
254 check_extraction(case, false);
255 }
256}
257
258#[test]
259fn private_group_rejects_consumed_systemd_record_on_erange() {
260 // NSS 버퍼 재시도 대신 완전한 varlink 레코드를 직접 검사함.
261 check_extraction("systemd-large-record", true);
262 check_extraction("systemd-large-shared", false);
263}
264
265#[test]
266fn private_group_rejects_userdb_dropins_and_probe_failures() {
267 for case in ["userdb-empty", "userdb-missing"] {
268 check_extraction(case, true);
269 }
270 for case in [
271 "userdb-d0",
272 "userdb-d1",
273 "userdb-host",
274 "userdb-d3",
275 "userdb-d4",
276 "userdb-probe-error",
277 "userdb-symlink",
278 "userdb-invalid-parent",
279 ] {
280 check_extraction(case, false);
281 }
282}
283
284#[test]
285fn private_group_accepts_sss_only_without_socket_and_caches() {
286 for case in ["sss-empty", "sss-files-only", "sss-missing-directories"] {
287 check_extraction(case, true);
288 }
289 for case in [
290 "sss-socket",
291 "sss-passwd-cache",
292 "sss-group-cache",
293 "sss-initgr-cache",
294 "sss-dangling-socket",
295 "sss-dangling-cache",
296 "sss-cache-symlink",
297 "sss-invalid-parent",
298 "sss-probe-error",
299 ] {
300 check_extraction(case, false);
301 }
302}
303
304fn shim() -> &'static PathBuf {
305 static LIBRARY: std::sync::OnceLock<(Scratch, PathBuf)> = std::sync::OnceLock::new();
306 &LIBRARY
307 .get_or_init(|| {
308 let scratch = Scratch::new();
309 let library = scratch.0.join("private-group.so");
310 assert!(
311 Command::new("cc")
312 .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"])
313 .arg(
314 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
315 .join("../../tests/rust-archive-worker/private_group_nss.c")
316 )
317 .args(["-ldl", "-o"])
318 .arg(&library)
319 .status()
320 .unwrap()
321 .success()
322 );
323 (scratch, library)
324 })
325 .1
326}
327
328struct FakeUserdb {
329 stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
330 thread: Option<std::thread::JoinHandle<()>>,
331}
332impl FakeUserdb {
333 fn new(root: &std::path::Path, case: &str, uid: u32, gid: u32) -> Self {
334 use std::os::fd::AsRawFd;
335 let sockets = root.join("s");
336 fs::create_dir_all(&sockets).unwrap();
337 for d in ["d0", "d1", "host/userdb", "d3", "d4"] {
338 fs::create_dir_all(root.join(d)).unwrap();
339 }
340 if case == "userdb-missing" {
341 fs::remove_dir_all(root.join("host")).unwrap();
342 }
343 if let Some(d) = case.strip_prefix("userdb-") {
344 let d = if d == "host" { "host/userdb" } else { d };
345 if root.join(d).is_dir() {
346 fs::write(root.join(d).join("fixture.user"), b"{}").unwrap();
347 }
348 }
349 if case == "userdb-symlink" {
350 fs::remove_dir(root.join("d0")).unwrap();
351 std::os::unix::fs::symlink("missing", root.join("d0")).unwrap();
352 }
353 if case == "userdb-invalid-parent" {
354 fs::remove_dir(root.join("d0")).unwrap();
355 fs::write(root.join("d0"), b"").unwrap();
356 }
357 let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
358 let mut result = Self {
359 stop: stop.clone(),
360 thread: None,
361 };
362 if case == "systemd-non-socket" {
363 fs::write(sockets.join("io.zipelo.Fixture"), b"").unwrap();
364 return result;
365 }
366 let parent = fs::File::open(&sockets).unwrap();
367 let path = format!("/proc/self/fd/{}/io.zipelo.Fixture", parent.as_raw_fd());
368 let listener = std::os::unix::net::UnixListener::bind(path).unwrap();
369 if case == "systemd-connect-error" {
370 return result;
371 }
372 if case == "systemd-second-service-error" {
373 drop(
374 std::os::unix::net::UnixListener::bind(format!(
375 "/proc/self/fd/{}/io.zipelo.Failed",
376 parent.as_raw_fd()
377 ))
378 .unwrap(),
379 );
380 }
381 if case == "systemd-socket-symlink" {
382 std::os::unix::fs::symlink("io.zipelo.Fixture", sockets.join("io.zipelo.Link"))
383 .unwrap();
384 }
385 let _relays = if case == "systemd-ignored-relays" {
386 Some(
387 ["io.systemd.Multiplexer", "io.systemd.NameServiceSwitch"].map(|v| {
388 std::os::unix::net::UnixListener::bind(format!(
389 "/proc/self/fd/{}/{v}",
390 parent.as_raw_fd()
391 ))
392 .unwrap()
393 }),
394 )
395 } else {
396 None
397 };
398 // 중계 소켓은 연결 불가 상태로 남겨 실제로 건너뛰는지 확인함.
399 drop(_relays);
400 listener.set_nonblocking(true).unwrap();
401 let case = case.to_owned();
402 result.thread = Some(std::thread::spawn(move || {
403 use serde_json::{Value, json};
404 use std::io::{Read, Write};
405 while !stop.load(Ordering::Relaxed) {
406 let (mut stream, _) = match listener.accept() {
407 Ok(v) => v,
408 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
409 std::thread::sleep(std::time::Duration::from_millis(1));
410 continue;
411 }
412 Err(e) => panic!("{e}"),
413 };
414 stream
415 .set_read_timeout(Some(std::time::Duration::from_secs(5)))
416 .unwrap();
417 let mut request = Vec::new();
418 loop {
419 let mut byte = [0];
420 stream.read_exact(&mut byte).unwrap();
421 if byte == [0] {
422 break;
423 }
424 request.push(byte[0]);
425 }
426 let request: Value = serde_json::from_slice(&request).unwrap();
427 assert_eq!(request["parameters"]["service"], "io.zipelo.Fixture");
428 assert_eq!(request["more"], true);
429 let method = request["method"]
430 .as_str()
431 .unwrap()
432 .rsplit('.')
433 .next()
434 .unwrap();
435 let no_record = json!({"error":"io.systemd.UserDatabase.NoRecordFound"});
436 let failure = json!({"error":"io.systemd.UserDatabase.ServiceNotAvailable"});
437 let mut reply = match method {
438 "GetGroupRecord" => {
439 json!({"parameters":{"record":{"groupName":"test-personal","gid":gid,"members":[]}}})
440 }
441 "GetUserRecord" => {
442 json!({"parameters":{"record":{"userName":"other","uid":uid+1,"gid":gid+1}}})
443 }
444 "GetMemberships" => no_record.clone(),
445 _ => panic!("unexpected method"),
446 };
447 if method == "GetGroupRecord" {
448 if case == "systemd-group-member" {
449 reply["parameters"]["record"]["members"] = json!(["other"]);
450 }
451 if case == "systemd-group-error" {
452 reply = failure.clone();
453 }
454 }
455 if method == "GetMemberships" {
456 if case == "systemd-membership-member" {
457 reply =
458 json!({"parameters":{"userName":"other","groupName":"test-personal"}});
459 }
460 if case == "systemd-unknown-membership" {
461 reply = json!({"parameters":{"userName":"other","groupName":"unknown"}});
462 }
463 if case == "systemd-malformed-membership" {
464 reply = json!({"parameters":{"userName":123,"groupName":"test-personal"}});
465 }
466 if case == "systemd-membership-error" {
467 reply = failure.clone();
468 }
469 }
470 if method == "GetUserRecord" {
471 if [
472 "systemd-dynamic-shared",
473 "systemd-homed-shared",
474 "systemd-large-shared",
475 ]
476 .contains(&case.as_str())
477 {
478 reply["parameters"]["record"]["gid"] = json!(gid);
479 }
480 if case == "systemd-large-record" || case == "systemd-large-shared" {
481 reply["parameters"]["record"]["realName"] = json!("x".repeat(32768));
482 }
483 if case == "systemd-buffer-limit" {
484 reply["parameters"]["record"]["realName"] = json!("x".repeat(1024 * 1024));
485 }
486 if case == "systemd-incomplete" {
487 reply["parameters"]["incomplete"] = json!(true);
488 }
489 if case == "systemd-overrides" {
490 reply["parameters"]["record"]["binding"] = json!({"machine":{"gid":gid}});
491 }
492 if case == "systemd-missing-gid" {
493 reply["parameters"]["record"]
494 .as_object_mut()
495 .unwrap()
496 .remove("gid");
497 }
498 if case == "systemd-wrong-type" {
499 reply["parameters"]["record"]["gid"] = json!("1000");
500 }
501 if case == "systemd-user-member" {
502 reply["parameters"]["record"]["memberOf"] = json!(["test-personal"]);
503 }
504 if case == "systemd-personal" {
505 reply = no_record.clone();
506 }
507 if case == "systemd-enumeration-error" {
508 reply = failure.clone();
509 }
510 if [
511 "systemd-partial-error",
512 "systemd-disconnect",
513 "systemd-final-shared",
514 ]
515 .contains(&case.as_str())
516 {
517 reply["continues"] = json!(true);
518 }
519 if case == "systemd-invalid-json" {
520 let _ = stream.write_all(b"{not-json}\0");
521 continue;
522 }
523 if case == "systemd-duplicate-key" {
524 let _ = stream.write_all(b"{\"error\":\"failure\",\"error\":\"io.systemd.UserDatabase.NoRecordFound\"}\0");
525 continue;
526 }
527 }
528 if method == "GetUserRecord" {
529 if case == "systemd-negative-gid" {
530 reply["parameters"]["record"]["gid"] = json!(-1);
531 }
532 if case == "systemd-float-gid" {
533 reply["parameters"]["record"]["gid"] = json!(1000.0);
534 }
535 if case == "systemd-bad-continues" {
536 reply["continues"] = json!("true");
537 }
538 if case == "systemd-multipart-empty" {
539 reply["continues"] = json!(true);
540 }
541 if case == "systemd-invalid-utf8" {
542 let _ = stream.write_all(b"\xff\0");
543 continue;
544 }
545 if case == "systemd-nested-duplicate" {
546 let _ = stream.write_all(b"{\"parameters\":{\"record\":{\"userName\":\"other\",\"uid\":1001,\"gid\":1000,\"gid\":1001}}}\0");
547 continue;
548 }
549 if case == "systemd-deep-json" {
550 let data = format!("{}0{}\0", "[".repeat(140), "]".repeat(140));
551 let _ = stream.write_all(data.as_bytes());
552 continue;
553 }
554 }
555 let mut bytes = serde_json::to_vec(&reply).unwrap();
556 bytes.push(0);
557 if method == "GetUserRecord" && case == "systemd-partial-error" {
558 bytes.extend(serde_json::to_vec(&failure).unwrap());
559 bytes.push(0);
560 }
561 if method == "GetUserRecord" && case == "systemd-final-shared" {
562 reply["parameters"]["record"]["gid"] = json!(gid);
563 reply["continues"] = json!(false);
564 bytes.extend(serde_json::to_vec(&reply).unwrap());
565 bytes.push(0);
566 }
567 if method == "GetUserRecord" && case == "systemd-multipart-empty" {
568 bytes.extend(serde_json::to_vec(&no_record).unwrap());
569 bytes.push(0);
570 }
571 if case == "systemd-fragmented" {
572 for byte in bytes {
573 if stream.write_all(&[byte]).is_err() {
574 break;
575 }
576 }
577 } else {
578 let _ = stream.write_all(&bytes);
579 }
580 }
581 }));
582 result
583 }
584}
585impl Drop for FakeUserdb {
586 fn drop(&mut self) {
587 self.stop.store(true, Ordering::Relaxed);
588 if let Some(thread) = self.thread.take() {
589 thread.join().unwrap();
590 }
591 }
592}