forked from NVIDIA/OpenShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
2708 lines (2482 loc) · 101 KB
/
Copy pathlib.rs
File metadata and controls
2708 lines (2482 loc) · 101 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
//! OpenShell Sandbox library.
//!
//! This crate provides process sandboxing and monitoring capabilities.
pub mod bypass_monitor;
mod child_env;
pub mod denial_aggregator;
mod grpc_client;
mod identity;
pub mod l7;
pub mod log_push;
pub mod mechanistic_mapper;
pub mod opa;
mod policy;
mod process;
pub mod procfs;
pub mod proxy;
mod sandbox;
mod secrets;
mod ssh;
use miette::{IntoDiagnostic, Result};
#[cfg(target_os = "linux")]
use std::collections::HashSet;
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicU32, Ordering};
#[cfg(target_os = "linux")]
use std::sync::{LazyLock, Mutex};
use std::time::Duration;
use tokio::time::timeout;
use tracing::{debug, info, trace, warn};
use openshell_ocsf::{
ActionId, ActivityId, AppLifecycleBuilder, ConfigStateChangeBuilder, DetectionFindingBuilder,
DispositionId, FindingInfo, LaunchTypeId, Process as OcsfProcess, ProcessActivityBuilder,
SandboxContext, SeverityId, StateId, StatusId, ocsf_emit,
};
// ---------------------------------------------------------------------------
// OCSF Context
// ---------------------------------------------------------------------------
//
// The following log sites intentionally remain as plain `tracing` macros
// and are NOT migrated to OCSF builders:
//
// - DEBUG/TRACE events (zombie reaping, ip commands, gRPC connects, PTY state)
// - Transient "about to do X" events where the result is logged separately
// (e.g., "Fetching sandbox policy via gRPC", "Creating OPA engine from proto")
// - Internal SSH channel warnings (unknown channel, PTY resize failures)
// - Denial flush telemetry (the individual denials are already OCSF events)
// - Status reporting failures (sync to gateway, non-actionable)
// - Route refresh interval validation warnings
//
// These are operational plumbing that don't represent security decisions,
// policy changes, or observable sandbox behavior worth structuring.
// ---------------------------------------------------------------------------
/// Process-wide OCSF sandbox context. Initialized once during `run_sandbox()`
/// startup and accessible from any module in the crate via [`ocsf_ctx()`].
static OCSF_CTX: OnceLock<SandboxContext> = OnceLock::new();
/// Fallback context used when `OCSF_CTX` has not been initialized (e.g. in
/// unit tests that exercise individual functions without calling `run_sandbox`).
static OCSF_CTX_FALLBACK: std::sync::LazyLock<SandboxContext> =
std::sync::LazyLock::new(|| SandboxContext {
sandbox_id: String::new(),
sandbox_name: String::new(),
container_image: String::new(),
hostname: "test".to_string(),
product_version: openshell_core::VERSION.to_string(),
proxy_ip: std::net::IpAddr::from([127, 0, 0, 1]),
proxy_port: 3128,
});
/// Return a reference to the process-wide [`SandboxContext`].
///
/// Falls back to a default context if `run_sandbox()` has not yet been called
/// (e.g. during unit tests).
pub(crate) fn ocsf_ctx() -> &'static SandboxContext {
OCSF_CTX.get().unwrap_or(&OCSF_CTX_FALLBACK)
}
use crate::identity::BinaryIdentityCache;
use crate::l7::tls::{
CertCache, ProxyTlsState, SandboxCa, build_upstream_client_config, read_system_ca_bundle,
write_ca_files,
};
use crate::opa::OpaEngine;
use crate::policy::{NetworkMode, NetworkPolicy, ProxyPolicy, SandboxPolicy};
use crate::proxy::ProxyHandle;
#[cfg(target_os = "linux")]
use crate::sandbox::linux::netns::NetworkNamespace;
use crate::secrets::SecretResolver;
pub use process::{ProcessHandle, ProcessStatus};
/// Default interval (seconds) for re-fetching the inference route bundle from
/// the gateway in cluster mode. Override at runtime with the
/// `OPENSHELL_ROUTE_REFRESH_INTERVAL_SECS` environment variable.
/// File-based routes (`--inference-routes`) are loaded once at startup and never
/// refreshed.
const DEFAULT_ROUTE_REFRESH_INTERVAL_SECS: u64 = 5;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum InferenceRouteSource {
File,
Cluster,
None,
}
fn infer_route_source(
sandbox_id: Option<&str>,
openshell_endpoint: Option<&str>,
inference_routes: Option<&str>,
) -> InferenceRouteSource {
if inference_routes.is_some() {
InferenceRouteSource::File
} else if sandbox_id.is_some() && openshell_endpoint.is_some() {
InferenceRouteSource::Cluster
} else {
InferenceRouteSource::None
}
}
fn disable_inference_on_empty_routes(source: InferenceRouteSource) -> bool {
!matches!(source, InferenceRouteSource::Cluster)
}
fn route_refresh_interval_secs() -> u64 {
match std::env::var("OPENSHELL_ROUTE_REFRESH_INTERVAL_SECS") {
Ok(value) => match value.parse::<u64>() {
Ok(interval) if interval > 0 => interval,
Ok(_) => {
warn!(
default_interval_secs = DEFAULT_ROUTE_REFRESH_INTERVAL_SECS,
"Ignoring zero route refresh interval"
);
DEFAULT_ROUTE_REFRESH_INTERVAL_SECS
}
Err(error) => {
warn!(
interval = %value,
error = %error,
default_interval_secs = DEFAULT_ROUTE_REFRESH_INTERVAL_SECS,
"Ignoring invalid route refresh interval"
);
DEFAULT_ROUTE_REFRESH_INTERVAL_SECS
}
},
Err(_) => DEFAULT_ROUTE_REFRESH_INTERVAL_SECS,
}
}
#[cfg(target_os = "linux")]
static MANAGED_CHILDREN: LazyLock<Mutex<HashSet<i32>>> =
LazyLock::new(|| Mutex::new(HashSet::new()));
#[cfg(target_os = "linux")]
pub(crate) fn register_managed_child(pid: u32) {
let Ok(pid) = i32::try_from(pid) else {
return;
};
if pid <= 0 {
return;
}
if let Ok(mut children) = MANAGED_CHILDREN.lock() {
children.insert(pid);
}
}
#[cfg(target_os = "linux")]
pub(crate) fn unregister_managed_child(pid: u32) {
let Ok(pid) = i32::try_from(pid) else {
return;
};
if pid <= 0 {
return;
}
if let Ok(mut children) = MANAGED_CHILDREN.lock() {
children.remove(&pid);
}
}
#[cfg(target_os = "linux")]
fn is_managed_child(pid: i32) -> bool {
MANAGED_CHILDREN
.lock()
.is_ok_and(|children| children.contains(&pid))
}
/// Run a command in the sandbox.
///
/// # Errors
///
/// Returns an error if the command fails to start or encounters a fatal error.
#[allow(clippy::too_many_arguments, clippy::similar_names)]
pub async fn run_sandbox(
command: Vec<String>,
workdir: Option<String>,
timeout_secs: u64,
interactive: bool,
sandbox_id: Option<String>,
sandbox: Option<String>,
openshell_endpoint: Option<String>,
policy_rules: Option<String>,
policy_data: Option<String>,
ssh_listen_addr: Option<String>,
ssh_handshake_secret: Option<String>,
ssh_handshake_skew_secs: u64,
_health_check: bool,
_health_port: u16,
inference_routes: Option<String>,
ocsf_enabled: Arc<std::sync::atomic::AtomicBool>,
) -> Result<i32> {
let (program, args) = command
.split_first()
.ok_or_else(|| miette::miette!("No command specified"))?;
// Initialize the process-wide OCSF context early so that events emitted
// during policy loading (filesystem config, validation) have a context.
// Proxy IP/port use defaults here; they are only significant for network
// events which happen after the netns is created.
{
let hostname = std::fs::read_to_string("/etc/hostname")
.map(|s| s.trim().to_string())
.unwrap_or_else(|_| "openshell-sandbox".to_string());
if OCSF_CTX
.set(SandboxContext {
sandbox_id: sandbox_id.clone().unwrap_or_default(),
sandbox_name: sandbox.as_deref().unwrap_or_default().to_string(),
container_image: std::env::var("OPENSHELL_CONTAINER_IMAGE").unwrap_or_default(),
hostname,
product_version: openshell_core::VERSION.to_string(),
proxy_ip: std::net::IpAddr::from([127, 0, 0, 1]),
proxy_port: 3128,
})
.is_err()
{
debug!("OCSF context already initialized, keeping existing");
}
}
// Load policy and initialize OPA engine
let openshell_endpoint_for_proxy = openshell_endpoint.clone();
let sandbox_name_for_agg = sandbox.clone();
let (policy, opa_engine, retained_proto) = load_policy(
sandbox_id.clone(),
sandbox,
openshell_endpoint.clone(),
policy_rules,
policy_data,
)
.await?;
// Validate that the required "sandbox" user exists in this image.
// All sandbox images must include this user for privilege dropping.
#[cfg(unix)]
validate_sandbox_user(&policy)?;
// Fetch provider environment variables from the server.
// This is done after loading the policy so the sandbox can still start
// even if provider env fetch fails (graceful degradation).
let provider_env = if let (Some(id), Some(endpoint)) = (&sandbox_id, &openshell_endpoint) {
match grpc_client::fetch_provider_environment(endpoint, id).await {
Ok(env) => {
ocsf_emit!(
ConfigStateChangeBuilder::new(ocsf_ctx())
.severity(SeverityId::Informational)
.status(StatusId::Success)
.state(StateId::Enabled, "loaded")
.message(format!(
"Fetched provider environment [env_count:{}]",
env.len()
))
.build()
);
env
}
Err(e) => {
ocsf_emit!(
ConfigStateChangeBuilder::new(ocsf_ctx())
.severity(SeverityId::Medium)
.status(StatusId::Failure)
.state(StateId::Other, "degraded")
.message(format!(
"Failed to fetch provider environment, continuing without: {e}"
))
.build()
);
std::collections::HashMap::new()
}
}
} else {
std::collections::HashMap::new()
};
let (provider_env, secret_resolver) = SecretResolver::from_provider_env(provider_env);
let secret_resolver = secret_resolver.map(Arc::new);
// Create identity cache for SHA256 TOFU when OPA is active
let identity_cache = opa_engine
.as_ref()
.map(|_| Arc::new(BinaryIdentityCache::new()));
// Prepare filesystem: create and chown read_write directories
prepare_filesystem(&policy)?;
// Generate ephemeral CA and TLS state for HTTPS L7 inspection.
// The CA cert is written to disk so sandbox processes can trust it.
let (tls_state, ca_file_paths) = if matches!(policy.network.mode, NetworkMode::Proxy) {
match SandboxCa::generate() {
Ok(ca) => {
let tls_dir = std::path::Path::new("/etc/openshell-tls");
let system_ca_bundle = read_system_ca_bundle();
match write_ca_files(&ca, tls_dir, &system_ca_bundle) {
Ok(paths) => {
// /etc/openshell-tls is subsumed by the /etc baseline
// path injected by enrich_*_baseline_paths(), so no
// explicit Landlock entry is needed here.
let upstream_config = build_upstream_client_config(&system_ca_bundle);
let cert_cache = CertCache::new(ca);
let state = Arc::new(ProxyTlsState::new(cert_cache, upstream_config));
ocsf_emit!(
ConfigStateChangeBuilder::new(ocsf_ctx())
.severity(SeverityId::Informational)
.status(StatusId::Success)
.state(StateId::Enabled, "enabled")
.message("TLS termination enabled: ephemeral CA generated")
.build()
);
(Some(state), Some(paths))
}
Err(e) => {
ocsf_emit!(
ConfigStateChangeBuilder::new(ocsf_ctx())
.severity(SeverityId::Medium)
.status(StatusId::Failure)
.state(StateId::Disabled, "disabled")
.message(format!(
"Failed to write CA files, TLS termination disabled: {e}"
))
.build()
);
(None, None)
}
}
}
Err(e) => {
ocsf_emit!(
ConfigStateChangeBuilder::new(ocsf_ctx())
.severity(SeverityId::Medium)
.status(StatusId::Failure)
.state(StateId::Disabled, "disabled")
.message(format!(
"Failed to generate ephemeral CA, TLS termination disabled: {e}"
))
.build()
);
(None, None)
}
}
} else {
(None, None)
};
// Create network namespace for proxy mode (Linux only)
// This must be created before the proxy AND SSH server so that SSH
// sessions can enter the namespace for network isolation.
#[cfg(target_os = "linux")]
let netns = if matches!(policy.network.mode, NetworkMode::Proxy) {
match NetworkNamespace::create() {
Ok(ns) => {
// Install bypass detection rules (iptables LOG + REJECT).
// This provides fast-fail UX and diagnostic logging for direct
// connection attempts that bypass the HTTP CONNECT proxy.
let proxy_port = policy
.network
.proxy
.as_ref()
.and_then(|p| p.http_addr)
.map_or(3128, |addr| addr.port());
if let Err(e) = ns.install_bypass_rules(proxy_port) {
ocsf_emit!(
ConfigStateChangeBuilder::new(ocsf_ctx())
.severity(SeverityId::Medium)
.status(StatusId::Failure)
.state(StateId::Disabled, "degraded")
.message(format!(
"Failed to install bypass detection rules (non-fatal): {e}"
))
.build()
);
}
Some(ns)
}
Err(e) => {
return Err(miette::miette!(
"Network namespace creation failed and proxy mode requires isolation. \
Ensure CAP_NET_ADMIN and CAP_SYS_ADMIN are available and iproute2 is installed. \
Error: {e}"
));
}
}
} else {
None
};
// On non-Linux, network namespace isolation is not supported
#[cfg(not(target_os = "linux"))]
#[allow(clippy::no_effect_underscore_binding)]
let _netns: Option<()> = None;
// Shared PID: set after process spawn so the proxy can look up
// the entrypoint process's /proc/net/tcp for identity binding.
let entrypoint_pid = Arc::new(AtomicU32::new(0));
let (_proxy, denial_rx, bypass_denial_tx) = if matches!(policy.network.mode, NetworkMode::Proxy)
{
let proxy_policy = policy.network.proxy.as_ref().ok_or_else(|| {
miette::miette!("Network mode is set to proxy but no proxy configuration was provided")
})?;
let engine = opa_engine.clone().ok_or_else(|| {
miette::miette!("Proxy mode requires an OPA engine (--rego-policy and --rego-data)")
})?;
let cache = identity_cache.clone().ok_or_else(|| {
miette::miette!("Proxy mode requires an identity cache (OPA engine must be configured)")
})?;
// If we have a network namespace, bind to the veth host IP so sandboxed
// processes can reach the proxy via TCP.
#[cfg(target_os = "linux")]
let bind_addr = netns.as_ref().map(|ns| {
let port = proxy_policy.http_addr.map_or(3128, |addr| addr.port());
SocketAddr::new(ns.host_ip(), port)
});
#[cfg(not(target_os = "linux"))]
let bind_addr: Option<SocketAddr> = None;
// Build inference context for local routing of intercepted inference calls.
let inference_ctx = build_inference_context(
sandbox_id.as_deref(),
openshell_endpoint_for_proxy.as_deref(),
inference_routes.as_deref(),
)
.await?;
// Create denial aggregator channel if in gRPC mode (sandbox_id present).
// Clone the sender for the bypass monitor before passing to the proxy.
let (denial_tx, denial_rx, bypass_denial_tx) = if sandbox_id.is_some() {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
let bypass_tx = tx.clone();
(Some(tx), Some(rx), Some(bypass_tx))
} else {
(None, None, None)
};
let proxy_handle = ProxyHandle::start_with_bind_addr(
proxy_policy,
bind_addr,
engine,
cache,
entrypoint_pid.clone(),
tls_state,
inference_ctx,
secret_resolver.clone(),
denial_tx,
)
.await?;
(Some(proxy_handle), denial_rx, bypass_denial_tx)
} else {
(None, None, None)
};
// Spawn bypass detection monitor (Linux only, proxy mode only).
// Reads /dev/kmsg for iptables LOG entries and emits structured
// tracing events for direct connection attempts that bypass the proxy.
#[cfg(target_os = "linux")]
let _bypass_monitor = if netns.is_some() {
bypass_monitor::spawn(
netns.as_ref().expect("netns is Some").name().to_string(),
entrypoint_pid.clone(),
bypass_denial_tx,
)
} else {
None
};
// On non-Linux, bypass_denial_tx is unused (no /dev/kmsg).
#[cfg(not(target_os = "linux"))]
drop(bypass_denial_tx);
// Compute the proxy URL and netns fd for SSH sessions.
// SSH shell processes need both to enforce network policy:
// - netns_fd: enter the network namespace via setns() so all traffic
// goes through the veth pair (hard enforcement, non-bypassable)
// - proxy_url: set proxy env vars so cooperative tools route through the
// CONNECT proxy; this also opts Node.js into honoring those vars
#[cfg(target_os = "linux")]
let ssh_netns_fd = netns.as_ref().and_then(NetworkNamespace::ns_fd);
#[cfg(not(target_os = "linux"))]
let ssh_netns_fd: Option<i32> = None;
let ssh_proxy_url = if matches!(policy.network.mode, NetworkMode::Proxy) {
#[cfg(target_os = "linux")]
{
netns.as_ref().map(|ns| {
let port = policy
.network
.proxy
.as_ref()
.and_then(|p| p.http_addr)
.map_or(3128, |addr| addr.port());
format!("http://{}:{port}", ns.host_ip())
})
}
#[cfg(not(target_os = "linux"))]
{
policy
.network
.proxy
.as_ref()
.and_then(|p| p.http_addr)
.map(|addr| format!("http://{addr}"))
}
} else {
None
};
// Zombie reaper — openshell-sandbox may run as PID 1 in containers and
// must reap orphaned grandchildren (e.g. background daemons started by
// coding agents) to prevent zombie accumulation.
//
// Use waitid(..., WNOWAIT) so we can inspect exited children before
// actually reaping them. This avoids racing explicit `child.wait()` calls
// for managed children (entrypoint and SSH session processes).
#[cfg(target_os = "linux")]
tokio::spawn(async {
use nix::sys::wait::{Id, WaitPidFlag, WaitStatus, waitid, waitpid};
use tokio::signal::unix::{SignalKind, signal};
use tokio::time::MissedTickBehavior;
let mut sigchld = match signal(SignalKind::child()) {
Ok(s) => s,
Err(e) => {
tracing::warn!(error = %e, "Failed to register SIGCHLD handler for zombie reaping");
return;
}
};
let mut retry = tokio::time::interval(Duration::from_secs(5));
retry.set_missed_tick_behavior(MissedTickBehavior::Skip);
loop {
tokio::select! {
_ = sigchld.recv() => {}
_ = retry.tick() => {}
}
loop {
let status = match waitid(
Id::All,
WaitPidFlag::WEXITED | WaitPidFlag::WNOHANG | WaitPidFlag::WNOWAIT,
) {
Ok(WaitStatus::StillAlive) | Err(nix::errno::Errno::ECHILD) => break,
Ok(status) => status,
Err(nix::errno::Errno::EINTR) => continue,
Err(e) => {
tracing::debug!(error = %e, "waitid error during zombie reaping");
break;
}
};
let Some(pid) = status.pid() else {
break;
};
if is_managed_child(pid.as_raw()) {
// Let the explicit waiter own this child status.
break;
}
match waitpid(pid, Some(WaitPidFlag::WNOHANG)) {
Ok(WaitStatus::StillAlive) | Err(nix::errno::Errno::ECHILD) => {}
Ok(reaped) => {
tracing::debug!(?reaped, "Reaped orphaned child process");
}
Err(nix::errno::Errno::EINTR) => {}
Err(e) => {
tracing::debug!(error = %e, "waitpid error during orphan reap");
break;
}
}
}
}
});
if let Some(listen_addr) = ssh_listen_addr {
let addr: SocketAddr = listen_addr.parse().into_diagnostic()?;
let policy_clone = policy.clone();
let workdir_clone = workdir.clone();
let secret = ssh_handshake_secret
.filter(|s| !s.is_empty())
.ok_or_else(|| {
miette::miette!(
"OPENSHELL_SSH_HANDSHAKE_SECRET is required when SSH is enabled.\n\
Set --ssh-handshake-secret or the OPENSHELL_SSH_HANDSHAKE_SECRET env var."
)
})?;
let proxy_url = ssh_proxy_url;
let netns_fd = ssh_netns_fd;
let ca_paths = ca_file_paths.clone();
let provider_env_clone = provider_env.clone();
let (ssh_ready_tx, ssh_ready_rx) = tokio::sync::oneshot::channel();
tokio::spawn(async move {
if let Err(err) = ssh::run_ssh_server(
addr,
ssh_ready_tx,
policy_clone,
workdir_clone,
secret,
ssh_handshake_skew_secs,
netns_fd,
proxy_url,
ca_paths,
provider_env_clone,
)
.await
{
ocsf_emit!(
AppLifecycleBuilder::new(ocsf_ctx())
.activity(ActivityId::Fail)
.severity(SeverityId::Critical)
.status(StatusId::Failure)
.message(format!("SSH server failed: {err}"))
.build()
);
}
});
// Wait for the SSH server to bind its socket before spawning the
// entrypoint process. This prevents exec requests from racing against
// SSH server startup when Kubernetes marks the pod Ready.
match timeout(Duration::from_secs(10), ssh_ready_rx).await {
Ok(Ok(Ok(()))) => {
ocsf_emit!(
AppLifecycleBuilder::new(ocsf_ctx())
.activity(ActivityId::Open)
.severity(SeverityId::Informational)
.status(StatusId::Success)
.message("SSH server is ready to accept connections")
.build()
);
}
Ok(Ok(Err(err))) => {
return Err(err.context("SSH server failed during startup"));
}
Ok(Err(_)) => {
return Err(miette::miette!(
"SSH server task panicked before signaling ready"
));
}
Err(_) => {
return Err(miette::miette!(
"SSH server did not start within 10 seconds"
));
}
}
}
#[cfg(target_os = "linux")]
let mut handle = ProcessHandle::spawn(
program,
args,
workdir.as_deref(),
interactive,
&policy,
netns.as_ref(),
ca_file_paths.as_ref(),
&provider_env,
)?;
#[cfg(not(target_os = "linux"))]
let mut handle = ProcessHandle::spawn(
program,
args,
workdir.as_deref(),
interactive,
&policy,
ca_file_paths.as_ref(),
&provider_env,
)?;
// Store the entrypoint PID so the proxy can resolve TCP peer identity
entrypoint_pid.store(handle.pid(), Ordering::Release);
ocsf_emit!(
ProcessActivityBuilder::new(ocsf_ctx())
.activity(ActivityId::Open)
.action(ActionId::Allowed)
.disposition(DispositionId::Allowed)
.severity(SeverityId::Informational)
.status(StatusId::Success)
.launch_type(LaunchTypeId::Spawn)
.process(OcsfProcess::new(program, i64::from(handle.pid())))
.message(format!("Process started: pid={}", handle.pid()))
.build()
);
// Spawn a task to resolve policy binary symlinks after the container
// filesystem becomes accessible via /proc/<pid>/root/. This expands
// symlinks like /usr/bin/python3 → /usr/bin/python3.11 in the OPA
// policy data so that either path matches at evaluation time.
//
// We cannot do this synchronously here because the child process has
// just been spawned and its mount namespace / procfs entries may not
// be fully populated yet. Instead, we probe with retries until
// /proc/<pid>/root/ is accessible or we exhaust attempts.
if let (Some(engine), Some(proto)) = (&opa_engine, &retained_proto) {
let resolve_engine = engine.clone();
let resolve_proto = proto.clone();
let resolve_pid = entrypoint_pid.clone();
tokio::spawn(async move {
let pid = resolve_pid.load(Ordering::Acquire);
let probe_path = format!("/proc/{pid}/root/");
// Retry up to 10 times with 500ms intervals (5s total).
// The child's mount namespace is typically ready within a
// few hundred ms of spawn.
for attempt in 1..=10 {
tokio::time::sleep(Duration::from_millis(500)).await;
if std::fs::metadata(&probe_path).is_ok() {
info!(
pid = pid,
attempt = attempt,
"Container filesystem accessible, resolving policy binary symlinks"
);
match resolve_engine.reload_from_proto_with_pid(&resolve_proto, pid) {
Ok(()) => {
info!(
pid = pid,
"Policy binary symlink resolution complete \
(check logs above for per-binary results)"
);
}
Err(e) => {
warn!(
"Failed to rebuild OPA engine with symlink resolution \
(non-fatal, falling back to literal path matching): {e}"
);
}
}
return;
}
debug!(
pid = pid,
attempt = attempt,
probe_path = %probe_path,
"Container filesystem not yet accessible, retrying symlink resolution"
);
}
warn!(
"Container filesystem /proc/{pid}/root/ not accessible after 10 attempts (5s); \
binary symlink resolution skipped. Policy binary paths will be matched literally. \
If binaries are symlinks, use canonical paths in your policy \
(run 'readlink -f <path>' inside the sandbox)"
);
});
}
// Spawn background policy poll task (gRPC mode only).
if let (Some(id), Some(endpoint), Some(engine)) =
(&sandbox_id, &openshell_endpoint, &opa_engine)
{
let poll_id = id.clone();
let poll_endpoint = endpoint.clone();
let poll_engine = engine.clone();
let poll_ocsf_enabled = ocsf_enabled.clone();
let poll_pid = entrypoint_pid.clone();
let poll_interval_secs: u64 = std::env::var("OPENSHELL_POLICY_POLL_INTERVAL_SECS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(10);
tokio::spawn(async move {
if let Err(e) = run_policy_poll_loop(
&poll_endpoint,
&poll_id,
&poll_engine,
&poll_pid,
poll_interval_secs,
&poll_ocsf_enabled,
)
.await
{
ocsf_emit!(
AppLifecycleBuilder::new(ocsf_ctx())
.activity(ActivityId::Fail)
.severity(SeverityId::Medium)
.status(StatusId::Failure)
.message(format!("Policy poll loop exited with error: {e}"))
.build()
);
}
});
// Spawn denial aggregator (gRPC mode only, when proxy is active).
if let Some(rx) = denial_rx {
// SubmitPolicyAnalysis resolves by sandbox *name*, not UUID.
let agg_name = sandbox_name_for_agg.clone().unwrap_or_else(|| id.clone());
let agg_endpoint = endpoint.clone();
let flush_interval_secs: u64 = std::env::var("OPENSHELL_DENIAL_FLUSH_INTERVAL_SECS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(10);
let aggregator = denial_aggregator::DenialAggregator::new(rx, flush_interval_secs);
tokio::spawn(async move {
aggregator
.run(|summaries| {
let endpoint = agg_endpoint.clone();
let sandbox_name = agg_name.clone();
async move {
if let Err(e) =
flush_proposals_to_gateway(&endpoint, &sandbox_name, summaries)
.await
{
warn!(error = %e, "Failed to flush denial summaries to gateway");
}
}
})
.await;
});
}
}
// Wait for process with optional timeout
let result = if timeout_secs > 0 {
if let Ok(result) = timeout(Duration::from_secs(timeout_secs), handle.wait()).await {
result
} else {
ocsf_emit!(
ProcessActivityBuilder::new(ocsf_ctx())
.activity(ActivityId::Close)
.action(ActionId::Denied)
.disposition(DispositionId::Blocked)
.severity(SeverityId::Critical)
.status(StatusId::Failure)
.message("Process timed out, killing")
.build()
);
handle.kill()?;
return Ok(124); // Standard timeout exit code
}
} else {
handle.wait().await
};
let status = result.into_diagnostic()?;
ocsf_emit!(
ProcessActivityBuilder::new(ocsf_ctx())
.activity(ActivityId::Close)
.action(ActionId::Allowed)
.disposition(DispositionId::Allowed)
.severity(SeverityId::Informational)
.status(StatusId::Success)
.exit_code(status.code())
.message(format!("Process exited with code {}", status.code()))
.build()
);
Ok(status.code())
}
/// Build an inference context for local routing, if route sources are available.
///
/// Route sources (in priority order):
/// 1. Inference routes file (standalone mode) — always takes precedence
/// 2. Cluster bundle (fetched from gateway via gRPC)
///
/// If both a routes file and cluster credentials are provided, the routes file
/// wins and the cluster bundle is not fetched.
///
/// Returns `None` if neither source is configured (inference routing disabled).
async fn build_inference_context(
sandbox_id: Option<&str>,
openshell_endpoint: Option<&str>,
inference_routes: Option<&str>,
) -> Result<Option<Arc<proxy::InferenceContext>>> {
use openshell_router::Router;
use openshell_router::config::RouterConfig;
let source = infer_route_source(sandbox_id, openshell_endpoint, inference_routes);
// Captured during the initial cluster bundle fetch so the background refresh
// loop can skip no-op updates from the very first tick.
let mut initial_revision: Option<String> = None;
let routes = match source {
InferenceRouteSource::File => {
let Some(path) = inference_routes else {
return Ok(None);
};
// Standalone mode: load routes from file (fail-fast on errors)
if sandbox_id.is_some() {
ocsf_emit!(ConfigStateChangeBuilder::new(ocsf_ctx())
.severity(SeverityId::Informational)
.status(StatusId::Success)
.state(StateId::Enabled, "loaded")
.unmapped("inference_routes", serde_json::json!(path))
.message(format!(
"Inference routes file takes precedence over cluster bundle [path:{path}]"
))
.build());
}
ocsf_emit!(
ConfigStateChangeBuilder::new(ocsf_ctx())
.severity(SeverityId::Informational)
.status(StatusId::Success)
.state(StateId::Other, "loading")
.unmapped("inference_routes", serde_json::json!(path))
.message(format!("Loading inference routes from file [path:{path}]"))
.build()
);
let config = RouterConfig::load_from_file(std::path::Path::new(path))
.map_err(|e| miette::miette!("failed to load inference routes {path}: {e}"))?;
config
.resolve_routes()
.map_err(|e| miette::miette!("failed to resolve routes from {path}: {e}"))?
}
InferenceRouteSource::Cluster => {
let (Some(_id), Some(endpoint)) = (sandbox_id, openshell_endpoint) else {
return Ok(None);
};
// Cluster mode: fetch bundle from gateway
info!(endpoint = %endpoint, "Fetching inference route bundle from gateway");
match grpc_client::fetch_inference_bundle(endpoint).await {
Ok(bundle) => {
initial_revision = Some(bundle.revision.clone());
ocsf_emit!(
ConfigStateChangeBuilder::new(ocsf_ctx())
.severity(SeverityId::Informational)
.status(StatusId::Success)
.state(StateId::Enabled, "loaded")
.unmapped("route_count", serde_json::json!(bundle.routes.len()))
.unmapped("revision", serde_json::json!(&bundle.revision))
.message(format!(
"Loaded inference route bundle [route_count:{} revision:{}]",
bundle.routes.len(),
bundle.revision
))
.build()
);
bundle_to_resolved_routes(&bundle)
}
Err(e) => {
// Distinguish expected "not configured" states from server errors.
// gRPC PermissionDenied/NotFound means inference bundle is unavailable
// for this sandbox — skip gracefully. Other errors are unexpected.
let msg = e.to_string();
if msg.contains("permission denied") || msg.contains("not found") {
ocsf_emit!(
ConfigStateChangeBuilder::new(ocsf_ctx())
.severity(SeverityId::Informational)
.status(StatusId::Success)
.state(StateId::Disabled, "disabled")
.unmapped("error", serde_json::json!(e.to_string()))
.message(format!(
"Inference bundle unavailable, routing disabled [error:{e}]"
))
.build()
);
return Ok(None);
}
ocsf_emit!(ConfigStateChangeBuilder::new(ocsf_ctx())
.severity(SeverityId::Medium)
.status(StatusId::Failure)
.state(StateId::Disabled, "disabled")
.unmapped("error", serde_json::json!(e.to_string()))
.message(format!(
"Failed to fetch inference bundle, inference routing disabled [error:{e}]"
))
.build());
return Ok(None);
}
}
}
InferenceRouteSource::None => {