Repository navigation
Expand file tree
/
Copy pathprocess.rs
More file actions
2104 lines (1943 loc) · 75.3 KB
/
Copy pathprocess.rs
File metadata and controls
2104 lines (1943 loc) · 75.3 KB
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//! Process management and signal handling.
use crate::child_env;
#[cfg(target_os = "linux")]
use crate::managed_children;
use crate::sandbox;
#[cfg(target_os = "linux")]
use miette::WrapErr;
use miette::{IntoDiagnostic, Result};
use nix::sys::signal::{self, Signal};
use nix::unistd::{Pid, User};
use openshell_core::policy::SandboxPolicy;
use std::collections::HashMap;
#[cfg(unix)]
use std::os::fd::AsRawFd;
#[cfg(target_os = "linux")]
use std::path::Path;
use std::path::PathBuf;
use std::process::Stdio;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock};
use tokio::process::{Child, ChildStderr, ChildStdin, ChildStdout, Command};
use tracing::debug;
// `libc::TIOCSCTTY` and the request parameter accepted by `ioctl` vary across
// glibc, musl, and BSD targets. The conversion is a no-op on some targets but
// is required on others.
#[cfg(unix)]
#[allow(unsafe_code, clippy::useless_conversion)]
fn set_controlling_tty(fd: libc::c_int) -> std::io::Result<()> {
// SAFETY: fd is the slave PTY of a pre-exec child that already ran
// setsid; argument zero requests ownership without stealing the
// terminal from another session.
if unsafe { libc::ioctl(fd, libc::TIOCSCTTY.into(), 0) } < 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
}
/// Resolved process workspace and its child-environment semantics.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ResolvedWorkspace {
root: Option<String>,
use_as_home: bool,
}
impl ResolvedWorkspace {
#[must_use]
pub fn new(root: Option<String>, use_as_home: bool) -> Self {
Self { root, use_as_home }
}
#[must_use]
pub fn root(&self) -> Option<&str> {
self.root.as_deref()
}
#[must_use]
pub fn owned_root(&self) -> Option<String> {
self.root.clone()
}
#[must_use]
pub fn home(&self) -> Option<&str> {
self.use_as_home.then(|| self.root()).flatten()
}
}
/// The sandbox launcher as the acting process of the Process Activity events it emits.
pub(crate) fn ocsf_launcher_process() -> openshell_ocsf::Process {
openshell_ocsf::Process::new("openshell-sandbox", i64::from(std::process::id()))
}
#[cfg(target_os = "linux")]
pub(crate) fn prepare_child_sandbox(
policy: &SandboxPolicy,
workdir: Option<&str>,
runtime_read_only: &[PathBuf],
) -> Result<Option<sandbox::linux::PreparedSandbox>> {
let effective_policy = policy_with_runtime_read_only(policy, runtime_read_only);
let prepared = sandbox::linux::prepare_capability_free(&effective_policy, workdir)?;
Ok(Some(prepared))
}
#[cfg(target_os = "linux")]
fn policy_with_runtime_read_only(
policy: &SandboxPolicy,
runtime_read_only: &[PathBuf],
) -> SandboxPolicy {
let mut effective_policy = policy.clone();
for path in runtime_read_only {
if !effective_policy.filesystem.read_only.contains(path) {
effective_policy.filesystem.read_only.push(path.clone());
}
}
effective_policy
}
#[cfg(target_os = "linux")]
pub(crate) fn ca_runtime_read_only_paths(ca_paths: Option<&(PathBuf, PathBuf)>) -> Vec<PathBuf> {
let Some((certificate, bundle)) = ca_paths else {
return Vec::new();
};
let mut paths = Vec::with_capacity(3);
if let Some(directory) = certificate.parent() {
paths.push(directory.to_path_buf());
}
paths.push(certificate.clone());
paths.push(bundle.clone());
paths
}
/// Prefix of environment variable names reserved for `OpenShell`.
pub(crate) const RESERVED_ENV_PREFIX: &str = "OPENSHELL_";
const SUPERVISOR_ONLY_ENV_VARS: &[&str] = &[
openshell_core::sandbox_env::OCI_IMAGE_USER,
openshell_core::sandbox_env::SANDBOX_UID,
openshell_core::sandbox_env::SANDBOX_GID,
openshell_core::sandbox_env::SANDBOX_TOKEN,
openshell_core::sandbox_env::SANDBOX_TOKEN_FILE,
openshell_core::sandbox_env::K8S_SA_TOKEN_FILE,
openshell_core::sandbox_env::TLS_CA,
openshell_core::sandbox_env::TLS_CERT,
openshell_core::sandbox_env::TLS_KEY,
openshell_core::sandbox_env::PROVIDER_SPIFFE_WORKLOAD_API_SOCKET,
openshell_core::sandbox_env::NETWORK_RUNTIME_CAPABILITIES,
];
const PROXY_ENV_VARS: &[&str] = &[
"ALL_PROXY",
"HTTP_PROXY",
"HTTPS_PROXY",
"NO_PROXY",
"all_proxy",
"http_proxy",
"https_proxy",
"no_proxy",
"grpc_proxy",
"NODE_USE_ENV_PROXY",
];
pub fn is_supervisor_only_env_var(key: &str) -> bool {
SUPERVISOR_ONLY_ENV_VARS.contains(&key)
}
fn strip_supervisor_only_env(cmd: &mut Command) {
for key in SUPERVISOR_ONLY_ENV_VARS {
cmd.env_remove(key);
}
}
/// Remove ambient proxy routing from a transparently mediated child.
pub fn strip_proxy_env(cmd: &mut Command) {
for key in PROXY_ENV_VARS {
cmd.env_remove(key);
}
}
/// [`strip_proxy_env`] for synchronous exec commands.
pub fn strip_proxy_env_std(cmd: &mut std::process::Command) {
for key in PROXY_ENV_VARS {
cmd.env_remove(key);
}
}
/// Whether an environment key can redirect a child around transparent
/// network mediation.
#[must_use]
pub fn is_proxy_env_var(key: &str) -> bool {
PROXY_ENV_VARS.contains(&key)
}
fn inject_provider_env(cmd: &mut Command, provider_env: &HashMap<String, String>) {
for (key, value) in provider_env {
if is_supervisor_only_env_var(key) {
continue;
}
cmd.env(key, value);
}
}
/// Derive the child USER and HOME from the policy's sandbox identity.
///
/// Name-based identities use their passwd entry. Numeric identities have no
/// reliable passwd entry, so their workspace remains the portable fallback.
pub(crate) fn session_user_and_home(
policy: &SandboxPolicy,
workdir_home: Option<&str>,
) -> (String, String) {
let (user, default_home) = match policy.process.run_as_user.as_deref() {
Some(user) if !user.is_empty() => {
if user.parse::<u32>().is_ok() {
(user.to_string(), "/sandbox".to_string())
} else {
let home = User::from_name(user).ok().flatten().map_or_else(
|| format!("/home/{user}"),
|entry| entry.dir.to_string_lossy().into_owned(),
);
(user.to_string(), home)
}
}
_ => ("sandbox".to_string(), "/sandbox".to_string()),
};
let home = workdir_home.map_or(default_home, str::to_string);
(user, home)
}
fn apply_canonical_process_environment(
cmd: &mut Command,
policy: &SandboxPolicy,
workspace: &ResolvedWorkspace,
interactive: bool,
user_environment: &HashMap<String, String>,
) {
// The canonical process inherits the sandbox's environment so the image's
// own ENV (PATH, LANG, JAVA_HOME, ...) reaches the workload. Remove the
// reserved OPENSHELL_ namespace inherited from the sandbox itself, which
// carries its own control state (for example the serialized user
// environment and log level), then restore the one marker the workload is
// meant to see. The gateway rejects declared variables in this namespace.
for (key, _) in std::env::vars_os() {
if key
.to_str()
.is_some_and(|key| key.starts_with(RESERVED_ENV_PREFIX))
{
cmd.env_remove(key);
}
}
cmd.env(openshell_core::sandbox_env::SANDBOX, "1");
cmd.envs(user_environment);
let (session_user, session_home) = session_user_and_home(policy, workspace.home());
// Resolve a shell present in the workload image. This code runs inside the
// workload boundary, where the image filesystem is visible.
let shell = openshell_core::shell::detect_login_shell();
for (key, value) in [
("HOME", session_home.as_str()),
("USER", session_user.as_str()),
("SHELL", shell.as_str()),
(
"TERM",
if interactive {
"xterm-256color"
} else {
"dumb"
},
),
] {
if !user_environment.contains_key(key) {
cmd.env(key, value);
}
}
}
static BOUNDARY_USER_ENVIRONMENT: OnceLock<HashMap<String, String>> = OnceLock::new();
#[cfg(target_os = "linux")]
pub(crate) fn install_boundary_user_environment(
environment: HashMap<String, String>,
) -> Result<(), String> {
BOUNDARY_USER_ENVIRONMENT
.set(environment)
.map_err(|_| "boundary workload environment already installed".to_string())
}
pub(crate) fn configured_user_environment() -> HashMap<String, String> {
if let Some(environment) = BOUNDARY_USER_ENVIRONMENT.get() {
return environment.clone();
}
std::env::var(openshell_core::sandbox_env::USER_ENVIRONMENT)
.ok()
.and_then(|json| serde_json::from_str(&json).ok())
.unwrap_or_default()
}
/// Composes the environment of a canonical workload process. Shared by the
/// PTY and pipe spawn paths so both apply the same layering: the inherited
/// sandbox environment minus the reserved `OPENSHELL_` namespace, the
/// declared user environment, supervisor-only and proxy variables stripped,
/// provider placeholders, TLS trust paths, and finally the OTLP relay
/// default, applied last so a provider cannot redirect traces, and only
/// while the relay is active and neither the declared environment nor the
/// image names an OTLP endpoint of its own.
#[allow(clippy::too_many_arguments)]
fn compose_canonical_process_environment(
cmd: &mut Command,
policy: &SandboxPolicy,
workspace: &ResolvedWorkspace,
interactive: bool,
user_environment: &HashMap<String, String>,
provider_env: &HashMap<String, String>,
ca_paths: Option<&(PathBuf, PathBuf)>,
tls_environment_mode: child_env::TlsEnvironmentMode,
otlp_relay_active: bool,
) {
apply_canonical_process_environment(cmd, policy, workspace, interactive, user_environment);
strip_supervisor_only_env(cmd);
inject_provider_env(cmd, provider_env);
strip_proxy_env(cmd);
// In interception mode OpenShell trust is authoritative. In direct
// additional-CA mode, retain all caller values and only fill gaps.
if let Some((ca_cert_path, combined_bundle_path)) = ca_paths {
// Provider credentials are injected before this point. Reassert
// caller TLS values in additive mode so a provider environment
// cannot accidentally replace a caller-selected trust store.
if matches!(
tls_environment_mode,
child_env::TlsEnvironmentMode::FillMissing
) {
for (key, value) in user_environment {
if child_env::is_tls_environment_variable(key) {
cmd.env(key, value);
}
}
}
for (key, value) in child_env::tls_env_vars_for_mode(
ca_cert_path,
combined_bundle_path,
tls_environment_mode,
user_environment,
) {
cmd.env(key, value);
}
}
child_env::apply_otlp_relay_env(
cmd,
otlp_relay_active,
child_env::ChildEnvironment::Inherited,
user_environment,
&[],
);
}
#[cfg(unix)]
pub fn harden_child_process() -> Result<()> {
use rustix::process::{Resource, Rlimit, setrlimit};
setrlimit(
Resource::Core,
Rlimit {
current: Some(0),
maximum: Some(0),
},
)
.map_err(|e| miette::miette!("Failed to disable core dumps: {e}"))?;
#[cfg(target_os = "linux")]
{
use rustix::process::{DumpableBehavior, set_dumpable_behavior};
set_dumpable_behavior(DumpableBehavior::NotDumpable)
.map_err(|e| miette::miette!("Failed to set PR_SET_DUMPABLE=0: {e}"))?;
}
Ok(())
}
#[cfg(target_os = "linux")]
const CGROUP_PIDS_MAX_PATH: &str = "/sys/fs/cgroup/pids.max";
#[cfg(target_os = "linux")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RuntimePidLimitStatus {
Limited(u64),
Unlimited,
Unavailable(String),
}
#[cfg(target_os = "linux")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuntimePidLimitMode {
Warn,
Require,
}
#[cfg(target_os = "linux")]
pub fn check_runtime_pid_limit(mode: RuntimePidLimitMode) -> Result<()> {
check_runtime_pid_limit_status(runtime_pid_limit_status(), mode)
}
#[cfg(target_os = "linux")]
fn check_runtime_pid_limit_status(
status: RuntimePidLimitStatus,
mode: RuntimePidLimitMode,
) -> Result<()> {
match status {
RuntimePidLimitStatus::Limited(limit) => {
debug!(pids_max = limit, "runtime PID limit detected");
Ok(())
}
RuntimePidLimitStatus::Unlimited => {
let message = "runtime cgroup pids.max is unlimited; configure the compute driver or container runtime to enforce a PID limit";
if matches!(mode, RuntimePidLimitMode::Require) {
Err(miette::miette!(message))
} else {
tracing::warn!("{message}");
Ok(())
}
}
RuntimePidLimitStatus::Unavailable(reason) => {
let message = format!(
"runtime cgroup pids.max is unavailable ({reason}); configure the compute driver or container runtime to enforce a PID limit"
);
if matches!(mode, RuntimePidLimitMode::Require) {
Err(miette::miette!(message))
} else {
tracing::warn!("{message}");
Ok(())
}
}
}
}
#[cfg(target_os = "linux")]
fn runtime_pid_limit_status() -> RuntimePidLimitStatus {
match std::fs::read_to_string(CGROUP_PIDS_MAX_PATH) {
Ok(contents) => parse_pids_max(&contents),
Err(err) => RuntimePidLimitStatus::Unavailable(err.to_string()),
}
}
#[cfg(target_os = "linux")]
fn parse_pids_max(contents: &str) -> RuntimePidLimitStatus {
let raw = contents.trim();
if raw.eq_ignore_ascii_case("max") {
return RuntimePidLimitStatus::Unlimited;
}
match raw.parse::<u64>() {
Ok(limit) => RuntimePidLimitStatus::Limited(limit),
Err(err) => {
RuntimePidLimitStatus::Unavailable(format!("invalid pids.max value {raw:?}: {err}"))
}
}
}
#[cfg(target_os = "linux")]
pub fn spawn_command_with_workload_launcher(
launcher: &crate::linux::workload_launcher::WorkloadLauncher,
mut cmd: Command,
) -> std::io::Result<Child> {
let runtime = tokio::runtime::Handle::current();
launcher.execute(move || {
let _guard = runtime.enter();
cmd.spawn()
})?
}
#[cfg(target_os = "linux")]
pub fn spawn_std_command_with_workload_launcher(
launcher: &crate::linux::workload_launcher::WorkloadLauncher,
mut cmd: std::process::Command,
) -> std::io::Result<std::process::Child> {
launcher.execute(move || cmd.spawn())?
}
/// Handle to a running process.
pub struct ProcessHandle {
child: Child,
pid: u32,
io: Option<ProcessIo>,
terminal: Arc<AtomicBool>,
signal_lock: Arc<std::sync::Mutex<()>>,
#[cfg(target_os = "linux")]
managed_child: Option<managed_children::ManagedChild>,
}
/// Supervisor-owned canonical-process I/O. These handles outlive individual
/// SSH attachments and are consumed by the main-session multiplexer.
pub enum ProcessIo {
Pty(std::fs::File),
Pipes {
stdin: ChildStdin,
stdout: ChildStdout,
stderr: ChildStderr,
},
}
impl ProcessHandle {
/// Spawn a new process.
///
/// # Errors
///
/// Returns an error if the process fails to start.
#[cfg(target_os = "linux")]
#[allow(clippy::too_many_arguments)]
pub fn spawn(
launcher: &crate::linux::workload_launcher::WorkloadLauncher,
program: &str,
args: &[String],
workspace: &ResolvedWorkspace,
interactive: bool,
policy: &SandboxPolicy,
ca_paths: Option<&(PathBuf, PathBuf)>,
tls_environment_mode: child_env::TlsEnvironmentMode,
provider_env: &HashMap<String, String>,
otlp_relay_active: bool,
) -> Result<Self> {
Self::spawn_impl(
launcher,
program,
args,
workspace,
interactive,
policy,
ca_paths,
tls_environment_mode,
provider_env,
otlp_relay_active,
)
}
/// Spawn a new process (non-Linux platforms).
///
/// # Errors
///
/// Returns an error if the process fails to start.
#[cfg(not(target_os = "linux"))]
#[allow(clippy::too_many_arguments)]
pub fn spawn(
program: &str,
args: &[String],
workspace: &ResolvedWorkspace,
interactive: bool,
policy: &SandboxPolicy,
ca_paths: Option<&(PathBuf, PathBuf)>,
tls_environment_mode: child_env::TlsEnvironmentMode,
provider_env: &HashMap<String, String>,
otlp_relay_active: bool,
) -> Result<Self> {
Self::spawn_impl(
program,
args,
workspace,
interactive,
policy,
ca_paths,
tls_environment_mode,
provider_env,
otlp_relay_active,
)
}
#[cfg(target_os = "linux")]
#[allow(clippy::too_many_arguments)]
fn spawn_impl(
launcher: &crate::linux::workload_launcher::WorkloadLauncher,
program: &str,
args: &[String],
workspace: &ResolvedWorkspace,
interactive: bool,
policy: &SandboxPolicy,
ca_paths: Option<&(PathBuf, PathBuf)>,
tls_environment_mode: child_env::TlsEnvironmentMode,
provider_env: &HashMap<String, String>,
otlp_relay_active: bool,
) -> Result<Self> {
let mut cmd = Command::new(program);
cmd.args(args).kill_on_drop(true);
let mut pty_master = None;
let mut terminal_slave_fd = None;
if interactive {
let winsize = nix::pty::Winsize {
ws_row: 24,
ws_col: 80,
ws_xpixel: 0,
ws_ypixel: 0,
};
let pty = nix::pty::openpty(Some(&winsize), None).into_diagnostic()?;
let master = std::fs::File::from(pty.master);
let slave = std::fs::File::from(pty.slave);
terminal_slave_fd = Some(slave.as_raw_fd());
cmd.stdin(slave.try_clone().into_diagnostic()?)
.stdout(slave.try_clone().into_diagnostic()?)
.stderr(slave);
pty_master = Some(master);
} else {
cmd.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
}
// Build the entrypoint's environment. It also strips supervisor-only
// identity material: the entrypoint drops to the sandbox user before
// `exec`, and without the strip sandbox code could recover
// supervisor credentials from its inherited environment.
compose_canonical_process_environment(
&mut cmd,
policy,
workspace,
interactive,
&configured_user_environment(),
provider_env,
ca_paths,
tls_environment_mode,
otlp_relay_active,
);
if let Some(dir) = workspace.root() {
cmd.current_dir(dir);
}
// Probe Landlock availability and emit OCSF logs from the parent
// process where the tracing subscriber is functional. The child's
// pre_exec context cannot reliably emit structured logs.
#[cfg(target_os = "linux")]
sandbox::linux::log_sandbox_readiness(policy, workspace.root());
// Prepare the Landlock ruleset as the workload UID. Inaccessible paths
// are already unavailable to the child and remain omitted.
#[cfg(target_os = "linux")]
let runtime_read_only = ca_runtime_read_only_paths(ca_paths);
let prepared_sandbox = prepare_child_sandbox(policy, workspace.root(), &runtime_read_only)
.map_err(|err| miette::miette!("Failed to prepare sandbox: {err}"))?;
#[cfg(target_os = "linux")]
let mut child_hardening = crate::linux::child_seccomp::prepare(std::process::id())
.map_err(|error| miette::miette!("prepare child self-protection filter: {error}"))?;
// Set up process group for signal handling (non-interactive mode only).
// In interactive mode, we inherit the parent's process group to maintain
// proper terminal control for shells and interactive programs.
// SAFETY: pre_exec runs after fork but before exec in the child process.
// setpgid and setns are async-signal-safe and safe to call in this context.
{
// Wrap in Option so we can .take() it out of the FnMut closure.
// pre_exec is only called once (after fork, before exec).
#[cfg(target_os = "linux")]
let mut prepared_sandbox = prepared_sandbox;
#[allow(unsafe_code)]
// SAFETY: pre_exec only registers the hook; the closure runs
// post-fork and pre-exec in the child process, never in the
// launcher parent.
unsafe {
cmd.pre_exec(move || {
if let Some(slave_fd) = terminal_slave_fd {
if libc::setsid() < 0 {
return Err(std::io::Error::last_os_error());
}
set_controlling_tty(slave_fd)?;
} else if libc::setpgid(0, 0) < 0 {
return Err(std::io::Error::last_os_error());
}
harden_child_process().map_err(|err| std::io::Error::other(err.to_string()))?;
// Phase 2 (as unprivileged user): Enforce the prepared
// Landlock ruleset via restrict_self() + apply seccomp.
// restrict_self() does not require root.
#[cfg(target_os = "linux")]
if let Some(prepared) = prepared_sandbox.take() {
sandbox::linux::enforce_capability_free(prepared, &mut child_hardening)
.map_err(|err| std::io::Error::other(err.to_string()))?;
}
Ok(())
});
}
}
// Name the program in the error: a bare "No such file or directory"
// here is otherwise indistinguishable from a missing working directory
// or interpreter, and is a common failure on images that lack the
// requested shell/binary (e.g. bash on Alpine).
#[cfg(target_os = "linux")]
let mut child_registry = managed_children::lock();
#[cfg(target_os = "linux")]
let mut child = spawn_command_with_workload_launcher(launcher, cmd)
.into_diagnostic()
.wrap_err_with(|| format!("failed to spawn sandbox entrypoint process '{program}'"))?;
#[cfg(not(target_os = "linux"))]
let mut child = cmd
.spawn()
.into_diagnostic()
.wrap_err_with(|| format!("failed to spawn sandbox entrypoint process '{program}'"))?;
let pid = child.id().unwrap_or(0);
let managed_child = child_registry.register(pid);
drop(child_registry);
let io = if let Some(master) = pty_master {
ProcessIo::Pty(master)
} else {
ProcessIo::Pipes {
stdin: child.stdin.take().expect("canonical stdin must be piped"),
stdout: child.stdout.take().expect("canonical stdout must be piped"),
stderr: child.stderr.take().expect("canonical stderr must be piped"),
}
};
debug!(pid, program, "Process spawned");
Ok(Self {
child,
pid,
io: Some(io),
terminal: Arc::new(AtomicBool::new(false)),
signal_lock: Arc::new(std::sync::Mutex::new(())),
#[cfg(target_os = "linux")]
managed_child,
})
}
#[cfg(not(target_os = "linux"))]
#[allow(clippy::too_many_arguments)]
fn spawn_impl(
program: &str,
args: &[String],
workspace: &ResolvedWorkspace,
interactive: bool,
policy: &SandboxPolicy,
ca_paths: Option<&(PathBuf, PathBuf)>,
tls_environment_mode: child_env::TlsEnvironmentMode,
provider_env: &HashMap<String, String>,
otlp_relay_active: bool,
) -> Result<Self> {
let mut cmd = Command::new(program);
cmd.args(args).kill_on_drop(true);
let mut pty_master = None;
let mut terminal_slave_fd = None;
#[cfg(unix)]
if interactive {
let winsize = nix::pty::Winsize {
ws_row: 24,
ws_col: 80,
ws_xpixel: 0,
ws_ypixel: 0,
};
let pty = nix::pty::openpty(Some(&winsize), None).into_diagnostic()?;
let master = std::fs::File::from(pty.master);
let slave = std::fs::File::from(pty.slave);
terminal_slave_fd = Some(slave.as_raw_fd());
cmd.stdin(slave.try_clone().into_diagnostic()?)
.stdout(slave.try_clone().into_diagnostic()?)
.stderr(slave);
pty_master = Some(master);
}
if !interactive {
cmd.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
}
// Build the entrypoint's environment, without supervisor-only
// identity material.
compose_canonical_process_environment(
&mut cmd,
policy,
workspace,
interactive,
&configured_user_environment(),
provider_env,
ca_paths,
tls_environment_mode,
otlp_relay_active,
);
if let Some(dir) = workspace.root() {
cmd.current_dir(dir);
}
// Create a dedicated session for PTY children and a dedicated process
// group for pipe children so attachment signals target only the
// canonical workload tree.
// SAFETY: pre_exec runs after fork but before exec in the child process.
// setpgid is async-signal-safe and safe to call in this context.
#[cfg(unix)]
{
let policy = policy.clone();
let workdir = workspace.owned_root();
#[allow(unsafe_code)]
unsafe {
cmd.pre_exec(move || {
if let Some(slave_fd) = terminal_slave_fd {
if libc::setsid() < 0 {
return Err(std::io::Error::last_os_error());
}
set_controlling_tty(slave_fd)?;
} else if libc::setpgid(0, 0) < 0 {
return Err(std::io::Error::last_os_error());
}
harden_child_process().map_err(|err| std::io::Error::other(err.to_string()))?;
sandbox::apply(&policy, workdir.as_deref())
.map_err(|err| std::io::Error::other(err.to_string()))?;
Ok(())
});
}
}
let mut child = cmd.spawn().into_diagnostic()?;
let pid = child.id().unwrap_or(0);
#[cfg(target_os = "linux")]
managed_children::register(pid);
debug!(pid, program, "Process spawned");
let io = if let Some(master) = pty_master {
ProcessIo::Pty(master)
} else {
ProcessIo::Pipes {
stdin: child.stdin.take().expect("canonical stdin must be piped"),
stdout: child.stdout.take().expect("canonical stdout must be piped"),
stderr: child.stderr.take().expect("canonical stderr must be piped"),
}
};
Ok(Self {
child,
pid,
io: Some(io),
terminal: Arc::new(AtomicBool::new(false)),
signal_lock: Arc::new(std::sync::Mutex::new(())),
})
}
/// Get the process ID.
#[must_use]
pub const fn pid(&self) -> u32 {
self.pid
}
/// Transfer retained stdio to the main-session multiplexer.
pub fn take_io(&mut self) -> ProcessIo {
self.io.take().expect("canonical process I/O already taken")
}
/// Shared state used by an independent boundary signal handle.
#[must_use]
pub fn signaling_state(&self) -> (Arc<AtomicBool>, Arc<std::sync::Mutex<()>>) {
(self.terminal.clone(), self.signal_lock.clone())
}
/// Wait for the process to exit.
///
/// # Errors
///
/// Returns an error if waiting fails.
pub async fn wait(&mut self) -> std::io::Result<ProcessStatus> {
let status = self.child.wait().await;
let _signal_guard = self
.signal_lock
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
self.terminal.store(true, Ordering::Release);
#[cfg(target_os = "linux")]
if let Some(child) = self.managed_child.take() {
managed_children::unregister(child);
}
let status = status?;
Ok(ProcessStatus::from(status))
}
/// Observe an already-terminated child without blocking.
pub fn try_wait(&mut self) -> std::io::Result<Option<ProcessStatus>> {
let status = self.child.try_wait()?;
if status.is_some() {
let _signal_guard = self
.signal_lock
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
self.terminal.store(true, Ordering::Release);
#[cfg(target_os = "linux")]
if let Some(child) = self.managed_child.take() {
managed_children::unregister(child);
}
}
Ok(status.map(ProcessStatus::from))
}
/// Send a signal to the process.
///
/// # Errors
///
/// Returns an error if the signal cannot be sent.
pub fn signal(&self, sig: Signal) -> Result<()> {
let _signal_guard = self
.signal_lock
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if self.terminal.load(Ordering::Acquire) {
return Err(miette::miette!("process has exited"));
}
let pid = i32::try_from(self.pid).unwrap_or(i32::MAX);
signal::kill(Pid::from_raw(pid), sig).into_diagnostic()
}
/// Kill the process.
///
/// # Errors
///
/// Returns an error if the process cannot be killed.
pub fn kill(&mut self) -> Result<()> {
// First try SIGTERM
if let Err(e) = self.signal(Signal::SIGTERM) {
openshell_ocsf::ocsf_emit!(
openshell_ocsf::ProcessActivityBuilder::new(openshell_ocsf::ctx::ctx())
.activity(openshell_ocsf::ActivityId::Close)
.severity(openshell_ocsf::SeverityId::Medium)
.status(openshell_ocsf::StatusId::Failure)
.actor_process(ocsf_launcher_process())
.message(format!("Failed to send SIGTERM: {e}"))
.build()
);
}
// Give the process a moment to terminate gracefully
std::thread::sleep(std::time::Duration::from_millis(100));
// Force kill if still running
if let Some(id) = self.child.id() {
debug!(pid = id, "Sending SIGKILL");
let pid = i32::try_from(id).unwrap_or(i32::MAX);
let _ = signal::kill(Pid::from_raw(pid), Signal::SIGKILL);
}
Ok(())
}
}
impl Drop for ProcessHandle {
fn drop(&mut self) {
#[cfg(target_os = "linux")]
if let Some(child) = self.managed_child.take() {
managed_children::unregister(child);
}
}
}
#[cfg(target_os = "linux")]
pub fn validate_oci_workspace_as_effective_identity(root: &Path) -> Result<()> {
use rustix::fs::{Access, AtFlags, FileType, Mode, OFlags};
let components = validated_workspace_components(root)?;
let open_flags = OFlags::PATH | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC;
let mut current_path = PathBuf::from("/");
let mut current_fd = rustix::fs::open("/", open_flags, Mode::empty()).into_diagnostic()?;
rustix::fs::accessat(
¤t_fd,
".",
Access::EXEC_OK,
AtFlags::EACCESS | AtFlags::SYMLINK_NOFOLLOW,
)
.map_err(|error| {
miette::miette!(
"workspace path component '{}' is not traversable by the sandbox identity in the image: {error}",
current_path.display()
)
})?;
let last_component = components.len().saturating_sub(1);
for (index, component) in components.into_iter().enumerate() {
current_path.push(&component);
let stat = rustix::fs::statat(¤t_fd, &component, AtFlags::SYMLINK_NOFOLLOW).map_err(
|error| {
if error == rustix::io::Errno::NOENT {
miette::miette!(
"image workspace path component '{}' does not exist",
current_path.display()
)
} else {
miette::miette!(
"failed to inspect image workspace path component '{}': {error}",
current_path.display()
)
}
},
)?;
let file_type = FileType::from_raw_mode(stat.st_mode);
if file_type.is_symlink() {
return Err(miette::miette!(
"workspace path component '{}' is a symlink — refusing to follow it",
current_path.display()
));
}
if !file_type.is_dir() {
return Err(miette::miette!(
"workspace path component '{}' is not a directory",
current_path.display()
));
}
let is_workspace = index == last_component;
rustix::fs::accessat(
¤t_fd,
&component,
Access::EXEC_OK,
AtFlags::EACCESS | AtFlags::SYMLINK_NOFOLLOW,
)
.map_err(|error| {
miette::miette!(
"workspace path component '{}' is not traversable by the sandbox identity in the image: {error}",
current_path.display()
)
})?;
let next_fd = rustix::fs::openat(¤t_fd, &component, open_flags, Mode::empty())
.map_err(|error| {