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