Reading process state from a script under macOS sandbox-exec

2026-12-05来源 dev.toEnglish

This is another note from putting the pre-commit checks of my reading app under sandbox-exec (the first one was about nesting sandbox-exec and SwiftPM). After a sandboxed run over every check, ten of them were red that were green outside the sandbox, and all ten came down to one thing, which is that they read process state through ps, and ps can't run inside the sandbox.

TLDR: /bin/ps is setuid root, and a process under a sandbox-exec profile can't exec a setuid binary unless the profile lets it leave the sandbox, so it fails with exit 71. sysctl from Python through ctypes works under the same profile and gives you the start time, the name, argv and the process list. Its p_stat doesn't tell a sleeping process from a running one, though, and a few other ps fields need care, so promise only what your callers read.

ps under a profile

The profile doesn't have to deny anything related, the one below allows everything apart from reading one directory, and ps still fails while echo runs fine:

$ cat outer.sb (version 1) (allow default) (deny file-read-data (subpath "/Users/Shared/nope")) $ sandbox-exec -f outer.sb /bin/echo hi hi $ sandbox-exec -f outer.sb /bin/ps -p $$ sandbox-exec: execvp() of '/bin/ps' failed: Operation not permitted $ echo $? 71 

The difference is the setuid bit, which ps has and pgrep doesn't (top and login are setuid too, and fail the same way):

$ ls -l /bin/ps /usr/bin/pgrep | awk '{print $1, $NF}' -rwsr-xr-x /bin/ps -rwxr-xr-x /usr/bin/pgrep 

There is a profile rule that gets ps running, (allow process-exec (literal "/bin/ps") (with no-sandbox)), but as the name says it runs ps outside the sandbox, which for checks whose results are only worth something because the sandbox limited them is the same as not sandboxing them.

pgrep runs under the profile, so if all a script needs is "is there a process called X", that's the easy way out. The scripts I had needed more than that (a start time to tell whether a lock file's owner is still the same process, a snapshot of a process group, and polling until a child turns into a zombie), so the other easy way out was to run those checks outside the sandbox. That works, but a check outside the sandbox is one whose result I can never reuse, which was the whole point of the sandbox, so let's read the same information without ps instead.

Reading it through sysctl

ps gets most of what it prints from sysctl, which an unprivileged process can call. KERN_PROC_PID returns a struct kinfo_proc for one process, KERN_PROC_ALL returns one for every process, and KERN_PROCARGS2 returns its arguments. Python's ctypes can call it without a compiler, and the code below also runs on the Python 3.9 that /usr/bin/python3 hands you from Xcode, which matters when the script has to run on a machine with nothing else installed:

import ctypes, struct, sys, time libc = ctypes.CDLL(None, use_errno=True) CTL_KERN, KERN_ARGMAX, KERN_PROC, KERN_PROC_PID, KERN_PROCARGS2 = 1, 8, 14, 1, 49 SZOMB = 5 KINFO_PROC_SIZE = 648 # sizeof(struct kinfo_proc) on arm64 and x86_64 def sysctl(mib, size): mib = (ctypes.c_int * len(mib))(*mib) buf = ctypes.create_string_buffer(size) length = ctypes.c_size_t(size) if libc.sysctl(mib, len(mib), buf, ctypes.byref(length), None, 0) != 0: raise OSError(ctypes.get_errno(), "sysctl") return buf.raw[:length.value] ARGMAX = struct.unpack("<i", sysctl([CTL_KERN, KERN_ARGMAX], 4))[0] def kinfo(pid): kp = sysctl([CTL_KERN, KERN_PROC, KERN_PROC_PID, pid], KINFO_PROC_SIZE) if not kp: return None # no such process if len(kp) != KINFO_PROC_SIZE: raise OSError("unexpected struct kinfo_proc size") start = struct.unpack_from("<qi", kp, 0) # p_starttime p_stat = kp[36] comm = kp[243:260].split(b"\0")[0].decode(errors="replace") # p_comm return start, p_stat, comm def args(pid): # sized from kern.argmax, since a short buffer is silently truncated raw = sysctl([CTL_KERN, KERN_PROCARGS2, pid], ARGMAX) argc = struct.unpack_from("<i", raw, 0)[0] _exec_path, _, rest = raw[4:].partition(b"\0") # argv starts after the padding, and the environment can follow it return [a.decode(errors="replace") for a in rest.lstrip(b"\0").split(b"\0")[:argc]] pid = int(sys.argv[1]) before = kinfo(pid) try: argv = args(pid) except OSError: argv = None # a zombie, another user's process, or one that just exited after = kinfo(pid) if before is None or after is None or after[0] != before[0]: sys.exit(1) # gone, or the pid was reused while we read it (sec, _usec), p_stat, comm = after if p_stat == SZOMB: stat, comm, command = "Z", "<defunct>", "<defunct>" else: stat, command = "-", " ".join(argv) if argv is not None else f"({comm})" print(time.strftime("%a %b %e %H:%M:%S %Y", time.gmtime(sec)), stat, comm, command) 

The two reads of kinfo around args are there because the process can exit, or exit and have its pid handed to another process, between the calls, and comparing the start times is how we notice that instead of printing the name of one process with the arguments of another. The offsets of the fields come from struct kinfo_proc in the macOS SDK headers, and the length check only catches the struct shrinking (a bigger one fails the call), not a field moving inside it, so a self-test that compares the reader with real ps (run outside the sandbox, where it works) is what catches a layout change after a macOS update. That self-test needs a zombie child among the processes it compares, because for every other process the reader prints - and a p_stat read from the wrong offset would look the same, and it has to compare the name with ps -o ucomm=, for the reason below.

The buffer size is easy to get wrong, since KERN_PROCARGS2 doesn't fail when the buffer is too small, it fills what fits and returns success. With a fixed 256 KB buffer and a process started with two 200,000-character arguments, the first version of the reader printed an environment variable of that process as its last argument, because argc still said five and the parser carried on into whatever bytes were left.

Run under the same profile, next to LC_ALL=C TZ=UTC ps -p <pid> -o lstart=,stat=,comm=,command= run outside it, for four children of a test script (a zombie, a stopped sleep, a sleeping sleep, and a busy yes), it prints:

reader: Tue Nov 24 14:30:52 2026 Z <defunct> <defunct> ps: Tue Nov 24 14:30:52 2026 ZN <defunct> <defunct> reader: Tue Nov 24 14:30:52 2026 - sleep /bin/sleep 60 ps: Tue Nov 24 14:30:52 2026 TN /bin/sleep /bin/sleep 60 reader: Tue Nov 24 14:30:52 2026 - sleep /bin/sleep 60 ps: Tue Nov 24 14:30:52 2026 SN /bin/sleep /bin/sleep 60 reader: Tue Nov 24 14:30:52 2026 - yes /usr/bin/yes ps: Tue Nov 24 14:30:52 2026 RN /usr/bin/yes /usr/bin/yes 

KERN_PROC_ALL works under the profile too. I listed every pid with it unsandboxed, then sandboxed, then unsandboxed again, and every pid that was in both unsandboxed lists was also in the sandboxed one, so as far as I can tell the sandbox doesn't hide any processes from it.

What it doesn't reproduce

My first version of the reader promised ps's stat letters exactly, and the output above shows why that couldn't work. p_stat is 2 (SRUN) for both the sleeping sleep and the busy yes, which ps shows as S and R. Only stopped (4) and zombie (5) differ, and kinfo_proc has nothing else that tells sleeping from running. For your own processes proc_pidinfo with PROC_PIDTASKINFO (from libproc) does, since its pti_numrunning was 0 for the sleeping child and 1 for the busy one under the same profile, and it refused pid 1. I didn't need it in the end, because every caller in the scripts compared the first letter with Z and nothing else, so the reader prints Z or -, and that's all it claims.

Before writing a replacement for ps, grep for what its callers parse, and reproduce only that.

The rest of the differences are smaller, but each one breaks a script that compares strings:

  • comm is not the same thing in both. ps -o comm= printed argv[0] in the probes (/bin/sleep for a process started by its full path, sleep for one started through PATH), while p_comm holds the first 16 characters of the executable's name, which is what ps -o ucomm= prints. A caller that matches on one won't match on the other.
  • A zombie has no arguments left, and KERN_PROCARGS2 fails on it with EINVAL, while ps prints <defunct> for both comm and command, so the reader does the same. KERN_PROCARGS2 also refuses other users' processes, and for those the reader prints the name in parentheses, (launchd) for pid 1, instead of failing.
  • KERN_PROCARGS2 returns argc, the exec path, some padding and argv, and for some processes the environment comes right after argv. In the probes it came back for a Homebrew Python and not for Apple's own binaries like /bin/sleep or /bin/zsh. The environment can hold tokens, so the parser stops after argc strings, which is why args slices with [:argc] rather than splitting the whole buffer. Skipping the padding by stripping every NUL also eats empty leading arguments, so a process started with an empty argv[0] would get one environment entry printed in its place, which is what ps does too.
  • lstart is a formatted string, and if old and new code both write it somewhere (a lock file, say) and compare it for equality, the new code has to produce exactly the same string. ps uses whole seconds, so the reader formats the truncated tv_sec under UTC, and both have to agree on the locale and time zone, which is why the comparison above runs ps with LC_ALL=C TZ=UTC. Whole seconds are only there to match what ps already wrote (the kernel has microseconds too), and the start time is set at fork, so a process that later execs another program keeps it.

The fix for ps under a sandbox is to read the same information through sysctl, which needs no privileges, rather than to look for a profile rule, since the only rule I found that lets a sandboxed process exec a setuid binary takes that process out of the sandbox. A reader like that can only promise what the kernel hands to an unprivileged process, and whether that's enough depends on what the scripts calling it read, so the order that worked for me was to grep the callers first, write down the smaller contract they need, and then check the reader against real ps output outside the sandbox, with a zombie among the processes it compares.

原文:https://www.a8q9.cn/en/article/reading-process-state-from-a-script-under-macos-sandbox-exec-d90ec1.html

相关文章