Skip to main content

subc_daemon/supervise/
privacy_exec.rs

1use super::*;
2
3#[cfg(target_os = "macos")]
4pub(super) struct PrivacyExec {
5    pub(super) content_check:
6        Option<tokio::task::JoinHandle<Result<(), crate::config_gate::GateError>>>,
7    gated: bool,
8    pub(super) admission_binding: Option<ProgramBindingPublication>,
9    pub(super) reader: tokio::io::unix::AsyncFd<std::io::PipeReader>,
10    pub(super) deadline: tokio::time::Instant,
11    pub(super) expected: Option<subc_os::FileIdentity>,
12    trampoline: Option<subc_os::FileIdentity>,
13    pub(super) signature: Option<Arc<subc_os::privacy_identity::SuspendedSignature>>,
14    module_id: String,
15    #[cfg(test)]
16    confirmation_pause: Option<(String, Option<tokio::net::TcpStream>)>,
17    #[cfg(test)]
18    pub(super) image_probe: Option<fn(u32) -> Option<subc_os::Observation>>,
19    #[cfg(test)]
20    image_read_delay: Option<Duration>,
21}
22
23#[cfg(all(test, target_os = "macos"))]
24pub(crate) fn test_privacy_trampoline() -> PathBuf {
25    // The fixture bin lives in the profile folder the unit-test executable was
26    // built into. This honors custom CARGO_TARGET_DIR too.
27    let path = cortexkit_test_support::cargo_profile_bin("privacy-trampoline-fixture");
28    // Without the fixture every macOS spawn is refused, and the tests that
29    // spawn fail later as a module in state Failed, which names the wrong
30    // cause. `cargo test -p subc-daemon --lib` alone does not build it.
31    assert!(
32        path.exists(),
33        "privacy-trampoline-fixture not built at {}: run `cargo build -p subc-daemon \
34         --bins --features test-support` or `cargo test -p subc-daemon` first",
35        path.display()
36    );
37    path
38}
39
40#[cfg(target_os = "macos")]
41pub(super) fn probe_privacy_trampoline(path: &std::path::Path) -> Result<(), String> {
42    use std::io::Read;
43    let mut probe = subc_os::child_spawn::spawn(
44        std::process::Command::new(path)
45            .args(["__disclaim-exec", "--probe-suspended"])
46            .stdin(Stdio::null())
47            .stdout(Stdio::piped())
48            .stderr(Stdio::piped()),
49    )
50    .map_err(|error| {
51        format!(
52            "privacy trampoline probe failed for {}: {error}",
53            path.display()
54        )
55    })?;
56    let deadline = std::time::Instant::now() + Duration::from_secs(5);
57    let status = loop {
58        match probe.try_wait() {
59            Ok(Some(status)) => break status,
60            Ok(None) if std::time::Instant::now() < deadline => {
61                std::thread::sleep(Duration::from_millis(5))
62            }
63            result => {
64                let _ = probe.kill();
65                let _ = probe.wait();
66                return Err(format!(
67                    "privacy trampoline probe failed or timed out for {}: {result:?}",
68                    path.display()
69                ));
70            }
71        }
72    };
73    let mut answer = String::new();
74    if let Some(stdout) = probe.stdout.take() {
75        let _ = stdout.take(256).read_to_string(&mut answer);
76    }
77    if status.success() && answer.trim() == subc_os::privacy_identity::SUSPENDED_TRAMPOLINE_PROBE {
78        return Ok(());
79    }
80    let mut diagnostic = String::new();
81    if let Some(stderr) = probe.stderr.take() {
82        let _ = stderr.take(1024).read_to_string(&mut diagnostic);
83    }
84    let cause = diagnostic
85        .trim()
86        .strip_prefix("ck-subc: own privacy identity refused: ")
87        .unwrap_or("binary does not implement the privacy trampoline protocol");
88    Err(format!(
89        "{cause}: probe of {} exited {status}",
90        path.display()
91    ))
92}
93
94#[cfg(target_os = "macos")]
95pub(super) fn privacy_command(
96    spec: &ModuleSpec,
97    binding: &SpawnProgramBinding,
98    roster: &ChildRoster,
99    gated: bool,
100) -> Result<
101    (
102        Command,
103        Option<PrivacyExec>,
104        subc_os::privacy_identity::ExecAcknowledgement,
105    ),
106    SuperviseError,
107> {
108    let failure = |cause: String| {
109        warn!(module_id = %spec.module_id, %cause, "privacy identity trampoline refused module spawn");
110        SuperviseError::Spawn {
111            program: spec.program.clone(),
112            source: io::Error::other(cause),
113            cgroup_path: None,
114        }
115    };
116    let trampoline = roster.privacy_trampoline().map_err(failure)?;
117    let expected = Some(binding.identity);
118    let trampoline_image = subc_os::file_identity(&trampoline);
119    let signature = gated
120        .then(|| {
121            subc_os::privacy_identity::SuspendedSignature::capture(&binding._file, &binding.path)
122                .map(Arc::new)
123        })
124        .transpose()
125        .map_err(|error| failure(error.to_string()))?;
126    if expected == trampoline_image {
127        return Err(failure(
128            "privacy identity module executable is missing or is the trampoline itself".to_string(),
129        ));
130    }
131    let (reader, ack) = subc_os::privacy_identity::ExecAcknowledgement::pipe()
132        .map_err(|error| failure(error.to_string()))?;
133    let reader =
134        tokio::io::unix::AsyncFd::new(reader).map_err(|error| failure(error.to_string()))?;
135    let mut command = Command::new(&trampoline);
136    command
137        .arg(if gated {
138            "__disclaim-exec-suspended"
139        } else {
140            "__disclaim-exec"
141        })
142        .arg(ack.fd().to_string())
143        .arg(&binding.path);
144    Ok((
145        command,
146        Some(PrivacyExec {
147            gated,
148            admission_binding: None,
149            content_check: None,
150            reader,
151            deadline: tokio::time::Instant::now() + Duration::from_secs(5),
152            expected,
153            trampoline: trampoline_image,
154            signature,
155            module_id: spec.module_id.clone(),
156            #[cfg(test)]
157            image_probe: None,
158            #[cfg(test)]
159            image_read_delay: spec
160                .env
161                .iter()
162                .find(|(key, _)| key == "SUBC_TEST_PRIVACY_IMAGE_DELAY_MS")
163                .map(|(_, millis)| Duration::from_millis(millis.parse().unwrap())),
164            #[cfg(test)]
165            confirmation_pause: spec
166                .env
167                .iter()
168                .find(|(key, _)| key == "SUBC_TEST_BEFORE_EXEC_CONFIRM")
169                .map(|(_, address)| (address.clone(), None)),
170        }),
171        ack,
172    ))
173}
174
175impl SupervisedChild {
176    #[cfg(target_os = "macos")]
177    pub(super) async fn confirm_privacy_exec(&mut self) {
178        if self
179            .privacy_exec
180            .as_ref()
181            .is_some_and(|pending| pending.content_check.is_some())
182        {
183            self.finish_privacy_content_check().await;
184            return;
185        }
186        let Some(pending) = &mut self.privacy_exec else {
187            return;
188        };
189        let result = tokio::time::timeout_at(pending.deadline, async {
190            let mut record = Vec::new();
191            loop {
192                let mut ready = pending.reader.readable().await?;
193                let read = ready.try_io(|reader| {
194                    use std::io::Read;
195                    let mut reader = reader.get_ref();
196                    let mut buffer = [0u8; 256];
197                    reader.read(&mut buffer).map(|count| (count, buffer))
198                });
199                match read {
200                    Ok(Ok((0, _))) => return Ok::<_, io::Error>(record),
201                    Ok(Ok((count, buffer))) => {
202                        if record.len() + count > 1024 {
203                            return Err(io::Error::other(
204                                "privacy exec refusal record is too long",
205                            ));
206                        }
207                        record.extend_from_slice(&buffer[..count]);
208                    }
209                    Ok(Err(error)) => return Err(error),
210                    Err(_) => continue,
211                }
212            }
213        })
214        .await;
215        #[cfg(test)]
216        let result = if let Some((address, stream)) = &mut pending.confirmation_pause {
217            use tokio::io::{AsyncReadExt, AsyncWriteExt};
218            if stream.is_none() {
219                *stream = Some(
220                    tokio::net::TcpStream::connect(address.as_str())
221                        .await
222                        .unwrap(),
223                );
224                stream.as_mut().unwrap().write_all(b"R").await.unwrap();
225                stream
226                    .as_mut()
227                    .unwrap()
228                    .write_all(&self.pid.to_ne_bytes())
229                    .await
230                    .unwrap();
231            }
232            let mut reply = [0];
233            stream
234                .as_mut()
235                .unwrap()
236                .read_exact(&mut reply)
237                .await
238                .unwrap();
239            pending.confirmation_pause = None;
240            if &reply == b"F" {
241                Ok(Err(io::Error::other("injected late exec refusal")))
242            } else {
243                assert_eq!(&reply, b"X");
244                result
245            }
246        } else {
247            result
248        };
249        // Keep the reader in self across await: select cancellation must not
250        // discard the handshake or reset its original five-second deadline.
251        // Use try_wait so a child reaped during confirmation has its program
252        // binding retired before another command can use its nonce.
253        let waited = if matches!(&result, Ok(Ok(record)) if record.is_empty()) {
254            Some(self.try_wait())
255        } else {
256            None
257        };
258        let pending = self.privacy_exec.as_ref().expect("pending exec");
259        let cause = match result {
260            Err(_) => Some("privacy identity trampoline did not exec within 5s".to_string()),
261            Ok(Err(error)) => Some(format!(
262                "privacy identity exec acknowledgement failed: {error}"
263            )),
264            Ok(Ok(record)) if !record.is_empty() => Some(
265                std::str::from_utf8(&record)
266                    .ok()
267                    .and_then(|record| {
268                        record
269                            .trim()
270                            .strip_prefix(subc_os::privacy_identity::EXEC_REFUSAL_TAG)
271                    })
272                    .filter(|cause| !cause.is_empty())
273                    .unwrap_or("invalid privacy exec refusal record")
274                    .to_string(),
275            ),
276            Ok(Ok(_)) if !pending.gated => match waited.expect("exec EOF checked child") {
277                Ok(Some(_)) => None,
278                Err(error) => Some(format!("privacy identity trampoline wait failed: {error}")),
279                Ok(None) => {
280                    #[cfg(test)]
281                    if let Some(delay) = pending.image_read_delay {
282                        tokio::time::sleep(delay).await;
283                    }
284                    let image = observe_spawned_image(self.pid);
285                    #[cfg(test)]
286                    let image = pending.image_probe.map_or(image, |probe| probe(self.pid));
287                    // An unstamped module can re-exec before we wake to read its
288                    // image. Only the trampoline image proves exec never happened;
289                    // retain the observed image for later orphan identification.
290                    if let Some(image) = image.filter(|image| {
291                        image.executable.is_some() && image.executable != pending.trampoline
292                    }) {
293                        match self
294                            .roster_guard
295                            .as_ref()
296                            .map(|guard| guard.confirm_executable(image))
297                            .transpose()
298                        {
299                            Err(error) => Some(format!(
300                                "could not durably record confirmed module image: {error}"
301                            )),
302                            Ok(_) => {
303                                let _ = self.report_ready.set(());
304                                None
305                            }
306                        }
307                    } else if image.is_none()
308                        || image.is_some_and(|image| image.executable.is_none())
309                    {
310                        // Empty EOF acknowledged exec. An image disappearing
311                        // during observation is an ordinary module exit.
312                        match tokio::time::timeout_at(pending.deadline, self.child.wait()).await {
313                            Ok(result) => {
314                                self.retire_registration();
315                                self.registration_channel.take();
316                                if let Some(binding) = &self._program_binding {
317                                    binding.retire();
318                                }
319                                result.err().map(|error| format!("privacy identity trampoline wait failed: {error}"))
320                            }
321                            Err(_) => Some("privacy identity module executable remained unreadable until the 5s exec deadline".to_string()),
322                        }
323                    } else {
324                        Some("privacy identity trampoline did not exec the module".to_string())
325                    }
326                }
327            },
328            Ok(Ok(_)) => match waited.expect("exec EOF checked child") {
329                Ok(Some(_)) => {
330                    Some("privacy identity target exited before suspended admission".to_string())
331                }
332                Err(error) => Some(format!("privacy identity trampoline wait failed: {error}")),
333                Ok(None) => {
334                    // CLOEXEC closes the ack just before the kernel reports the
335                    // suspended target. EOF alone must never admit a running image.
336                    let stopped = tokio::time::timeout_at(pending.deadline, async {
337                        loop {
338                            if subc_os::privacy_identity::SuspendedSignature::is_suspended(
339                                self.pid,
340                            )? {
341                                return Ok::<_, io::Error>(());
342                            }
343                            tokio::time::sleep(Duration::from_millis(1)).await;
344                        }
345                    })
346                    .await;
347                    match stopped {
348                        Err(_) => {
349                            Some("privacy identity target was not suspended within 5s".to_string())
350                        }
351                        Ok(Err(error)) => Some(format!(
352                            "privacy identity suspended target unavailable: {error}"
353                        )),
354                        Ok(Ok(())) => {
355                            let image = observe_spawned_image(self.pid);
356                            if image.is_some_and(|image| {
357                                image.executable.is_some()
358                                    && image.executable != pending.trampoline
359                                    && image.executable == pending.expected
360                            }) {
361                                None
362                            } else {
363                                Some("privacy identity trampoline executable mismatch: expected the suspended module program".to_string())
364                            }
365                        }
366                    }
367                }
368            },
369        };
370        #[cfg(test)]
371        if let Some(binding) = &self._program_binding {
372            binding.pause_after_wait_for_test().await;
373        }
374        if cause.is_none() && pending.gated {
375            let publication = pending.admission_binding.clone();
376            let live = self.live_program_binding.clone();
377            let signature = Arc::clone(pending.signature.as_ref().expect("gated signature"));
378            let pid = self.pid;
379            let gated = pending.gated;
380            self.privacy_exec
381                .as_mut()
382                .expect("pending exec")
383                .content_check = Some(tokio::task::spawn_blocking(move || {
384                signature.verify(pid).map_err(|error| {
385                    crate::config_gate::GateError::new("program_refused", error)
386                })?;
387                if !gated {
388                    return Ok(());
389                }
390                match (publication, live) {
391                    (Some(publication), _) => publication.verify(),
392                    (None, Some(live)) => live.check(),
393                    _ => Err(crate::config_gate::GateError::new(
394                        "config_delivery_deferred",
395                        "live program witness is unavailable",
396                    )),
397                }
398            }));
399            self.finish_privacy_content_check().await;
400        } else {
401            self.finish_privacy_exec(cause);
402        }
403    }
404
405    #[cfg(target_os = "macos")]
406    async fn finish_privacy_content_check(&mut self) {
407        let result = self
408            .privacy_exec
409            .as_mut()
410            .expect("pending exec")
411            .content_check
412            .as_mut()
413            .expect("pending content check")
414            .await;
415        let cause = match result {
416            Ok(Ok(())) => None,
417            Ok(Err(error)) => Some(format!("{}: {}", error.code, error.detail)),
418            Err(error) => Some(format!(
419                "config_delivery_deferred: content check stopped: {error}"
420            )),
421        };
422        self.finish_privacy_exec(cause);
423    }
424
425    #[cfg(target_os = "macos")]
426    fn finish_privacy_exec(&mut self, mut cause: Option<String>) {
427        let mut pending = self.privacy_exec.take().expect("pending exec");
428        if cause.is_none() && pending.gated {
429            let admission = (|| -> io::Result<()> {
430                let image = observe_spawned_image(self.pid)
431                    .filter(|image| image.executable == pending.expected)
432                    .ok_or_else(|| io::Error::other("suspended executable mismatch"))?;
433                if let Some(guard) = &self.roster_guard {
434                    guard.confirm_executable(image)?;
435                }
436                pending
437                    .signature
438                    .as_ref()
439                    .expect("gated signature")
440                    .resume(self.pid)?;
441                let _ = self.report_ready.set(());
442                info!(module_id = %pending.module_id, pid = self.pid,
443                    "verified suspended module resumed with own privacy identity");
444                Ok(())
445            })();
446            if let Err(error) = admission {
447                cause = Some(format!("program_refused: {error}"));
448            }
449        }
450        if cause.is_some() {
451            if let Some(spawn) = &self.registration_spawn {
452                spawn.refuse();
453            }
454            if let Some(binding) = &mut pending.admission_binding {
455                binding.reject();
456            }
457        } else if let Some(spawn) = &self.registration_spawn {
458            spawn.ready();
459        }
460        // Exec confirmation describes launch success, not roster retirement.
461        // Keep even a reaped child recorded until its terminal history exists.
462        self.exec.0.finish(if cause.is_some() {
463            crate::activity::ExecState::Refused
464        } else {
465            crate::activity::ExecState::CommittedExec
466        });
467        if let Some(cause) = cause {
468            warn!(module_id = %pending.module_id, pid = self.pid, %cause, "privacy identity trampoline refused module spawn");
469            self.spawn_failure = Some(
470                if pending.gated
471                    && (cause.contains("executable mismatch")
472                        || cause.starts_with("program_refused:"))
473                {
474                    format!("program_refused: {cause}")
475                } else if pending.gated {
476                    format!("config_delivery_deferred: {cause}")
477                } else {
478                    cause
479                },
480            );
481            // No resume signal is sent on failure; kill the entire fresh group
482            // even if a faulty trampoline did not honor the suspended protocol.
483            let _ = self.start_admission_kill();
484        }
485    }
486}
487
488impl Supervisor {
489    /// Verify the trampoline once when configured. Missing private OS support
490    /// refuses every macOS launch by name but does not stop the daemon's control
491    /// server. Embedders must explicitly provide a binary with the subc-os hidden
492    /// entry point; the library must not exec an arbitrary hosting program.
493    pub fn with_privacy_trampoline(self, path: impl Into<PathBuf>) -> Self {
494        let path = path.into();
495        #[cfg(target_os = "macos")]
496        {
497            let result = probe_privacy_trampoline(&path).map(|()| path);
498            if let Err(cause) = &result {
499                error!(%cause, "macOS privacy identity unavailable; supervised launches will refuse");
500            }
501            self.child_roster.set_privacy_trampoline(result);
502        }
503        #[cfg(not(target_os = "macos"))]
504        let _ = path;
505        self
506    }
507}