1pub const ALLOW_PTRACE_ENV: &str = "AGENTMUX_ALLOW_PTRACE";
36
37#[derive(Debug, PartialEq, Eq)]
39pub enum Skipped {
40 OptedOut,
41 DevBuild,
42 Headless,
43}
44
45pub fn decide(opt_out: bool, dev_build: bool, headless: bool) -> Result<(), Skipped> {
47 if opt_out {
48 Err(Skipped::OptedOut)
49 } else if dev_build {
50 Err(Skipped::DevBuild)
51 } else if headless {
52 Err(Skipped::Headless)
53 } else {
54 Ok(())
55 }
56}
57
58pub fn deny_memory_access(headless: bool) -> bool {
63 let opt_out = std::env::var_os(ALLOW_PTRACE_ENV).is_some_and(|v| !v.is_empty());
64 let dev_build = std::env::current_exe()
65 .ok()
66 .and_then(|exe| exe.parent().map(|dir| crate::is_dev_build_exe(dir)))
67 .unwrap_or(false);
68 if decide(opt_out, dev_build, headless).is_err() {
69 return false;
70 }
71 apply()
72}
73
74#[cfg(target_os = "linux")]
76pub fn apply() -> bool {
77 unsafe { libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0) == 0 }
79}
80
81#[cfg(target_os = "macos")]
82pub fn apply() -> bool {
83 const PT_DENY_ATTACH: libc::c_int = 31;
85 unsafe { libc::ptrace(PT_DENY_ATTACH, 0, std::ptr::null_mut(), 0) == 0 }
87}
88
89#[cfg(windows)]
92pub fn apply() -> bool {
93 win::harden()
94}
95
96#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
97pub fn apply() -> bool {
98 false
99}
100
101#[cfg(windows)]
105pub fn relax() -> bool {
106 win::relax()
107}
108
109#[cfg(not(windows))]
110pub fn relax() -> bool {
111 false
112}
113
114#[cfg(windows)]
116pub fn restore() -> bool {
117 win::restore()
118}
119
120#[cfg(not(windows))]
121pub fn restore() -> bool {
122 false
123}
124
125#[cfg(windows)]
148mod win {
149 use std::ptr::null_mut;
150 use std::sync::atomic::{AtomicBool, Ordering};
151 use std::sync::OnceLock;
152
153 use windows_sys::Win32::Foundation::{CloseHandle, LocalFree, HANDLE};
154 use windows_sys::Win32::Security::Authorization::{
155 ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1,
156 };
157 use windows_sys::Win32::Security::{
158 GetTokenInformation, SetKernelObjectSecurity, TokenUser, DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR,
159 TOKEN_QUERY, TOKEN_USER,
160 };
161 use windows_sys::Win32::System::Diagnostics::ToolHelp::{
162 CreateToolhelp32Snapshot, Thread32First, Thread32Next, TH32CS_SNAPTHREAD, THREADENTRY32,
163 };
164 use windows_sys::Win32::System::Threading::{
165 GetCurrentProcessId, GetCurrentThread, OpenThread, GetCurrentProcess, OpenProcessToken, PROCESS_QUERY_INFORMATION, PROCESS_QUERY_LIMITED_INFORMATION,
166 PROCESS_SET_QUOTA, PROCESS_TERMINATE,
167 };
168
169 const SYNCHRONIZE: u32 = 0x0010_0000;
171 const ALL_ACCESS: u32 = 0x001F_FFFF;
173
174 const USER_RIGHTS: u32 =
178 PROCESS_TERMINATE | PROCESS_SET_QUOTA | PROCESS_QUERY_INFORMATION | PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE;
179
180 pub(super) fn hardened_sddl(user_sid: &str) -> String {
185 format!("D:P(A;;0x{ALL_ACCESS:X};;;SY)(A;;0x{USER_RIGHTS:X};;;{user_sid})(A;;;;;OW)")
186 }
187
188 const THREAD_USER_RIGHTS: u32 = 0x2 | 0x8 | 0x40 | 0x800 | SYNCHRONIZE;
193
194 pub(super) fn thread_sddl(user_sid: &str) -> String {
196 format!("D:P(A;;0x{ALL_ACCESS:X};;;SY)(A;;0x{THREAD_USER_RIGHTS:X};;;{user_sid})(A;;;;;OW)")
197 }
198
199 pub(super) fn open_sddl(user_sid: &str) -> String {
201 format!("D:P(A;;0x{ALL_ACCESS:X};;;SY)(A;;0x{ALL_ACCESS:X};;;{user_sid})")
202 }
203
204 struct Prepared(usize);
207
208 fn prepare(sddl: &str) -> Option<Prepared> {
209 let wide: Vec<u16> = sddl.encode_utf16().chain(std::iter::once(0)).collect();
210 let mut sd: PSECURITY_DESCRIPTOR = null_mut();
211 let ok = unsafe {
214 ConvertStringSecurityDescriptorToSecurityDescriptorW(wide.as_ptr(), SDDL_REVISION_1, &mut sd, null_mut())
215 };
216 (ok != 0 && !sd.is_null()).then(|| Prepared(sd as usize))
217 }
218
219 fn set(p: &Prepared) -> bool {
220 unsafe { SetKernelObjectSecurity(GetCurrentProcess(), DACL_SECURITY_INFORMATION, p.0 as PSECURITY_DESCRIPTOR) != 0 }
223 }
224
225 static LISTS: OnceLock<Option<(Prepared, Prepared)>> = OnceLock::new();
226
227 static THREAD_LIST: OnceLock<Option<Prepared>> = OnceLock::new();
229 static THREADS_HARDENED: AtomicBool = AtomicBool::new(false);
231
232 const DLL_THREAD_ATTACH: u32 = 2;
235 unsafe extern "system" fn on_thread_start(_module: *mut core::ffi::c_void, reason: u32, _reserved: *mut core::ffi::c_void) {
236 if reason == DLL_THREAD_ATTACH && THREADS_HARDENED.load(Ordering::SeqCst) {
237 if let Some(Some(list)) = THREAD_LIST.get() {
238 unsafe { SetKernelObjectSecurity(GetCurrentThread(), DACL_SECURITY_INFORMATION, list.0 as PSECURITY_DESCRIPTOR) };
241 }
242 }
243 }
244
245 #[used]
248 #[link_section = ".CRT$XLB"]
249 static THREAD_START: unsafe extern "system" fn(*mut core::ffi::c_void, u32, *mut core::ffi::c_void) = on_thread_start;
250
251 fn harden_existing_threads(list: &Prepared) -> bool {
253 const WRITE_DAC: u32 = 0x0004_0000;
254 let mut all = true;
255 unsafe {
258 let snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
259 if snap as isize == -1 {
260 return false;
261 }
262 let me = GetCurrentProcessId();
263 let mut entry: THREADENTRY32 = std::mem::zeroed();
264 entry.dwSize = std::mem::size_of::<THREADENTRY32>() as u32;
265 let mut more = Thread32First(snap, &mut entry) != 0;
266 while more {
267 if entry.th32OwnerProcessID == me {
268 let thread = OpenThread(WRITE_DAC, 0, entry.th32ThreadID);
269 if thread.is_null() {
270 all = false;
271 } else {
272 all &= SetKernelObjectSecurity(thread, DACL_SECURITY_INFORMATION, list.0 as PSECURITY_DESCRIPTOR) != 0;
273 CloseHandle(thread);
274 }
275 }
276 entry.dwSize = std::mem::size_of::<THREADENTRY32>() as u32;
277 more = Thread32Next(snap, &mut entry) != 0;
278 }
279 CloseHandle(snap);
280 }
281 all
282 }
283
284 fn lists() -> Option<&'static (Prepared, Prepared)> {
286 LISTS
287 .get_or_init(|| {
288 let sid = user_sid()?;
289 Some((prepare(&hardened_sddl(&sid))?, prepare(&open_sddl(&sid))?))
290 })
291 .as_ref()
292 }
293
294 static HARDENED: AtomicBool = AtomicBool::new(false);
297
298 pub(super) fn harden() -> bool {
299 let ok = lists().is_some_and(|(hardened, _)| set(hardened));
300 if ok {
301 HARDENED.store(true, Ordering::SeqCst);
302 }
303 std::hint::black_box(&THREAD_START);
306 let threads = user_sid()
307 .and_then(|sid| THREAD_LIST.get_or_init(|| prepare(&thread_sddl(&sid))).as_ref())
308 .is_some_and(|list| {
309 THREADS_HARDENED.store(true, Ordering::SeqCst);
310 harden_existing_threads(list)
311 });
312 ok && threads
313 }
314
315 pub(super) fn relax() -> bool {
316 HARDENED.load(Ordering::SeqCst) && LISTS.get().and_then(Option::as_ref).is_some_and(|(_, open)| set(open))
317 }
318
319 pub(super) fn restore() -> bool {
320 HARDENED.load(Ordering::SeqCst) && LISTS.get().and_then(Option::as_ref).is_some_and(|(hardened, _)| set(hardened))
321 }
322
323 fn user_sid() -> Option<String> {
325 unsafe {
328 let mut token: HANDLE = null_mut();
329 if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 {
330 return None;
331 }
332 let mut len = 0u32;
333 GetTokenInformation(token, TokenUser, null_mut(), 0, &mut len);
334 let mut buf = vec![0u64; (len as usize).div_ceil(8).max(1)];
335 let got = GetTokenInformation(token, TokenUser, buf.as_mut_ptr().cast(), len, &mut len) != 0;
336 CloseHandle(token);
337 if !got {
338 return None;
339 }
340 let user = &*(buf.as_ptr() as *const TOKEN_USER);
341 let mut text: *mut u16 = null_mut();
342 if ConvertSidToStringSidW(user.User.Sid, &mut text) == 0 || text.is_null() {
343 return None;
344 }
345 let n = (0..).take_while(|&i| *text.add(i) != 0).count();
346 let sid = String::from_utf16_lossy(std::slice::from_raw_parts(text, n));
347 LocalFree(text.cast());
348 Some(sid)
349 }
350 }
351}
352
353#[cfg(test)]
354mod tests {
355 use super::*;
356
357 #[test]
358 fn a_normal_process_is_hardened() {
359 assert_eq!(decide(false, false, false), Ok(()));
360 }
361
362 #[cfg(windows)]
363 #[test]
364 fn the_hardened_list_names_what_the_user_keeps_and_takes_the_owner_s_implicit_rights() {
365 let sddl = win::hardened_sddl("S-1-5-21-1-2-3-1001");
366 assert_eq!(sddl, "D:P(A;;0x1FFFFF;;;SY)(A;;0x101501;;;S-1-5-21-1-2-3-1001)(A;;;;;OW)");
368 assert!(win::open_sddl("S-1-5-21-1-2-3-1001").contains("(A;;0x1FFFFF;;;S-1-5-21-1-2-3-1001)"));
369 }
370
371 #[cfg(windows)]
374 #[test]
375 #[ignore = "runs as the child of another_process_of_the_user_is_refused_the_memory_of_a_hardened_one"]
376 fn hardened_process_child() {
377 use std::io::{BufRead, Write};
378 if std::env::var_os("AGENTMUX_PH_CHILD").is_none() {
379 return;
380 }
381 use windows_sys::Win32::System::Threading::GetCurrentThreadId;
382 let spawn_parked = || {
384 let (tx, rx) = std::sync::mpsc::channel();
385 std::thread::spawn(move || {
386 tx.send(unsafe { GetCurrentThreadId() }).unwrap();
388 std::thread::park();
389 });
390 rx.recv().unwrap()
391 };
392 let before = spawn_parked();
393 println!("HARDENED {}", apply());
394 let after = spawn_parked();
395 println!("THREADS {} {before} {after}", unsafe { GetCurrentThreadId() });
397 std::io::stdout().flush().unwrap();
398 for line in std::io::stdin().lock().lines() {
399 let done = match line.unwrap().as_str() {
400 "relax" => relax(),
401 "restore" => restore(),
402 _ => false,
403 };
404 println!("DONE {done}");
405 std::io::stdout().flush().unwrap();
406 }
407 }
408
409 #[cfg(windows)]
410 fn open_error(access: u32, pid: u32) -> Option<u32> {
411 use windows_sys::Win32::Foundation::{CloseHandle, GetLastError};
412 use windows_sys::Win32::System::Threading::OpenProcess;
413 unsafe {
415 let h = OpenProcess(access, 0, pid);
416 if h.is_null() {
417 Some(GetLastError())
418 } else {
419 CloseHandle(h);
420 None
421 }
422 }
423 }
424
425 #[cfg(windows)]
426 fn thread_open_error(access: u32, tid: u32) -> Option<u32> {
427 use windows_sys::Win32::Foundation::{CloseHandle, GetLastError};
428 use windows_sys::Win32::System::Threading::OpenThread;
429 unsafe {
431 let h = OpenThread(access, 0, tid);
432 if h.is_null() {
433 Some(GetLastError())
434 } else {
435 CloseHandle(h);
436 None
437 }
438 }
439 }
440
441 #[cfg(windows)]
442 #[test]
443 fn the_thread_list_keeps_suspend_and_registers_for_dumps_and_takes_the_rest() {
444 let sddl = win::thread_sddl("S-1-5-21-1-2-3-1001");
445 assert_eq!(sddl, "D:P(A;;0x1FFFFF;;;SY)(A;;0x10084A;;;S-1-5-21-1-2-3-1001)(A;;;;;OW)");
447 }
448
449 #[cfg(windows)]
452 #[test]
453 fn another_process_of_the_user_is_refused_the_memory_of_a_hardened_one() {
454 use std::io::{BufRead, BufReader};
455 use std::process::{Command, Stdio};
456 const VM_READ: u32 = 0x10;
457 const VM_WRITE_OPERATION: u32 = 0x28;
458 const CREATE_THREAD: u32 = 0x2;
459 const DUP_HANDLE: u32 = 0x40;
460 const WRITE_DAC: u32 = 0x40000;
461 const QUERY_LIMITED: u32 = 0x1000;
462 const QUERY: u32 = 0x400;
463 const TERMINATE_QUOTA: u32 = 0x101;
464 const SYNCHRONIZE: u32 = 0x10_0000;
465 const ACCESS_DENIED: u32 = 5;
466
467 if crate::debug_privilege::refusal_cannot_be_observed("another_process_of_the_user_is_refused_the_memory_of_a_hardened_one") {
468 return;
469 }
470 let mut child = Command::new(std::env::current_exe().unwrap())
471 .args(["--exact", "process_hardening::tests::hardened_process_child", "--ignored", "--nocapture"])
472 .env("AGENTMUX_PH_CHILD", "1")
473 .stdin(Stdio::piped())
474 .stdout(Stdio::piped())
475 .spawn()
476 .unwrap();
477 let pid = child.id();
478 let mut lines = BufReader::new(child.stdout.take().unwrap()).lines();
479 let mut hardened = None;
480 for line in lines.by_ref() {
481 if let Some(v) = line.unwrap().strip_prefix("HARDENED ") {
482 hardened = Some(v.to_string());
483 break;
484 }
485 }
486 assert_eq!(hardened.as_deref(), Some("true"), "the child hardened itself");
487 let threads: Vec<u32> = lines.next().unwrap().unwrap().strip_prefix("THREADS ").unwrap().split(' ').map(|t| t.parse().unwrap()).collect();
488 assert_eq!(threads.len(), 3);
489
490 for tid in &threads {
494 for (name, access) in [
495 ("set the registers or queue work", 0x10u32),
496 ("end a thread", 0x1),
497 ("change a thread", 0x20),
498 ("set a thread's token", 0x80),
499 ("rewrite the list", 0x40000),
500 ] {
501 assert_eq!(thread_open_error(access, *tid), Some(ACCESS_DENIED), "must not {name} (thread {tid})");
502 }
503 for (name, access) in [
504 ("suspend, read the registers and query", 0x2 | 0x8 | 0x40),
505 ("query limited information", 0x800),
506 ("wait", SYNCHRONIZE),
507 ] {
508 assert_eq!(thread_open_error(access, *tid), None, "must still {name} (thread {tid})");
509 }
510 }
511
512 for (name, access) in [
513 ("read memory", VM_READ),
514 ("write memory", VM_WRITE_OPERATION),
515 ("start a thread", CREATE_THREAD),
516 ("duplicate a handle", DUP_HANDLE),
517 ("rewrite the list", WRITE_DAC),
518 ] {
519 assert_eq!(open_error(access, pid), Some(ACCESS_DENIED), "must not {name}");
520 }
521 for (name, access) in [
522 ("query limited information", QUERY_LIMITED),
523 ("query information", QUERY),
524 ("wait", SYNCHRONIZE),
525 ("end it and put it in a job", TERMINATE_QUOTA),
526 ] {
527 assert_eq!(open_error(access, pid), None, "must still {name}");
528 }
529
530 let mut stdin = child.stdin.take().unwrap();
532 let mut ask = |word: &str| {
533 use std::io::Write;
534 writeln!(stdin, "{word}").unwrap();
535 stdin.flush().unwrap();
536 lines.next().unwrap().unwrap()
537 };
538 assert_eq!(ask("relax"), "DONE true");
539 assert_eq!(open_error(VM_READ, pid), None, "relaxed: the memory can be opened");
540 assert_eq!(ask("restore"), "DONE true");
541 assert_eq!(open_error(VM_READ, pid), Some(ACCESS_DENIED), "restored: refused again");
542
543 drop(stdin);
545 assert!(child.wait().unwrap().success());
546 }
547
548 #[cfg(windows)]
551 #[test]
552 #[ignore = "runs as the child of thread_timing_measurement"]
553 fn thread_timing_child() {
554 use std::io::Write;
555 if std::env::var_os("AGENTMUX_PH_CHILD").is_none() {
556 return;
557 }
558 if std::env::var_os("AGENTMUX_PH_CONTROL").is_some() {
559 println!("HARDENED false");
560 } else {
561 println!("HARDENED {}", apply());
562 }
563 std::io::stdout().flush().unwrap();
564 let n: usize = std::env::var("AGENTMUX_PH_STORM").ok().and_then(|v| v.parse().ok()).unwrap_or(4000);
565 let batch: usize = std::env::var("AGENTMUX_PH_BATCH").ok().and_then(|v| v.parse().ok()).unwrap_or(500);
568 for _ in 0..n / batch {
569 let handles: Vec<_> =
570 (0..batch).map(|_| std::thread::Builder::new().stack_size(64 * 1024).spawn(std::thread::park).unwrap()).collect();
571 std::thread::sleep(std::time::Duration::from_millis(2));
572 for h in handles {
573 h.thread().unpark();
574 h.join().unwrap();
575 }
576 }
577 println!("STORM done");
578 std::io::stdout().flush().unwrap();
579 }
580
581 #[cfg(windows)]
585 #[test]
586 #[ignore = "measurement, asserts nothing: cargo test -p agentmux-common thread_timing_measurement -- --ignored --nocapture"]
587 fn thread_timing_measurement() {
588 for control in [true, false] {
589 measure(control);
590 }
591 }
592
593 #[cfg(windows)]
595 fn child_thread_id_range(pid: u32) -> (u32, u32) {
596 use windows_sys::Win32::Foundation::CloseHandle;
597 use windows_sys::Win32::System::Diagnostics::ToolHelp::{
598 CreateToolhelp32Snapshot, Thread32First, Thread32Next, TH32CS_SNAPTHREAD, THREADENTRY32,
599 };
600 let (mut lo, mut hi) = (u32::MAX, 0);
601 unsafe {
603 let snap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
604 let mut e: THREADENTRY32 = std::mem::zeroed();
605 e.dwSize = std::mem::size_of::<THREADENTRY32>() as u32;
606 let mut more = Thread32First(snap, &mut e) != 0;
607 while more {
608 if e.th32OwnerProcessID == pid {
609 lo = lo.min(e.th32ThreadID);
610 hi = hi.max(e.th32ThreadID);
611 }
612 e.dwSize = std::mem::size_of::<THREADENTRY32>() as u32;
613 more = Thread32Next(snap, &mut e) != 0;
614 }
615 CloseHandle(snap);
616 }
617 (lo, hi.max(lo))
618 }
619
620 #[cfg(windows)]
621 fn measure(control: bool) {
622 use std::io::{BufRead, BufReader};
623 use std::process::{Command, Stdio};
624 use windows_sys::Win32::Foundation::CloseHandle;
625 use windows_sys::Win32::System::Threading::{GetProcessIdOfThread, OpenThread};
626 const SET_CONTEXT: u32 = 0x10 | 0x800;
628 let mut child = Command::new(std::env::current_exe().unwrap())
629 .args(["--exact", "process_hardening::tests::thread_timing_child", "--ignored", "--nocapture"])
630 .env("AGENTMUX_PH_CHILD", "1")
631 .envs(control.then_some(("AGENTMUX_PH_CONTROL", "1")))
632 .stdout(Stdio::piped())
633 .spawn()
634 .unwrap();
635 let pid = child.id();
636 let mut lines = BufReader::new(child.stdout.take().unwrap()).lines();
637 let hardened = lines.by_ref().map(|l| l.unwrap()).find(|l| l.starts_with("HARDENED "));
638 assert_eq!(hardened.as_deref(), Some(if control { "HARDENED false" } else { "HARDENED true" }));
639 let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
640 let d2 = done.clone();
641 let waiter = std::thread::spawn(move || {
642 for l in lines {
643 if l.unwrap() == "STORM done" {
644 break;
645 }
646 }
647 d2.store(true, std::sync::atomic::Ordering::SeqCst);
648 });
649 let (mut sweeps, mut tries, mut hits) = (0u64, 0u64, 0u64);
650 let start = std::time::Instant::now();
651 std::thread::sleep(std::time::Duration::from_millis(50));
652 let (mut lo, mut hi) = child_thread_id_range(pid);
653 println!("RANGE {lo}..{hi}");
654 while !done.load(std::sync::atomic::Ordering::SeqCst) {
655 sweeps += 1;
656 if sweeps % 20 == 0 {
658 let (l, h) = child_thread_id_range(pid);
659 (lo, hi) = (lo.min(l), hi.max(h));
660 }
661 let mut tid = lo.saturating_sub(64) & !3;
662 while tid < hi + 64 {
663 tries += 1;
664 unsafe {
666 let h = OpenThread(SET_CONTEXT, 0, tid);
667 if !h.is_null() {
668 if GetProcessIdOfThread(h) == pid {
669 hits += 1;
670 }
671 CloseHandle(h);
672 }
673 }
674 tid += 4;
675 }
676 }
677 waiter.join().unwrap();
678 let _ = child.wait();
679 println!("TIMING control={control} sweeps={sweeps} opens_tried={tries} secs={:.1} opened={hits}", start.elapsed().as_secs_f64());
680 }
681
682 #[test]
683 fn an_opt_out_a_dev_build_and_a_headless_srv_are_left_alone() {
684 assert_eq!(decide(true, false, false), Err(Skipped::OptedOut));
685 assert_eq!(decide(false, true, false), Err(Skipped::DevBuild));
686 assert_eq!(decide(false, false, true), Err(Skipped::Headless));
687 }
688
689 #[cfg(target_os = "linux")]
691 #[test]
692 fn apply_marks_the_process_not_dumpable() {
693 unsafe {
695 let pid = libc::fork();
696 assert!(pid >= 0);
697 if pid == 0 {
698 let before = libc::prctl(libc::PR_GET_DUMPABLE, 0, 0, 0, 0);
699 let applied = apply();
700 let after = libc::prctl(libc::PR_GET_DUMPABLE, 0, 0, 0, 0);
701 libc::_exit(if before == 1 && applied && after == 0 {
702 0
703 } else {
704 1
705 });
706 }
707 let mut status = 0;
708 libc::waitpid(pid, &mut status, 0);
709 assert!(
710 libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0,
711 "child status {status}"
712 );
713 }
714 }
715
716 #[cfg(target_os = "linux")]
719 #[test]
720 fn after_apply_another_process_cannot_read_environ_but_can_read_stat() {
721 unsafe {
723 let mut ready = [0 as libc::c_int; 2];
724 let mut done = [0 as libc::c_int; 2];
725 assert_eq!(libc::pipe(ready.as_mut_ptr()), 0);
726 assert_eq!(libc::pipe(done.as_mut_ptr()), 0);
727 let pid = libc::fork();
728 assert!(pid >= 0);
729 if pid == 0 {
730 let ok = apply();
731 let byte = [ok as u8];
732 libc::write(ready[1], byte.as_ptr().cast(), 1);
733 let mut sink = [0u8; 1];
734 libc::read(done[0], sink.as_mut_ptr().cast(), 1);
735 libc::_exit(0);
736 }
737 let mut got = [0u8; 1];
738 assert_eq!(libc::read(ready[0], got.as_mut_ptr().cast(), 1), 1);
739 let environ = std::fs::read(format!("/proc/{pid}/environ"));
740 let stat = std::fs::read_to_string(format!("/proc/{pid}/stat"));
741 libc::write(done[1], got.as_ptr().cast(), 1);
742 let mut status = 0;
743 libc::waitpid(pid, &mut status, 0);
744 assert_eq!(got[0], 1, "apply() failed in the child");
745 assert!(stat.is_ok(), "stat should stay readable: {stat:?}");
746 if libc::geteuid() != 0 {
748 assert!(
749 environ.is_err(),
750 "environ was readable by another process after apply()"
751 );
752 }
753 }
754 }
755
756 #[cfg(target_os = "linux")]
759 #[test]
760 fn a_program_the_process_starts_is_dumpable_again() {
761 use std::ffi::CString;
762 let prog = CString::new("python3").unwrap();
763 let args = [
764 prog.clone(),
765 CString::new("-c").unwrap(),
766 CString::new("import ctypes, sys; sys.exit(0 if ctypes.CDLL(None).prctl(3, 0, 0, 0, 0) == 1 else 7)").unwrap(),
767 ];
768 let argv: Vec<*const libc::c_char> = args
769 .iter()
770 .map(|a| a.as_ptr())
771 .chain(std::iter::once(std::ptr::null()))
772 .collect();
773 unsafe {
775 let pid = libc::fork();
776 assert!(pid >= 0);
777 if pid == 0 {
778 if !apply() {
779 libc::_exit(9);
780 }
781 libc::execvp(prog.as_ptr(), argv.as_ptr());
782 libc::_exit(127);
783 }
784 let mut status = 0;
785 libc::waitpid(pid, &mut status, 0);
786 if libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 127 {
787 return; }
789 assert!(
790 libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0,
791 "child status {status}"
792 );
793 }
794 }
795}