Skip to main content

subc_os/
local_peer.rs

1//! Who is at the other end of an accepted local-endpoint connection: a
2//! Unix-domain socket on macOS and Linux, a named-pipe client on Windows.
3//!
4//! Unlike [`crate::socket_peer`], which searches process tables for the holder
5//! of a loopback TCP socket, peer identity comes from kernel primitives tied
6//! to the accepted connection. Optional code metadata is derived from that
7//! captured identity:
8//!
9//! - macOS: the `LOCAL_PEERTOKEN` audit token. `uid` is the token's effective
10//!   uid. The guest code for the token (`SecCodeCopyGuestWithAttributes`)
11//!   gives `exe`, its path, and `signing_id`, its signing identifier, which is
12//!   reported only when `SecCodeCheckValidity` with no requirement passes.
13//! - Linux: `SO_PEERPIDFD` (kernel 6.5 and later) and the `SO_PEERCRED` uid
14//!   and pid. `exe` is read from `/proc/<pid>/exe` while the pidfd is held, and
15//!   kept only if the pidfd still reports the process alive after the read, so
16//!   a pid reused after the peer exited cannot lend its executable. Without
17//!   `SO_PEERPIDFD` the peer is [`ObservedPeer::Unobserved`]: the credentials
18//!   alone cannot pin the process the pid names. There is no `signing_id`.
19//! - Windows: `GetNamedPipeClientProcessId` on a local pipe client, then a
20//!   handle on that pid opened with `PROCESS_QUERY_LIMITED_INFORMATION`: `sid`
21//!   is the user SID of its token and `exe` comes from
22//!   `QueryFullProcessImageNameW`. A client on another machine is never
23//!   observed. There is no `signing_id`.
24//!
25//! If the user (uid or SID) cannot be read, the peer is unobserved. If only
26//! `exe` or `signing_id` cannot be read, that value alone is absent.
27//!
28//! An observation describes the peer; it is not an authorization decision.
29
30use std::path::PathBuf;
31
32#[cfg(target_os = "linux")]
33mod linux;
34#[cfg(target_os = "macos")]
35mod macos;
36#[cfg(windows)]
37mod windows;
38
39#[cfg(test)]
40mod tests;
41
42#[cfg(all(target_os = "macos", feature = "test-support"))]
43pub mod fixture;
44
45/// The result of observing the peer of an accepted local connection.
46#[derive(Clone, Debug, PartialEq, Eq)]
47pub enum ObservedPeer {
48    /// The platform lacks the primitive, or the peer's user could not be read.
49    Unobserved,
50    /// The kernel named the peer process and its user.
51    Observed(PeerObservation),
52}
53
54/// What the kernel reported about an observed peer process.
55#[derive(Clone, Debug, PartialEq, Eq)]
56pub struct PeerObservation {
57    /// The peer's user: a uid on macOS and Linux, a SID on Windows.
58    pub user: PeerUser,
59    /// The peer's process id as the kernel recorded it for this connection.
60    pub pid: u32,
61    /// The peer's executable path, absent when it could not be read.
62    pub exe: Option<PathBuf>,
63    /// The peer's code-signing identifier (macOS only), present only when its
64    /// signature passed `SecCodeCheckValidity`.
65    pub signing_id: Option<String>,
66}
67
68/// The user a peer runs as.
69#[derive(Clone, Debug, PartialEq, Eq)]
70pub enum PeerUser {
71    /// Effective uid (macOS, from the audit token) or uid (Linux, from
72    /// `SO_PEERCRED`).
73    Uid(u32),
74    /// The user SID of the peer process's token, in `S-1-…` string form.
75    Sid(String),
76}
77
78/// An accept-time observation that may carry a private audit token for macOS
79/// code verification. Advisory fields alone cannot create that token.
80#[derive(Clone)]
81#[non_exhaustive]
82pub struct CapturedPeer {
83    observation: ObservedPeer,
84    #[cfg(target_os = "macos")]
85    token: Option<macos::AuditToken>,
86}
87
88impl std::fmt::Debug for CapturedPeer {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        f.debug_struct("CapturedPeer")
91            .field("observation", &self.observation)
92            .finish_non_exhaustive()
93    }
94}
95
96impl From<ObservedPeer> for CapturedPeer {
97    fn from(observation: ObservedPeer) -> Self {
98        Self {
99            observation,
100            #[cfg(target_os = "macos")]
101            token: None,
102        }
103    }
104}
105
106/// A signature check's closed result. Only `Satisfied` is affirmative;
107/// missing primitives, invalid requirements and read errors fail closed.
108#[derive(Clone, Debug, PartialEq, Eq)]
109#[non_exhaustive]
110pub enum CodeRequirementOutcome {
111    /// The running code satisfies the requirement and uses hardened runtime.
112    Satisfied(VerifiedCode),
113    /// The code or its signature does not meet the policy.
114    NotSatisfied,
115    /// The platform could not establish the claim.
116    Unverifiable(CodeVerificationError),
117}
118
119/// Metadata copied from the signature-validated code, never a reopened path.
120#[derive(Clone, Debug, PartialEq, Eq)]
121#[non_exhaustive]
122pub struct VerifiedCode {
123    /// `CFBundleShortVersionString` from the validated signing information.
124    pub short_version: Option<String>,
125}
126
127/// Why verification could not establish a claim.
128#[derive(Clone, Copy, Debug, PartialEq, Eq)]
129#[non_exhaustive]
130pub enum CodeVerificationError {
131    UnsupportedPlatform,
132    MissingAuditToken,
133    FrameworkUnavailable,
134    InvalidRequirement,
135    GuestUnavailable,
136    SigningInformationUnavailable,
137    ValidityCheckFailed(i32),
138}
139
140impl CapturedPeer {
141    pub fn observation(&self) -> &ObservedPeer {
142        &self.observation
143    }
144
145    /// Whether this capture can be submitted for macOS code verification.
146    pub fn has_audit_token(&self) -> bool {
147        #[cfg(target_os = "macos")]
148        return self.token.is_some();
149        #[cfg(not(target_os = "macos"))]
150        false
151    }
152
153    /// Resolve the advisory path and signing identifier from the captured
154    /// audit token. This may access disk or block in Security.framework; do
155    /// not call it inline in a listener or on an async runtime worker.
156    #[cfg(target_os = "macos")]
157    pub fn observe_code(&self) -> ObservedPeer {
158        macos::observe_code(self, ForcedFailures::default())
159    }
160
161    /// Evaluate a code-signing requirement against the captured peer token.
162    /// Hardened runtime is also required. Repeating this check revalidates the
163    /// same process incarnation; neither a pid nor a path is accepted as proof.
164    pub fn check_code_requirement(&self, requirement: &str) -> CodeRequirementOutcome {
165        #[cfg(target_os = "macos")]
166        return macos::check_requirement(self.token, requirement);
167        #[cfg(not(target_os = "macos"))]
168        {
169            let _ = requirement;
170            CodeRequirementOutcome::Unverifiable(CodeVerificationError::UnsupportedPlatform)
171        }
172    }
173}
174
175/// Capture peer facts at accept and, on macOS, retain the private audit token
176/// for later code verification.
177#[cfg(unix)]
178pub fn capture_unix_peer(socket: &impl std::os::fd::AsFd) -> CapturedPeer {
179    #[cfg(target_os = "macos")]
180    return macos::capture(socket.as_fd(), ForcedFailures::default());
181    #[cfg(not(target_os = "macos"))]
182    observe_unix_peer(socket).into()
183}
184
185/// Capture kernel peer facts without consulting macOS Security.framework.
186/// On macOS only the audit-token uid and pid are observed at this point.
187#[cfg(unix)]
188pub fn capture_unix_peer_credentials(socket: &impl std::os::fd::AsFd) -> CapturedPeer {
189    #[cfg(target_os = "macos")]
190    return macos::capture_credentials(socket.as_fd(), ForcedFailures::default());
191    #[cfg(not(target_os = "macos"))]
192    capture_unix_peer(socket)
193}
194
195/// Capture the authorization peer and, separately, the kernel PID for route
196/// diagnostics. The diagnostic PID alone must not be used to recognize an
197/// operator app or make any trust decision.
198#[cfg(unix)]
199pub fn capture_unix_peer_with_diagnostic_pid(
200    socket: &impl std::os::fd::AsFd,
201) -> (CapturedPeer, Option<u32>) {
202    #[cfg(target_os = "linux")]
203    {
204        let (peer, diagnostic_pid) = linux::observe_with_pid(
205            socket.as_fd(),
206            ForcedFailures::default(),
207            linux::pidfd_alive,
208        );
209        (peer.into(), diagnostic_pid)
210    }
211    #[cfg(not(target_os = "linux"))]
212    {
213        use std::os::fd::AsRawFd;
214        (
215            capture_unix_peer_credentials(socket),
216            unix_peer_pid(socket.as_fd().as_raw_fd()),
217        )
218    }
219}
220
221#[cfg(unix)]
222pub(crate) fn unix_peer_pid(socket: std::os::fd::RawFd) -> Option<u32> {
223    #[cfg(target_os = "linux")]
224    return linux::peer_pid(socket);
225    #[cfg(target_os = "macos")]
226    return macos::peer_pid(socket);
227    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
228    {
229        let _ = socket;
230        None
231    }
232}
233
234/// Diagnostic identity for the process that opened a local endpoint. The
235/// PID and name are advisory and must never be used for authorization.
236#[derive(Debug, Clone)]
237pub struct DiagnosticProcess {
238    pid: u32,
239    #[cfg(any(target_os = "linux", target_os = "macos"))]
240    start: Option<u64>,
241    #[cfg(windows)]
242    process: Option<std::sync::Arc<std::os::windows::io::OwnedHandle>>,
243}
244
245impl DiagnosticProcess {
246    /// Capture process identity at accept so a later name lookup can reject
247    /// a process that reused the opener's PID.
248    pub fn capture(pid: u32) -> Self {
249        Self {
250            pid,
251            #[cfg(any(target_os = "linux", target_os = "macos"))]
252            start: crate::start_time(pid),
253            #[cfg(windows)]
254            process: windows::open_diagnostic_process(pid).map(std::sync::Arc::new),
255        }
256    }
257
258    pub fn pid(&self) -> u32 {
259        self.pid
260    }
261
262    /// Read the current short name, if the opener is still alive and readable.
263    pub fn short_name(&self) -> Option<String> {
264        #[cfg(target_os = "linux")]
265        let name = {
266            let bytes = std::fs::read(format!("/proc/{}/comm", self.pid)).ok()?;
267            String::from_utf8_lossy(bytes.strip_suffix(b"\n").unwrap_or(&bytes)).into_owned()
268        };
269        #[cfg(target_os = "macos")]
270        let name = crate::process_tree::program_name(self.pid);
271
272        #[cfg(any(target_os = "linux", target_os = "macos"))]
273        return (!name.is_empty() && self.start? == crate::start_time(self.pid)?).then_some(name);
274        #[cfg(windows)]
275        return windows::process_name(self.process.as_deref()?);
276        #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
277        None
278    }
279}
280
281/// Read failures a test can force, to show how each one shapes the result
282/// without needing a platform that actually fails that read.
283#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
284pub struct ForcedFailures {
285    /// The uid or SID read fails: the peer is unobserved.
286    pub user: bool,
287    /// The executable read fails: only `exe` is absent.
288    pub exe: bool,
289    /// macOS: `SecCodeCheckValidity` fails, as for a broken signature: only
290    /// `signing_id` is absent.
291    pub signing_id: bool,
292    /// Linux: the kernel does not support `SO_PEERPIDFD`: the peer is
293    /// unobserved.
294    pub peer_pidfd: bool,
295}
296
297/// Observe the peer of an accepted Unix-domain stream socket. Call it when the
298/// connection is accepted. On a Unix other than macOS and Linux the peer is
299/// unobserved.
300#[cfg(unix)]
301pub fn observe_unix_peer(socket: &impl std::os::fd::AsFd) -> ObservedPeer {
302    unix_peer(socket.as_fd(), ForcedFailures::default())
303}
304
305/// [`observe_unix_peer`] with read failures forced, for tests.
306#[cfg(all(unix, feature = "test-support"))]
307pub fn observe_unix_peer_forcing(
308    socket: &impl std::os::fd::AsFd,
309    forced: ForcedFailures,
310) -> ObservedPeer {
311    unix_peer(socket.as_fd(), forced)
312}
313
314#[cfg(unix)]
315fn unix_peer(socket: std::os::fd::BorrowedFd<'_>, forced: ForcedFailures) -> ObservedPeer {
316    #[cfg(target_os = "macos")]
317    return macos::observe(socket, forced);
318    #[cfg(target_os = "linux")]
319    return linux::observe(socket, forced);
320    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
321    {
322        let _ = (socket, forced);
323        ObservedPeer::Unobserved
324    }
325}
326
327/// Observe the client of a connected named-pipe server instance. Call it when
328/// the client has connected. A client on another machine is unobserved.
329#[cfg(windows)]
330pub fn observe_pipe_client(pipe: &impl std::os::windows::io::AsHandle) -> ObservedPeer {
331    windows::observe(pipe.as_handle(), ForcedFailures::default())
332}
333
334/// Refuse non-local clients before observing the peer of a connected pipe.
335/// The returned diagnostic PID must not be used to recognize an operator app
336/// or make any trust decision.
337#[cfg(windows)]
338pub fn capture_pipe_client_with_diagnostic_pid(
339    pipe: &impl std::os::windows::io::AsRawHandle,
340) -> std::io::Result<(CapturedPeer, u32)> {
341    let pid = crate::named_pipe::local_client_pid(pipe.as_raw_handle())?;
342    Ok((
343        windows::observe_local_process(pid, ForcedFailures::default()).into(),
344        pid,
345    ))
346}
347
348/// [`observe_pipe_client`] with read failures forced, for tests.
349#[cfg(all(windows, feature = "test-support"))]
350pub fn observe_pipe_client_forcing(
351    pipe: &impl std::os::windows::io::AsHandle,
352    forced: ForcedFailures,
353) -> ObservedPeer {
354    windows::observe(pipe.as_handle(), forced)
355}