subc-os 0.1.51

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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! Each case observes a separate child process (this test binary re-run as a
//! fixture) so that an implementation describing the observing process
//! itself, rather than the peer, fails.

use super::*;
use std::{
    path::Path,
    process::{Child, Command, Stdio},
    time::{Duration, Instant},
};

#[test]
fn code_requirement_without_a_captured_token_is_unverifiable() {
    let peer: CapturedPeer = ObservedPeer::Unobserved.into();
    let result = peer.check_code_requirement("always");
    #[cfg(target_os = "macos")]
    assert_eq!(
        result,
        CodeRequirementOutcome::Unverifiable(CodeVerificationError::MissingAuditToken)
    );
    #[cfg(not(target_os = "macos"))]
    assert_eq!(
        result,
        CodeRequirementOutcome::Unverifiable(CodeVerificationError::UnsupportedPlatform)
    );
}

#[cfg(target_os = "macos")]
#[test]
fn code_requirement_uses_the_captured_peer_and_signed_metadata() {
    let root = cortexkit_test_support::ScratchDir::new("code-requirement");
    let mut fixture = fixture::SignedPeerFixture::new(
        &root,
        "subc.requirement.fixture",
        Some("1.2.10"),
        true,
        None,
    );
    let (_stream, peer) = fixture.connect();
    assert_eq!(
        peer.check_code_requirement("identifier \"subc.requirement.fixture\""),
        CodeRequirementOutcome::Satisfied(VerifiedCode {
            short_version: Some("1.2.10".into())
        })
    );
    assert_eq!(
        peer.check_code_requirement("identifier \"other\""),
        CodeRequirementOutcome::NotSatisfied
    );
    assert_eq!(
        peer.check_code_requirement("this is not a requirement"),
        CodeRequirementOutcome::Unverifiable(CodeVerificationError::InvalidRequirement)
    );
    drop(fixture);
    assert!(matches!(
        peer.check_code_requirement("always"),
        CodeRequirementOutcome::Unverifiable(CodeVerificationError::GuestUnavailable)
    ));
}

/// Kills and reaps a fixture child however its test ends.
struct ChildGuard(Child);

impl Drop for ChildGuard {
    fn drop(&mut self) {
        let _ = self.0.kill();
        let _ = self.0.wait();
    }
}

fn spawn_fixture(test: &str, env: &str, value: &std::ffi::OsStr) -> ChildGuard {
    ChildGuard(
        Command::new(std::env::current_exe().unwrap())
            .args([
                test,
                "--exact",
                "--ignored",
                "--nocapture",
                "--test-threads=1",
            ])
            .env(env, value)
            .stdin(Stdio::piped())
            .stdout(Stdio::null())
            .spawn()
            .unwrap(),
    )
}

fn same_file(left: &Path, right: &Path) -> bool {
    left.canonicalize().unwrap() == right.canonicalize().unwrap()
}

fn observation(peer: ObservedPeer) -> PeerObservation {
    match peer {
        ObservedPeer::Observed(observation) => observation,
        ObservedPeer::Unobserved => panic!("expected an observed peer"),
    }
}

#[cfg(unix)]
mod unix {
    use super::*;
    use cortexkit_test_support::ScratchDir;
    #[cfg(target_os = "linux")]
    use std::os::fd::AsFd;
    use std::{
        io::Read,
        os::unix::net::{UnixListener, UnixStream},
        path::PathBuf,
    };

    const CONNECT_ENV: &str = "SUBC_OS_LOCAL_PEER_CONNECT";
    /// A socket path short enough for `sockaddr_un` (104 bytes on macOS).
    /// The per-process scratch directory can be longer than that on macOS, so
    /// fall back to a uniquely named file in the system temp directory.
    struct SocketPath {
        path: PathBuf,
        _scratch: ScratchDir,
    }

    impl SocketPath {
        fn new() -> Self {
            let scratch = ScratchDir::new("subc-lp");
            let mut path = scratch.join("s");
            if path.as_os_str().len() >= 100 {
                use std::sync::atomic::{AtomicU32, Ordering};
                static NEXT: AtomicU32 = AtomicU32::new(0);
                path = std::env::temp_dir().join(format!(
                    "subc-lp-{}-{}",
                    std::process::id(),
                    NEXT.fetch_add(1, Ordering::Relaxed)
                ));
                let _ = std::fs::remove_file(&path);
            }
            Self {
                path,
                _scratch: scratch,
            }
        }
    }

    impl Drop for SocketPath {
        fn drop(&mut self) {
            let _ = std::fs::remove_file(&self.path);
        }
    }

    struct Connection {
        stream: UnixStream,
        child: ChildGuard,
        _path: SocketPath,
    }

    /// Accept one connection from `child`, giving up if it exits or takes
    /// longer than ten seconds.
    fn accept_from(path: SocketPath, listener: UnixListener, mut child: ChildGuard) -> Connection {
        listener.set_nonblocking(true).unwrap();
        let deadline = Instant::now() + Duration::from_secs(10);
        loop {
            match listener.accept() {
                Ok((stream, _)) => {
                    stream.set_nonblocking(false).unwrap();
                    return Connection {
                        stream,
                        child,
                        _path: path,
                    };
                }
                Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {}
                Err(error) => panic!("accept: {error}"),
            }
            assert!(
                child.0.try_wait().unwrap().is_none(),
                "fixture exited without connecting"
            );
            assert!(Instant::now() < deadline, "fixture never connected");
            std::thread::sleep(Duration::from_millis(5));
        }
    }

    fn connect_fixture() -> Connection {
        let path = SocketPath::new();
        let listener = UnixListener::bind(&path.path).unwrap();
        let child = spawn_fixture(
            "local_peer::tests::unix::connecting_child",
            CONNECT_ENV,
            path.path.as_os_str(),
        );
        accept_from(path, listener, child)
    }

    #[test]
    #[ignore = "re-exec fixture that connects and holds the socket until its parent closes stdin"]
    fn connecting_child() {
        let path = std::env::var_os(CONNECT_ENV).unwrap();
        let stream = UnixStream::connect(path).unwrap();
        let _ = std::io::stdin().read(&mut [0]);
        drop(stream);
    }

    #[cfg(target_os = "linux")]
    fn kernel_has_peer_pidfd() -> bool {
        let release = std::fs::read_to_string("/proc/sys/kernel/osrelease").unwrap();
        let mut parts = release
            .trim()
            .split(|c: char| !c.is_ascii_digit())
            .map(|part| part.parse::<u32>().unwrap_or(0));
        let version = (parts.next().unwrap_or(0), parts.next().unwrap_or(0));
        version >= (6, 5)
    }

    /// `codesign` reports the identifier sealed into a file's signature and
    /// whether the signature verifies, independently of the code under test.
    #[cfg(target_os = "macos")]
    fn codesign_identifier(exe: &Path) -> Option<String> {
        let verified = Command::new("/usr/bin/codesign")
            .arg("--verify")
            .arg(exe)
            .stderr(Stdio::null())
            .status()
            .unwrap()
            .success();
        if !verified {
            return None;
        }
        let output = Command::new("/usr/bin/codesign")
            .args(["-d", "-v"])
            .arg(exe)
            .output()
            .unwrap();
        String::from_utf8_lossy(&output.stderr)
            .lines()
            .find_map(|line| line.strip_prefix("Identifier=").map(str::to_owned))
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn unix_peer_is_the_connecting_process() {
        let connection = connect_fixture();
        let observed = observe_unix_peer(&connection.stream);
        #[cfg(target_os = "linux")]
        if !kernel_has_peer_pidfd() {
            assert_eq!(observed, ObservedPeer::Unobserved);
            eprintln!("kernel lacks SO_PEERPIDFD; checked the unobserved fallback only");
            return;
        }
        let observed = observation(observed);
        assert_eq!(observed.pid, connection.child.0.id());
        assert_ne!(observed.pid, std::process::id());
        assert_eq!(observed.user, PeerUser::Uid(effective_uid()));
        let exe = observed.exe.as_deref().expect("peer executable");
        assert!(same_file(exe, &std::env::current_exe().unwrap()), "{exe:?}");
        #[cfg(target_os = "macos")]
        assert_eq!(observed.signing_id, codesign_identifier(exe));
        #[cfg(not(target_os = "macos"))]
        assert_eq!(observed.signing_id, None);
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[allow(unsafe_code)]
    fn effective_uid() -> u32 {
        // SAFETY: geteuid has no preconditions and cannot fail.
        unsafe { libc::geteuid() }
    }

    /// A system binary signed by Apple, found by its audit token: the guest
    /// code and signing identifier belong to `nc`, not to this test binary.
    #[cfg(target_os = "macos")]
    #[test]
    fn macos_peer_signing_id_comes_from_the_peer_code() {
        let nc = Path::new("/usr/bin/nc");
        let path = SocketPath::new();
        let listener = UnixListener::bind(&path.path).unwrap();
        let child = ChildGuard(
            Command::new(nc)
                .arg("-U")
                .arg(&path.path)
                .stdin(Stdio::piped())
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .spawn()
                .unwrap(),
        );
        let connection = accept_from(path, listener, child);
        let capture = super::super::capture_unix_peer_credentials(&connection.stream);
        assert!(capture.has_audit_token());
        let credentials = observation(capture.observation().clone());
        assert_eq!(credentials.pid, connection.child.0.id());
        assert_eq!(credentials.user, PeerUser::Uid(effective_uid()));
        assert_eq!((credentials.exe, credentials.signing_id), (None, None));
        let observed = observation(capture.observe_code());
        assert_eq!(observed.pid, connection.child.0.id());
        let exe = observed.exe.as_deref().expect("peer executable");
        assert!(same_file(exe, nc), "{exe:?}");
        let expected = codesign_identifier(nc);
        assert!(expected.is_some(), "system nc verifies");
        assert_eq!(observed.signing_id, expected);
    }

    #[test]
    fn forced_user_failure_is_unobserved() {
        let connection = connect_fixture();
        let forced = ForcedFailures {
            user: true,
            ..ForcedFailures::default()
        };
        assert_eq!(
            observe_unix_peer_forcing(&connection.stream, forced),
            ObservedPeer::Unobserved
        );
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn forced_exe_failure_omits_only_exe() {
        let connection = connect_fixture();
        let full = observe_unix_peer(&connection.stream);
        #[cfg(target_os = "linux")]
        if !kernel_has_peer_pidfd() {
            return;
        }
        let full = observation(full);
        assert!(full.exe.is_some());
        let forced = ForcedFailures {
            exe: true,
            ..ForcedFailures::default()
        };
        let without_exe = observation(observe_unix_peer_forcing(&connection.stream, forced));
        assert_eq!(
            without_exe,
            PeerObservation {
                exe: None,
                ..full.clone()
            }
        );
    }

    /// Forced, because a live peer with a broken signature could not be
    /// arranged as a fixture on Apple silicon: a process that marks its own
    /// code invalid (`csops`) is killed by the kernel before it can be
    /// observed, and a modified file whose changed page never loads still
    /// passes `SecCodeCheckValidity`, which checks the running code.
    #[cfg(target_os = "macos")]
    #[test]
    fn macos_forced_validity_failure_omits_only_signing_id() {
        let connection = connect_fixture();
        let full = observation(observe_unix_peer(&connection.stream));
        let forced = ForcedFailures {
            signing_id: true,
            ..ForcedFailures::default()
        };
        let invalid = observation(observe_unix_peer_forcing(&connection.stream, forced));
        assert!(invalid.exe.is_some());
        assert_eq!(
            invalid,
            PeerObservation {
                signing_id: None,
                ..full
            }
        );
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn linux_without_peer_pidfd_is_unobserved() {
        let connection = connect_fixture();
        let forced = ForcedFailures {
            peer_pidfd: true,
            ..ForcedFailures::default()
        };
        assert_eq!(
            observe_unix_peer_forcing(&connection.stream, forced),
            ObservedPeer::Unobserved
        );
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn linux_exe_is_dropped_when_the_pidfd_reports_exit_after_the_read() {
        if !kernel_has_peer_pidfd() {
            return;
        }
        let connection = connect_fixture();
        let observed = observation(super::super::linux::observe_checking(
            connection.stream.as_fd(),
            ForcedFailures::default(),
            |_| false,
        ));
        assert_eq!(observed.pid, connection.child.0.id());
        assert_eq!(observed.exe, None);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn linux_pidfd_alive_tracks_process_exit() {
        use rustix::process::{pidfd_open, Pid, PidfdFlags};

        let mut child = ChildGuard(
            Command::new(std::env::current_exe().unwrap())
                .args([
                    "local_peer::tests::unix::connecting_child",
                    "--exact",
                    "--ignored",
                ])
                .env(CONNECT_ENV, "/nonexistent/subc-os-local-peer")
                .stdin(Stdio::piped())
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .spawn()
                .unwrap(),
        );
        // The child fails to connect and exits; until reaped, its pid stays
        // valid for pidfd_open.
        let pid = Pid::from_raw(child.0.id() as i32).unwrap();
        let pidfd = pidfd_open(pid, PidfdFlags::empty()).unwrap();
        child.0.wait().unwrap();
        assert!(!super::super::linux::pidfd_alive(&pidfd));

        let live = connect_fixture();
        let pid = Pid::from_raw(live.child.0.id() as i32).unwrap();
        let pidfd = pidfd_open(pid, PidfdFlags::empty()).unwrap();
        assert!(super::super::linux::pidfd_alive(&pidfd));
    }
}

#[cfg(windows)]
mod windows {
    #![allow(unsafe_code)]

    use super::*;
    use std::{
        io::Read,
        os::windows::{
            ffi::OsStrExt,
            io::{AsRawHandle, FromRawHandle, OwnedHandle},
        },
        sync::mpsc,
    };
    use windows_sys::Win32::{
        Foundation::{ERROR_PIPE_CONNECTED, INVALID_HANDLE_VALUE},
        Storage::FileSystem::PIPE_ACCESS_DUPLEX,
        System::Pipes::{
            ConnectNamedPipe, CreateNamedPipeW, PIPE_REJECT_REMOTE_CLIENTS, PIPE_TYPE_BYTE,
            PIPE_WAIT,
        },
    };

    const PIPE_ENV: &str = "SUBC_OS_LOCAL_PEER_PIPE";

    fn create_server(name: &str) -> OwnedHandle {
        let wide: Vec<u16> = std::ffi::OsStr::new(name)
            .encode_wide()
            .chain(Some(0))
            .collect();
        // SAFETY: wide is NUL-terminated and live for the call; default
        // security is enough for a same-user test client.
        let handle = unsafe {
            CreateNamedPipeW(
                wide.as_ptr(),
                PIPE_ACCESS_DUPLEX,
                PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
                1,
                0,
                0,
                0,
                std::ptr::null(),
            )
        };
        assert!(
            !handle.is_null() && handle != INVALID_HANDLE_VALUE,
            "CreateNamedPipeW: {}",
            std::io::Error::last_os_error()
        );
        // SAFETY: a new server handle owned here alone.
        unsafe { OwnedHandle::from_raw_handle(handle) }
    }

    struct Connection {
        server: OwnedHandle,
        child: ChildGuard,
    }

    fn connect_fixture() -> Connection {
        use std::sync::atomic::{AtomicU32, Ordering};
        static NEXT: AtomicU32 = AtomicU32::new(0);
        let name = format!(
            r"\\.\pipe\subc-os-local-peer-{}-{}",
            std::process::id(),
            NEXT.fetch_add(1, Ordering::Relaxed)
        );
        let server = create_server(&name);
        let mut child = spawn_fixture(
            "local_peer::tests::windows::connecting_child",
            PIPE_ENV,
            std::ffi::OsStr::new(&name),
        );
        let (sender, receiver) = mpsc::channel();
        std::thread::spawn(move || {
            // SAFETY: server is a live, unconnected pipe instance; a null
            // OVERLAPPED makes the call block until a client connects.
            let connected =
                unsafe { ConnectNamedPipe(server.as_raw_handle(), std::ptr::null_mut()) } != 0
                    || std::io::Error::last_os_error().raw_os_error()
                        == Some(ERROR_PIPE_CONNECTED as i32);
            let _ = sender.send(connected.then_some(server));
        });
        let deadline = Instant::now() + Duration::from_secs(10);
        loop {
            match receiver.recv_timeout(Duration::from_millis(50)) {
                Ok(server) => {
                    return Connection {
                        server: server.expect("ConnectNamedPipe"),
                        child,
                    }
                }
                Err(mpsc::RecvTimeoutError::Timeout) => {}
                Err(error) => panic!("{error}"),
            }
            assert!(
                child.0.try_wait().unwrap().is_none(),
                "fixture exited without connecting"
            );
            assert!(Instant::now() < deadline, "fixture never connected");
        }
    }

    #[test]
    #[ignore = "re-exec fixture that opens the pipe and holds it until its parent closes stdin"]
    fn connecting_child() {
        let name = std::env::var_os(PIPE_ENV).unwrap();
        let pipe = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(name)
            .unwrap();
        let _ = std::io::stdin().read(&mut [0]);
        drop(pipe);
    }

    /// The current user's SID as `whoami` prints it, independent of the token
    /// reads under test.
    fn whoami_sid() -> String {
        let output = Command::new("whoami")
            .args(["/user", "/fo", "csv", "/nh"])
            .output()
            .unwrap();
        assert!(output.status.success());
        let text = String::from_utf8_lossy(&output.stdout);
        text.trim()
            .rsplit(',')
            .next()
            .unwrap()
            .trim_matches('"')
            .to_owned()
    }

    #[test]
    fn pipe_client_is_the_connecting_process() {
        let connection = connect_fixture();
        let observed = observation(observe_pipe_client(&connection.server));
        assert_eq!(observed.pid, connection.child.0.id());
        assert_ne!(observed.pid, std::process::id());
        assert_eq!(observed.user, PeerUser::Sid(whoami_sid()));
        let exe = observed.exe.as_deref().expect("client executable");
        assert!(same_file(exe, &std::env::current_exe().unwrap()), "{exe:?}");
        assert_eq!(observed.signing_id, None);
    }

    #[test]
    fn forced_sid_failure_is_unobserved() {
        let connection = connect_fixture();
        let forced = ForcedFailures {
            user: true,
            ..ForcedFailures::default()
        };
        assert_eq!(
            observe_pipe_client_forcing(&connection.server, forced),
            ObservedPeer::Unobserved
        );
    }

    #[test]
    fn forced_exe_failure_omits_only_exe() {
        let connection = connect_fixture();
        let full = observation(observe_pipe_client(&connection.server));
        assert!(full.exe.is_some());
        let forced = ForcedFailures {
            exe: true,
            ..ForcedFailures::default()
        };
        let without_exe = observation(observe_pipe_client_forcing(&connection.server, forced));
        assert_eq!(without_exe, PeerObservation { exe: None, ..full });
    }
}