team-ljyzipelo

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