Skip to main content

agentmux_common/
process_hardening.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Keeping other processes of the same user out of srv's and the host's memory.
5//!
6//! The host's IPC token and the launcher's secrets live in these processes'
7//! memory. An ordinary process of the same user could otherwise read them with
8//! `ptrace`, `process_vm_readv` or `/proc/<pid>/mem` (Linux), or by attaching a
9//! debugger (macOS). [`deny_memory_access`] turns that off for the calling
10//! process: on Linux the process is marked not dumpable (`/proc/<pid>/mem`,
11//! `environ`, `maps`, `fd/` and ptrace need `CAP_SYS_PTRACE` from then on; the
12//! flag resets by itself in anything the process `exec`s, so the agents srv
13//! starts are unaffected); on macOS `PT_DENY_ATTACH` refuses debugger attach; on Windows
14//! the process's access-control list stops other processes of the user reading or
15//! changing its memory (see [`win`]).
16//!
17//! The host calls it once CEF is initialized, not at startup: Chromium's user-namespace
18//! sandbox launches the zygotes from the browser process during `CefInitialize`, and a
19//! non-dumpable browser process cannot (`No usable sandbox!`). Every helper is started
20//! from those zygotes or by `exec`, so none of them inherits the flag.
21//!
22//! On Windows the launcher calls it too, at startup: it holds the handles it started srv and the
23//! host with.
24//!
25//! Left alone, on purpose: a headless srv (it runs without a launcher, and the
26//! launcher's check for an orphaned one reads its environment), a dev build
27//! (people attach debuggers to those), and any process started with
28//! `AGENTMUX_ALLOW_PTRACE=1`.
29//!
30//! A process that holds `SeDebugPrivilege` enabled (an elevated admin token) ignores the
31//! access-control list on Windows, so it can still read a hardened process; this is by design
32//! and the tests that look for a refusal skip on such a runner (`debug_privilege`).
33
34/// Set to anything non-empty to leave a process attachable (a debugger, `perf`).
35pub const ALLOW_PTRACE_ENV: &str = "AGENTMUX_ALLOW_PTRACE";
36
37/// Why [`deny_memory_access`] left the process as it was, if it did.
38#[derive(Debug, PartialEq, Eq)]
39pub enum Skipped {
40    OptedOut,
41    DevBuild,
42    Headless,
43}
44
45/// What to do for a process, from the facts about it. Pure, so the policy is tested.
46pub 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
58/// Denies other processes of this user access to this process's memory, unless
59/// the process is a dev build, headless, or started with [`ALLOW_PTRACE_ENV`].
60/// Never fails the caller: a platform without the control, or a refusal, leaves
61/// the process as it was. Returns whether the control was applied.
62pub 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/// Applies the control, whatever the policy says (`deny_memory_access` decides first).
75#[cfg(target_os = "linux")]
76pub fn apply() -> bool {
77    // SAFETY: prctl with PR_SET_DUMPABLE and a plain integer argument touches no memory.
78    unsafe { libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0) == 0 }
79}
80
81#[cfg(target_os = "macos")]
82pub fn apply() -> bool {
83    // PT_DENY_ATTACH (31): the process refuses a debugger from now on.
84    const PT_DENY_ATTACH: libc::c_int = 31;
85    // SAFETY: ptrace(PT_DENY_ATTACH, 0, NULL, 0) takes no pointer into this process.
86    unsafe { libc::ptrace(PT_DENY_ATTACH, 0, std::ptr::null_mut(), 0) == 0 }
87}
88
89/// Windows: the process's access-control list keeps other processes of the user to seeing it,
90/// waiting for it and ending it. See [`win`].
91#[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/// Lets the user's other processes read this process again, for the one caller that needs it: the
102/// crash handler, just before the out-of-process writer opens the crashing process to write its
103/// dump. Does nothing where [`apply`] did nothing. Call [`restore`] afterwards.
104#[cfg(windows)]
105pub fn relax() -> bool {
106    win::relax()
107}
108
109#[cfg(not(windows))]
110pub fn relax() -> bool {
111    false
112}
113
114/// Puts back what [`apply`] set, after [`relax`].
115#[cfg(windows)]
116pub fn restore() -> bool {
117    win::restore()
118}
119
120#[cfg(not(windows))]
121pub fn restore() -> bool {
122    false
123}
124
125/// The Windows control: a new access-control list on the process object.
126///
127/// Another process of the same user opens this one with `OpenProcess`, and what it can then do
128/// is whatever the list grants that user. Left alone, that includes `ReadProcessMemory`,
129/// injecting a thread, duplicating handles out of the process and attaching a debugger. After
130/// [`harden`] the user keeps what the tools that watch and stop a process need (its existence,
131/// times, working set and command line; waiting for it; ending it; putting it in a job), and
132/// loses reading and writing its memory, creating threads in it, duplicating its handles and the
133/// right to rewrite the list.
134///
135/// Each thread object has a list of its own, so [`harden`] sets one on every thread the process
136/// has and, through a thread-start callback, on every thread it starts later. The user keeps
137/// suspending a thread, reading its registers and querying it (what a dump of a crashed or hung
138/// process needs) and loses everything that changes a thread: setting its registers, queueing
139/// work onto it, ending it, changing its priority or token.
140///
141/// A handle opened before the change keeps the rights it was opened with. That is what lets the
142/// launcher, which holds the handles `CreateProcess` gave it for srv and the host, still wait
143/// for them, end them and write a dump of a hung host. On Windows the launcher gets the same
144/// list, so those handles cannot be copied out of it.
145///
146/// The system account keeps every right, so Windows Error Reporting still writes its dumps.
147#[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    /// `SYNCHRONIZE`: waiting for the process to end.
170    const SYNCHRONIZE: u32 = 0x0010_0000;
171    /// `PROCESS_ALL_ACCESS`.
172    const ALL_ACCESS: u32 = 0x001F_FFFF;
173
174    /// What the user's other processes keep. `PROCESS_QUERY_INFORMATION` stays because
175    /// `taskkill /F` refuses to end a process without it; with no `PROCESS_VM_READ` it shows
176    /// nothing of the memory. `PROCESS_SET_QUOTA` is the other half of putting a process in a job.
177    const USER_RIGHTS: u32 =
178        PROCESS_TERMINATE | PROCESS_SET_QUOTA | PROCESS_QUERY_INFORMATION | PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE;
179
180    /// The list for a hardened process: the system account everything; the user [`USER_RIGHTS`];
181    /// and an explicit empty entry for the owner. Without that last entry Windows lets the
182    /// owner of an object open it for `WRITE_DAC` whatever the list says, and a process that can
183    /// rewrite the list can give itself memory access again.
184    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    /// What the user keeps of a thread: `THREAD_SUSPEND_RESUME`, `THREAD_GET_CONTEXT`,
189    /// `THREAD_QUERY_INFORMATION`, `THREAD_QUERY_LIMITED_INFORMATION` and `SYNCHRONIZE`. Setting
190    /// the registers (`THREAD_SET_CONTEXT`, which also queues an APC) is what moves a thread's
191    /// execution, so it is not among them.
192    const THREAD_USER_RIGHTS: u32 = 0x2 | 0x8 | 0x40 | 0x800 | SYNCHRONIZE;
193
194    /// The list for a thread of a hardened process, with the same empty entry for the owner.
195    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    /// The list for a process the user may open freely, as Windows gives a new one.
200    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    /// A security descriptor made once from its text and kept for the life of the process, so
205    /// that switching lists later (in a crash handler) allocates nothing.
206    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        // SAFETY: `wide` is NUL-terminated and outlives the call; `sd` receives a LocalAlloc'd
212        // descriptor which this module keeps for the life of the process.
213        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        // SAFETY: the pseudo-handle for this process needs no closing; `p.0` is a valid
221        // descriptor kept alive for the life of the process.
222        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    /// The thread list, made once; the thread-start callback reads it without allocating.
228    static THREAD_LIST: OnceLock<Option<Prepared>> = OnceLock::new();
229    /// Set once the thread list is ready: from then on each new thread gets it as it starts.
230    static THREADS_HARDENED: AtomicBool = AtomicBool::new(false);
231
232    /// Windows calls this, in the new thread, for every thread the process starts (the loader's
233    /// thread-attach notification, delivered through the executable's TLS directory).
234    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                // SAFETY: the pseudo-handle for the calling thread has every right; the descriptor
239                // lives for the life of the process.
240                unsafe { SetKernelObjectSecurity(GetCurrentThread(), DACL_SECURITY_INFORMATION, list.0 as PSECURITY_DESCRIPTOR) };
241            }
242        }
243    }
244
245    /// Registers [`on_thread_start`] in the TLS callback table the linker builds (the same place
246    /// the standard library registers its own).
247    #[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    /// Puts the thread list on every thread this process already has. Returns whether all took.
252    fn harden_existing_threads(list: &Prepared) -> bool {
253        const WRITE_DAC: u32 = 0x0004_0000;
254        let mut all = true;
255        // SAFETY: a toolhelp snapshot walked with correctly sized entries and closed; each
256        // thread handle is closed after its list is set.
257        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    /// The hardened and the open list for this process's user, made on first use.
285    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    /// Whether [`harden`] has taken effect: the switches below do nothing before it, and
295    /// never allocate (they run in a crash handler).
296    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        // Keep the callback registration linked in; then the threads: new ones from now on, then
304        // the ones that exist.
305        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    /// This process's user as the text form of its SID.
324    fn user_sid() -> Option<String> {
325        // SAFETY: plain Win32 calls on this process's own token, closed on every path; the
326        // buffer is 8-byte aligned and as long as the call asked for.
327        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        // terminate, set quota, query information, query limited information, synchronize
367        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    /// Runs only as the child of the next test: hardens itself, then follows its stdin: "relax"
372    /// switches to the open list, "restore" back, and the end of input ends it.
373    #[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        // One thread that exists before hardening and one that starts after it.
383        let spawn_parked = || {
384            let (tx, rx) = std::sync::mpsc::channel();
385            std::thread::spawn(move || {
386                // SAFETY: returns the calling thread's id.
387                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        // SAFETY: returns the calling thread's id.
396        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        // SAFETY: OpenProcess on a pid, handle closed on success.
414        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        // SAFETY: OpenThread on a thread id, handle closed on success.
430        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        // suspend/resume, get context, query information, query limited information, synchronize
446        assert_eq!(sddl, "D:P(A;;0x1FFFFF;;;SY)(A;;0x10084A;;;S-1-5-21-1-2-3-1001)(A;;;;;OW)");
447    }
448
449    // The proof, with a real second process: a child of this test hardens itself and this one,
450    // which is the same user, is refused its memory and kept to watching and ending it.
451    #[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        // Its threads: the main one, one that existed before hardening and one started after.
491        // The user may suspend a thread, read its registers and query it, and may not set the
492        // registers (which also queues work onto it), end it, change it or rewrite its list.
493        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        // The crash path's switch: while relaxed the memory can be opened, and not after restoring.
531        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        // Ending the child: its creator's handle (this process) has kept every right.
544        drop(stdin);
545        assert!(child.wait().unwrap().success());
546    }
547
548    /// For the timing measurement below: a child that starts threads in batches, hardened or, as the
549    /// control, not.
550    #[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        // Batches of threads that stay alive until the batch is released, so that a thread which
566        // can be opened at all can be opened for as long as it lives.
567        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    /// How many threads of a hardened child, and of an unhardened control, another process can open
582    /// with the set-registers right while the child starts threads. Prints the counts; asserts nothing,
583    /// so it can be rerun whenever the thread access lists change.
584    #[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    /// The lowest and highest thread id the process has right now.
594    #[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        // SAFETY: a toolhelp snapshot walked with correctly sized entries and closed.
602        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        // Set-registers plus query-limited, which is what recognising the owner of a handle needs.
627        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            // Later batches can use ids outside the first snapshot: widen the range as it grows.
657            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                // SAFETY: OpenThread on a thread id; the handle is closed.
665                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    // fork, so the test process itself stays dumpable (the test harness reads its own /proc).
690    #[cfg(target_os = "linux")]
691    #[test]
692    fn apply_marks_the_process_not_dumpable() {
693        // SAFETY: the child only calls async-signal-safe functions before _exit.
694        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    // What the control is for: after `apply()` another process of the user (here the parent)
717    // can read the child's `/proc/<pid>/stat` but not its `environ`.
718    #[cfg(target_os = "linux")]
719    #[test]
720    fn after_apply_another_process_cannot_read_environ_but_can_read_stat() {
721        // SAFETY: the child calls only async-signal-safe functions (write, read, _exit) after fork.
722        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            // Root (a test run as uid 0) can read it whatever the flag says.
747            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    // The claim agents depend on: a process this one starts is dumpable again. `execvp` in
757    // the forked child (not `Command`), and python3 asks the kernel with PR_GET_DUMPABLE (3).
758    #[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        // SAFETY: the child only calls prctl, execvp and _exit before leaving the forked image.
774        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; // no python3 here: nothing to ask the kernel with
788            }
789            assert!(
790                libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0,
791                "child status {status}"
792            );
793        }
794    }
795}