team-ljyzipelo

공개

개인 그룹의 기본 구성원 검증을 보완함

작성자
시로사키 하나
작성 시각
커밋
31eeb501ec69b264512babeb3eb3246079157ab8
부모
26121d4
이 시점의 파일 보기

변경된 파일 4개

+281-40
수정experiments/rust-archive-worker/src/filesystem.rs+48-5
@@ -210,11 +210,52 @@ mod platform {
210210 gid: u32,
211211 members: *mut *mut i8,
212212 }
213삭제: /// 현재 계정의 기본 그룹이 따로 등록된 구성원이 없는 개인 그룹인지 확인함.
214삭제: /// Ubuntu는 계정마다 같은 이름의 개인 그룹을 만들고 umask 002를 써서,
215삭제: /// 파일 관리자나 폴더 선택 창에서 새로 만든 폴더가 그룹 쓰기 권한(775)을 가짐.
213추가: // 원격 계정 열거는 불완전할 수 있으므로 로컬 계정만 확인 가능한 경우에 허용함.
214추가: fn primary_group_is_private(gid: u32) -> bool {
215추가: let Ok(policy) = std::fs::read_to_string("/etc/nsswitch.conf") else {
216추가: return false;
217추가: };
218추가: let mut sources = policy.lines().filter_map(|line| {
219추가: let line = line.split('#').next().unwrap_or_default();
220추가: let (database, sources) = line.split_once(':')?;
221추가: (database.trim() == "passwd").then_some(sources)
222추가: });
223추가: let Some(source) = sources.next() else {
224추가: return false;
225추가: };
226추가: if sources.next().is_some() || !source.split_whitespace().eq(["files"]) {
227추가: return false;
228추가: }
229추가: let Ok(accounts) = std::fs::read_to_string("/etc/passwd") else {
230추가: return false;
231추가: };
232추가: let current_uid = unsafe { geteuid() };
233추가: let mut found_current = false;
234추가: for account in accounts.lines() {
235추가: if account.trim().is_empty() || account.starts_with('#') {
236추가: continue;
237추가: }
238추가: let fields: Vec<_> = account.split(':').collect();
239추가: if fields.len() != 7 || fields[0].is_empty() {
240추가: return false;
241추가: }
242추가: let (Ok(uid), Ok(primary_gid)) = (fields[2].parse::<u32>(), fields[3].parse::<u32>())
243추가: else {
244추가: return false;
245추가: };
246추가: if primary_gid == gid {
247추가: if uid != current_uid {
248추가: return false;
249추가: }
250추가: found_current = true;
251추가: }
252추가: }
253추가: found_current
254추가: }
255추가:
256추가: // 기본 구성원과 보조 구성원을 모두 확인함.
216257 fn private_group(gid: u32) -> bool {
217삭제: if gid != unsafe { getegid() } {
258추가: if gid != unsafe { getegid() } || !primary_group_is_private(gid) {
218259 return false;
219260 }
220261 let mut group = Group {
@@ -237,7 +278,9 @@ mod platform {
237278 // 그룹 정보를 읽지 못하면 안전하다고 볼 근거가 없으므로 거부함.
238279 status == 0
239280 && !result.is_null()
240삭제: && (group.members.is_null() || unsafe { *group.members }.is_null())
281추가: && group.gid == gid
282추가: && !group.members.is_null()
283추가: && unsafe { *group.members }.is_null()
241284 }
242285 pub struct Dir {
243286 file: File,
수정tests/rust-archive-worker/main.rs+7-35
@@ -519,44 +519,13 @@ fn symlink_parent_escape_is_rejected() {
519519 assert_eq!(fs::read_dir(s.0.join("outside")).unwrap().count(), 0);
520520}
521521
522삭제: // umask 002에서 폴더 선택 창으로 새로 만든 폴더(775)에도 풀 수 있어야 함.
523삭제: // 다른 계정이 쓸 수 있는 폴더(777)는 계속 거부함.
522추가: // 개인 그룹의 압축 해제만 허용하고 공유 쓰기는 거부함.
524523#[cfg(target_os = "linux")]
525524#[test]
526525fn private_group_writable_output_is_accepted() {
527삭제: use std::os::unix::fs::{MetadataExt, PermissionsExt};
528삭제: for (mode, other) in [(0o775, false), (0o777, true)] {
529삭제: let s = Scratch::new();
530삭제: fs::create_dir(s.0.join("output")).unwrap();
531삭제: fs::set_permissions(s.0.join("output"), fs::Permissions::from_mode(mode)).unwrap();
532삭제: let gid = fs::metadata(s.0.join("output")).unwrap().gid();
533삭제: let entry = Command::new("getent")
534삭제: .args(["group", &gid.to_string()])
535삭제: .output()
536삭제: .unwrap();
537삭제: let entry = String::from_utf8_lossy(&entry.stdout);
538삭제: let egid = Command::new("id").arg("-g").output().unwrap();
539삭제: let private = String::from_utf8_lossy(&egid.stdout).trim() == gid.to_string()
540삭제: && entry.trim_end().ends_with(':');
541삭제: let e = extract(
542삭제: &s,
543삭제: include_bytes!("fixtures/store.zip"),
544삭제: None,
545삭제: Selection::All,
546삭제: None,
547삭제: Limits::default(),
548삭제: );
549삭제: if other || !private {
550삭제: assert_eq!(terminal(&e).error, ErrorCode::UnsafePath, "{mode:o}");
551삭제: assert!(!s.0.join("output/folder").exists());
552삭제: } else {
553삭제: assert_eq!(terminal(&e).outcome, Outcome::Completed, "{e:?}");
554삭제: assert_eq!(
555삭제: fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
556삭제: PAYLOAD
557삭제: );
558삭제: }
559삭제: }
526추가: private_group::check_extraction("personal", true);
527추가: private_group::check_extraction("shared-primary", false);
528추가: private_group::check_extraction("world-writable", false);
560529}
561530
562531#[test]
@@ -1676,3 +1645,6 @@ mod spool_location;
16761645
16771646#[cfg(target_os = "linux")]
16781647mod spool_fallback;
1648추가:
1649추가: #[cfg(target_os = "linux")]
1650추가: mod private_group;
추가tests/rust-archive-worker/private_group.rs+172-0
@@ -0,0 +1,172 @@
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추가: 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" => "passwd: files sss\n",
55추가: "unknown-accounts" => "passwd: files systemd\n",
56추가: "duplicate-policy" => "passwd: files\npasswd: files\n",
57추가: "missing-policy" => "group: files\n",
58추가: _ => "# fixture\npasswd: files # local accounts\n",
59추가: };
60추가: let nss_path = scratch.0.join("nsswitch.conf");
61추가: fs::write(&nss_path, nss).unwrap();
62추가: if case == "nss-unavailable" {
63추가: fs::remove_file(&nss_path).unwrap();
64추가: }
65추가: let library = scratch.0.join("private-group.so");
66추가: assert!(
67추가: Command::new("cc")
68추가: .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"])
69추가: .arg(
70추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
71추가: .join("../../tests/rust-archive-worker/private_group_nss.c")
72추가: )
73추가: .args(["-ldl", "-o"])
74추가: .arg(&library)
75추가: .status()
76추가: .unwrap()
77추가: .success()
78추가: );
79추가: let result = Command::new(std::env::current_exe().unwrap())
80추가: .args([
81추가: "--exact",
82추가: "private_group::probe_child",
83추가: "--test-threads=1",
84추가: "--nocapture",
85추가: ])
86추가: .env("LD_PRELOAD", library)
87추가: .env("ZIPELO_GROUP_CASE", case)
88추가: .env("ZIPELO_GROUP_PASSWD", passwd_path)
89추가: .env("ZIPELO_GROUP_NSS", nss_path)
90추가: .env("ZIPELO_GROUP_OUTPUT", &output)
91추가: .env("ZIPELO_GROUP_SAFE", if safe { "1" } else { "0" })
92추가: .env("ZIPELO_GROUP_EXTRACT", if extraction { "1" } else { "0" })
93추가: .output()
94추가: .unwrap();
95추가: assert!(
96추가: result.status.success(),
97추가: "{case}: {} {}",
98추가: String::from_utf8_lossy(&result.stdout),
99추가: String::from_utf8_lossy(&result.stderr)
100추가: );
101추가: if extraction && safe {
102추가: assert_eq!(fs::read(output.join("folder/hello.txt")).unwrap(), PAYLOAD);
103추가: } else {
104추가: assert_eq!(fs::read_dir(&output).unwrap().count(), 0);
105추가: }
106추가: assert_eq!(fs::metadata(&output).unwrap().mode() & 0o777, mode);
107추가: }
108추가:
109추가: #[test]
110추가: fn probe_child() {
111추가: let Some(path) = std::env::var_os("ZIPELO_GROUP_OUTPUT") else {
112추가: return;
113추가: };
114추가: let path = std::path::Path::new(&path);
115추가: let actual = zipelo_archive_worker::filesystem::Dir::root(path);
116추가: if std::env::var("ZIPELO_GROUP_SAFE").unwrap() == "1" {
117추가: assert!(actual.is_ok());
118추가: } else {
119추가: assert!(matches!(actual, Err(ErrorCode::UnsafePath)));
120추가: }
121추가: if std::env::var("ZIPELO_GROUP_EXTRACT").unwrap() == "1" {
122추가: let events = execute(Start {
123추가: action: Action::Extract {
124추가: archive: NativePath::from_path(&path.parent().unwrap().join("input")),
125추가: destination: NativePath::from_path(path),
126추가: selection: Selection::All,
127추가: list_id: None,
128추가: gzip_output_name: None,
129추가: },
130추가: limits: Limits::default(),
131추가: });
132추가: if std::env::var("ZIPELO_GROUP_SAFE").unwrap() == "1" {
133추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
134추가: } else {
135추가: assert_eq!(terminal(&events).error, ErrorCode::UnsafePath, "{events:?}");
136추가: }
137추가: }
138추가: }
139추가:
140추가: #[test]
141추가: fn private_group_accepts_only_current_primary_member() {
142추가: for case in ["personal", "unrelated-primary"] {
143추가: check_case(case, true);
144추가: }
145추가: }
146추가:
147추가: #[test]
148추가: fn private_group_rejects_another_primary_member() {
149추가: check_case("shared-primary", false);
150추가: }
151추가:
152추가: #[test]
153추가: fn private_group_rejects_incomplete_account_information() {
154추가: for case in [
155추가: "missing-owner",
156추가: "malformed-passwd",
157추가: "nis-passwd",
158추가: "passwd-unavailable",
159추가: "nss-unavailable",
160추가: "remote-accounts",
161추가: "unknown-accounts",
162추가: "duplicate-policy",
163추가: "missing-policy",
164추가: "group-error",
165추가: "group-missing",
166추가: "group-null-members",
167추가: "group-wrong-gid",
168추가: "supplementary-member",
169추가: ] {
170추가: check_case(case, false);
171추가: }
172추가: }
추가tests/rust-archive-worker/private_group_nss.c+54-0
@@ -0,0 +1,54 @@
1추가: #define _GNU_SOURCE
2추가: #include <dlfcn.h>
3추가: #include <errno.h>
4추가: #include <fcntl.h>
5추가: #include <grp.h>
6추가: #include <stdarg.h>
7추가: #include <stdlib.h>
8추가: #include <string.h>
9추가:
10추가: int open64(const char *path, int flags, ...) {
11추가: int (*original)(const char *, int, ...) = dlsym(RTLD_NEXT, "open64");
12추가: mode_t mode = 0;
13추가: if (flags & O_CREAT) {
14추가: va_list args;
15추가: va_start(args, flags);
16추가: mode = va_arg(args, unsigned int);
17추가: va_end(args);
18추가: }
19추가: if (!strcmp(path, "/etc/passwd")) {
20추가: path = getenv("ZIPELO_GROUP_PASSWD");
21추가: } else if (!strcmp(path, "/etc/nsswitch.conf")) {
22추가: path = getenv("ZIPELO_GROUP_NSS");
23추가: }
24추가: if (!path) {
25추가: errno = EACCES;
26추가: return -1;
27추가: }
28추가: return original(path, flags, mode);
29추가: }
30추가:
31추가: int getgrgid_r(gid_t gid, struct group *group, char *buffer, size_t length,
32추가: struct group **result) {
33추가: (void)buffer;
34추가: (void)length;
35추가: const char *phase = getenv("ZIPELO_GROUP_CASE");
36추가: *result = NULL;
37추가: if (!phase || !strcmp(phase, "group-error")) {
38추가: return EIO;
39추가: }
40추가: if (!strcmp(phase, "group-missing")) {
41추가: return 0;
42추가: }
43추가: static char *empty[] = {NULL};
44추가: static char *shared[] = {"other", NULL};
45추가: *group = (struct group){
46추가: .gr_name = "fixture",
47추가: .gr_passwd = "x",
48추가: .gr_gid = !strcmp(phase, "group-wrong-gid") ? gid + 1 : gid,
49추가: .gr_mem = !strcmp(phase, "group-null-members") ? NULL :
50추가: (!strcmp(phase, "supplementary-member") ? shared : empty)
51추가: };
52추가: *result = group;
53추가: return 0;
54추가: }