1use std::path::Path;
25
26#[cfg(unix)]
28const WRITABLE_BY_ALL: u32 = 0o002;
29
30#[cfg(unix)]
35#[must_use]
36pub fn may_widen_scope(dir: &Path, root: &Path) -> bool {
37 use std::os::unix::fs::MetadataExt;
38 let (Ok(dir_meta), Ok(root_meta)) = (std::fs::metadata(dir), std::fs::metadata(root)) else {
39 return false;
40 };
41 owner_rule_allows(
42 dir_meta.uid(),
43 dir_meta.mode(),
44 root_meta.uid(),
45 rustix::process::geteuid().as_raw(),
46 )
47}
48
49#[cfg(windows)]
53#[must_use]
54pub fn may_widen_scope(dir: &Path, root: &Path) -> bool {
55 let (Some(dir_owner), Some(root_owner), Some(user)) = (
56 windows_owner::owner_sid(dir),
57 windows_owner::owner_sid(root),
58 windows_owner::process_user_sid(),
59 ) else {
60 return false;
61 };
62 sid_owner_rule_allows(&dir_owner, &root_owner, &user)
63}
64
65#[cfg(not(any(unix, windows)))]
69#[must_use]
70pub fn may_widen_scope(_dir: &Path, _root: &Path) -> bool {
71 true
72}
73
74#[cfg(any(windows, test))]
79fn sid_owner_rule_allows(dir_owner: &[u8], root_owner: &[u8], user: &[u8]) -> bool {
80 dir_owner == user || dir_owner == root_owner
81}
82
83#[cfg(windows)]
87#[expect(unsafe_code, reason = "the owner SID lookups require Win32 FFI calls")]
88mod windows_owner {
89 use std::os::windows::ffi::OsStrExt;
90 use std::path::Path;
91
92 use windows_sys::Win32::Foundation::{CloseHandle, ERROR_SUCCESS, HANDLE, LocalFree};
93 use windows_sys::Win32::Security::Authorization::{GetNamedSecurityInfoW, SE_FILE_OBJECT};
94 use windows_sys::Win32::Security::{
95 GetLengthSid, GetTokenInformation, IsValidSid, OWNER_SECURITY_INFORMATION,
96 PSECURITY_DESCRIPTOR, PSID, TOKEN_QUERY, TOKEN_USER, TokenUser,
97 };
98 use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
99
100 pub(super) fn owner_sid(path: &Path) -> Option<Vec<u8>> {
102 let mut wide: Vec<u16> = path.as_os_str().encode_wide().collect();
103 if wide.contains(&0) {
104 return None;
105 }
106 wide.push(0);
107 let mut owner: PSID = std::ptr::null_mut();
108 let mut descriptor: PSECURITY_DESCRIPTOR = std::ptr::null_mut();
109 let status = unsafe {
113 GetNamedSecurityInfoW(
114 wide.as_ptr(),
115 SE_FILE_OBJECT,
116 OWNER_SECURITY_INFORMATION,
117 &raw mut owner,
118 std::ptr::null_mut(),
119 std::ptr::null_mut(),
120 std::ptr::null_mut(),
121 &raw mut descriptor,
122 )
123 };
124 if status != ERROR_SUCCESS {
125 return None;
126 }
127 let sid = copy_sid(owner);
128 unsafe { LocalFree(descriptor) };
132 sid
133 }
134
135 pub(super) fn process_user_sid() -> Option<Vec<u8>> {
137 let mut token: HANDLE = std::ptr::null_mut();
138 let process = unsafe { GetCurrentProcess() };
141 if unsafe { OpenProcessToken(process, TOKEN_QUERY, &raw mut token) } == 0 {
143 return None;
144 }
145 let sid = token_user_sid(token);
146 unsafe { CloseHandle(token) };
149 sid
150 }
151
152 fn token_user_sid(token: HANDLE) -> Option<Vec<u8>> {
154 let mut len: u32 = 0;
155 unsafe { GetTokenInformation(token, TokenUser, std::ptr::null_mut(), 0, &raw mut len) };
159 let byte_len = usize::try_from(len).ok()?;
160 if byte_len < std::mem::size_of::<TOKEN_USER>() {
161 return None;
162 }
163 let mut buffer = vec![0_u64; byte_len.div_ceil(8)];
165 let ok = unsafe {
168 GetTokenInformation(
169 token,
170 TokenUser,
171 buffer.as_mut_ptr().cast(),
172 len,
173 &raw mut len,
174 )
175 };
176 if ok == 0 {
177 return None;
178 }
179 let user = unsafe { &*buffer.as_ptr().cast::<TOKEN_USER>() };
182 copy_sid(user.User.Sid)
183 }
184
185 fn copy_sid(sid: PSID) -> Option<Vec<u8>> {
188 if sid.is_null() {
189 return None;
190 }
191 if unsafe { IsValidSid(sid) } == 0 {
194 return None;
195 }
196 let len = usize::try_from(unsafe { GetLengthSid(sid) }).ok()?;
198 let bytes = unsafe { std::slice::from_raw_parts(sid.cast::<u8>(), len) };
201 Some(bytes.to_vec())
202 }
203}
204
205#[cfg(unix)]
209const fn owner_rule_allows(dir_uid: u32, dir_mode: u32, root_uid: u32, euid: u32) -> bool {
210 dir_mode & WRITABLE_BY_ALL == 0 && (dir_uid == euid || dir_uid == root_uid)
211}
212
213#[cfg(all(test, unix))]
214mod tests {
215 use super::*;
216
217 const PRIVATE_DIR: u32 = 0o040_755;
218 const SHARED_DIR: u32 = 0o041_777;
219
220 #[test]
221 fn a_directory_of_the_current_user_widens_the_scope() {
222 assert!(owner_rule_allows(501, PRIVATE_DIR, 1001, 501));
223 }
224
225 #[test]
226 fn a_directory_of_the_root_owner_widens_the_scope_for_another_user() {
227 assert!(owner_rule_allows(1001, PRIVATE_DIR, 1001, 0));
228 }
229
230 #[test]
231 fn a_directory_of_a_third_user_does_not_widen_the_scope() {
232 assert!(!owner_rule_allows(2002, PRIVATE_DIR, 1001, 0));
233 }
234
235 #[test]
236 fn a_directory_that_all_users_can_write_never_widens_the_scope() {
237 assert!(!owner_rule_allows(501, SHARED_DIR, 501, 501));
238 assert!(!owner_rule_allows(1001, SHARED_DIR, 1001, 0));
239 }
240
241 #[test]
242 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
243 fn a_directory_that_all_users_can_write_does_not_widen_the_scope() {
244 use std::os::unix::fs::PermissionsExt;
245 let dir = tempfile::tempdir().expect("temp dir");
246 let root = dir.path().join("root");
247 std::fs::create_dir(&root).expect("root dir");
248 assert!(may_widen_scope(dir.path(), &root));
249 std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o777))
250 .expect("chmod");
251 assert!(!may_widen_scope(dir.path(), &root));
252 std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700))
253 .expect("chmod");
254 }
255
256 #[test]
258 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
259 fn a_directory_that_another_user_owns_does_not_widen_the_scope() {
260 if rustix::process::geteuid().is_root() {
261 return;
262 }
263 let root = tempfile::tempdir().expect("temp dir");
264 assert!(!may_widen_scope(Path::new("/usr"), root.path()));
265 }
266}
267
268#[cfg(test)]
269mod sid_tests {
270 use super::sid_owner_rule_allows;
271
272 const fn user_sid(rid: u8) -> [u8; 28] {
274 [
275 1, 5, 0, 0, 0, 0, 0, 5, 21, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, rid, 3, 0, 0,
276 ]
277 }
278
279 #[test]
280 fn a_directory_of_the_process_user_widens_the_scope() {
281 assert!(sid_owner_rule_allows(
282 &user_sid(1),
283 &user_sid(2),
284 &user_sid(1)
285 ));
286 }
287
288 #[test]
289 fn a_directory_of_the_root_owner_widens_the_scope_for_another_user() {
290 assert!(sid_owner_rule_allows(
291 &user_sid(2),
292 &user_sid(2),
293 &user_sid(1)
294 ));
295 }
296
297 #[test]
298 fn a_directory_of_a_third_user_does_not_widen_the_scope() {
299 assert!(!sid_owner_rule_allows(
300 &user_sid(3),
301 &user_sid(2),
302 &user_sid(1)
303 ));
304 }
305}
306
307#[cfg(all(test, windows))]
308mod windows_tests {
309 use super::may_widen_scope;
310
311 #[test]
312 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
313 fn a_directory_of_the_current_user_widens_the_scope_of_a_root_below_it() {
314 let dir = tempfile::tempdir().expect("temp dir");
315 let root = dir.path().join("root");
316 std::fs::create_dir(&root).expect("root dir");
317 assert!(may_widen_scope(dir.path(), &root));
318 }
319
320 #[test]
321 #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
322 fn a_path_without_an_owner_does_not_widen_the_scope() {
323 let dir = tempfile::tempdir().expect("temp dir");
324 let missing = dir.path().join("missing");
325 assert!(!may_widen_scope(&missing, dir.path()));
326 }
327}