subc-os 0.1.60

Operating-system primitives for the subc daemon that need unsafe code, behind a safe API: per-process identity, signalling, memory and CPU usage, and the launch-nonce descriptor handoff.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! Who is at the other end of an accepted local-endpoint connection: a
//! Unix-domain socket on macOS and Linux, a named-pipe client on Windows.
//!
//! Unlike [`crate::socket_peer`], which searches process tables for the holder
//! of a loopback TCP socket, peer identity comes from kernel primitives tied
//! to the accepted connection. Optional code metadata is derived from that
//! captured identity:
//!
//! - macOS: the `LOCAL_PEERTOKEN` audit token. `uid` is the token's effective
//!   uid. The guest code for the token (`SecCodeCopyGuestWithAttributes`)
//!   gives `exe`, its path, and `signing_id`, its signing identifier, which is
//!   reported only when `SecCodeCheckValidity` with no requirement passes.
//! - Linux: `SO_PEERPIDFD` (kernel 6.5 and later) and the `SO_PEERCRED` uid
//!   and pid. `exe` is read from `/proc/<pid>/exe` while the pidfd is held, and
//!   kept only if the pidfd still reports the process alive after the read, so
//!   a pid reused after the peer exited cannot lend its executable. Without
//!   `SO_PEERPIDFD` the peer is [`ObservedPeer::Unobserved`]: the credentials
//!   alone cannot pin the process the pid names. There is no `signing_id`.
//! - Windows: `GetNamedPipeClientProcessId` on a local pipe client, then a
//!   handle on that pid opened with `PROCESS_QUERY_LIMITED_INFORMATION`: `sid`
//!   is the user SID of its token and `exe` comes from
//!   `QueryFullProcessImageNameW`. A client on another machine is never
//!   observed. There is no `signing_id`.
//!
//! If the user (uid or SID) cannot be read, the peer is unobserved. If only
//! `exe` or `signing_id` cannot be read, that value alone is absent.
//!
//! An observation describes the peer; it is not an authorization decision.

use std::path::PathBuf;

#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(windows)]
mod windows;

#[cfg(test)]
mod tests;

#[cfg(all(target_os = "macos", feature = "test-support"))]
pub mod fixture;

/// The result of observing the peer of an accepted local connection.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ObservedPeer {
    /// The platform lacks the primitive, or the peer's user could not be read.
    Unobserved,
    /// The kernel named the peer process and its user.
    Observed(PeerObservation),
}

/// What the kernel reported about an observed peer process.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PeerObservation {
    /// The peer's user: a uid on macOS and Linux, a SID on Windows.
    pub user: PeerUser,
    /// The peer's process id as the kernel recorded it for this connection.
    pub pid: u32,
    /// The peer's executable path, absent when it could not be read.
    pub exe: Option<PathBuf>,
    /// The peer's code-signing identifier (macOS only), present only when its
    /// signature passed `SecCodeCheckValidity`.
    pub signing_id: Option<String>,
}

/// The user a peer runs as.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PeerUser {
    /// Effective uid (macOS, from the audit token) or uid (Linux, from
    /// `SO_PEERCRED`).
    Uid(u32),
    /// The user SID of the peer process's token, in `S-1-…` string form.
    Sid(String),
}

/// An accept-time observation that may carry a private audit token for macOS
/// code verification. Advisory fields alone cannot create that token.
#[derive(Clone)]
#[non_exhaustive]
pub struct CapturedPeer {
    observation: ObservedPeer,
    #[cfg(target_os = "macos")]
    token: Option<macos::AuditToken>,
}

impl std::fmt::Debug for CapturedPeer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CapturedPeer")
            .field("observation", &self.observation)
            .finish_non_exhaustive()
    }
}

impl From<ObservedPeer> for CapturedPeer {
    fn from(observation: ObservedPeer) -> Self {
        Self {
            observation,
            #[cfg(target_os = "macos")]
            token: None,
        }
    }
}

/// A signature check's closed result. Only `Satisfied` is affirmative;
/// missing primitives, invalid requirements and read errors fail closed.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum CodeRequirementOutcome {
    /// The running code satisfies the requirement and uses hardened runtime.
    Satisfied(VerifiedCode),
    /// The code or its signature does not meet the policy.
    NotSatisfied,
    /// The platform could not establish the claim.
    Unverifiable(CodeVerificationError),
}

/// Metadata copied from the signature-validated code, never a reopened path.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct VerifiedCode {
    /// `CFBundleShortVersionString` from the validated signing information.
    pub short_version: Option<String>,
}

/// Why verification could not establish a claim.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum CodeVerificationError {
    UnsupportedPlatform,
    MissingAuditToken,
    FrameworkUnavailable,
    InvalidRequirement,
    GuestUnavailable,
    SigningInformationUnavailable,
    ValidityCheckFailed(i32),
}

impl CapturedPeer {
    pub fn observation(&self) -> &ObservedPeer {
        &self.observation
    }

    /// Whether this capture can be submitted for macOS code verification.
    pub fn has_audit_token(&self) -> bool {
        #[cfg(target_os = "macos")]
        return self.token.is_some();
        #[cfg(not(target_os = "macos"))]
        false
    }

    /// Resolve the advisory path and signing identifier from the captured
    /// audit token. This may access disk or block in Security.framework; do
    /// not call it inline in a listener or on an async runtime worker.
    #[cfg(target_os = "macos")]
    pub fn observe_code(&self) -> ObservedPeer {
        macos::observe_code(self, ForcedFailures::default())
    }

    /// Evaluate a code-signing requirement against the captured peer token.
    /// Hardened runtime is also required. Repeating this check revalidates the
    /// same process incarnation; neither a pid nor a path is accepted as proof.
    pub fn check_code_requirement(&self, requirement: &str) -> CodeRequirementOutcome {
        #[cfg(target_os = "macos")]
        return macos::check_requirement(self.token, requirement);
        #[cfg(not(target_os = "macos"))]
        {
            let _ = requirement;
            CodeRequirementOutcome::Unverifiable(CodeVerificationError::UnsupportedPlatform)
        }
    }

    /// Proves that the process named by the captured audit token satisfies the
    /// requirement and runtime rules, and that its matching on-disk app bundle
    /// passes strict resource and nested-code validation at the time of check.
    #[cfg(target_os = "macos")]
    pub fn check_sealed_app(&self, requirement: &str) -> Result<SignedAppBundle, AppBundleError> {
        macos::check_sealed_app(self.token, requirement)
    }

    /// Checks the running process named by the captured audit token, not the
    /// current occupant of a PID. A successful result pins its running slice
    /// and verifies the runtime rules and matching on-disk bundle seal.
    /// `None` means the verifier did not identify the process as this dev app.
    #[cfg(target_os = "macos")]
    pub fn check_dev_app(
        &self,
        identifier: &str,
    ) -> Option<Result<SignedAppBundle, AppBundleError>> {
        macos::check_dev_app(self.token, identifier)
    }

    /// Resolve the executable of the process named by the captured audit
    /// token. This is descriptive prompt text, not an authorization decision.
    #[cfg(target_os = "macos")]
    pub fn running_executable(&self) -> Option<std::path::PathBuf> {
        macos::running_executable(self.token?)
    }
}

/// Signing metadata copied from the verified app, not from a separately
/// opened Info.plist. A cdhash identifies one architecture's CodeDirectory.
#[cfg(target_os = "macos")]
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct SignedAppBundle {
    pub cdhash: [u8; 20],
    pub short_version: Option<String>,
    pub build_time: Option<String>,
}

#[cfg(target_os = "macos")]
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum AppBundleError {
    VerifierUnavailable,
    NotAppBundle,
    WrongIdentifier,
    InvalidSignature,
    HardenedRuntimeRequired,
    ForbiddenEntitlement(&'static str),
    InvalidBundleSeal,
    InvalidNestedSeal,
    UnpinnedNestedLayout {
        item: String,
        count: usize,
        kind: &'static str,
    },
}

#[cfg(target_os = "macos")]
impl AppBundleError {
    pub fn message(self) -> String {
        match self {
            Self::VerifierUnavailable => "macOS could not verify the code signature.".into(),
            Self::NotAppBundle => "Select a macOS .app bundle.".into(),
            Self::WrongIdentifier => "The code signature has the wrong signing identifier.".into(),
            Self::InvalidSignature => "The app does not have a valid code signature.".into(),
            Self::HardenedRuntimeRequired => "The app must be signed with hardened runtime.".into(),
            Self::ForbiddenEntitlement(name) => {
                format!("The app's signature must not include {name}.")
            }
            Self::InvalidBundleSeal => {
                "The app's signed bundle seal is invalid; check its resources and nested code."
                    .into()
            }
            Self::InvalidNestedSeal => {
                "Nested code does not match the exact hash recorded in the signed bundle seal."
                    .into()
            }
            Self::UnpinnedNestedLayout { item, count, kind } => {
                format!("Nested code {item} has {count} {kind}; the seal pins only one.")
            }
        }
    }
}

/// Proves the current on-disk .app has a valid signature for `identifier`,
/// meets the runtime rules, and matches its resource and nested-code seal.
/// This checks no running process; callers must pin the returned hash, not
/// authorize whatever happens to occupy the path later.
#[cfg(target_os = "macos")]
pub fn check_dev_app_bundle(
    path: &std::path::Path,
    identifier: &str,
) -> Result<SignedAppBundle, AppBundleError> {
    macos::check_dev_app_bundle(path, identifier)
}

/// Capture peer facts at accept and, on macOS, retain the private audit token
/// for later code verification.
#[cfg(unix)]
pub fn capture_unix_peer(socket: &impl std::os::fd::AsFd) -> CapturedPeer {
    #[cfg(target_os = "macos")]
    return macos::capture(socket.as_fd(), ForcedFailures::default());
    #[cfg(not(target_os = "macos"))]
    observe_unix_peer(socket).into()
}

/// Capture kernel peer facts without consulting macOS Security.framework.
/// On macOS only the audit-token uid and pid are observed at this point.
#[cfg(unix)]
pub fn capture_unix_peer_credentials(socket: &impl std::os::fd::AsFd) -> CapturedPeer {
    #[cfg(target_os = "macos")]
    return macos::capture_credentials(socket.as_fd(), ForcedFailures::default());
    #[cfg(not(target_os = "macos"))]
    capture_unix_peer(socket)
}

/// Capture the authorization peer and, separately, the kernel PID for route
/// diagnostics. The diagnostic PID alone must not be used to recognize an
/// operator app or make any trust decision.
#[cfg(unix)]
pub fn capture_unix_peer_with_diagnostic_pid(
    socket: &impl std::os::fd::AsFd,
) -> (CapturedPeer, Option<u32>) {
    #[cfg(target_os = "linux")]
    {
        let (peer, diagnostic_pid) = linux::observe_with_pid(
            socket.as_fd(),
            ForcedFailures::default(),
            linux::pidfd_alive,
        );
        (peer.into(), diagnostic_pid)
    }
    #[cfg(not(target_os = "linux"))]
    {
        use std::os::fd::AsRawFd;
        (
            capture_unix_peer_credentials(socket),
            unix_peer_pid(socket.as_fd().as_raw_fd()),
        )
    }
}

#[cfg(unix)]
pub(crate) fn unix_peer_pid(socket: std::os::fd::RawFd) -> Option<u32> {
    #[cfg(target_os = "linux")]
    return linux::peer_pid(socket);
    #[cfg(target_os = "macos")]
    return macos::peer_pid(socket);
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        let _ = socket;
        None
    }
}

/// Diagnostic identity for the process that opened a local endpoint. The
/// PID and name are advisory and must never be used for authorization.
#[derive(Debug, Clone)]
pub struct DiagnosticProcess {
    pid: u32,
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    start: Option<u64>,
    #[cfg(windows)]
    process: Option<std::sync::Arc<std::os::windows::io::OwnedHandle>>,
}

impl DiagnosticProcess {
    /// Capture process identity at accept so a later name lookup can reject
    /// a process that reused the opener's PID.
    pub fn capture(pid: u32) -> Self {
        Self {
            pid,
            #[cfg(any(target_os = "linux", target_os = "macos"))]
            start: crate::start_time(pid),
            #[cfg(windows)]
            process: windows::open_diagnostic_process(pid).map(std::sync::Arc::new),
        }
    }

    pub fn pid(&self) -> u32 {
        self.pid
    }

    /// Read the current short name, if the opener is still alive and readable.
    pub fn short_name(&self) -> Option<String> {
        #[cfg(target_os = "linux")]
        let name = {
            let bytes = std::fs::read(format!("/proc/{}/comm", self.pid)).ok()?;
            String::from_utf8_lossy(bytes.strip_suffix(b"\n").unwrap_or(&bytes)).into_owned()
        };
        #[cfg(target_os = "macos")]
        let name = crate::process_tree::program_name(self.pid);

        #[cfg(any(target_os = "linux", target_os = "macos"))]
        return (!name.is_empty() && self.start? == crate::start_time(self.pid)?).then_some(name);
        #[cfg(windows)]
        return windows::process_name(self.process.as_deref()?);
        #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
        None
    }
}

/// Read failures a test can force, to show how each one shapes the result
/// without needing a platform that actually fails that read.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ForcedFailures {
    /// The uid or SID read fails: the peer is unobserved.
    pub user: bool,
    /// The executable read fails: only `exe` is absent.
    pub exe: bool,
    /// macOS: `SecCodeCheckValidity` fails, as for a broken signature: only
    /// `signing_id` is absent.
    pub signing_id: bool,
    /// Linux: the kernel does not support `SO_PEERPIDFD`: the peer is
    /// unobserved.
    pub peer_pidfd: bool,
}

/// Observe the peer of an accepted Unix-domain stream socket. Call it when the
/// connection is accepted. On a Unix other than macOS and Linux the peer is
/// unobserved.
#[cfg(unix)]
pub fn observe_unix_peer(socket: &impl std::os::fd::AsFd) -> ObservedPeer {
    unix_peer(socket.as_fd(), ForcedFailures::default())
}

/// [`observe_unix_peer`] with read failures forced, for tests.
#[cfg(all(unix, feature = "test-support"))]
pub fn observe_unix_peer_forcing(
    socket: &impl std::os::fd::AsFd,
    forced: ForcedFailures,
) -> ObservedPeer {
    unix_peer(socket.as_fd(), forced)
}

#[cfg(unix)]
fn unix_peer(socket: std::os::fd::BorrowedFd<'_>, forced: ForcedFailures) -> ObservedPeer {
    #[cfg(target_os = "macos")]
    return macos::observe(socket, forced);
    #[cfg(target_os = "linux")]
    return linux::observe(socket, forced);
    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    {
        let _ = (socket, forced);
        ObservedPeer::Unobserved
    }
}

/// Observe the client of a connected named-pipe server instance. Call it when
/// the client has connected. A client on another machine is unobserved.
#[cfg(windows)]
pub fn observe_pipe_client(pipe: &impl std::os::windows::io::AsHandle) -> ObservedPeer {
    windows::observe(pipe.as_handle(), ForcedFailures::default())
}

/// Refuse non-local clients before observing the peer of a connected pipe.
/// The returned diagnostic PID must not be used to recognize an operator app
/// or make any trust decision.
#[cfg(windows)]
pub fn capture_pipe_client_with_diagnostic_pid(
    pipe: &impl std::os::windows::io::AsRawHandle,
) -> std::io::Result<(CapturedPeer, u32)> {
    let pid = crate::named_pipe::local_client_pid(pipe.as_raw_handle())?;
    Ok((
        windows::observe_local_process(pid, ForcedFailures::default()).into(),
        pid,
    ))
}

/// [`observe_pipe_client`] with read failures forced, for tests.
#[cfg(all(windows, feature = "test-support"))]
pub fn observe_pipe_client_forcing(
    pipe: &impl std::os::windows::io::AsHandle,
    forced: ForcedFailures,
) -> ObservedPeer {
    windows::observe(pipe.as_handle(), forced)
}