From a31ab56bdec6a1ea89f5b16f2874e42430f958c8 Mon Sep 17 00:00:00 2001 From: Drew Newberry Date: Mon, 23 Nov 2026 22:30:03 -0800 Subject: [PATCH 1/3] feat(sandbox): add privileged VM sandbox mode with BPF LSM seal Signed-off-by: Drew Newberry --- Cargo.lock | 40 + crates/openshell-cli/src/main.rs | 8 + crates/openshell-cli/src/run.rs | 5 + .../openshell-driver-docker/src/isolation.rs | 2 + crates/openshell-driver-docker/src/lib.rs | 6 + .../openshell-driver-kubernetes/src/config.rs | 6 + .../openshell-driver-kubernetes/src/driver.rs | 222 ++-- .../src/isolation.rs | 7 + .../openshell-driver-kubernetes/src/main.rs | 4 + crates/openshell-driver-podman/src/driver.rs | 6 + .../openshell-driver-podman/src/isolation.rs | 2 + .../runtime/kernel/openshell.kconfig | 50 +- .../scripts/openshell-vm-sandbox-init.sh | 64 +- crates/openshell-driver-vm/src/driver.rs | 36 +- .../src/embedded_runtime.rs | 27 +- .../openshell-driver-vm/src/isolation/mod.rs | 7 + crates/openshell-sandbox-backend/src/audit.rs | 25 + .../src/boundary_protocol.rs | 9 + .../src/delegated.rs | 1 + .../src/isolation_protocol.rs | 1 + crates/openshell-sandbox-backend/src/lib.rs | 1 + .../src/privileged.rs | 119 +++ .../openshell-sandbox-backend/src/runtime.rs | 16 +- .../src/runtime/test_support.rs | 1 + crates/openshell-sandbox/Cargo.toml | 1 + .../openshell-sandbox/bpf/openshell_lsm.bpf.c | 945 ++++++++++++++++++ crates/openshell-sandbox/build.rs | 54 + crates/openshell-sandbox/src/boundary_exec.rs | 142 ++- .../openshell-sandbox/src/boundary_server.rs | 272 ++++- crates/openshell-sandbox/src/lib.rs | 11 + .../src/linux/child_seccomp.rs | 74 ++ .../src/linux/seccomp_notify.rs | 24 + .../src/linux/workload_launcher.rs | 37 +- crates/openshell-sandbox/src/main.rs | 83 +- .../src/privileged/bpf_lsm.rs | 474 +++++++++ .../openshell-sandbox/src/privileged/mod.rs | 491 +++++++++ .../src/privileged/path_view.rs | 91 ++ .../src/privileged/placement.rs | 786 +++++++++++++++ crates/openshell-sandbox/src/process.rs | 74 +- crates/openshell-sdk/src/client.rs | 2 + crates/openshell-sdk/src/types.rs | 2 + crates/openshell-server/src/compute/mod.rs | 21 + crates/openshell-server/src/test_support.rs | 1 + .../src/backend_setup/tests.rs | 1 + deploy/helm/openshell/README.md | 1 + deploy/helm/openshell/templates/_helpers.tpl | 2 +- deploy/helm/openshell/values.yaml | 4 + e2e/rust/Cargo.toml | 5 + e2e/rust/e2e-vm.sh | 7 +- e2e/rust/tests/vm_privileged.rs | 298 ++++++ proto/compute_driver.proto | 6 + proto/openshell.proto | 4 + tasks/scripts/vm/build-libkrun.sh | 35 +- tests/testkit/testkit/src/context.rs | 2 + 54 files changed, 4487 insertions(+), 128 deletions(-) create mode 100644 crates/openshell-sandbox-backend/src/privileged.rs create mode 100644 crates/openshell-sandbox/bpf/openshell_lsm.bpf.c create mode 100644 crates/openshell-sandbox/build.rs create mode 100644 crates/openshell-sandbox/src/privileged/bpf_lsm.rs create mode 100644 crates/openshell-sandbox/src/privileged/mod.rs create mode 100644 crates/openshell-sandbox/src/privileged/path_view.rs create mode 100644 crates/openshell-sandbox/src/privileged/placement.rs create mode 100644 e2e/rust/tests/vm_privileged.rs diff --git a/Cargo.lock b/Cargo.lock index aa9b3e450e..1b328d3d5e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -307,6 +307,12 @@ dependencies = [ "serde_json", ] +[[package]] +name = "assert_matches" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9" + [[package]] name = "async-broadcast" version = "0.7.2" @@ -772,6 +778,36 @@ dependencies = [ "tracing", ] +[[package]] +name = "aya" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66e644424fada9fff4fdc63848db1732fb69b626e8328202ef55c03df1f4d939" +dependencies = [ + "assert_matches", + "aya-obj", + "bitflags 2.13.2", + "hashbrown 0.17.0", + "libc", + "log", + "object 0.39.1", + "once_cell", + "scopeguard", + "thiserror 2.0.20", +] + +[[package]] +name = "aya-obj" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c76b9c75d9cdc155ff8f6a06d61e873f67bf47be8cfa92a3b5aaea43f4b4077" +dependencies = [ + "bytes", + "log", + "object 0.39.1", + "thiserror 2.0.20", +] + [[package]] name = "backon" version = "1.6.0" @@ -4655,6 +4691,9 @@ version = "0.39.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" dependencies = [ + "crc32fast", + "hashbrown 0.17.0", + "indexmap 2.14.0", "memchr", ] @@ -5582,6 +5621,7 @@ version = "0.0.0" dependencies = [ "anyhow", "async-trait", + "aya", "base64 0.22.1", "bytes", "clap", diff --git a/crates/openshell-cli/src/main.rs b/crates/openshell-cli/src/main.rs index 8b362d6328..2ef8cbec86 100644 --- a/crates/openshell-cli/src/main.rs +++ b/crates/openshell-cli/src/main.rs @@ -1718,6 +1718,12 @@ enum SandboxCommands { #[arg(long, value_parser = ["manual", "auto"], default_value = "manual")] approval_mode: String, + /// Run the sandbox workload as true guest root inside a hardened VM + /// boundary sealed by boot-once BPF LSM. Requires a compute driver that + /// supports privileged mode. + #[arg(long, visible_alias = "priv")] + privileged: bool, + /// Output format. #[arg(short = 'o', long = "output", value_enum, default_value_t = OutputFormat::Table, conflicts_with_all = ["editor", "no_keep", "forward"])] output: OutputFormat, @@ -3655,6 +3661,7 @@ async fn run_async() -> Result<()> { env_from, no_credential_warnings, approval_mode, + privileged, output, command, } => { @@ -3753,6 +3760,7 @@ async fn run_async() -> Result<()> { restart_policy: &restart_policy, provision_timeout_secs: timeout.map(std::num::NonZeroU32::get), create_retry_timeout_secs, + privileged, }, &cli.workspace, &tls, diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index 3a7e45582c..2c67c175c6 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -440,6 +440,7 @@ async fn finalize_sandbox_create_session( /// on the function signature, following the `provider_refresh_config(server, input, tls)` /// precedent. This struct captures sandbox-specific options. #[derive(Debug)] +#[allow(clippy::struct_excessive_bools)] pub struct SandboxCreateConfig<'a> { pub name: Option<&'a str>, pub template: Option<&'a str>, @@ -472,6 +473,7 @@ pub struct SandboxCreateConfig<'a> { /// disables retries; `None` reads `OPENSHELL_CREATE_RETRY_TIMEOUT` or the /// 60s default. pub create_retry_timeout_secs: Option, + pub privileged: bool, } impl Default for SandboxCreateConfig<'_> { @@ -505,6 +507,7 @@ impl Default for SandboxCreateConfig<'_> { restart_policy: "never", provision_timeout_secs: None, create_retry_timeout_secs: None, + privileged: false, } } } @@ -1051,6 +1054,7 @@ pub async fn sandbox_create( restart_policy, provision_timeout_secs, create_retry_timeout_secs, + privileged, } = config; if editor.is_some() && !command.is_empty() { @@ -1215,6 +1219,7 @@ pub async fn sandbox_create( "always" => SandboxRestartPolicy::Always as i32, value => return Err(miette::miette!("invalid restart policy '{value}'")), }, + privileged, ..SandboxSpec::default() }), name: name.unwrap_or_default().to_string(), diff --git a/crates/openshell-driver-docker/src/isolation.rs b/crates/openshell-driver-docker/src/isolation.rs index 9935ff0cbe..204baa7acf 100644 --- a/crates/openshell-driver-docker/src/isolation.rs +++ b/crates/openshell-driver-docker/src/isolation.rs @@ -118,6 +118,7 @@ impl DockerBoundarySpec { workload_identity: self.workload_identity.clone(), provisioning_evidence: provisioning_evidence.clone(), child_env: self.child_env, + privileged: None, }, runtime_descriptor: SandboxRuntimeDescriptor { boundary_id: self.boundary_id, @@ -131,6 +132,7 @@ impl DockerBoundarySpec { host_gateway_ip: self.host_gateway_ip, resource_claims, provisioning_evidence, + privileged: None, }, }) } diff --git a/crates/openshell-driver-docker/src/lib.rs b/crates/openshell-driver-docker/src/lib.rs index 75e894bd5e..19a4519e62 100644 --- a/crates/openshell-driver-docker/src/lib.rs +++ b/crates/openshell-driver-docker/src/lib.rs @@ -1137,6 +1137,7 @@ impl DockerComputeDriver { Vec::new() }, )), + supports_privileged: false, } } @@ -1161,6 +1162,11 @@ impl DockerComputeDriver { .spec .as_ref() .ok_or_else(|| Status::invalid_argument("sandbox.spec is required"))?; + if spec.privileged { + return Err(Status::failed_precondition( + "privileged sandboxes are not supported by the docker compute driver", + )); + } let template = spec .template .as_ref() diff --git a/crates/openshell-driver-kubernetes/src/config.rs b/crates/openshell-driver-kubernetes/src/config.rs index 82f98cdb54..3dbcfdd41e 100644 --- a/crates/openshell-driver-kubernetes/src/config.rs +++ b/crates/openshell-driver-kubernetes/src/config.rs @@ -430,6 +430,11 @@ pub struct KubernetesComputeConfig { /// by the gateway administrator; sandbox creators cannot change it, and /// it never inherits the workload class. Empty (default) = omit the field. pub supervisor_runtime_class_name: String, + /// Kubernetes `runtimeClassName` used for `--privileged` (true guest root + + /// boot-once BPF LSM) sandbox pods, such as a hardened Kata Containers class. + /// Empty (default) disables privileged sandboxes on Kubernetes. + #[serde(default)] + pub privileged_runtime_class_name: String, /// Pod annotation keys that sandbox templates may set. Each entry is an /// exact key (`example.com/team`) or a prefix wildcard (`example.com/*`). /// Empty (default) rejects every caller-supplied pod annotation. @@ -552,6 +557,7 @@ impl Default for KubernetesComputeConfig { workspace_storage_class: String::new(), default_runtime_class_name: String::new(), supervisor_runtime_class_name: String::new(), + privileged_runtime_class_name: String::new(), allowed_pod_annotations: Vec::new(), allowed_pod_labels: Vec::new(), sa_token_ttl_secs: 3600, diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index fab746d814..a941ed66c6 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -1327,6 +1327,7 @@ impl KubernetesComputeDriver { .to_string(), ], )), + supports_privileged: !self.config.privileged_runtime_class_name.is_empty(), }) } @@ -2153,6 +2154,8 @@ impl KubernetesComputeDriver { default_image: &self.config.default_image, image_pull_secrets: &self.config.image_pull_secrets, default_runtime_class_name: &self.config.default_runtime_class_name, + privileged_runtime_class_name: &self.config.privileged_runtime_class_name, + privileged: sandbox.spec.as_ref().is_some_and(|spec| spec.privileged), service_account_name: &self.config.service_account_name, ..Default::default() }; @@ -2569,6 +2572,13 @@ impl KubernetesComputeDriver { sandbox, ) .map_err(admission_error)?; + let is_privileged = sandbox.spec.as_ref().is_some_and(|spec| spec.privileged); + if is_privileged && self.config.privileged_runtime_class_name.is_empty() { + return Err(KubernetesDriverError::InvalidArgument( + "privileged sandboxes require a configured kubernetes privileged_runtime_class_name (for example a hardened Kata Containers RuntimeClass)" + .to_string(), + )); + } self.validate_pod_metadata_for_sandbox(sandbox) .map_err(KubernetesDriverError::InvalidArgument)?; let gpu_requirements = sandbox @@ -2652,6 +2662,8 @@ impl KubernetesComputeDriver { workspace_default_storage_size: &self.config.workspace_default_storage_size, workspace_storage_class: &self.config.workspace_storage_class, default_runtime_class_name: &self.config.default_runtime_class_name, + privileged_runtime_class_name: &self.config.privileged_runtime_class_name, + privileged: is_privileged, sandbox_uid: resolved_user_id, sandbox_gid: resolved_group_id, boundary_port: self.config.sandbox_runtime.boundary_port, @@ -2672,6 +2684,9 @@ impl KubernetesComputeDriver { } let mut obj = DynamicObject::new(&kube_name, &agent_sandbox_api.resource); let mut annotations = sandbox_annotations(sandbox); + if is_privileged { + annotations.insert(ANNOTATION_SANDBOX_PRIVILEGED.into(), "true".into()); + } annotations.insert( crate::resource_admission::IDENTITIES.into(), serde_json::to_string(&resource_identities) @@ -3112,6 +3127,7 @@ impl KubernetesComputeDriver { uid: u32, gid: u32, sandbox_secret_name: &str, + privileged_runtime_class: Option<&str>, ) -> Result<(), KubernetesDriverError> { let fail = |message: &str| { KubernetesDriverError::Precondition(format!( @@ -3190,7 +3206,13 @@ impl KubernetesComputeDriver { .security_context .as_ref() .ok_or_else(|| fail("missing Pod security context"))?; - if security.run_as_user != Some(i64::from(uid)) + if let Some(expected_rc) = privileged_runtime_class { + if spec.runtime_class_name.as_deref() != Some(expected_rc) { + return Err(fail( + "privileged Pod runtimeClassName does not match configured privileged_runtime_class_name", + )); + } + } else if security.run_as_user != Some(i64::from(uid)) || security.run_as_group != Some(i64::from(gid)) || security.run_as_non_root != Some(true) || security.fs_group != Some(i64::from(gid)) @@ -3207,19 +3229,21 @@ impl KubernetesComputeDriver { } let pod_json = serde_json::to_value(pod) .map_err(|error| KubernetesDriverError::Message(error.to_string()))?; - if let Some(policy) = pod_json.pointer("/spec/securityContext/supplementalGroupsPolicy") - && policy != &serde_json::json!("Strict") - { - return Err(fail("supplementalGroupsPolicy is not Strict")); - } - if pod_json - .pointer("/spec/securityContext/supplementalGroupsPolicy") - .is_none() - { - tracing::warn!( - pod = pod.metadata.name.as_deref().unwrap_or(""), - "Kubernetes omitted supplementalGroupsPolicy; exact runtime groups remain enforced by boundary confirmation" - ); + if privileged_runtime_class.is_none() { + if let Some(policy) = pod_json.pointer("/spec/securityContext/supplementalGroupsPolicy") + && policy != &serde_json::json!("Strict") + { + return Err(fail("supplementalGroupsPolicy is not Strict")); + } + if pod_json + .pointer("/spec/securityContext/supplementalGroupsPolicy") + .is_none() + { + tracing::warn!( + pod = pod.metadata.name.as_deref().unwrap_or(""), + "Kubernetes omitted supplementalGroupsPolicy; exact runtime groups remain enforced by boundary confirmation" + ); + } } let unprivileged_port_sysctl = pod_json .pointer("/spec/securityContext/sysctls") @@ -3267,7 +3291,20 @@ impl KubernetesComputeDriver { .iter() .find(|container| container.name == "agent") .ok_or_else(|| fail("agent container missing"))?; - check_container(agent, "agent")?; + if privileged_runtime_class.is_some() { + let context = agent + .security_context + .as_ref() + .ok_or_else(|| fail("privileged agent container has no security context"))?; + if context.privileged != Some(true) + || context.run_as_user != Some(0) + || context.run_as_group != Some(0) + { + return Err(fail("privileged agent security context changed")); + } + } else { + check_container(agent, "agent")?; + } let bootstrap = spec .init_containers .as_deref() @@ -3834,6 +3871,23 @@ impl KubernetesComputeDriver { self.admit_stored_resources(&admission_object) .await .map_err(admission_error)?; + let is_privileged = admission_object + .metadata + .annotations + .as_ref() + .and_then(|annotations| annotations.get(ANNOTATION_SANDBOX_PRIVILEGED)) + .is_some_and(|value| value == "true"); + let privileged_runtime_class = if is_privileged { + if self.config.privileged_runtime_class_name.is_empty() { + return Err(KubernetesDriverError::Precondition( + "privileged Sandbox cannot launch without a configured privileged_runtime_class_name" + .to_string(), + )); + } + Some(self.config.privileged_runtime_class_name.as_str()) + } else { + None + }; Self::validate_capability_free_workload_pod( &workload_pod, cr_uid, @@ -3841,6 +3895,7 @@ impl KubernetesComputeDriver { agent_uid, agent_gid, &names.sandbox_secret, + privileged_runtime_class, )?; let workload_pod_uid = workload_pod.metadata.uid.clone().ok_or_else(|| { @@ -3944,6 +3999,7 @@ impl KubernetesComputeDriver { host_gateway_ip: self.config.host_gateway_ip.parse().ok(), workload_identity, child_env, + privileged: is_privileged, } .provision() .map_err(|error| KubernetesDriverError::Message(error.to_string()))?; @@ -7377,6 +7433,8 @@ fn extract_image_size(message: &str) -> Option { const SANDBOX_RUNTIME_VOLUME_NAME: &str = "openshell-runtime"; const SANDBOX_STATE_VOLUME_NAME: &str = "openshell-runtime-state"; +const ANNOTATION_SANDBOX_PRIVILEGED: &str = "openshell.ai/privileged"; + const SANDBOX_BOOTSTRAP_VOLUME_NAME: &str = "openshell-sandbox-bootstrap"; const SANDBOX_BOOTSTRAP_CONTAINER_NAME: &str = "openshell-sandbox-bootstrap"; const SANDBOX_POD_IDENTITY_VOLUME_NAME: &str = "openshell-pod-identity"; @@ -7491,20 +7549,31 @@ fn apply_supervisor_sandbox_runtime_boundary( ] }), ); - spec.insert( - "securityContext".to_string(), - serde_json::json!({ - "runAsUser": params.sandbox_uid, - "runAsGroup": params.sandbox_gid, - "runAsNonRoot": true, - "fsGroup": params.sandbox_gid, - "fsGroupChangePolicy": "OnRootMismatch", - "supplementalGroups": [], - "supplementalGroupsPolicy": "Strict", - "seccompProfile": {"type": "RuntimeDefault"}, - "sysctls": [{"name": "net.ipv4.ip_unprivileged_port_start", "value": "0"}] - }), - ); + if params.privileged { + spec.insert( + "securityContext".to_string(), + serde_json::json!({ + "fsGroup": params.sandbox_gid, + "fsGroupChangePolicy": "OnRootMismatch", + "sysctls": [{"name": "net.ipv4.ip_unprivileged_port_start", "value": "0"}] + }), + ); + } else { + spec.insert( + "securityContext".to_string(), + serde_json::json!({ + "runAsUser": params.sandbox_uid, + "runAsGroup": params.sandbox_gid, + "runAsNonRoot": true, + "fsGroup": params.sandbox_gid, + "fsGroupChangePolicy": "OnRootMismatch", + "supplementalGroups": [], + "supplementalGroupsPolicy": "Strict", + "seccompProfile": {"type": "RuntimeDefault"}, + "sysctls": [{"name": "net.ipv4.ip_unprivileged_port_start", "value": "0"}] + }), + ); + } let volumes = spec .entry("volumes") .or_insert_with(|| serde_json::json!([])) @@ -7569,24 +7638,48 @@ fn apply_supervisor_sandbox_runtime_boundary( let container = containers[index] .as_object_mut() .expect("agent container must be an object"); - container.insert( - "command".to_string(), - serde_json::json!([ - format!("{SANDBOX_RUNTIME_MOUNT_PATH}/openshell-sandbox"), - "--bootstrap", - BOUNDARY_CONFIG_PATH, - ]), - ); - container.insert( - "securityContext".to_string(), - serde_json::json!({ - "runAsUser": params.sandbox_uid, - "runAsGroup": params.sandbox_gid, - "runAsNonRoot": true, - "allowPrivilegeEscalation": false, - "capabilities": {"drop": ["ALL"]} - }), - ); + if params.privileged { + container.insert( + "command".to_string(), + serde_json::json!([ + format!("{SANDBOX_RUNTIME_MOUNT_PATH}/openshell-sandbox"), + "--bootstrap", + BOUNDARY_CONFIG_PATH, + "--privileged", + "--workload-root", + "/", + ]), + ); + container.insert( + "securityContext".to_string(), + serde_json::json!({ + "privileged": true, + "runAsUser": 0, + "runAsGroup": 0, + "allowPrivilegeEscalation": true, + "seccompProfile": {"type": "Unconfined"} + }), + ); + } else { + container.insert( + "command".to_string(), + serde_json::json!([ + format!("{SANDBOX_RUNTIME_MOUNT_PATH}/openshell-sandbox"), + "--bootstrap", + BOUNDARY_CONFIG_PATH, + ]), + ); + container.insert( + "securityContext".to_string(), + serde_json::json!({ + "runAsUser": params.sandbox_uid, + "runAsGroup": params.sandbox_gid, + "runAsNonRoot": true, + "allowPrivilegeEscalation": false, + "capabilities": {"drop": ["ALL"]} + }), + ); + } container.insert( "ports".to_string(), serde_json::json!([{ @@ -7827,6 +7920,8 @@ struct SandboxPodParams<'a> { workspace_default_storage_size: &'a str, workspace_storage_class: &'a str, default_runtime_class_name: &'a str, + privileged_runtime_class_name: &'a str, + privileged: bool, /// Resolved sandbox UID for supervisor `runAsUser` and env var. sandbox_uid: u32, /// Resolved sandbox GID for PVC init container operations. @@ -7851,6 +7946,8 @@ impl Default for SandboxPodParams<'_> { workspace_default_storage_size: DEFAULT_WORKSPACE_STORAGE_SIZE, workspace_storage_class: "", default_runtime_class_name: "", + privileged_runtime_class_name: "", + privileged: false, sandbox_uid: DEFAULT_SANDBOX_UID, sandbox_gid: DEFAULT_SANDBOX_UID, boundary_port: 5500, @@ -8038,15 +8135,20 @@ fn sandbox_template_to_k8s_with_validated_config( } let mut spec = serde_json::Map::new(); - let runtime_class_name = platform_config_string(template, "runtime_class_name") - .or_else(|| { - (!driver_config.pod.runtime_class_name.is_empty()) - .then(|| driver_config.pod.runtime_class_name.clone()) - }) - .or_else(|| { - (!params.default_runtime_class_name.is_empty()) - .then(|| params.default_runtime_class_name.to_string()) - }); + let runtime_class_name = if params.privileged { + (!params.privileged_runtime_class_name.is_empty()) + .then(|| params.privileged_runtime_class_name.to_string()) + } else { + platform_config_string(template, "runtime_class_name") + .or_else(|| { + (!driver_config.pod.runtime_class_name.is_empty()) + .then(|| driver_config.pod.runtime_class_name.clone()) + }) + .or_else(|| { + (!params.default_runtime_class_name.is_empty()) + .then(|| params.default_runtime_class_name.to_string()) + }) + }; if let Some(runtime_class) = runtime_class_name { spec.insert( "runtimeClassName".to_string(), @@ -8063,9 +8165,11 @@ fn sandbox_template_to_k8s_with_validated_config( // Per-sandbox portable intent overrides the cluster-wide default. This // driver owns the Kubernetes-specific `hostUsers` translation. - let use_user_namespaces = template - .user_namespaces - .unwrap_or(params.enable_user_namespaces); + // Privileged Kata Pods use VM isolation instead of host user namespaces. + let use_user_namespaces = !params.privileged + && template + .user_namespaces + .unwrap_or(params.enable_user_namespaces); if use_user_namespaces { spec.insert("hostUsers".to_string(), serde_json::json!(false)); diff --git a/crates/openshell-driver-kubernetes/src/isolation.rs b/crates/openshell-driver-kubernetes/src/isolation.rs index d943bac705..d2e10b481c 100644 --- a/crates/openshell-driver-kubernetes/src/isolation.rs +++ b/crates/openshell-driver-kubernetes/src/isolation.rs @@ -408,6 +408,7 @@ pub struct KubernetesSandboxRuntimeBoundarySpec { pub host_gateway_ip: Option, pub workload_identity: ResolvedWorkloadIdentity, pub child_env: HashMap, + pub privileged: bool, } /// Protected workload-pod config and matching sandbox-runtime descriptor. @@ -548,6 +549,9 @@ impl KubernetesSandboxRuntimeBoundarySpec { }), } .project(&self.generation)?; + let privileged = self + .privileged + .then_some(openshell_sandbox_backend::privileged::PrivilegedGuestProfile::vm_bpf_lsm()); Ok(KubernetesSandboxRuntimeBoundaryProvisioning { boundary_config: BoundaryConfig { boundary_id: self.boundary_id.clone(), @@ -566,6 +570,7 @@ impl KubernetesSandboxRuntimeBoundarySpec { workload_identity: self.workload_identity.clone(), provisioning_evidence: provisioning_evidence.clone(), child_env: self.child_env, + privileged, }, runtime_descriptor: SandboxRuntimeDescriptor { boundary_id: self.boundary_id, @@ -577,6 +582,7 @@ impl KubernetesSandboxRuntimeBoundarySpec { host_gateway_ip: self.host_gateway_ip, resource_claims, provisioning_evidence, + privileged, }, }) } @@ -676,6 +682,7 @@ mod tests { ) .unwrap(), child_env: HashMap::new(), + privileged: false, } } diff --git a/crates/openshell-driver-kubernetes/src/main.rs b/crates/openshell-driver-kubernetes/src/main.rs index 9f2b18068a..663ba3e715 100644 --- a/crates/openshell-driver-kubernetes/src/main.rs +++ b/crates/openshell-driver-kubernetes/src/main.rs @@ -336,6 +336,10 @@ async fn main() -> Result<()> { "OPENSHELL_K8S_SUPERVISOR_RUNTIME_CLASS_NAME", ) .unwrap_or_default(), + privileged_runtime_class_name: std::env::var( + "OPENSHELL_K8S_PRIVILEGED_RUNTIME_CLASS_NAME", + ) + .unwrap_or_default(), allowed_pod_annotations: args.allowed_pod_annotations, allowed_pod_labels: args.allowed_pod_labels, sa_token_ttl_secs: args.sa_token_ttl_secs, diff --git a/crates/openshell-driver-podman/src/driver.rs b/crates/openshell-driver-podman/src/driver.rs index a263bcf7d2..f2b9339eb4 100644 --- a/crates/openshell-driver-podman/src/driver.rs +++ b/crates/openshell-driver-podman/src/driver.rs @@ -753,6 +753,7 @@ impl PodmanComputeDriver { openshell_core::VERSION, [], )), + supports_privileged: false, }) } @@ -1096,6 +1097,11 @@ impl PodmanComputeDriver { // any workload/supervisor pair is admitted. Do not turn a tampered // artifact into a runtime-only supervisor failure. self.verify_network_trust()?; + if sandbox.spec.as_ref().is_some_and(|spec| spec.privileged) { + return Err(ComputeDriverError::Precondition( + "privileged sandboxes are not supported by the podman compute driver".into(), + )); + } if sandbox.name.is_empty() { return Err(ComputeDriverError::Precondition( "sandbox name is required".into(), diff --git a/crates/openshell-driver-podman/src/isolation.rs b/crates/openshell-driver-podman/src/isolation.rs index f9fc790588..d9c85ff933 100644 --- a/crates/openshell-driver-podman/src/isolation.rs +++ b/crates/openshell-driver-podman/src/isolation.rs @@ -287,6 +287,7 @@ pub fn bootstrap_archives( workload_identity: identity.clone(), provisioning_evidence: provisioning_evidence.clone(), child_env: child_env.clone(), + privileged: None, }; let runtime_descriptor = SandboxRuntimeDescriptor { boundary_id: sandbox_id.into(), @@ -309,6 +310,7 @@ pub fn bootstrap_archives( resource_claims, workload_identity: identity.clone(), provisioning_evidence, + privileged: None, }; // Libpod resolves the requested upload destination once for a stopped // container. Archive entries must be relative to the selected named volume, diff --git a/crates/openshell-driver-vm/runtime/kernel/openshell.kconfig b/crates/openshell-driver-vm/runtime/kernel/openshell.kconfig index c3573759f1..92f5086335 100644 --- a/crates/openshell-driver-vm/runtime/kernel/openshell.kconfig +++ b/crates/openshell-driver-vm/runtime/kernel/openshell.kconfig @@ -26,8 +26,25 @@ CONFIG_CGROUPS=y CONFIG_CGROUP_DEVICE=y CONFIG_CGROUP_CPUACCT=y CONFIG_CGROUP_PIDS=y +CONFIG_CGROUP_FREEZER=y CONFIG_MEMCG=y +# Namespaces and overlayfs for privileged VM workloads (Chrome, bubblewrap, dockerd). +CONFIG_NAMESPACES=y +CONFIG_USER_NS=y +CONFIG_PID_NS=y +CONFIG_NET_NS=y +CONFIG_IPC_NS=y +CONFIG_UTS_NS=y +CONFIG_OVERLAY_FS=y +CONFIG_VETH=y +CONFIG_BRIDGE=y +CONFIG_NETFILTER=y +CONFIG_NF_TABLES=y +CONFIG_IP_NF_IPTABLES=y +CONFIG_IP_NF_FILTER=y +CONFIG_IP_NF_NAT=y + # Disable the kernel headers archive to avoid cpio issues in CI. # CONFIG_IKHEADERS is not set @@ -35,13 +52,44 @@ CONFIG_MEMCG=y CONFIG_POSIX_MQUEUE=y CONFIG_POSIX_MQUEUE_SYSCTL=y -# Capability-free sandbox enforcement. +# Capability-free and privileged BPF LSM sandbox enforcement. CONFIG_SECURITY=y CONFIG_SECURITY_LANDLOCK=y +CONFIG_SECURITY_LOCKDOWN_LSM=y +CONFIG_SECURITY_LOCKDOWN_LSM_EARLY=y +CONFIG_PERF_EVENTS=y +CONFIG_FTRACE=y +CONFIG_FUNCTION_TRACER=y +CONFIG_DYNAMIC_FTRACE=y +CONFIG_KPROBES=y +CONFIG_KPROBE_EVENTS=y +CONFIG_BPF=y +CONFIG_BPF_SYSCALL=y +CONFIG_BPF_JIT=y +CONFIG_BPF_JIT_ALWAYS_ON=y +CONFIG_BPF_EVENTS=y +CONFIG_BPF_LSM=y +# CONFIG_DEBUG_INFO_NONE is not set +CONFIG_DEBUG_KERNEL=y +CONFIG_DEBUG_INFO=y +CONFIG_DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT=y +CONFIG_DEBUG_INFO_BTF=y CONFIG_LSM="landlock,lockdown,yama,loadpin,safesetid,ipe,bpf" CONFIG_SECCOMP=y CONFIG_SECCOMP_FILTER=y +# Root-to-kernel hardening for privileged VM workloads. +# CONFIG_MODULES is not set +# CONFIG_KEXEC is not set +# CONFIG_KEXEC_FILE is not set +# CONFIG_HIBERNATION is not set +# CONFIG_DEVMEM is not set +# CONFIG_DEVKMEM is not set +# CONFIG_PROC_KCORE is not set +# CONFIG_BLK_DEV_WRITE_MOUNTED is not set +# CONFIG_UPROBE_EVENTS is not set +# CONFIG_UPROBES is not set + # Kernel memory hardening. Keep init-on-free disabled because its runtime cost # is too high for sandbox workloads. CONFIG_HARDENED_USERCOPY=y diff --git a/crates/openshell-driver-vm/scripts/openshell-vm-sandbox-init.sh b/crates/openshell-driver-vm/scripts/openshell-vm-sandbox-init.sh index 37950675b0..9e8383e893 100644 --- a/crates/openshell-driver-vm/scripts/openshell-vm-sandbox-init.sh +++ b/crates/openshell-driver-vm/scripts/openshell-vm-sandbox-init.sh @@ -258,6 +258,20 @@ setup_overlay_root() { fi fi + # Privileged mode uses an ephemeral root overlay across boots: wipe any + # mutated non-workspace entries in /overlay/upper while preserving /sandbox + # and the driver-injected /.openshell bootstrap staging directory. + if [ "${OPENSHELL_VM_PRIVILEGED:-0}" = "1" ]; then + for entry in /overlay/upper/* /overlay/upper/.[!.]* /overlay/upper/..?*; do + [ -e "$entry" ] || [ -L "$entry" ] || continue + base="$(basename "$entry")" + case "$base" in + sandbox|.openshell) ;; + *) rm -rf "$entry" ;; + esac + done + fi + # The host makes upper under the gateway's umask and uid, and it becomes /. chown 0:0 /overlay/upper chmod 0755 /overlay/upper @@ -274,11 +288,13 @@ setup_overlay_root() { setup_gpu || ts "WARNING: GPU init failed; continuing without GPU" fi - bind_mount_into_newroot /proc - bind_mount_into_newroot /sys - bind_mount_into_newroot /tmp - bind_mount_into_newroot /dev - bind_mount_into_newroot /run + if [ "${OPENSHELL_VM_PRIVILEGED:-0}" != "1" ]; then + bind_mount_into_newroot /proc + bind_mount_into_newroot /sys + bind_mount_into_newroot /tmp + bind_mount_into_newroot /dev + bind_mount_into_newroot /run + fi ROOT_PREFIX="/newroot" run_post_overlay_setup @@ -648,6 +664,10 @@ run_post_overlay_setup() { wait fi + if [ "${OPENSHELL_VM_PRIVILEGED:-0}" = "1" ]; then + mkdir -p /sys/fs/cgroup + mount -t cgroup2 cgroup2 /sys/fs/cgroup 2>/dev/null || true + fi mkdir -p "$(root_path /dev/pts)" "$(root_path /dev/shm)" "$(root_path /sys/fs/cgroup)" mount -t devpts devpts "$(root_path /dev/pts)" 2>/dev/null & mount -t tmpfs tmpfs "$(root_path /dev/shm)" 2>/dev/null & @@ -710,16 +730,42 @@ if [ -n "${OPENSHELL_SANDBOX_ID:-}" ]; then fi ts "starting OpenShell VM sandbox" -_sandbox_owner="$(sandbox_owner)" -_sandbox_uid="${_sandbox_owner%%:*}" -_sandbox_gid="${_sandbox_owner##*:}" _sandbox_bootstrap_guest="${OPENSHELL_VM_SANDBOX_BOOTSTRAP:-/.openshell/state/bootstrap.json}" _sandbox_bootstrap="$(root_path "$_sandbox_bootstrap_guest")" _sandbox_state_dir="${_sandbox_bootstrap%/*}" if [ ! -f "$_sandbox_bootstrap" ]; then - ts "FATAL: capability-free sandbox bootstrap is missing" + ts "FATAL: sandbox bootstrap is missing" exit 1 fi + +if [ "${OPENSHELL_VM_PRIVILEGED:-0}" = "1" ]; then + # Stage bootstrap and TLS material into runtime-private tmpfs on the + # read-only runtime root and remove them from the workload overlay so + # guest-root workloads never see bootstrap secrets. + mkdir -p /run/openshell/bootstrap /run/openshell/tls + chmod 0700 /run/openshell /run/openshell/bootstrap + chmod 0755 /run/openshell/tls + for _sandbox_private_file in "$_sandbox_state_dir"/*; do + [ -f "$_sandbox_private_file" ] || continue + _dst="/run/openshell/bootstrap/$(basename "$_sandbox_private_file")" + cp "$_sandbox_private_file" "$_dst" + chmod 0600 "$_dst" + done + rm -rf "$_sandbox_state_dir" + # Ensure the workload root has no bootstrap mount exposing the runtime root. + umount /newroot/.openshell-bootstrap 2>/dev/null || true + rmdir /newroot/.openshell-bootstrap 2>/dev/null || true + _priv_bootstrap="/run/openshell/bootstrap/$(basename "$_sandbox_bootstrap")" + ts "exec openshell-sandbox --privileged (workload root: ${ROOT_PREFIX:-/newroot})" + exec /opt/openshell/bin/openshell-sandbox \ + --bootstrap "$_priv_bootstrap" \ + --privileged \ + --workload-root "${ROOT_PREFIX:-/newroot}" +fi + +_sandbox_owner="$(sandbox_owner)" +_sandbox_uid="${_sandbox_owner%%:*}" +_sandbox_gid="${_sandbox_owner##*:}" chown "${_sandbox_uid}:${_sandbox_gid}" "$_sandbox_state_dir" chmod 0700 "$_sandbox_state_dir" for _sandbox_private_file in "$_sandbox_state_dir"/*; do diff --git a/crates/openshell-driver-vm/src/driver.rs b/crates/openshell-driver-vm/src/driver.rs index 69a0f766ad..9c5af6538c 100644 --- a/crates/openshell-driver-vm/src/driver.rs +++ b/crates/openshell-driver-vm/src/driver.rs @@ -1588,6 +1588,7 @@ impl VmDriver { .into_owned(), rootfs_tar_max_bytes: self.config.rootfs_tar_max_bytes(), extension: Some(extension), + supports_privileged: true, } } @@ -2112,6 +2113,12 @@ impl VmDriver { }) }) .collect::, _>>()?; + let is_privileged = sandbox.spec.as_ref().is_some_and(|spec| spec.privileged); + let sandbox_tls = if is_privileged { + privileged_guest_boundary_tls_paths(&boundary_generation) + } else { + guest_boundary_tls_paths(&boundary_generation) + }; let provisioning = VmBoundarySpec { boundary_id: sandbox.id.clone(), generation: launch_authentication @@ -2126,12 +2133,13 @@ impl VmDriver { image_identity, transport, supervisor_tls, - sandbox_tls: guest_boundary_tls_paths(&boundary_generation), + sandbox_tls, control_port: VM_CONTROL_PORT, agent_uid: sandbox_owner_state.uid, agent_gid: sandbox_owner_state.gid, child_env: merged_environment(&sandbox), gpu_requested: is_gpu, + privileged: is_privileged, } .provision() .map_err(|error| Status::failed_precondition(error.to_string()))?; @@ -6765,6 +6773,9 @@ fn build_guest_environment(sandbox: &Sandbox, config: &VmDriverConfig) -> Vec>(); pairs.sort_by(|left, right| left.0.cmp(&right.0)); pairs @@ -7637,7 +7648,17 @@ fn inject_guest_boundary_bundle( ), (tls.private_key_path, material.private_key_pem.as_bytes()), ] { - let path = overlay_upper_path(guest_path.to_string_lossy().as_ref()); + // Privileged mode stages TLS material from `GUEST_BOUNDARY_CONFIG_DIR` + // into runtime-private `/run/openshell/bootstrap` before removing the + // staging directory from the workload overlay. + let staged_guest_path = if config.privileged.is_some() + && let Some(file_name) = guest_path.file_name().and_then(|n| n.to_str()) + { + format!("{GUEST_BOUNDARY_CONFIG_DIR}/{file_name}") + } else { + guest_path.to_string_lossy().into_owned() + }; + let path = overlay_upper_path(&staged_guest_path); write_rootfs_image_file(overlay_disk, &path, contents)?; set_rootfs_image_file_mode(overlay_disk, &path, 0o600)?; } @@ -7670,6 +7691,17 @@ fn guest_boundary_tls_paths(generation: &str) -> SandboxTlsServerConfig { } } +fn privileged_guest_boundary_tls_paths(generation: &str) -> SandboxTlsServerConfig { + SandboxTlsServerConfig { + certificate_chain_path: PathBuf::from(format!( + "/run/openshell/bootstrap/sandbox-{generation}.crt" + )), + private_key_path: PathBuf::from(format!( + "/run/openshell/bootstrap/sandbox-{generation}.key" + )), + } +} + #[allow(clippy::result_large_err)] #[tracing::instrument( name = "vm.prepare_guest", diff --git a/crates/openshell-driver-vm/src/embedded_runtime.rs b/crates/openshell-driver-vm/src/embedded_runtime.rs index 4b75bd4ba8..5919b6c4b9 100644 --- a/crates/openshell-driver-vm/src/embedded_runtime.rs +++ b/crates/openshell-driver-vm/src/embedded_runtime.rs @@ -66,10 +66,6 @@ pub fn ensure_runtime_extracted() -> Result { cleanup_old_versions(&cache_dir)?; - if cache_dir.exists() { - fs::remove_dir_all(&cache_dir) - .map_err(|e| format!("remove old runtime cache {}: {e}", cache_dir.display()))?; - } fs::create_dir_all(&cache_dir) .map_err(|e| format!("create runtime cache {}: {e}", cache_dir.display()))?; @@ -83,13 +79,15 @@ pub fn ensure_runtime_extracted() -> Result { { let unversioned = cache_dir.join("libkrunfw.dylib"); if !unversioned.exists() { - std::os::unix::fs::symlink(resources::LIBKRUNFW_NAME, &unversioned) - .map_err(|e| format!("symlink {}: {e}", unversioned.display()))?; + let _ = std::os::unix::fs::symlink(resources::LIBKRUNFW_NAME, &unversioned); } } - fs::write(&version_marker, cache_key) - .map_err(|e| format!("write runtime marker {}: {e}", version_marker.display()))?; + let marker_tmp = cache_dir.join(format!(".version.tmp.{}", std::process::id())); + fs::write(&marker_tmp, &cache_key) + .map_err(|e| format!("write runtime marker {}: {e}", marker_tmp.display()))?; + fs::rename(&marker_tmp, &version_marker) + .map_err(|e| format!("publish runtime marker {}: {e}", version_marker.display()))?; Ok(cache_dir) } @@ -163,5 +161,16 @@ fn extract_resource(compressed: &[u8], dest: &Path) -> Result<(), String> { let decompressed = zstd::decode_all(compressed).map_err(|e| format!("decompress {}: {e}", dest.display()))?; - fs::write(dest, decompressed).map_err(|e| format!("write {}: {e}", dest.display())) + // Stage into a per-process temporary file and rename atomically so + // concurrent VM launchers never truncate a mapped shared library in place. + let tmp_name = format!( + ".{}.tmp.{}", + dest.file_name() + .and_then(|name| name.to_str()) + .unwrap_or("runtime"), + std::process::id() + ); + let tmp_path = dest.with_file_name(tmp_name); + fs::write(&tmp_path, decompressed).map_err(|e| format!("write {}: {e}", tmp_path.display()))?; + fs::rename(&tmp_path, dest).map_err(|e| format!("publish {}: {e}", dest.display())) } diff --git a/crates/openshell-driver-vm/src/isolation/mod.rs b/crates/openshell-driver-vm/src/isolation/mod.rs index f52456b50e..da69cab95d 100644 --- a/crates/openshell-driver-vm/src/isolation/mod.rs +++ b/crates/openshell-driver-vm/src/isolation/mod.rs @@ -60,6 +60,7 @@ pub struct VmBoundarySpec { pub agent_gid: u32, pub child_env: HashMap, pub gpu_requested: bool, + pub privileged: bool, } /// The protected guest config and matching host descriptor for one VM. @@ -91,6 +92,9 @@ impl VmBoundarySpec { network_device_count: 0, } .project()?; + let privileged = self + .privileged + .then_some(openshell_sandbox_backend::privileged::PrivilegedGuestProfile::vm_bpf_lsm()); Ok(VmBoundaryProvisioning { boundary_config: BoundaryConfig { boundary_id: self.boundary_id.clone(), @@ -123,6 +127,7 @@ impl VmBoundarySpec { workload_identity: workload_identity.clone(), provisioning_evidence: provisioning_evidence.clone(), child_env: self.child_env, + privileged, }, runtime_descriptor: SandboxRuntimeDescriptor { boundary_id: self.boundary_id, @@ -137,6 +142,7 @@ impl VmBoundarySpec { host_gateway_ip: Some(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)), resource_claims, provisioning_evidence, + privileged, }, }) } @@ -209,6 +215,7 @@ mod tests { agent_gid: 1000, child_env: HashMap::new(), gpu_requested, + privileged: false, } .provision() .unwrap(); diff --git a/crates/openshell-sandbox-backend/src/audit.rs b/crates/openshell-sandbox-backend/src/audit.rs index c94b92d49a..a02a7de140 100644 --- a/crates/openshell-sandbox-backend/src/audit.rs +++ b/crates/openshell-sandbox-backend/src/audit.rs @@ -5,6 +5,8 @@ use openshell_isolation_interface::contract::BackendError; +use crate::privileged::{PrivilegedGuestProfile, PrivilegedSandboxAuditEvidence}; + /// Validate the built-in Linux backend's measured enforcement state. pub fn validate_native_linux_audit(evidence: &serde_json::Value) -> Result<(), BackendError> { let audit: crate::boundary_protocol::NativeLinuxSandboxAuditEvidence = @@ -14,6 +16,29 @@ pub fn validate_native_linux_audit(evidence: &serde_json::Value) -> Result<(), B audit.validate() } +/// Validate a privileged guest runtime's evidence against the admitted profile. +pub fn validate_privileged_audit( + evidence: &serde_json::Value, + admitted: PrivilegedGuestProfile, +) -> Result<(), BackendError> { + let audit: PrivilegedSandboxAuditEvidence = + serde_json::from_value(evidence.clone()).map_err(|error| { + BackendError::Confirm(format!("decode privileged sandbox audit evidence: {error}")) + })?; + audit.validate(admitted) +} + +/// Validate built-in runtime evidence for the boundary's admitted mode. +pub fn validate_builtin_audit( + evidence: &serde_json::Value, + admitted: Option, +) -> Result<(), BackendError> { + admitted.map_or_else( + || validate_native_linux_audit(evidence), + |profile| validate_privileged_audit(evidence, profile), + ) +} + #[cfg(test)] mod tests { use super::validate_native_linux_audit; diff --git a/crates/openshell-sandbox-backend/src/boundary_protocol.rs b/crates/openshell-sandbox-backend/src/boundary_protocol.rs index 17aa9f9a1e..9a9be03d10 100644 --- a/crates/openshell-sandbox-backend/src/boundary_protocol.rs +++ b/crates/openshell-sandbox-backend/src/boundary_protocol.rs @@ -509,6 +509,10 @@ pub struct SandboxRuntimeDescriptor { pub resource_claims: std::collections::BTreeMap, /// Backend-neutral projection of the validated outer network fence. pub provisioning_evidence: ProvisioningEvidence, + /// Optional driver-admitted privileged VM guest profile. Absent for the + /// default capability-free runtime. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub privileged: Option, } impl fmt::Debug for SandboxRuntimeDescriptor { @@ -523,6 +527,7 @@ impl fmt::Debug for SandboxRuntimeDescriptor { .field("host_gateway_ip", &self.host_gateway_ip) .field("resource_claims", &self.resource_claims) .field("provisioning_evidence", &self.provisioning_evidence) + .field("privileged", &self.privileged) .finish() } } @@ -580,6 +585,10 @@ pub struct BoundaryConfig { /// Driver-resolved environment exposed only to workload processes. #[serde(default)] pub child_env: std::collections::HashMap, + /// Optional driver-admitted privileged VM guest profile. Absent for the + /// default capability-free runtime, which refuses a config that sets it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub privileged: Option, } /// Default time a runtime keeps a workload frozen, after losing its diff --git a/crates/openshell-sandbox-backend/src/delegated.rs b/crates/openshell-sandbox-backend/src/delegated.rs index 96e2047ecb..045f448124 100644 --- a/crates/openshell-sandbox-backend/src/delegated.rs +++ b/crates/openshell-sandbox-backend/src/delegated.rs @@ -48,6 +48,7 @@ impl DelegatedLaunch { host_gateway_ip: self.host_gateway_ip, resource_claims: self.resource_claims, provisioning_evidence: self.provisioning_evidence, + privileged: None, }; crate::runtime::validate_runtime_coordinates(&descriptor)?; Ok(descriptor) diff --git a/crates/openshell-sandbox-backend/src/isolation_protocol.rs b/crates/openshell-sandbox-backend/src/isolation_protocol.rs index 6576d8a24f..272d41e12f 100644 --- a/crates/openshell-sandbox-backend/src/isolation_protocol.rs +++ b/crates/openshell-sandbox-backend/src/isolation_protocol.rs @@ -98,6 +98,7 @@ pub fn validate_open( || descriptor.workload_identity != config.workload_identity || descriptor.resource_claims != config.resource_claims || descriptor.provisioning_evidence != config.provisioning_evidence + || descriptor.privileged != config.privileged { return Err(tonic::Status::permission_denied( "driver descriptor does not match provisioned boundary", diff --git a/crates/openshell-sandbox-backend/src/lib.rs b/crates/openshell-sandbox-backend/src/lib.rs index 3df3f90ef7..57fcbe6278 100644 --- a/crates/openshell-sandbox-backend/src/lib.rs +++ b/crates/openshell-sandbox-backend/src/lib.rs @@ -15,6 +15,7 @@ pub mod boundary_protocol; pub mod delegated; pub mod isolation_protocol; pub mod mediation; +pub mod privileged; pub mod protobuf; mod runtime; mod runtime_initiated; diff --git a/crates/openshell-sandbox-backend/src/privileged.rs b/crates/openshell-sandbox-backend/src/privileged.rs new file mode 100644 index 0000000000..f2a33ef3a5 --- /dev/null +++ b/crates/openshell-sandbox-backend/src/privileged.rs @@ -0,0 +1,119 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Privileged (true guest root) VM isolation profile and confirmation evidence. +//! +//! When a VM compute driver boots a hardened `CONFIG_BPF_LSM=y` guest kernel +//! with an outer network fence, it may admit [`PrivilegedGuestProfile`] in both +//! `BoundaryConfig::privileged` and `SandboxRuntimeDescriptor::privileged`. +//! The runtime boots as guest PID 1 from a read-only runtime root, loads a +//! boot-once BPF LSM seal + policy program, and places workload processes as +//! guest `UID 0` inside private mount, PID, cgroup, and loopback-only network +//! namespaces with inherited `seccomp_notify` network mediation. + +use openshell_isolation_interface::contract::BackendError; +use serde::{Deserialize, Serialize}; + +/// Driver-admitted privileged VM guest profile. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PrivilegedGuestProfile { + /// Boot-once BPF LSM enforces shim seal, `filesystem_policy`, `process` + /// rules, and kernel-sourced telemetry. + pub bpf_lsm: bool, +} + +impl PrivilegedGuestProfile { + /// Standard privileged VM profile with boot-once BPF LSM enforcement. + #[must_use] + pub const fn vm_bpf_lsm() -> Self { + Self { bpf_lsm: true } + } + + /// Reject profiles that disable required kernel enforcement. + pub fn validate(&self) -> Result<(), BackendError> { + if !self.bpf_lsm { + return Err(BackendError::Descriptor( + "privileged guest profile requires bpf_lsm enforcement".to_string(), + )); + } + Ok(()) + } +} + +/// Measured enforcement evidence reported on `Confirm` by `openshell-sandbox --privileged`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +#[allow( + clippy::struct_excessive_bools, + reason = "audit evidence preserves independently measured security results" +)] +pub struct PrivilegedSandboxAuditEvidence { + /// Profile the runtime was bootstrapped with. + pub profile: PrivilegedGuestProfile, + /// Real, effective, and saved UID of the runtime (guest PID 1 root). + pub runtime_uid: u32, + /// Guest UID of workload processes (real guest root: 0). + pub workload_uid: u32, + pub sandbox_dumpable: bool, + pub core_limit_zero: bool, + pub native_architecture: String, + pub kernel_release: String, + /// The workload root is mounted separately from the read-only runtime root + /// and every workload process pivots into it. + pub separate_workload_root: bool, + /// Boot-once BPF LSM seal hooks are attached and the seal config map is frozen. + pub bpf_lsm_sealed: bool, + /// Workload `filesystem_policy` and `process` hooks are attached in BPF LSM. + pub bpf_policy_enforced: bool, + /// Workload processes run in a dedicated loopback-only network namespace + /// separate from the shim's initial network namespace. + pub init_net_isolated: bool, + /// Unmarked tasks cannot open `AF_VSOCK` sockets. + pub vsock_blocked: bool, + /// Networking-only `seccomp_notify` mediation (with `io_uring` blocked) is active. + pub network_mediation: bool, + /// `seccomp_notify` + `ADDFD` round trip qualified at startup. + pub seccomp_addfd_send: bool, + /// Supervisor loss freezes the runtime-owned workload cgroup (`cgroup.freeze`). + /// When `false`, supervisor loss terminates the workload instead of freezing it. + pub standing_freeze: bool, + /// Privileged mode enforces filesystem policy via BPF LSM rather than Landlock. + pub landlock_applied: bool, +} + +impl PrivilegedSandboxAuditEvidence { + /// Validate measured evidence against the profile admitted by the supervisor. + pub fn validate(&self, admitted: PrivilegedGuestProfile) -> Result<(), BackendError> { + admitted + .validate() + .map_err(|error| BackendError::Confirm(error.to_string()))?; + if self.profile != admitted { + return Err(BackendError::Confirm( + "privileged sandbox evidence names a different profile than the admitted one" + .to_string(), + )); + } + let complete = self.runtime_uid == 0 + && self.workload_uid == 0 + && !self.sandbox_dumpable + && self.core_limit_zero + && !self.native_architecture.is_empty() + && !self.kernel_release.is_empty() + && self.separate_workload_root + && self.bpf_lsm_sealed + && self.bpf_policy_enforced + && self.init_net_isolated + && self.vsock_blocked + && self.network_mediation + && self.seccomp_addfd_send + && !self.landlock_applied; + if complete { + Ok(()) + } else { + Err(BackendError::Confirm( + "privileged sandbox audit evidence is incomplete".to_string(), + )) + } + } +} diff --git a/crates/openshell-sandbox-backend/src/runtime.rs b/crates/openshell-sandbox-backend/src/runtime.rs index 578460504f..d2a2bf9460 100644 --- a/crates/openshell-sandbox-backend/src/runtime.rs +++ b/crates/openshell-sandbox-backend/src/runtime.rs @@ -571,6 +571,10 @@ impl OpenShellRuntimeBackend { let generation = runtime_descriptor.generation.clone(); let session_id = runtime_descriptor.session_id; let provisioning_evidence = runtime_descriptor.provisioning_evidence.clone(); + let privileged = runtime_descriptor.privileged; + if let Some(profile) = privileged { + profile.validate()?; + } let mut client = BoundaryClient::with_backend( runtime_descriptor, self.sandbox_bearer.clone(), @@ -625,6 +629,7 @@ impl OpenShellRuntimeBackend { session_id, resource_claims, provisioning_evidence, + privileged, takeover, })) } @@ -772,6 +777,7 @@ pub struct BoundBoundary { session_id: openshell_core::SandboxSessionId, resource_claims: std::collections::BTreeMap, provisioning_evidence: openshell_isolation_interface::contract::ProvisioningEvidence, + privileged: Option, takeover: Option, } @@ -840,7 +846,7 @@ impl BoundBoundary { )); } if self.client.backend_name == crate::BACKEND_NAME { - crate::audit::validate_native_linux_audit(&confirmation.backend_audit)?; + crate::audit::validate_builtin_audit(&confirmation.backend_audit, self.privileged)?; } let client = self.client.clone(); // Adopt from a snapshot taken after the promotion: the replaced owner @@ -4635,6 +4641,7 @@ mod tests { host_gateway_ip: None, resource_claims: std::collections::BTreeMap::new(), provisioning_evidence: test_provisioning_evidence(), + privileged: None, } } @@ -4859,6 +4866,7 @@ mod tests { resource_claims: std::collections::BTreeMap::new(), provisioning_evidence, takeover: None, + privileged: None, }; assert!(matches!( @@ -4912,6 +4920,7 @@ mod tests { host_gateway_ip: Some(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)), resource_claims: std::collections::BTreeMap::new(), provisioning_evidence: test_provisioning_evidence(), + privileged: None, }; let debug = format!("{runtime_descriptor:?}"); assert!(debug.contains("")); @@ -4932,6 +4941,7 @@ mod tests { host_gateway_ip: None, resource_claims: std::collections::BTreeMap::new(), provisioning_evidence: test_provisioning_evidence(), + privileged: None, }; assert!(matches!( validate_runtime_descriptor(&runtime_descriptor, &sandbox()), @@ -4954,6 +4964,7 @@ mod tests { host_gateway_ip: None, resource_claims: std::collections::BTreeMap::new(), provisioning_evidence: test_provisioning_evidence(), + privileged: None, }; assert!(matches!( validate_runtime_descriptor(&runtime_descriptor, &sandbox()), @@ -4976,6 +4987,7 @@ mod tests { host_gateway_ip: None, resource_claims: std::collections::BTreeMap::new(), provisioning_evidence: test_provisioning_evidence(), + privileged: None, }; validate_runtime_descriptor(&runtime_descriptor, &sandbox()) .expect("TCP runtime descriptor should be valid"); @@ -5291,6 +5303,7 @@ mod tests { host_gateway_ip: None, resource_claims: std::collections::BTreeMap::new(), provisioning_evidence: test_provisioning_evidence(), + privileged: None, }, test_bearer(&"a".repeat(32)), )); @@ -5796,6 +5809,7 @@ mod tests { host_gateway_ip: None, resource_claims: std::collections::BTreeMap::new(), provisioning_evidence: test_provisioning_evidence(), + privileged: None, }, test_bearer(&"a".repeat(32)), ); diff --git a/crates/openshell-sandbox-backend/src/runtime/test_support.rs b/crates/openshell-sandbox-backend/src/runtime/test_support.rs index 418891ae65..bfb72c46da 100644 --- a/crates/openshell-sandbox-backend/src/runtime/test_support.rs +++ b/crates/openshell-sandbox-backend/src/runtime/test_support.rs @@ -753,6 +753,7 @@ fn client(peer: Peer) -> Arc { resource_claims: std::collections::BTreeMap::default(), provisioning_evidence: ProvisioningEvidence::from_enforcement_evidence("test", b"test") .unwrap(), + privileged: None, }; let bearer = SessionBearerTokenSlot::new( SecretJwt::parse("a".repeat(32)).unwrap(), diff --git a/crates/openshell-sandbox/Cargo.toml b/crates/openshell-sandbox/Cargo.toml index 0ccc79af88..4a6d4f8e48 100644 --- a/crates/openshell-sandbox/Cargo.toml +++ b/crates/openshell-sandbox/Cargo.toml @@ -72,6 +72,7 @@ russh-sftp = "3.0" uuid = { workspace = true } [target.'cfg(target_os = "linux")'.dependencies] +aya = "0.14" landlock = "0.4" seccompiler = "0.5" socket2 = { workspace = true, features = ["all"] } diff --git a/crates/openshell-sandbox/bpf/openshell_lsm.bpf.c b/crates/openshell-sandbox/bpf/openshell_lsm.bpf.c new file mode 100644 index 0000000000..4b55b07965 --- /dev/null +++ b/crates/openshell-sandbox/bpf/openshell_lsm.bpf.c @@ -0,0 +1,945 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Boot-once BPF LSM for privileged (true guest root) VM sandboxes. +// +// Enforces three planes inside a hardened Linux 6.12+ VM kernel: +// 1. Shim seal: protects openshell-sandbox (guest PID 1 + launcher), its +// /run/openshell superblock, its freezer cgroup, AF_VSOCK, init_net, and +// the bpf() syscall itself against guest UID 0. +// 2. Workload filesystem_policy: enforces read-only / read-write / denied +// inode ancestry rules and blocks read-write remount / shadow bypasses, +// supporting live map reload from the sealed shim. +// 3. Workload process rules & telemetry: checks bprm_check_security against +// process rules, tracks task lineage in BPF_MAP_TYPE_TASK_STORAGE, and +// streams kernel-sourced events over a BPF ringbuf. + +typedef unsigned char __u8; +typedef unsigned short __u16; +typedef unsigned int __u32; +typedef unsigned long long __u64; +typedef int __s32; +typedef long long __s64; +typedef int pid_t; +typedef __u32 dev_t; +typedef __u16 umode_t; + +#define EPERM 1 +#define EACCES 13 +#define AF_UNIX 1 +#define AF_VSOCK 40 +#define O_ACCMODE 00000003 +#define O_WRONLY 00000001 +#define O_RDWR 00000002 +#define O_CREAT 00000100 +#define O_TRUNC 00001000 +#define O_APPEND 00002000 +#define MS_RDONLY 1UL +#define MS_REMOUNT 32UL +#define CLONE_THREAD 0x00010000UL +#define CGROUP2_SUPER_MAGIC 0x63677270UL + +#define BPF_MAP_TYPE_HASH 1 +#define BPF_MAP_TYPE_ARRAY 2 +#define BPF_MAP_TYPE_RINGBUF 27 +#define BPF_MAP_TYPE_TASK_STORAGE 29 +#define BPF_F_NO_PREALLOC (1U << 0) +#define BPF_LOCAL_STORAGE_GET_F_CREATE (1ULL << 0) + +#define SEC(name) __attribute__((section(name), used)) +#define __uint(name, val) int (*name)[val] +#define __type(name, val) typeof(val) *name +#define __always_inline inline __attribute__((always_inline)) + +// Minimal CO-RE kernel struct definitions (relocated against /sys/kernel/btf/vmlinux). +struct ns_common { + unsigned int inum; +} __attribute__((preserve_access_index)); + +struct net { + struct ns_common ns; +} __attribute__((preserve_access_index)); + +struct nsproxy { + struct net *net_ns; +} __attribute__((preserve_access_index)); + +struct task_struct { + pid_t pid; + pid_t tgid; + struct task_struct *real_parent; + struct task_struct *group_leader; + struct nsproxy *nsproxy; +} __attribute__((preserve_access_index)); + +struct super_block { + dev_t s_dev; + unsigned long s_magic; +} __attribute__((preserve_access_index)); + +struct inode { + umode_t i_mode; + struct super_block *i_sb; + unsigned long i_ino; +} __attribute__((preserve_access_index)); + +struct dentry { + struct dentry *d_parent; + struct inode *d_inode; + struct super_block *d_sb; +} __attribute__((preserve_access_index)); + +struct vfsmount { + struct super_block *mnt_sb; +} __attribute__((preserve_access_index)); + +struct path { + struct vfsmount *mnt; + struct dentry *dentry; +} __attribute__((preserve_access_index)); + +struct file { + struct path f_path; + struct inode *f_inode; + unsigned int f_flags; +} __attribute__((preserve_access_index)); + +struct linux_binprm { + struct file *file; +} __attribute__((preserve_access_index)); + +// BPF helpers (stable Linux UAPI helper IDs). +static void *(*bpf_map_lookup_elem)(void *map, const void *key) = (void *)1; +static long (*bpf_probe_read_kernel)(void *dst, __u32 size, const void *unsafe_ptr) = (void *)113; +static __u64 (*bpf_get_current_pid_tgid)(void) = (void *)14; +static __u64 (*bpf_get_current_uid_gid)(void) = (void *)15; +static long (*bpf_get_current_comm)(void *buf, __u32 size_of_buf) = (void *)16; +static struct task_struct *(*bpf_get_current_task_btf)(void) = (void *)158; +static void *(*bpf_task_storage_get)(void *map, struct task_struct *task, void *value, __u64 flags) = (void *)156; +static void *(*bpf_ringbuf_reserve)(void *ringbuf, __u64 size, __u64 flags) = (void *)131; +static void (*bpf_ringbuf_submit)(void *data, __u64 flags) = (void *)132; + +#define CORE_READ(dst, ptr, field) \ + bpf_probe_read_kernel(&(dst), sizeof(dst), __builtin_preserve_access_index(&(ptr)->field)) + +// Frozen seal configuration populated once at startup before workload launch. +struct seal_config { + __u32 active; + __u32 shim_tgid; + __u32 launcher_tgid; + __u32 runtime_sb_dev; + __u32 runtime_root_dev; + __u32 init_net_inum; + __u64 freezer_cgroup_ino; + __u32 cgroup_sb_dev; + __u32 guest_parent_tgid; +}; + +// Live-reloadable policy flags updated only by the sealed shim. +struct policy_config { + __u32 fs_enabled; + __u32 proc_enabled; + __u32 proc_default_deny; + __u32 _pad; +}; + +struct inode_key { + __u32 dev; + __u32 _pad; + __u64 ino; +}; + +// Filesystem rule verdicts. +#define FS_RULE_RW 1U +#define FS_RULE_RO 2U +#define FS_RULE_DENY 3U + +// Process rule verdicts. +#define PROC_RULE_ALLOW 1U +#define PROC_RULE_DENY 2U + +// Task lineage stored in BPF_MAP_TYPE_TASK_STORAGE. +struct task_lineage { + __u32 tgid; + __u32 parent_tgid; + __u32 flags; + __u32 _pad; +}; + +#define TASK_FLAG_SHIM 1U +#define TASK_FLAG_WORKLOAD 2U + +// Telemetry event types streamed over telemetry_rb. +#define EVT_EXEC 1U +#define EVT_DENY_SEAL 2U +#define EVT_DENY_FS 3U +#define EVT_DENY_PROC 4U +#define EVT_TASK_EXIT 5U + +// Seal denial sub-reasons. +#define SEAL_REASON_BPF 1U +#define SEAL_REASON_PTRACE 2U +#define SEAL_REASON_PERF 3U +#define SEAL_REASON_KILL 4U +#define SEAL_REASON_RLIMIT 5U +#define SEAL_REASON_VSOCK 6U +#define SEAL_REASON_INIT_NET 7U +#define SEAL_REASON_RUNTIME_FS 8U +#define SEAL_REASON_FREEZER 9U +#define SEAL_REASON_MOUNT 10U +#define SEAL_REASON_LOCKDOWN 11U + +struct telemetry_event { + __u32 event_type; + __u32 reason; + __u32 pid; + __u32 tgid; + __u32 ppid; + __u32 uid; + __u32 dev; + __u32 _pad; + __u64 ino; + char comm[16]; +}; + +struct { + __uint(type, BPF_MAP_TYPE_ARRAY); + __uint(max_entries, 1); + __type(key, __u32); + __type(value, struct seal_config); +} seal_cfg SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_ARRAY); + __uint(max_entries, 2); + __type(key, __u32); + __type(value, __u32); +} shim_id SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_ARRAY); + __uint(max_entries, 1); + __type(key, __u32); + __type(value, struct policy_config); +} policy_cfg SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_HASH); + __uint(max_entries, 4096); + __type(key, struct inode_key); + __type(value, __u32); +} fs_rules SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_HASH); + __uint(max_entries, 1024); + __type(key, struct inode_key); + __type(value, __u32); +} proc_rules SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_TASK_STORAGE); + __uint(map_flags, BPF_F_NO_PREALLOC); + __type(key, int); + __type(value, struct task_lineage); +} task_meta SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_RINGBUF); + __uint(max_entries, 256 * 1024); +} telemetry_rb SEC(".maps"); + +static __always_inline const struct seal_config *get_seal_cfg(void) { + __u32 zero = 0; + return bpf_map_lookup_elem(&seal_cfg, &zero); +} + +static __always_inline const struct policy_config *get_policy_cfg(void) { + __u32 zero = 0; + return bpf_map_lookup_elem(&policy_cfg, &zero); +} + +static __always_inline int is_shim_tgid(const struct seal_config *cfg, __u32 tgid) { + if (!cfg || tgid == 0) { + return 0; + } + return tgid == cfg->shim_tgid || (cfg->launcher_tgid != 0 && tgid == cfg->launcher_tgid); +} + +static __always_inline int current_is_shim(const struct seal_config *cfg) { + __u32 tgid = (__u32)(bpf_get_current_pid_tgid() >> 32); + return is_shim_tgid(cfg, tgid); +} + +// Guest root-PID-namespace init (e.g. kata-agent in a Kata Containers VM, +// where openshell-sandbox runs in a child container with shim_tgid > 1) is +// part of the VM TCB and owns container teardown (SIGTERM/SIGKILL, vsock +// ttrpc, and rootfs unmount). No workload process can ever have root tgid == 1. +static __always_inline int current_is_guest_init(const struct seal_config *cfg) { + if (!cfg || cfg->shim_tgid <= 1) { + return 0; + } + __u32 tgid = (__u32)(bpf_get_current_pid_tgid() >> 32); + return tgid == 1 || (cfg->guest_parent_tgid != 0 && tgid == cfg->guest_parent_tgid); +} + +static __always_inline int current_is_shim_or_guest_init(const struct seal_config *cfg) { + return current_is_shim(cfg) || current_is_guest_init(cfg); +} + +static __always_inline int task_is_shim(const struct seal_config *cfg, struct task_struct *task) { + if (!cfg || !task) { + return 0; + } + pid_t tgid = 0; + CORE_READ(tgid, task, tgid); + return is_shim_tgid(cfg, (__u32)tgid); +} + +static __always_inline __u32 current_parent_tgid(void) { + struct task_struct *cur = bpf_get_current_task_btf(); + if (!cur) { + return 0; + } + struct task_lineage *meta = bpf_task_storage_get(&task_meta, cur, 0, 0); + if (meta && meta->parent_tgid != 0) { + return meta->parent_tgid; + } + struct task_struct *parent = 0; + CORE_READ(parent, cur, real_parent); + if (!parent) { + return 0; + } + pid_t ptgid = 0; + CORE_READ(ptgid, parent, tgid); + return (__u32)ptgid; +} + +static __always_inline void emit_event(__u32 event_type, __u32 reason, __u32 dev, __u64 ino) { + struct telemetry_event *evt = bpf_ringbuf_reserve(&telemetry_rb, sizeof(*evt), 0); + if (!evt) { + return; + } + __u64 pid_tgid = bpf_get_current_pid_tgid(); + evt->event_type = event_type; + evt->reason = reason; + evt->pid = (__u32)pid_tgid; + evt->tgid = (__u32)(pid_tgid >> 32); + evt->ppid = current_parent_tgid(); + evt->uid = (__u32)bpf_get_current_uid_gid(); + evt->dev = dev; + evt->_pad = 0; + evt->ino = ino; + bpf_get_current_comm(evt->comm, sizeof(evt->comm)); + bpf_ringbuf_submit(evt, 0); +} + +static __always_inline __u32 current_net_inum(void) { + struct task_struct *cur = bpf_get_current_task_btf(); + if (!cur) { + return 0; + } + struct nsproxy *nsp = 0; + CORE_READ(nsp, cur, nsproxy); + if (!nsp) { + return 0; + } + struct net *net_ns = 0; + CORE_READ(net_ns, nsp, net_ns); + if (!net_ns) { + return 0; + } + unsigned int inum = 0; + CORE_READ(inum, net_ns, ns.inum); + return (__u32)inum; +} + +// Check if a dentry belongs to the runtime superblocks or protected freezer cgroup. +static __always_inline int is_protected_runtime_dentry( + const struct seal_config *cfg, + struct dentry *dentry, + int is_write, + __u32 *out_dev, + __u64 *out_ino +) { + if (!cfg || !dentry) { + return 0; + } + struct super_block *sb = 0; + CORE_READ(sb, dentry, d_sb); + if (!sb) { + return 0; + } + dev_t s_dev = 0; + unsigned long s_magic = 0; + CORE_READ(s_dev, sb, s_dev); + CORE_READ(s_magic, sb, s_magic); + *out_dev = (__u32)s_dev; + + struct inode *inode = 0; + CORE_READ(inode, dentry, d_inode); + unsigned long ino = 0; + if (inode) { + CORE_READ(ino, inode, i_ino); + } + *out_ino = (__u64)ino; + + if (is_write && ((cfg->runtime_sb_dev != 0 && s_dev == cfg->runtime_sb_dev) || + (cfg->runtime_root_dev != 0 && s_dev == cfg->runtime_root_dev))) { + return SEAL_REASON_RUNTIME_FS; + } + + // Protect the runtime-owned workload freezer cgroup directory (and its + // control files such as cgroup.freeze) from any write by unmarked tasks. + if (is_write && cfg->freezer_cgroup_ino != 0 && s_magic == CGROUP2_SUPER_MAGIC) { + struct dentry *cur = dentry; + #pragma unroll + for (int i = 0; i < 4; i++) { + if (!cur) { + break; + } + struct inode *ci = 0; + CORE_READ(ci, cur, d_inode); + if (ci) { + unsigned long cino = 0; + CORE_READ(cino, ci, i_ino); + if (cino == cfg->freezer_cgroup_ino) { + return SEAL_REASON_FREEZER; + } + } + struct dentry *parent = 0; + CORE_READ(parent, cur, d_parent); + if (!parent || parent == cur) { + break; + } + cur = parent; + } + } + return 0; +} + +// Walk dentry->d_parent up to 24 levels looking for the most-specific fs_rules entry. +static __always_inline __u32 lookup_fs_rule(struct dentry *dentry, __u32 *matched_dev, __u64 *matched_ino) { + if (!dentry) { + return 0; + } + struct super_block *sb = 0; + CORE_READ(sb, dentry, d_sb); + if (!sb) { + return 0; + } + dev_t s_dev = 0; + CORE_READ(s_dev, sb, s_dev); + + struct dentry *cur = dentry; + for (int i = 0; i < 24; i++) { + if (!cur) { + break; + } + struct inode *ci = 0; + CORE_READ(ci, cur, d_inode); + if (ci) { + unsigned long cino = 0; + CORE_READ(cino, ci, i_ino); + struct inode_key key = { + .dev = (__u32)s_dev, + ._pad = 0, + .ino = (__u64)cino, + }; + __u32 *rule = bpf_map_lookup_elem(&fs_rules, &key); + if (rule) { + *matched_dev = key.dev; + *matched_ino = key.ino; + return *rule; + } + } + struct dentry *parent = 0; + CORE_READ(parent, cur, d_parent); + if (!parent || parent == cur) { + break; + } + cur = parent; + } + return 0; +} + +static __always_inline int check_dentry_access(struct dentry *dentry, int is_write) { + const struct seal_config *cfg = get_seal_cfg(); + if (!cfg || !cfg->active || current_is_shim_or_guest_init(cfg)) { + return 0; + } + __u32 dev = 0; + __u64 ino = 0; + int seal_reason = is_protected_runtime_dentry(cfg, dentry, is_write, &dev, &ino); + if (seal_reason != 0) { + emit_event(EVT_DENY_SEAL, (__u32)seal_reason, dev, ino); + return -EPERM; + } + + const struct policy_config *pcfg = get_policy_cfg(); + if (!pcfg || !pcfg->fs_enabled) { + return 0; + } + __u32 mdev = dev; + __u64 mino = ino; + __u32 rule = lookup_fs_rule(dentry, &mdev, &mino); + if (rule == FS_RULE_DENY) { + emit_event(EVT_DENY_FS, rule, mdev, mino); + return -EACCES; + } + if (is_write && rule == FS_RULE_RO) { + emit_event(EVT_DENY_FS, rule, mdev, mino); + return -EACCES; + } + return 0; +} + +// --------------------------------------------------------------------------- +// Plane 1: Shim seal hooks +// --------------------------------------------------------------------------- + +SEC("lsm/bpf") +int openshell_lsm_bpf(unsigned long long *ctx) { + int ret = (int)ctx[3]; + if (ret != 0) { + return ret; + } + const struct seal_config *cfg = get_seal_cfg(); + if (!cfg || !cfg->active) { + __u32 k0 = 0; + __u32 *recorded = bpf_map_lookup_elem(&shim_id, &k0); + if (recorded && *recorded == 0) { + *recorded = (__u32)(bpf_get_current_pid_tgid() >> 32); + } + __u32 k1 = 1; + __u32 *rec_parent = bpf_map_lookup_elem(&shim_id, &k1); + if (rec_parent && *rec_parent == 0) { + struct task_struct *cur = bpf_get_current_task_btf(); + if (cur) { + struct task_struct *parent = 0; + CORE_READ(parent, cur, real_parent); + if (parent) { + pid_t ptgid = 0; + CORE_READ(ptgid, parent, tgid); + if (ptgid > 0) { + *rec_parent = (__u32)ptgid; + } + } + } + } + return 0; + } + if (current_is_shim(cfg)) { + return 0; + } + emit_event(EVT_DENY_SEAL, SEAL_REASON_BPF, 0, (__u64)ctx[0]); + return -EPERM; +} + +SEC("lsm/ptrace_access_check") +int openshell_lsm_ptrace(unsigned long long *ctx) { + int ret = (int)ctx[2]; + if (ret != 0) { + return ret; + } + const struct seal_config *cfg = get_seal_cfg(); + if (!cfg || !cfg->active || current_is_shim(cfg)) { + return 0; + } + struct task_struct *child = (struct task_struct *)ctx[0]; + if (task_is_shim(cfg, child)) { + emit_event(EVT_DENY_SEAL, SEAL_REASON_PTRACE, 0, (__u64)ctx[1]); + return -EACCES; + } + return 0; +} + +SEC("lsm/perf_event_alloc") +int openshell_lsm_perf(unsigned long long *ctx) { + int ret = (int)ctx[1]; + if (ret != 0) { + return ret; + } + const struct seal_config *cfg = get_seal_cfg(); + if (!cfg || !cfg->active || current_is_shim(cfg)) { + return 0; + } + emit_event(EVT_DENY_SEAL, SEAL_REASON_PERF, 0, 0); + return -EACCES; +} + +SEC("lsm/task_kill") +int openshell_lsm_task_kill(unsigned long long *ctx) { + int ret = (int)ctx[4]; + if (ret != 0) { + return ret; + } + const struct seal_config *cfg = get_seal_cfg(); + if (!cfg || !cfg->active || current_is_shim_or_guest_init(cfg)) { + return 0; + } + struct task_struct *target = (struct task_struct *)ctx[0]; + if (task_is_shim(cfg, target)) { + emit_event(EVT_DENY_SEAL, SEAL_REASON_KILL, 0, (__u64)ctx[2]); + return -EPERM; + } + return 0; +} + +SEC("lsm/task_setrlimit") +int openshell_lsm_task_setrlimit(unsigned long long *ctx) { + int ret = (int)ctx[3]; + if (ret != 0) { + return ret; + } + const struct seal_config *cfg = get_seal_cfg(); + if (!cfg || !cfg->active || current_is_shim(cfg)) { + return 0; + } + struct task_struct *target = (struct task_struct *)ctx[0]; + if (task_is_shim(cfg, target)) { + emit_event(EVT_DENY_SEAL, SEAL_REASON_RLIMIT, 0, (__u64)ctx[1]); + return -EPERM; + } + return 0; +} + +SEC("lsm/socket_create") +int openshell_lsm_socket_create(unsigned long long *ctx) { + int ret = (int)ctx[4]; + if (ret != 0) { + return ret; + } + int kern = (int)ctx[3]; + if (kern != 0) { + return 0; + } + const struct seal_config *cfg = get_seal_cfg(); + if (!cfg || !cfg->active || current_is_shim_or_guest_init(cfg)) { + return 0; + } + int family = (int)ctx[0]; + if (family == AF_VSOCK) { + emit_event(EVT_DENY_SEAL, SEAL_REASON_VSOCK, 0, (__u64)family); + return -EPERM; + } + if (cfg->init_net_inum != 0 && family != AF_UNIX) { + __u32 net_inum = current_net_inum(); + if (net_inum == cfg->init_net_inum) { + emit_event(EVT_DENY_SEAL, SEAL_REASON_INIT_NET, net_inum, (__u64)family); + return -EPERM; + } + } + return 0; +} + +SEC("lsm/sb_remount") +int openshell_lsm_sb_remount(unsigned long long *ctx) { + int ret = (int)ctx[2]; + if (ret != 0) { + return ret; + } + const struct seal_config *cfg = get_seal_cfg(); + if (!cfg || !cfg->active || current_is_shim_or_guest_init(cfg)) { + return 0; + } + struct super_block *sb = (struct super_block *)ctx[0]; + if (!sb) { + return 0; + } + dev_t s_dev = 0; + CORE_READ(s_dev, sb, s_dev); + if ((cfg->runtime_sb_dev != 0 && s_dev == cfg->runtime_sb_dev) || + (cfg->runtime_root_dev != 0 && s_dev == cfg->runtime_root_dev)) { + emit_event(EVT_DENY_SEAL, SEAL_REASON_MOUNT, (__u32)s_dev, 0); + return -EPERM; + } + return 0; +} + +SEC("lsm/sb_umount") +int openshell_lsm_sb_umount(unsigned long long *ctx) { + int ret = (int)ctx[2]; + if (ret != 0) { + return ret; + } + const struct seal_config *cfg = get_seal_cfg(); + if (!cfg || !cfg->active || current_is_shim_or_guest_init(cfg)) { + return 0; + } + struct vfsmount *mnt = (struct vfsmount *)ctx[0]; + if (!mnt) { + return 0; + } + struct super_block *sb = 0; + CORE_READ(sb, mnt, mnt_sb); + if (!sb) { + return 0; + } + dev_t s_dev = 0; + CORE_READ(s_dev, sb, s_dev); + if ((cfg->runtime_sb_dev != 0 && s_dev == cfg->runtime_sb_dev) || + (cfg->runtime_root_dev != 0 && s_dev == cfg->runtime_root_dev)) { + emit_event(EVT_DENY_SEAL, SEAL_REASON_MOUNT, (__u32)s_dev, 0); + return -EPERM; + } + return 0; +} + +SEC("lsm/locked_down") +int openshell_lsm_locked_down(unsigned long long *ctx) { + int ret = (int)ctx[1]; + if (ret != 0) { + return ret; + } + const struct seal_config *cfg = get_seal_cfg(); + if (!cfg || !cfg->active || current_is_shim(cfg)) { + return 0; + } + emit_event(EVT_DENY_SEAL, SEAL_REASON_LOCKDOWN, 0, (__u64)ctx[0]); + return -EPERM; +} + +// --------------------------------------------------------------------------- +// Plane 2: Workload filesystem_policy & mount bypass prevention +// --------------------------------------------------------------------------- + +SEC("lsm/file_open") +int openshell_lsm_file_open(unsigned long long *ctx) { + int ret = (int)ctx[1]; + if (ret != 0) { + return ret; + } + struct file *file = (struct file *)ctx[0]; + if (!file) { + return 0; + } + unsigned int flags = 0; + CORE_READ(flags, file, f_flags); + int is_write = ((flags & O_ACCMODE) == O_WRONLY) || + ((flags & O_ACCMODE) == O_RDWR) || + ((flags & (O_CREAT | O_TRUNC | O_APPEND)) != 0); + struct dentry *dentry = 0; + CORE_READ(dentry, file, f_path.dentry); + return check_dentry_access(dentry, is_write); +} + +SEC("lsm/inode_create") +int openshell_lsm_inode_create(unsigned long long *ctx) { + int ret = (int)ctx[3]; + if (ret != 0) { + return ret; + } + struct dentry *dentry = (struct dentry *)ctx[1]; + return check_dentry_access(dentry, 1); +} + +SEC("lsm/inode_unlink") +int openshell_lsm_inode_unlink(unsigned long long *ctx) { + int ret = (int)ctx[2]; + if (ret != 0) { + return ret; + } + struct dentry *dentry = (struct dentry *)ctx[1]; + return check_dentry_access(dentry, 1); +} + +SEC("lsm/inode_rename") +int openshell_lsm_inode_rename(unsigned long long *ctx) { + int ret = (int)ctx[4]; + if (ret != 0) { + return ret; + } + struct dentry *old_dentry = (struct dentry *)ctx[1]; + int rc = check_dentry_access(old_dentry, 1); + if (rc != 0) { + return rc; + } + struct dentry *new_dentry = (struct dentry *)ctx[3]; + return check_dentry_access(new_dentry, 1); +} + +SEC("lsm/inode_setattr") +int openshell_lsm_inode_setattr(unsigned long long *ctx) { + int ret = (int)ctx[3]; + if (ret != 0) { + return ret; + } + struct dentry *dentry = (struct dentry *)ctx[1]; + return check_dentry_access(dentry, 1); +} + +SEC("lsm/sb_mount") +int openshell_lsm_sb_mount(unsigned long long *ctx) { + int ret = (int)ctx[5]; + if (ret != 0) { + return ret; + } + const struct seal_config *cfg = get_seal_cfg(); + if (!cfg || !cfg->active || current_is_shim_or_guest_init(cfg)) { + return 0; + } + const struct path *path = (const struct path *)ctx[1]; + if (!path) { + return 0; + } + unsigned long flags = (unsigned long)ctx[3]; + struct dentry *target = 0; + CORE_READ(target, path, dentry); + if (!target) { + return 0; + } + + __u32 dev = 0; + __u64 ino = 0; + int seal_reason = is_protected_runtime_dentry(cfg, target, 1, &dev, &ino); + if (seal_reason != 0) { + emit_event(EVT_DENY_SEAL, SEAL_REASON_MOUNT, dev, ino); + return -EPERM; + } + + const struct policy_config *pcfg = get_policy_cfg(); + if (!pcfg || !pcfg->fs_enabled) { + return 0; + } + __u32 mdev = dev; + __u64 mino = ino; + __u32 rule = lookup_fs_rule(target, &mdev, &mino); + if (rule == FS_RULE_DENY) { + emit_event(EVT_DENY_FS, rule, mdev, mino); + return -EPERM; + } + // Block read-write remounts or writable shadow mounts over read-only policy paths. + // Read-only remounts/binds (e.g. bwrap --ro-bind) stay allowed. + if (rule == FS_RULE_RO && !(flags & MS_RDONLY)) { + emit_event(EVT_DENY_FS, rule, mdev, mino); + return -EPERM; + } + return 0; +} + +// --------------------------------------------------------------------------- +// Plane 3: Workload process rules & kernel-sourced lineage/telemetry +// --------------------------------------------------------------------------- + +SEC("lsm/bprm_check_security") +int openshell_lsm_bprm_check(unsigned long long *ctx) { + int ret = (int)ctx[1]; + if (ret != 0) { + return ret; + } + const struct seal_config *cfg = get_seal_cfg(); + if (!cfg || !cfg->active || current_is_shim(cfg)) { + return 0; + } + struct linux_binprm *bprm = (struct linux_binprm *)ctx[0]; + if (!bprm) { + return 0; + } + struct file *file = 0; + CORE_READ(file, bprm, file); + if (!file) { + return 0; + } + struct dentry *dentry = 0; + CORE_READ(dentry, file, f_path.dentry); + struct inode *inode = 0; + CORE_READ(inode, file, f_inode); + __u32 dev = 0; + __u64 ino = 0; + if (inode) { + struct super_block *sb = 0; + CORE_READ(sb, inode, i_sb); + if (sb) { + dev_t s_dev = 0; + CORE_READ(s_dev, sb, s_dev); + dev = (__u32)s_dev; + } + unsigned long i_ino = 0; + CORE_READ(i_ino, inode, i_ino); + ino = (__u64)i_ino; + } + + const struct policy_config *pcfg = get_policy_cfg(); + if (pcfg && pcfg->proc_enabled && inode) { + struct inode_key key = { .dev = dev, ._pad = 0, .ino = ino }; + __u32 *rule = bpf_map_lookup_elem(&proc_rules, &key); + if (rule) { + if (*rule == PROC_RULE_DENY) { + emit_event(EVT_DENY_PROC, PROC_RULE_DENY, dev, ino); + return -EACCES; + } + } else if (pcfg->proc_default_deny) { + emit_event(EVT_DENY_PROC, PROC_RULE_DENY, dev, ino); + return -EACCES; + } + } + + emit_event(EVT_EXEC, 0, dev, ino); + return 0; +} + +SEC("lsm/task_alloc") +int openshell_lsm_task_alloc(unsigned long long *ctx) { + int ret = (int)ctx[2]; + if (ret != 0) { + return ret; + } + const struct seal_config *cfg = get_seal_cfg(); + if (!cfg || !cfg->active) { + return 0; + } + struct task_struct *child = (struct task_struct *)ctx[0]; + if (!child) { + return 0; + } + unsigned long clone_flags = (unsigned long)ctx[1]; + __u32 parent_tgid = (__u32)(bpf_get_current_pid_tgid() >> 32); + struct task_lineage *meta = bpf_task_storage_get( + &task_meta, + child, + 0, + BPF_LOCAL_STORAGE_GET_F_CREATE + ); + if (meta) { + pid_t child_tgid = 0; + CORE_READ(child_tgid, child, tgid); + meta->tgid = (__u32)child_tgid; + meta->parent_tgid = parent_tgid; + // Only same-process threads of the shim inherit TASK_FLAG_SHIM; + // forked workload children never inherit shim authority. + if ((clone_flags & CLONE_THREAD) && is_shim_tgid(cfg, parent_tgid)) { + meta->flags = TASK_FLAG_SHIM; + } else { + meta->flags = TASK_FLAG_WORKLOAD; + } + meta->_pad = 0; + } + return 0; +} + +SEC("lsm/task_free") +int openshell_lsm_task_free(unsigned long long *ctx) { + const struct seal_config *cfg = get_seal_cfg(); + if (!cfg || !cfg->active) { + return 0; + } + struct task_struct *task = (struct task_struct *)ctx[0]; + if (!task || task_is_shim(cfg, task)) { + return 0; + } + struct task_lineage *meta = bpf_task_storage_get(&task_meta, task, 0, 0); + if (!meta || meta->flags != TASK_FLAG_WORKLOAD) { + return 0; + } + pid_t pid = 0; + pid_t tgid = 0; + CORE_READ(pid, task, pid); + CORE_READ(tgid, task, tgid); + if (pid == tgid) { + emit_event(EVT_TASK_EXIT, 0, 0, (__u64)tgid); + } + return 0; +} + +char _license[] SEC("license") = "Dual BSD/GPL"; diff --git a/crates/openshell-sandbox/build.rs b/crates/openshell-sandbox/build.rs new file mode 100644 index 0000000000..f463ed6237 --- /dev/null +++ b/crates/openshell-sandbox/build.rs @@ -0,0 +1,54 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::env; +use std::path::PathBuf; +use std::process::Command; + +fn main() { + println!("cargo:rerun-if-changed=bpf/openshell_lsm.bpf.c"); + if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("linux") { + return; + } + + let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR")); + let src = manifest_dir.join("bpf/openshell_lsm.bpf.c"); + let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR")); + let obj = out_dir.join("openshell_lsm.bpf.o"); + + let compiled = try_compile_with_zig(&src, &obj) || try_compile_with_clang(&src, &obj); + assert!( + compiled, + "failed to compile {} for BPF LSM: neither `zig cc` nor `clang` succeeded", + src.display() + ); +} + +fn try_compile_with_zig(src: &PathBuf, obj: &PathBuf) -> bool { + Command::new("zig") + .args([ + "cc", + "-target", + "bpfel-freestanding", + "-O2", + "-g", + "-Wall", + "-Werror", + "-c", + ]) + .arg(src) + .arg("-o") + .arg(obj) + .status() + .is_ok_and(|status| status.success()) +} + +fn try_compile_with_clang(src: &PathBuf, obj: &PathBuf) -> bool { + Command::new("clang") + .args(["-target", "bpf", "-O2", "-g", "-Wall", "-Werror", "-c"]) + .arg(src) + .arg("-o") + .arg(obj) + .status() + .is_ok_and(|status| status.success()) +} diff --git a/crates/openshell-sandbox/src/boundary_exec.rs b/crates/openshell-sandbox/src/boundary_exec.rs index 40c433adff..06657f60cf 100644 --- a/crates/openshell-sandbox/src/boundary_exec.rs +++ b/crates/openshell-sandbox/src/boundary_exec.rs @@ -139,9 +139,17 @@ impl LocalBoundaryExec { }) } + fn login_shell(&self) -> Option { + #[cfg(target_os = "linux")] + if let Some(placement) = self.launcher.privileged_placement() { + return crate::privileged::find_workload_login_shell(placement.workload_root()); + } + openshell_core::shell::find_login_shell() + } + fn command(&self, spec: &ExecSpec) -> Result { let (program, args) = if let Some(shell_spec) = &spec.shell { - let shell = openshell_core::shell::find_login_shell().ok_or_else(|| { + let shell = self.login_shell().ok_or_else(|| { BackendError::Process( "sandbox image does not provide an executable shell at /bin/bash, /usr/bin/bash, or /bin/sh" .to_string(), @@ -174,15 +182,28 @@ impl LocalBoundaryExec { let effective_workdir = spec.workdir.as_deref().or(self.base_workdir.as_deref()); let (session_user, session_home) = crate::process::session_user_and_home(&self.policy, effective_workdir); - let path = std::env::var("PATH").unwrap_or_else(|_| "/usr/local/bin:/usr/bin:/bin".into()); + #[cfg(target_os = "linux")] + let is_privileged = self.launcher.privileged_placement().is_some(); + #[cfg(not(target_os = "linux"))] + let is_privileged = false; + let path = if is_privileged { + crate::process::GUEST_WORKLOAD_PATH.to_string() + } else { + std::env::var("PATH").unwrap_or_else(|_| "/usr/local/bin:/usr/bin:/bin".into()) + }; + let effective_user = if is_privileged { + "root".to_string() + } else { + session_user + }; command .env_clear() .env(openshell_core::sandbox_env::SANDBOX, "1") .env("HOME", session_home) - .env("USER", session_user) + .env("USER", effective_user) .env("PATH", path) .env("TERM", if spec.pty { "xterm-256color" } else { "dumb" }); - if let Some(shell) = openshell_core::shell::find_login_shell() { + if let Some(shell) = self.login_shell() { command.env("SHELL", shell); } for (key, value) in &self.user_environment { @@ -247,21 +268,40 @@ impl LocalBoundaryExec { .stderr(Stdio::piped()); let effective_workdir = spec.workdir.as_deref().or(self.base_workdir.as_deref()); #[cfg(target_os = "linux")] - let prepared = self.prepare_sandbox(effective_workdir)?; - #[cfg(target_os = "linux")] - let child_hardening = crate::linux::child_seccomp::prepare(std::process::id()) + if let Some(placement) = self.launcher.privileged_placement() { + placement + .install( + &mut command, + effective_workdir.unwrap_or("/"), + crate::privileged::placement::ChildSession::Pipes, + ) + .map_err(|error| { + BackendError::Process(format!("prepare privileged exec placement: {error}")) + })?; + } else { + let prepared = self.prepare_sandbox(effective_workdir)?; + let child_hardening = crate::linux::child_seccomp::prepare(std::process::id()) + .map_err(|error| BackendError::Process(error.to_string()))?; + crate::pty::install_dedicated_process_group(&mut command); + crate::pty::install_pre_exec_no_pty( + &mut command, + self.policy.clone(), + effective_workdir.map(str::to_string), + prepared, + child_hardening, + ) .map_err(|error| BackendError::Process(error.to_string()))?; - crate::pty::install_dedicated_process_group(&mut command); - crate::pty::install_pre_exec_no_pty( - &mut command, - self.policy.clone(), - effective_workdir.map(str::to_string), - #[cfg(target_os = "linux")] - prepared, - #[cfg(target_os = "linux")] - child_hardening, - ) - .map_err(|error| BackendError::Process(error.to_string()))?; + } + #[cfg(not(target_os = "linux"))] + { + crate::pty::install_dedicated_process_group(&mut command); + crate::pty::install_pre_exec_no_pty( + &mut command, + self.policy.clone(), + effective_workdir.map(str::to_string), + ) + .map_err(|error| BackendError::Process(error.to_string()))?; + } #[cfg(target_os = "linux")] let mut child_registry = crate::managed_children::lock(); #[cfg(target_os = "linux")] @@ -385,19 +425,36 @@ impl LocalBoundaryExec { command.stdin(stdin).stdout(stdout).stderr(slave); let effective_workdir = spec.workdir.as_deref().or(self.base_workdir.as_deref()); #[cfg(target_os = "linux")] - let prepared = self.prepare_sandbox(effective_workdir)?; - #[cfg(target_os = "linux")] - let child_hardening = crate::linux::child_seccomp::prepare(std::process::id()) + if let Some(placement) = self.launcher.privileged_placement() { + placement + .install( + &mut command, + effective_workdir.unwrap_or("/"), + crate::privileged::placement::ChildSession::Terminal, + ) + .map_err(|error| { + BackendError::Process(format!("prepare privileged PTY placement: {error}")) + })?; + } else { + let prepared = self.prepare_sandbox(effective_workdir)?; + let child_hardening = crate::linux::child_seccomp::prepare(std::process::id()) + .map_err(|error| BackendError::Process(error.to_string()))?; + crate::pty::install_pre_exec( + &mut command, + self.policy.clone(), + effective_workdir.map(str::to_string), + slave_fd, + prepared, + child_hardening, + ) .map_err(|error| BackendError::Process(error.to_string()))?; + } + #[cfg(not(target_os = "linux"))] crate::pty::install_pre_exec( &mut command, self.policy.clone(), effective_workdir.map(str::to_string), slave_fd, - #[cfg(target_os = "linux")] - prepared, - #[cfg(target_os = "linux")] - child_hardening, ) .map_err(|error| BackendError::Process(error.to_string()))?; #[cfg(target_os = "linux")] @@ -478,6 +535,41 @@ impl BoundaryExec for LocalBoundaryExec { async fn exec(&self, spec: ExecSpec) -> Result { #[cfg(target_os = "linux")] if spec.runtime_helper.is_some() { + if self.launcher.privileged_placement().is_some() { + let root = spec + .workdir + .as_deref() + .or(self.base_workdir.as_deref()) + .ok_or_else(|| { + BackendError::Process("SFTP requires a workload directory".to_string()) + })? + .to_string(); + let helper_spec = ExecSpec { + program: "/opt/openshell/bin/openshell-sandbox".to_string(), + args: vec![ + crate::privileged::SFTP_ROLE.to_string(), + "--root".to_string(), + root.clone(), + ], + workdir: Some(root), + pty: false, + shell: None, + env: Vec::new(), + runtime_helper: None, + }; + let executor = self.clone(); + let (send, receive) = tokio::sync::oneshot::channel(); + tokio::task::spawn_blocking(move || { + let _ = send.send(executor.spawn_piped(&helper_spec)); + }); + let mut spawned = receive.await.map_err(|_| { + BackendError::Process("privileged SFTP helper spawn cancelled".to_string()) + })??; + spawned.armed = false; + return spawned.session.take().ok_or_else(|| { + BackendError::Process("privileged SFTP helper session missing".to_string()) + }); + } return self.runtime_helper(spec); } let executor = self.clone(); diff --git a/crates/openshell-sandbox/src/boundary_server.rs b/crates/openshell-sandbox/src/boundary_server.rs index 7a74565139..3e453acd30 100644 --- a/crates/openshell-sandbox/src/boundary_server.rs +++ b/crates/openshell-sandbox/src/boundary_server.rs @@ -256,6 +256,12 @@ mod linux { format!("decode boundary config {}: {error}", config_path.display()) })?; validate_config(&config)?; + if config.privileged.is_some() { + return Err( + "boundary config selects privileged mode; launch openshell-sandbox with --privileged" + .to_string(), + ); + } validate_runtime_resource_claims(&config)?; validate_running_identity( &config.workload_identity, @@ -305,6 +311,90 @@ mod linux { serve_then_stop(process_runtime, &config.listener, runtime) } + pub fn run_privileged_boundary(config_path: &Path, workload_root: &Path) -> Result<(), String> { + install_boundary_signal_handlers()?; + make_boundary_nondumpable()?; + disable_core_dumps()?; + let bytes = std::fs::read(config_path) + .map_err(|error| format!("read boundary config {}: {error}", config_path.display()))?; + let config: BoundaryConfig = serde_json::from_slice(&bytes).map_err(|error| { + format!("decode boundary config {}: {error}", config_path.display()) + })?; + validate_config(&config)?; + let Some(profile) = config.privileged else { + return Err( + "openshell-sandbox --privileged requires a privileged boundary bootstrap" + .to_string(), + ); + }; + profile + .validate() + .map_err(|error| format!("invalid privileged profile: {error}"))?; + validate_runtime_resource_claims(&config)?; + std::fs::remove_file(config_path).map_err(|error| { + format!("consume boundary config {}: {error}", config_path.display()) + })?; + crate::process::install_boundary_user_environment(config.child_env.clone())?; + if nix::unistd::getpid().as_raw() != 1 { + rustix::process::set_child_subreaper(Some(rustix::process::getpid())) + .map_err(|error| format!("become child subreaper: {error}"))?; + } + crate::managed_children::start_orphan_reaper() + .map_err(|error| format!("start sandbox orphan reaper: {error}"))?; + let protected_control_port = match &config.listener { + BoundaryListenerConfig::TlsTcp { address, .. } => Some(address.port()), + BoundaryListenerConfig::RuntimeInitiatedTlsTcp { addresses, .. } => { + addresses.first().map(std::net::SocketAddr::port) + } + BoundaryListenerConfig::Unix { .. } + | BoundaryListenerConfig::Vsock { .. } + | BoundaryListenerConfig::RuntimeInitiatedUnix { .. } + | BoundaryListenerConfig::RuntimeInitiatedVsock { .. } => None, + }; + let process_runtime = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .map_err(|error| format!("create boundary process runtime: {error}"))?; + let runtime_guard = process_runtime.enter(); + let (privileged_runtime, launcher, network_broker) = + crate::privileged::PrivilegedRuntime::start( + profile, + workload_root.to_path_buf(), + protected_control_port, + ) + .map_err(|error| format!("start privileged sandbox runtime: {error}"))?; + drop(runtime_guard); + let dummy_qualification = crate::RuntimeQualification { + seccomp: openshell_sandbox_backend::boundary_protocol::SeccompEvidence { + new_listener: true, + notification_round_trip: true, + id_validation: true, + addfd_send: true, + retained_socket_operation: true, + proc_fd_identity: true, + task_memory_read: true, + }, + landlock_abi: 0, + landlock_allow_deny: false, + udp_dns_round_trip: true, + tcp_dns_round_trip: true, + tcp_allow_round_trip: true, + tcp_deny_round_trip: true, + socket_loopback_confinement: true, + }; + let runtime = Arc::new( + BoundaryRuntime::new( + config.clone(), + process_runtime.handle().clone(), + network_broker, + launcher, + dummy_qualification, + )? + .with_privileged(privileged_runtime), + ); + serve_then_stop(process_runtime, &config.listener, runtime) + } + fn serve_then_stop( process_runtime: tokio::runtime::Runtime, config: &BoundaryListenerConfig, @@ -2578,6 +2668,7 @@ mod linux { network_broker: NetworkBroker, workload_launcher: crate::linux::workload_launcher::WorkloadLauncher, qualification: crate::RuntimeQualification, + privileged: Option>, } #[derive(Clone)] @@ -2888,9 +2979,18 @@ mod linux { network_broker, workload_launcher, qualification, + privileged: None, }) } + fn with_privileged( + mut self, + privileged: Arc, + ) -> Self { + self.privileged = Some(privileged); + self + } + #[cfg(test)] fn with_filesystem_flush(mut self, filesystem_flush: FilesystemFlush) -> Self { self.filesystem_flush = Some(filesystem_flush); @@ -2913,7 +3013,15 @@ mod linux { Ok(principal) } - fn discover_image_policy() -> Response { + fn discover_image_policy(&self) -> Response { + if let Some(priv_rt) = &self.privileged { + return Response::ImagePolicy { + yaml: crate::privileged::discover_workload_image_policy( + priv_rt.workload_root(), + ), + invalid: false, + }; + } Self::discover_image_policy_from_paths(&[ openshell_policy::CONTAINER_POLICY_PATH, openshell_policy::LEGACY_CONTAINER_POLICY_PATH, @@ -3137,6 +3245,9 @@ mod linux { if let SupervisorConnectionState::Frozen { recovery_id } = *connection && let Some(process) = process { + if let Some(priv_rt) = &self.privileged { + priv_rt.thaw_workload(); + } if !process.boundary_runtime.resume(recovery_id) { return Err(( BoundaryErrorKind::Process, @@ -3238,13 +3349,20 @@ mod linux { // The recovery identity is allocated before the freeze so a // failed deferred sweep can name it. let recovery_id = self.next_recovery_id.fetch_add(1, Ordering::Relaxed); + let mut freeze_failed = false; if let Some(process) = &process { self.network_broker.set_workload_frozen(true); + if let Some(priv_rt) = &self.privileged + && !priv_rt.freeze_workload() + { + freeze_failed = true; + } let _ = process.boundary_runtime.freeze(recovery_id); } *connection = SupervisorConnectionState::Frozen { recovery_id }; - recovery_id + (recovery_id, freeze_failed) }; + let (recovery_id, freeze_failed) = recovery_id; tracing::warn!( recovery_id, "Sandbox Protocol connection lost; workload frozen pending authenticated recovery" @@ -3263,8 +3381,13 @@ mod linux { .build() ); // The supervisor whose connection was in force chose how long its - // replacement may take. - let recovery_timeout = recovery_offer.unwrap_or(self.default_recovery_timeout); + // replacement may take. If cgroup freeze failed in privileged mode, + // expire immediately instead of leaving the workload running unsupervised. + let recovery_timeout = if freeze_failed { + Duration::ZERO + } else { + recovery_offer.unwrap_or(self.default_recovery_timeout) + }; #[cfg(test)] lock(&self.scheduled_recoveries).push(recovery_timeout); let runtime = Arc::downgrade(self); @@ -3342,6 +3465,9 @@ mod linux { Some(process) => Self::terminate_process_tree(&process, false).await, None => Ok(()), }; + if let Some(priv_rt) = &self.privileged { + priv_rt.kill_workload(); + } // The host may end the VM on acknowledgement. Flush dirty writes // first, even if process termination failed. self.flush_filesystem().await; @@ -3449,7 +3575,7 @@ mod linux { let request_id = envelope.request_id; let payload_digest = envelope.payload_digest; let response = match envelope.request { - Request::DiscoverPolicy => Self::discover_image_policy(), + Request::DiscoverPolicy => self.discover_image_policy(), Request::Attach { policy, supervisor_takeover, @@ -3757,6 +3883,33 @@ mod linux { { return guest_error(BoundaryErrorKind::Denied, error); } + if let Some(priv_rt) = &self.privileged { + let sandbox_policy: openshell_core::policy::SandboxPolicy = policy.clone().into(); + if matches!( + sandbox_policy.landlock.compatibility, + openshell_core::policy::LandlockCompatibility::HardRequirement + ) { + return guest_error( + BoundaryErrorKind::Denied, + "privileged mode enforces filesystem policy via BPF LSM and does not support landlock.compatibility: hard_requirement", + ); + } + if matches!( + sandbox_policy.network.mode, + openshell_core::policy::NetworkMode::Allow + ) { + return guest_error( + BoundaryErrorKind::Denied, + "privileged mode does not permit unrestricted network mode", + ); + } + if let Err(error) = priv_rt.apply_policy(&sandbox_policy, "/sandbox") { + return guest_error( + BoundaryErrorKind::Process, + format!("apply BPF LSM policy: {error}"), + ); + } + } let accepted = match &*state { RuntimeState::AwaitingAttach => { let prepared = match PreparedBoundary::establish(self.network_broker.clone()) { @@ -3868,6 +4021,26 @@ mod linux { } fn measure_confirmation(&self) -> Result { + if let Some(priv_rt) = &self.privileged { + self.network_broker + .confirm_healthy() + .map_err(|error| format!("verify sandbox network broker: {error}"))?; + if !self.workload_launcher.is_alive() { + return Err("sandbox workload launcher is not running".to_string()); + } + let audit = priv_rt.audit_evidence(true); + let backend_audit = serde_json::to_value(audit).map_err(|error| { + format!("encode privileged sandbox audit evidence: {error}") + })?; + return Ok(BoundaryConfirmation { + generation: self.config.generation.clone(), + identity: self.config.workload_identity.clone(), + session_id: self.config.session_id, + provisioning_evidence_digest: self.config.provisioning_evidence.evidence_digest, + resource_claims: self.config.resource_claims.clone(), + backend_audit, + }); + } validate_running_identity( &self.config.workload_identity, allows_runtime_supplementary_groups(&self.config), @@ -3990,6 +4163,71 @@ mod linux { format!("invalid provider files: {error}"), ); } + if let Some(priv_rt) = &self.privileged { + if !provider_files.is_empty() { + return guest_error( + BoundaryErrorKind::Denied, + "in-guest provider files are refused by default in privileged mode; use supervisor L7 credential injection", + ); + } + let ca_file_paths = match (ca_cert.as_deref(), ca_bundle.as_deref()) { + (Some(cert), Some(bundle)) => { + match priv_rt.install_ca_material(cert.as_bytes(), bundle.as_bytes()) { + Ok(paths) => Some(paths), + Err(error) => { + return guest_error( + BoundaryErrorKind::Process, + format!("install privileged CA material: {error}"), + ); + } + } + } + _ => None, + }; + let mut policy: openshell_core::policy::SandboxPolicy = policy.into(); + if let Err(error) = + priv_rt.apply_policy(&policy, spec.workdir.as_deref().unwrap_or("/sandbox")) + { + return guest_error( + BoundaryErrorKind::Process, + format!("apply BPF LSM policy: {error}"), + ); + } + policy.process.run_as_user = Some("0".to_string()); + policy.process.run_as_group = Some("0".to_string()); + let launch = ManagedProcessLaunch { + process_id: format!("{}:main:0", self.config.generation), + spec, + policy, + provider_env_revision, + provider_env, + ca_file_paths, + }; + let provider_file_count = provider_files.len(); + let process = match ManagedProcess::spawn( + &self.process_runtime, + &self.workload_launcher, + launch, + prepared.clone(), + ) { + Ok(process) => Arc::new(process), + Err(error) => return guest_error(BoundaryErrorKind::Process, error), + }; + *lock(&self.started_agent) = Some(requested); + let process_id = process.process_id(); + let revision = process.provider_credentials.snapshot().revision; + let generation = *lock(&process.provider_environment_generation); + *state = RuntimeState::Running(process); + tracing::info!( + provider_file_count, + "Privileged workload canonical process started" + ); + return Response::Started { + process_id, + provider_env_revision: revision, + provider_env_generation: generation, + }; + } let ca_file_paths = match install_ca_material(ca_cert, ca_bundle) { Ok(paths) => paths, Err(error) => return guest_error(BoundaryErrorKind::Process, error), @@ -5606,6 +5844,7 @@ mod linux { host_gateway_ip: None, resource_claims: config.resource_claims.clone(), provisioning_evidence: config.provisioning_evidence.clone(), + privileged: None, }; OpenBoundaryRequest { session_id: config.session_id.to_string(), @@ -5709,6 +5948,7 @@ mod linux { workload_identity: test_workload_identity(), provisioning_evidence: test_provisioning_evidence(), child_env: std::collections::HashMap::new(), + privileged: None, }; let debug = format!("{config:?}"); assert!(debug.contains("test-key")); @@ -5823,6 +6063,7 @@ mod linux { workload_identity: test_workload_identity(), provisioning_evidence: test_provisioning_evidence(), child_env: std::collections::HashMap::new(), + privileged: None, }; assert!(allows_runtime_supplementary_groups(&config)); } @@ -5907,6 +6148,7 @@ mod linux { workload_identity: test_workload_identity(), provisioning_evidence: test_provisioning_evidence(), child_env: std::collections::HashMap::new(), + privileged: None, }, tokio::runtime::Handle::current(), broker, @@ -6380,6 +6622,7 @@ mod linux { workload_identity: test_workload_identity(), provisioning_evidence: test_provisioning_evidence(), child_env: std::collections::HashMap::new(), + privileged: None, }, process_runtime.handle().clone(), network_broker, @@ -6900,6 +7143,7 @@ mod linux { workload_identity: test_workload_identity(), provisioning_evidence: test_provisioning_evidence(), child_env: std::collections::HashMap::new(), + privileged: None, }; validate_config(&config).unwrap(); @@ -7080,6 +7324,7 @@ mod linux { workload_identity: test_workload_identity(), provisioning_evidence: test_provisioning_evidence(), child_env: std::collections::HashMap::new(), + privileged: None, }; for address in [ "127.0.0.1:5500", @@ -7736,6 +7981,7 @@ mod linux { workload_identity: test_workload_identity(), provisioning_evidence: test_provisioning_evidence(), child_env: std::collections::HashMap::new(), + privileged: None, }; validate_config(&config).expect("valid runtime claim configuration"); @@ -8033,6 +8279,7 @@ mod linux { workload_identity: test_workload_identity(), provisioning_evidence: test_provisioning_evidence(), child_env: std::collections::HashMap::new(), + privileged: None, }, tokio::runtime::Handle::current(), network_broker, @@ -8342,6 +8589,7 @@ mod linux { workload_identity: test_workload_identity(), provisioning_evidence: test_provisioning_evidence(), child_env: std::collections::HashMap::new(), + privileged: None, }, process_runtime.handle().clone(), network_broker, @@ -8760,6 +9008,7 @@ mod linux { workload_identity: test_workload_identity(), provisioning_evidence: test_provisioning_evidence(), child_env: std::collections::HashMap::new(), + privileged: None, }, process_runtime.handle().clone(), network_broker, @@ -8980,6 +9229,7 @@ mod linux { workload_identity: test_workload_identity(), provisioning_evidence: test_provisioning_evidence(), child_env: std::collections::HashMap::new(), + privileged: None, }, process_runtime.handle().clone(), network_broker, @@ -10400,6 +10650,7 @@ mod linux { workload_identity: test_workload_identity(), provisioning_evidence: test_provisioning_evidence(), child_env: std::collections::HashMap::new(), + privileged: None, }, process_runtime.handle().clone(), network_broker, @@ -10830,6 +11081,7 @@ mod linux { workload_identity: test_workload_identity(), provisioning_evidence: test_provisioning_evidence(), child_env: std::collections::HashMap::new(), + privileged: None, }, process_runtime.handle().clone(), broker, @@ -10973,3 +11225,13 @@ pub fn run_boundary( ) -> Result<(), String> { Err("boundary mode is supported only on Linux".to_string()) } + +#[cfg(target_os = "linux")] +pub fn run_privileged_boundary(config_path: &Path, workload_root: &Path) -> Result<(), String> { + linux::run_privileged_boundary(config_path, workload_root) +} + +#[cfg(not(target_os = "linux"))] +pub fn run_privileged_boundary(_config_path: &Path, _workload_root: &Path) -> Result<(), String> { + Err("privileged boundary mode is supported only on Linux".to_string()) +} diff --git a/crates/openshell-sandbox/src/lib.rs b/crates/openshell-sandbox/src/lib.rs index 3c280cc977..910003ab55 100644 --- a/crates/openshell-sandbox/src/lib.rs +++ b/crates/openshell-sandbox/src/lib.rs @@ -32,6 +32,8 @@ mod network_broker; #[cfg(all(target_os = "linux", feature = "perf-harness"))] pub mod perf; #[cfg(target_os = "linux")] +pub mod privileged; +#[cfg(target_os = "linux")] pub mod process; #[cfg(target_os = "linux")] mod provider_files; @@ -84,5 +86,14 @@ pub fn run( .map_err(|error| miette::miette!(error)) } +/// Run the privileged (true guest root) VM sandbox sealed by boot-once BPF LSM. +pub fn run_privileged( + config_path: &std::path::Path, + workload_root: &std::path::Path, +) -> miette::Result<()> { + boundary_server::run_privileged_boundary(config_path, workload_root) + .map_err(|error| miette::miette!(error)) +} + #[cfg(target_os = "linux")] mod native_api; diff --git a/crates/openshell-sandbox/src/linux/child_seccomp.rs b/crates/openshell-sandbox/src/linux/child_seccomp.rs index 1d37444125..a641e284cc 100644 --- a/crates/openshell-sandbox/src/linux/child_seccomp.rs +++ b/crates/openshell-sandbox/src/linux/child_seccomp.rs @@ -86,6 +86,37 @@ impl ChildHardeningProgram { } } + /// Install this filter on the calling thread without setting + /// `PR_SET_NO_NEW_PRIVS` (requires `CAP_SYS_ADMIN` in the caller). + pub fn install_privileged(&mut self) -> io::Result<()> { + mark_inherited_descriptors_close_on_exec()?; + let len = u16::try_from(self.instructions.len()).map_err(|_| { + io::Error::new( + io::ErrorKind::InvalidInput, + "child seccomp filter is too large", + ) + })?; + let mut program = libc::sock_fprog { + len, + filter: self.instructions.as_mut_ptr(), + }; + // SAFETY: `program` references the prebuilt cBPF instruction vector + // for the complete syscall. No TSYNC flag is used. + let result = unsafe { + libc::syscall( + libc::SYS_seccomp, + SECCOMP_SET_MODE_FILTER, + 0, + std::ptr::addr_of_mut!(program), + ) + }; + if result < 0 { + Err(io::Error::last_os_error()) + } else { + Ok(()) + } + } + /// Number of cBPF instructions, exposed for admission diagnostics. #[must_use] pub fn instruction_count(&self) -> usize { @@ -144,6 +175,49 @@ pub fn prepare(sandbox_tgid: u32) -> io::Result { build(sandbox_tgid, Mediation::Brokered) } +/// Build the minimal hardening filter for privileged (true guest root) VM +/// workloads. +/// +/// The boot-once BPF LSM protects the shim, runtime mounts, freezer cgroup, +/// `bpf()`, and `AF_VSOCK`/`init_net`. This child filter closes only the +/// seccomp-level network mediation bypasses: `io_uring` (async socket connect +/// outside `seccomp_notify`) and nested `SECCOMP_FILTER_FLAG_NEW_LISTENER`. +/// Ordinary seccomp filters (used by Chrome and `bwrap`), namespaces, mounts, +/// `ptrace`/`strace`/`gdb`, and `clone3` stay allowed. +pub fn prepare_privileged() -> io::Result { + const SECCOMP_FILTER_FLAG_NEW_LISTENER: u32 = 1 << 3; + let mut instructions = vec![ + stmt(BPF_LD_W_ABS, SECCOMP_DATA_ARCH_OFFSET), + jump(BPF_JMP_JEQ_K, native_audit_arch(), 1, 0), + stmt(BPF_RET_K, SECCOMP_RET_KILL_PROCESS), + stmt(BPF_LD_W_ABS, SECCOMP_DATA_NR_OFFSET), + ]; + #[cfg(target_arch = "x86_64")] + instructions.extend([ + jump(BPF_JMP_JSET_K, X32_SYSCALL_BIT, 0, 1), + stmt(BPF_RET_K, SECCOMP_RET_KILL_PROCESS), + ]); + + for syscall in [ + libc::SYS_io_uring_setup, + libc::SYS_io_uring_enter, + libc::SYS_io_uring_register, + ] { + append_unconditional_deny(&mut instructions, syscall)?; + } + // Block nested seccomp user-notification listeners while keeping ordinary + // seccomp filters (used by Chrome and bubblewrap) allowed. + append_argument_masked_deny( + &mut instructions, + libc::SYS_seccomp, + 1, + SECCOMP_FILTER_FLAG_NEW_LISTENER, + )?; + + instructions.push(stmt(BPF_RET_K, SECCOMP_RET_ALLOW)); + Ok(ChildHardeningProgram { instructions }) +} + /// Build the self-protection program for a child no broker mediates. /// /// Nothing can check a named scheduling, priority, or resource-limit target diff --git a/crates/openshell-sandbox/src/linux/seccomp_notify.rs b/crates/openshell-sandbox/src/linux/seccomp_notify.rs index b45dbccd93..d77ee97f5b 100644 --- a/crates/openshell-sandbox/src/linux/seccomp_notify.rs +++ b/crates/openshell-sandbox/src/linux/seccomp_notify.rs @@ -342,6 +342,30 @@ pub fn install_listener(syscalls: &[i64]) -> io::Result { install_notification_filter(syscalls) } +/// INET networking syscalls mediated by the network broker in privileged mode. +pub const NETWORK_NOTIFIED_SYSCALLS: [i64; 8] = [ + libc::SYS_socket, + libc::SYS_connect, + libc::SYS_bind, + libc::SYS_listen, + libc::SYS_sendto, + libc::SYS_sendmsg, + libc::SYS_sendmmsg, + libc::SYS_setsockopt, +]; + +/// Install a networking-only notification listener on a guest-root launcher +/// thread without setting `PR_SET_NO_NEW_PRIVS`. +/// +/// Requires `CAP_SYS_ADMIN` (guest PID 1 root). Leaving `no_new_privs` unset +/// lets setuid helpers inside the privileged workload continue working while +/// keeping every INET socket mediated irreversibly (even guest `UID 0` cannot +/// remove an installed seccomp filter). +pub fn install_network_listener_privileged() -> io::Result { + verify_notification_sizes()?; + install_notification_filter(&NETWORK_NOTIFIED_SYSCALLS) +} + /// Install the capability-free workload networking listener on the calling /// launcher thread. /// diff --git a/crates/openshell-sandbox/src/linux/workload_launcher.rs b/crates/openshell-sandbox/src/linux/workload_launcher.rs index 26431a2a81..2901d42ad0 100644 --- a/crates/openshell-sandbox/src/linux/workload_launcher.rs +++ b/crates/openshell-sandbox/src/linux/workload_launcher.rs @@ -16,7 +16,9 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc; use std::thread; -use crate::linux::seccomp_notify::{NotificationListener, install_workload_listener}; +use crate::linux::seccomp_notify::{ + NotificationListener, install_network_listener_privileged, install_workload_listener, +}; type LaunchJob = Box; @@ -26,9 +28,27 @@ type LaunchJob = Box; pub struct WorkloadLauncher { jobs: mpsc::SyncSender, alive: Arc, + privileged_placement: Option>, } impl WorkloadLauncher { + /// Bind a privileged guest placement to every launch through this launcher. + #[must_use] + pub fn with_privileged_placement( + mut self, + placement: Arc, + ) -> Self { + self.privileged_placement = Some(placement); + self + } + + /// The privileged placement, when this launcher serves `--privileged` mode. + #[must_use] + pub fn privileged_placement( + &self, + ) -> Option<&Arc> { + self.privileged_placement.as_ref() + } /// Execute one prebuilt spawn operation on the filtered launcher thread. /// /// The closure must only perform audited launch work. It must not open an @@ -72,6 +92,18 @@ impl WorkloadLauncher { /// Start the only workload launcher and return its listener to an unfiltered /// sandbox thread. pub fn start() -> io::Result<(WorkloadLauncher, NotificationListener)> { + start_with(install_workload_listener) +} + +/// Start a launcher whose inherited listener mediates only INET networking +/// without `PR_SET_NO_NEW_PRIVS` (for `--privileged` guest PID 1 root). +pub fn start_privileged_networking() -> io::Result<(WorkloadLauncher, NotificationListener)> { + start_with(install_network_listener_privileged) +} + +fn start_with( + install: fn() -> io::Result, +) -> io::Result<(WorkloadLauncher, NotificationListener)> { let (jobs_tx, jobs_rx) = mpsc::sync_channel::(64); let (ready_tx, ready_rx) = mpsc::sync_channel(1); let alive = Arc::new(AtomicBool::new(true)); @@ -79,7 +111,7 @@ pub fn start() -> io::Result<(WorkloadLauncher, NotificationListener)> { thread::Builder::new() .name("openshell-workload-launcher".to_string()) .spawn(move || { - match install_workload_listener() { + match install() { Ok(listener) => { if ready_tx.send(Ok(listener)).is_err() { thread_alive.store(false, Ordering::Release); @@ -152,6 +184,7 @@ pub fn start() -> io::Result<(WorkloadLauncher, NotificationListener)> { WorkloadLauncher { jobs: jobs_tx, alive, + privileged_placement: None, }, listener, )) diff --git a/crates/openshell-sandbox/src/main.rs b/crates/openshell-sandbox/src/main.rs index 8978659ba7..a29b65533a 100644 --- a/crates/openshell-sandbox/src/main.rs +++ b/crates/openshell-sandbox/src/main.rs @@ -62,6 +62,14 @@ struct BoundaryArgs { /// Log level (trace, debug, info, warn, error). #[arg(long, default_value = "warn", env = openshell_core::sandbox_env::LOG_LEVEL)] log_level: String, + + /// Run as privileged (true guest root) VM boundary sealed by boot-once BPF LSM. + #[arg(long, visible_alias = "priv")] + privileged: bool, + + /// Separate mounted workload rootfs used in `--privileged` mode. + #[arg(long, default_value = "/newroot")] + workload_root: std::path::PathBuf, } /// Run the active Phase 0 probe inside the exact workload runtime profile. @@ -1812,6 +1820,70 @@ fn run_boundary(_bootstrap: &Path, _log_level: &str) -> Result<()> { Err(miette::miette!("openshell-sandbox requires Linux")) } +#[cfg(target_os = "linux")] +fn run_privileged_boundary(bootstrap: &Path, workload_root: &Path, log_level: &str) -> Result<()> { + let console_filter = + EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(log_level)); + let _ = tracing_subscriber::registry() + .with( + OcsfShorthandLayer::new( + openshell_sandbox::container_log::ContainerLog::process().launcher_writer(), + ) + .with_non_ocsf(true) + .with_filter(console_filter), + ) + .try_init(); + openshell_sandbox::run_privileged(bootstrap, workload_root) +} + +#[cfg(not(target_os = "linux"))] +fn run_privileged_boundary( + _bootstrap: &Path, + _workload_root: &Path, + _log_level: &str, +) -> Result<()> { + Err(miette::miette!( + "openshell-sandbox --privileged requires Linux" + )) +} + +fn run_privileged_role(role: &str, args: &[String]) -> Option> { + #[cfg(target_os = "linux")] + { + use openshell_sandbox::privileged::{FREEZE_CANARY_ROLE, SFTP_ROLE, WORKLOAD_HOLD_ROLE}; + match role { + WORKLOAD_HOLD_ROLE => { + return Some(match args { + [flag, root] if flag == "--root" => { + openshell_sandbox::privileged::placement::run_workload_hold(Path::new(root)) + .into_diagnostic() + } + _ => Err(miette::miette!( + "usage: openshell-sandbox {WORKLOAD_HOLD_ROLE} --root " + )), + }); + } + FREEZE_CANARY_ROLE => { + return Some(openshell_sandbox::privileged::run_freeze_canary().into_diagnostic()); + } + SFTP_ROLE => { + return Some(match args { + [flag, root] if flag == "--root" => { + openshell_sandbox::privileged::run_sftp_helper(root.into()) + } + _ => Err(miette::miette!( + "usage: openshell-sandbox {SFTP_ROLE} --root " + )), + }); + } + _ => {} + } + } + #[cfg(not(target_os = "linux"))] + let _ = (role, args); + None +} + fn main() -> Result<()> { let raw_args = std::env::args().collect::>(); if raw_args.get(1).map(String::as_str) == Some(COPY_SELF_SUBCOMMAND) { @@ -1851,9 +1923,18 @@ fn main() -> Result<()> { if raw_args.get(1).map(String::as_str) == Some(CAPABILITY_FREE_LAUNCH_SUBCOMMAND) { return launch_capability_free(&raw_args[2..]); } + if let Some(role) = raw_args.get(1) + && let Some(result) = run_privileged_role(role, &raw_args[2..]) + { + return result; + } let args = BoundaryArgs::parse(); - run_boundary(&args.bootstrap, &args.log_level) + if args.privileged { + run_privileged_boundary(&args.bootstrap, &args.workload_root, &args.log_level) + } else { + run_boundary(&args.bootstrap, &args.log_level) + } } #[cfg(all(test, target_os = "linux"))] diff --git a/crates/openshell-sandbox/src/privileged/bpf_lsm.rs b/crates/openshell-sandbox/src/privileged/bpf_lsm.rs new file mode 100644 index 0000000000..14b0606498 --- /dev/null +++ b/crates/openshell-sandbox/src/privileged/bpf_lsm.rs @@ -0,0 +1,474 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Boot-once BPF LSM loader, policy map updater, and ringbuf telemetry reader. + +#![allow(unsafe_code)] + +use std::io; +use std::os::fd::AsFd as _; +use std::os::fd::AsRawFd as _; +use std::path::{Path, PathBuf}; + +use aya::maps::{Array, HashMap as BpfHashMap, RingBuf}; +use aya::programs::{Lsm, lsm::LsmLink}; +use aya::{Btf, Ebpf, Pod}; +use openshell_core::policy::SandboxPolicy; +use openshell_ocsf::{ + ActionId, ActivityId, ConfidenceId, DetectionFindingBuilder, DispositionId, FindingInfo, + Process, ProcessActivityBuilder, SeverityId, StatusId, ocsf_emit, +}; +use tokio::io::unix::AsyncFd; + +use super::path_view::stat_in_root; + +const BPF_MAP_FREEZE: libc::c_long = 22; + +const FS_RULE_RW: u32 = 1; +const FS_RULE_RO: u32 = 2; + +const EVT_EXEC: u32 = 1; +const EVT_DENY_SEAL: u32 = 2; +const EVT_DENY_FS: u32 = 3; +const EVT_DENY_PROC: u32 = 4; +const EVT_TASK_EXIT: u32 = 5; + +static BPF_OBJECT_BYTES: &[u8] = + aya::include_bytes_aligned!(concat!(env!("OUT_DIR"), "/openshell_lsm.bpf.o")); + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +pub struct SealConfig { + pub active: u32, + pub shim_tgid: u32, + pub launcher_tgid: u32, + pub runtime_sb_dev: u32, + pub runtime_root_dev: u32, + pub init_net_inum: u32, + pub freezer_cgroup_ino: u64, + pub cgroup_sb_dev: u32, + pub guest_parent_tgid: u32, +} + +// SAFETY: `SealConfig` is a plain C-layout struct matching `struct seal_config` +// in `bpf/openshell_lsm.bpf.c` with no padding invariants. +unsafe impl Pod for SealConfig {} + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +struct PolicyConfig { + fs_enabled: u32, + proc_enabled: u32, + proc_default_deny: u32, + _pad: u32, +} + +// SAFETY: `PolicyConfig` is a plain C-layout struct matching `struct policy_config`. +unsafe impl Pod for PolicyConfig {} + +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +struct InodeKey { + dev: u32, + _pad: u32, + ino: u64, +} + +// SAFETY: `InodeKey` is a plain C-layout struct matching `struct inode_key`. +unsafe impl Pod for InodeKey {} + +#[repr(C)] +#[derive(Clone, Copy, Debug)] +struct TelemetryEvent { + event_type: u32, + reason: u32, + pid: u32, + tgid: u32, + ppid: u32, + uid: u32, + dev: u32, + _pad: u32, + ino: u64, + comm: [u8; 16], +} + +/// Convert userspace `stat().st_dev` into Linux kernel `super_block->s_dev` +/// (`MKDEV(major, minor) = (major << 20) | minor`). +#[must_use] +pub fn kernel_dev(st_dev: u64) -> u32 { + let major = libc::major(st_dev); + let minor = libc::minor(st_dev); + (major << 20) | minor +} + +fn freeze_map_fd(fd: i32) -> io::Result<()> { + #[repr(C)] + struct BpfMapFreezeAttr { + map_fd: u32, + } + let attr = BpfMapFreezeAttr { + map_fd: u32::try_from(fd) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "negative bpf map fd"))?, + }; + // SAFETY: `SYS_bpf(BPF_MAP_FREEZE, ...)` reads only `map_fd` from `attr`. + let rc = unsafe { + libc::syscall( + libc::SYS_bpf, + BPF_MAP_FREEZE, + &raw const attr, + size_of::(), + ) + }; + if rc < 0 { + Err(io::Error::last_os_error()) + } else { + Ok(()) + } +} + +/// Owns the loaded BPF LSM programs, links (held open by guest PID 1), and maps. +pub struct BpfLsmHandle { + ebpf: Ebpf, + _links: Vec, + tracked_fs_keys: Vec, +} + +const LSM_HOOKS: &[(&str, &str)] = &[ + ("openshell_lsm_bpf", "bpf"), + ("openshell_lsm_ptrace", "ptrace_access_check"), + ("openshell_lsm_perf", "perf_event_alloc"), + ("openshell_lsm_task_kill", "task_kill"), + ("openshell_lsm_task_setrlimit", "task_setrlimit"), + ("openshell_lsm_socket_create", "socket_create"), + ("openshell_lsm_sb_remount", "sb_remount"), + ("openshell_lsm_sb_umount", "sb_umount"), + ("openshell_lsm_locked_down", "locked_down"), + ("openshell_lsm_file_open", "file_open"), + ("openshell_lsm_inode_create", "inode_create"), + ("openshell_lsm_inode_unlink", "inode_unlink"), + ("openshell_lsm_inode_rename", "inode_rename"), + ("openshell_lsm_inode_setattr", "inode_setattr"), + ("openshell_lsm_sb_mount", "sb_mount"), + ("openshell_lsm_bprm_check", "bprm_check_security"), + ("openshell_lsm_task_alloc", "task_alloc"), + ("openshell_lsm_task_free", "task_free"), +]; + +impl BpfLsmHandle { + /// Load, attach, arm, and freeze the boot-once BPF LSM program. + pub fn load_and_seal(mut cfg: SealConfig) -> anyhow::Result { + let btf = Btf::from_sys_fs() + .map_err(|e| anyhow::anyhow!("read /sys/kernel/btf/vmlinux for BPF LSM: {e}"))?; + let mut ebpf = aya::EbpfLoader::new() + .allow_unsupported_maps() + .load(BPF_OBJECT_BYTES) + .map_err(|e| anyhow::anyhow!("load openshell BPF LSM object: {e}"))?; + + let mut links = Vec::with_capacity(LSM_HOOKS.len()); + for &(prog_name, hook_name) in LSM_HOOKS { + let program = ebpf + .program_mut(prog_name) + .ok_or_else(|| anyhow::anyhow!("missing BPF LSM program '{prog_name}'"))?; + let lsm: &mut Lsm = program + .try_into() + .map_err(|e| anyhow::anyhow!("program '{prog_name}' is not an LSM program: {e}"))?; + lsm.load(hook_name, &btf) + .map_err(|e| anyhow::anyhow!("load BPF LSM hook '{hook_name}': {e}"))?; + let link_id = lsm + .attach() + .map_err(|e| anyhow::anyhow!("attach BPF LSM hook '{hook_name}': {e}"))?; + let link = lsm + .take_link(link_id) + .map_err(|e| anyhow::anyhow!("take BPF LSM link '{hook_name}': {e}"))?; + links.push(link); + } + + // Measure our true root-PID-namespace TGID and parent TGID from inside + // the kernel via `openshell_lsm_bpf` before arming and freezing + // `seal_cfg`. This works both when running as guest PID 1 + // (libkrun/Firecracker) and inside a child PID namespace (Kata + // Containers on Kubernetes, where `kata-agent` is our parent task). + let (kernel_tgid, guest_parent_tgid) = { + let map = ebpf + .map("shim_id") + .ok_or_else(|| anyhow::anyhow!("missing shim_id BPF map"))?; + let array: Array<_, u32> = + Array::try_from(map).map_err(|e| anyhow::anyhow!("open shim_id BPF array: {e}"))?; + // First lookup triggers lsm/bpf (which populates shim_id[0..2]); + // subsequent lookups read back the recorded kernel TGIDs. + let _ = array.get(&0, 0); + let tgid = array + .get(&0, 0) + .map_err(|e| anyhow::anyhow!("read shim_id[0] BPF array: {e}"))?; + let parent_tgid = array + .get(&1, 0) + .map_err(|e| anyhow::anyhow!("read shim_id[1] BPF array: {e}"))?; + (tgid, parent_tgid) + }; + if kernel_tgid == 0 { + anyhow::bail!("BPF LSM failed to record kernel shim TGID"); + } + cfg.shim_tgid = kernel_tgid; + cfg.guest_parent_tgid = if kernel_tgid > 1 { + guest_parent_tgid + } else { + 0 + }; + cfg.active = 1; + { + let map = ebpf + .map_mut("seal_cfg") + .ok_or_else(|| anyhow::anyhow!("missing seal_cfg BPF map"))?; + let mut array: Array<_, SealConfig> = Array::try_from(map) + .map_err(|e| anyhow::anyhow!("open seal_cfg BPF array: {e}"))?; + array + .set(0, cfg, 0) + .map_err(|e| anyhow::anyhow!("write seal_cfg BPF map: {e}"))?; + } + { + let map = ebpf + .map("seal_cfg") + .ok_or_else(|| anyhow::anyhow!("missing seal_cfg BPF map"))?; + let aya::maps::Map::Array(data) = map else { + anyhow::bail!("seal_cfg BPF map is not an array"); + }; + let info = data + .info() + .map_err(|e| anyhow::anyhow!("read seal_cfg BPF map info: {e}"))?; + let map_fd = info + .fd() + .map_err(|e| anyhow::anyhow!("open seal_cfg BPF map fd: {e}"))?; + freeze_map_fd(map_fd.as_fd().as_raw_fd()) + .map_err(|e| anyhow::anyhow!("freeze seal_cfg BPF map: {e}"))?; + } + + tracing::info!( + hooks = links.len(), + shim_tgid = cfg.shim_tgid, + runtime_sb_dev = cfg.runtime_sb_dev, + init_net_inum = cfg.init_net_inum, + freezer_cgroup_ino = cfg.freezer_cgroup_ino, + "boot-once BPF LSM seal armed and frozen" + ); + + Ok(Self { + ebpf, + _links: links, + tracked_fs_keys: Vec::new(), + }) + } + + /// Populate or live-reload `filesystem_policy` and `process` rules in the + /// BPF LSM maps from `policy`. + pub fn apply_policy( + &mut self, + workload_root: &Path, + policy: &SandboxPolicy, + workdir: &str, + ) -> anyhow::Result { + let mut entries: Vec<(InodeKey, u32)> = Vec::new(); + for ro_path in &policy.filesystem.read_only { + if let Ok((st_dev, st_ino)) = stat_in_root(workload_root, ro_path) { + entries.push(( + InodeKey { + dev: kernel_dev(st_dev), + _pad: 0, + ino: st_ino, + }, + FS_RULE_RO, + )); + } + } + let mut rw_paths: Vec = policy.filesystem.read_write.clone(); + if !workdir.is_empty() && !rw_paths.iter().any(|p| p == Path::new(workdir)) { + rw_paths.push(PathBuf::from(workdir)); + } + for rw_path in &rw_paths { + if let Ok((st_dev, st_ino)) = stat_in_root(workload_root, rw_path) { + entries.push(( + InodeKey { + dev: kernel_dev(st_dev), + _pad: 0, + ino: st_ino, + }, + FS_RULE_RW, + )); + } + } + + // Remove stale entries before inserting the new snapshot so live reload + // drops removed rules without leaving orphans. + let new_keys: Vec = entries.iter().map(|(k, _)| *k).collect(); + let stale: Vec = self + .tracked_fs_keys + .iter() + .copied() + .filter(|old| !new_keys.contains(old)) + .collect(); + + { + let map = self + .ebpf + .map_mut("fs_rules") + .ok_or_else(|| anyhow::anyhow!("missing fs_rules BPF map"))?; + let mut fs_map: BpfHashMap<_, InodeKey, u32> = BpfHashMap::try_from(map) + .map_err(|e| anyhow::anyhow!("open fs_rules BPF map: {e}"))?; + for key in stale { + let _ = fs_map.remove(&key); + } + for &(key, verdict) in &entries { + fs_map + .insert(key, verdict, 0) + .map_err(|e| anyhow::anyhow!("insert fs_rules BPF entry: {e}"))?; + } + } + self.tracked_fs_keys = new_keys; + + let fs_enabled = u32::from(!policy.filesystem.read_only.is_empty()); + { + let map = self + .ebpf + .map_mut("policy_cfg") + .ok_or_else(|| anyhow::anyhow!("missing policy_cfg BPF map"))?; + let mut array: Array<_, PolicyConfig> = Array::try_from(map) + .map_err(|e| anyhow::anyhow!("open policy_cfg BPF map: {e}"))?; + array + .set( + 0, + PolicyConfig { + fs_enabled, + proc_enabled: 0, + proc_default_deny: 0, + _pad: 0, + }, + 0, + ) + .map_err(|e| anyhow::anyhow!("update policy_cfg BPF map: {e}"))?; + } + + tracing::info!( + rules = entries.len(), + fs_enabled = fs_enabled != 0, + "updated BPF LSM filesystem policy map" + ); + Ok(entries.len()) + } + + /// Spawn a background tokio task that drains kernel-sourced telemetry from + /// the BPF ringbuf and emits OCSF events. + pub fn spawn_telemetry_reader(&mut self) -> anyhow::Result<()> { + let Some(map) = self.ebpf.take_map("telemetry_rb") else { + return Ok(()); + }; + let ring = RingBuf::try_from(map) + .map_err(|e| anyhow::anyhow!("open telemetry_rb BPF ringbuf: {e}"))?; + // SAFETY: `ring` owns its valid BPF ringbuf file descriptor for the + // entire lifetime of `async_fd`. + let async_fd = unsafe { AsyncFd::register(ring) } + .map_err(|e| anyhow::anyhow!("register telemetry_rb with tokio: {e}"))?; + tokio::spawn(async move { + let mut async_fd = async_fd; + loop { + let Ok(mut guard) = async_fd.readable_mut().await else { + break; + }; + while let Some(item) = guard.get_inner_mut().next() { + if item.len() >= size_of::() { + // SAFETY: `TelemetryEvent` is a plain `#[repr(C)]` POD + // written by the BPF ringbuf producer; `read_unaligned` + // handles any ringbuf buffer alignment. + let evt = unsafe { + std::ptr::read_unaligned(item.as_ptr().cast::()) + }; + emit_telemetry_ocsf(&evt); + } + } + guard.clear_ready(); + } + }); + Ok(()) + } +} + +fn emit_telemetry_ocsf(evt: &TelemetryEvent) { + let nul = evt + .comm + .iter() + .position(|&b| b == 0) + .unwrap_or(evt.comm.len()); + let comm = String::from_utf8_lossy(&evt.comm[..nul]).into_owned(); + let proc_info = Process::new(&comm, i64::from(evt.tgid)); + let actor = Process::new("openshell-sandbox", i64::from(std::process::id())); + + match evt.event_type { + EVT_EXEC => { + let event = ProcessActivityBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::Open) + .severity(SeverityId::Informational) + .status(StatusId::Success) + .process(proc_info) + .actor_process(actor) + .message(format!( + "bpf-lsm exec pid={} ppid={} uid={} comm={comm} ino={}", + evt.tgid, evt.ppid, evt.uid, evt.ino + )) + .build(); + ocsf_emit!(event); + } + EVT_TASK_EXIT => { + let event = ProcessActivityBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::Close) + .severity(SeverityId::Informational) + .status(StatusId::Success) + .process(proc_info) + .actor_process(actor) + .message(format!( + "bpf-lsm exit pid={} ppid={} uid={} comm={comm}", + evt.tgid, evt.ppid, evt.uid + )) + .build(); + ocsf_emit!(event); + } + EVT_DENY_SEAL => { + let finding = DetectionFindingBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::Open) + .action(ActionId::Denied) + .disposition(DispositionId::Blocked) + .severity(SeverityId::High) + .confidence(ConfidenceId::High) + .is_alert(true) + .finding_info(FindingInfo::new( + "sandbox-bpf-lsm-seal-denied", + "BPF LSM shim seal violation", + )) + .message(format!( + "bpf-lsm seal denied reason={} pid={} uid={} comm={comm} dev={} ino={}", + evt.reason, evt.tgid, evt.uid, evt.dev, evt.ino + )) + .build(); + ocsf_emit!(finding); + } + EVT_DENY_FS | EVT_DENY_PROC => { + let kind = if evt.event_type == EVT_DENY_FS { + "filesystem" + } else { + "process" + }; + let event = ProcessActivityBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::Open) + .action(ActionId::Denied) + .disposition(DispositionId::Blocked) + .severity(SeverityId::Medium) + .status(StatusId::Failure) + .process(proc_info) + .actor_process(actor) + .message(format!( + "bpf-lsm {kind} policy denied rule={} pid={} uid={} comm={comm} dev={} ino={}", + evt.reason, evt.tgid, evt.uid, evt.dev, evt.ino + )) + .build(); + ocsf_emit!(event); + } + _ => {} + } +} diff --git a/crates/openshell-sandbox/src/privileged/mod.rs b/crates/openshell-sandbox/src/privileged/mod.rs new file mode 100644 index 0000000000..457b2d9c0d --- /dev/null +++ b/crates/openshell-sandbox/src/privileged/mod.rs @@ -0,0 +1,491 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Privileged (true guest root) VM runtime with boot-once BPF LSM sealing. + +#![allow(unsafe_code)] + +pub mod bpf_lsm; +pub mod path_view; +pub mod placement; + +use std::fs::{self, File}; +use std::io::{self, Read as _, Write as _}; +use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use openshell_core::policy::SandboxPolicy; +use openshell_sandbox_backend::privileged::{ + PrivilegedGuestProfile, PrivilegedSandboxAuditEvidence, +}; + +use crate::linux::workload_launcher::WorkloadLauncher; +use crate::network_broker::NetworkBroker; +use bpf_lsm::{BpfLsmHandle, SealConfig, kernel_dev}; +use placement::PrivilegedPlacement; + +/// Runtime-private root tmpfs directory (holds bootstrap, CA material, state). +pub const RUNTIME_BASE_DIR: &str = "/run/openshell"; +/// Runtime-owned CA material, bind-mounted read-only into the workload. +pub const RUNTIME_TLS_DIR: &str = "/run/openshell/tls"; +/// Where the workload sees the CA material. +pub const WORKLOAD_TLS_DIR: &str = "/etc/openshell-tls"; +/// Runtime-owned freezer cgroup parent (outside the workload's cgroupns). +pub const WORKLOAD_CGROUP_DIR: &str = "/sys/fs/cgroup/openshell-workload"; +/// Workload's child cgroup directory (the workload's cgroupns root). +pub const WORKLOAD_CGROUP_INIT_DIR: &str = "/sys/fs/cgroup/openshell-workload/init"; + +/// Hidden subcommand for the workload namespace holder (workload PID 1). +pub const WORKLOAD_HOLD_ROLE: &str = "workload-hold"; +/// Hidden subcommand for the cgroup freezer qualification canary. +pub const FREEZE_CANARY_ROLE: &str = "guest-freeze-canary"; +/// Hidden subcommand for placed SFTP helper (runs inside workload namespaces). +pub const SFTP_ROLE: &str = "sftp-server"; + +/// Freezer-qualification canary: arms a periodic `SIGCONT` timer and writes +/// progress bytes until killed. Proves `cgroup.freeze` holds even against a +/// hostile self-resuming workload. +pub fn run_freeze_canary() -> io::Result<()> { + // SAFETY: zeroed sigevent/itimerspec for timer_create/timer_settime. + unsafe { + let mut event: libc::sigevent = std::mem::zeroed(); + event.sigev_notify = libc::SIGEV_SIGNAL; + event.sigev_signo = libc::SIGCONT; + let mut timer: libc::timer_t = std::mem::zeroed(); + if libc::timer_create(libc::CLOCK_MONOTONIC, &raw mut event, &raw mut timer) != 0 { + return Err(io::Error::last_os_error()); + } + let period = libc::timespec { + tv_sec: 0, + tv_nsec: 20_000_000, + }; + let spec = libc::itimerspec { + it_interval: period, + it_value: period, + }; + if libc::timer_settime(timer, 0, &raw const spec, std::ptr::null_mut()) != 0 { + return Err(io::Error::last_os_error()); + } + } + let mut stdout = io::stdout().lock(); + loop { + stdout.write_all(b".")?; + stdout.flush()?; + std::thread::sleep(Duration::from_millis(5)); + } +} + +/// Serve SFTP over stdin/stdout inside the placed workload namespaces. +pub fn run_sftp_helper(root: PathBuf) -> miette::Result<()> { + use miette::IntoDiagnostic as _; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .into_diagnostic()?; + runtime.block_on(crate::sftp::serve( + tokio::io::join(tokio::io::stdin(), tokio::io::stdout()), + root, + )) +} + +/// Find a login shell confined to `workload_root`. +#[must_use] +pub fn find_workload_login_shell(workload_root: &Path) -> Option { + for candidate in ["/bin/bash", "/usr/bin/bash", "/bin/sh", "/usr/bin/sh"] { + if path_view::is_executable_in_root(workload_root, Path::new(candidate)) { + return Some(candidate.to_string()); + } + } + None +} + +/// Detect a login shell inside `workload_root`, defaulting to `/bin/sh`. +#[must_use] +pub fn detect_workload_login_shell(workload_root: &Path) -> String { + find_workload_login_shell(workload_root).unwrap_or_else(|| "/bin/sh".to_string()) +} + +/// Read an image-embedded sandbox policy confined to `workload_root`. +pub fn discover_workload_image_policy(workload_root: &Path) -> Option { + for path in [ + "/etc/openshell/policy.yaml", + "/etc/openshell/policy.yml", + "/.openshell/policy.yaml", + ] { + if let Ok(content) = + path_view::read_to_string_in_root(workload_root, Path::new(path), 1024 * 1024) + && !content.trim().is_empty() + { + return Some(content); + } + } + None +} + +fn qualify_cgroup_freezer() -> bool { + let freeze_file = Path::new(WORKLOAD_CGROUP_DIR).join("cgroup.freeze"); + let procs_file = Path::new(WORKLOAD_CGROUP_INIT_DIR).join("cgroup.procs"); + let _ = fs::create_dir_all(WORKLOAD_CGROUP_INIT_DIR); + if !freeze_file.exists() || !procs_file.exists() { + return false; + } + let Ok(exe) = std::env::current_exe() else { + return false; + }; + let Ok(mut child) = Command::new(exe) + .arg(FREEZE_CANARY_ROLE) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + else { + return false; + }; + let pid = child.id(); + if fs::write(&procs_file, format!("{pid}\n")).is_err() { + let _ = child.kill(); + let _ = child.wait(); + return false; + } + let Some(mut stdout) = child.stdout.take() else { + let _ = child.kill(); + let _ = child.wait(); + return false; + }; + let mut byte = [0u8; 1]; + if stdout.read_exact(&mut byte).is_err() { + let _ = child.kill(); + let _ = child.wait(); + return false; + } + // Freeze the cgroup and confirm frozen=1 in cgroup.events. + if fs::write(&freeze_file, "1\n").is_err() { + let _ = child.kill(); + let _ = child.wait(); + return false; + } + let deadline = Instant::now() + Duration::from_secs(2); + let mut frozen = false; + while Instant::now() < deadline { + if let Ok(events) = fs::read_to_string(Path::new(WORKLOAD_CGROUP_DIR).join("cgroup.events")) + && events.lines().any(|line| line.trim() == "frozen 1") + { + frozen = true; + break; + } + std::thread::sleep(Duration::from_millis(10)); + } + let _ = child.kill(); + let _ = fs::write(&freeze_file, "0\n"); + let _ = child.wait(); + frozen +} + +/// Active privileged (true guest root) runtime owned by `BoundaryServer`. +pub struct PrivilegedRuntime { + profile: PrivilegedGuestProfile, + workload_root: PathBuf, + placement: Arc, + bpf_lsm: Mutex, + standing_freeze: bool, + init_net_isolated: bool, + seccomp_addfd_send: bool, + kernel_release: String, + native_architecture: String, +} + +impl PrivilegedRuntime { + /// Bootstrap the privileged runtime, qualify cgroup freeze, start the + /// workload namespace holder, arm and freeze the boot-once BPF LSM, and + /// return the runtime plus the networking `WorkloadLauncher` and `NetworkBroker`. + pub fn start( + profile: PrivilegedGuestProfile, + workload_root: PathBuf, + protected_control_port: Option, + ) -> anyhow::Result<(Arc, WorkloadLauncher, NetworkBroker)> { + profile + .validate() + .map_err(|e| anyhow::anyhow!("invalid privileged profile: {e}"))?; + + let uid = nix::unistd::geteuid().as_raw(); + if uid != 0 { + anyhow::bail!("--privileged requires guest root (UID 0), got UID {uid}"); + } + + // Harden the shim process itself before forking anything. + // SAFETY: PR_SET_DUMPABLE=0 and RLIMIT_CORE=0 are scalar process transitions. + unsafe { + if libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0) != 0 { + return Err(io::Error::last_os_error().into()); + } + let zero = libc::rlimit { + rlim_cur: 0, + rlim_max: 0, + }; + let _ = libc::setrlimit(libc::RLIMIT_CORE, &raw const zero); + } + + // Ensure /run/openshell is a dedicated runtime-private tmpfs mount + // (distinct from `/`) so BPF LSM guards it even when the container's + // `/` is itself the workload rootfs (e.g. Kata Containers on k8s). + fs::create_dir_all(RUNTIME_BASE_DIR)?; + let root_dev_raw = fs::metadata("/")?.dev(); + if fs::metadata(RUNTIME_BASE_DIR)?.dev() == root_dev_raw { + let src = std::ffi::CString::new("tmpfs").expect("static"); + let dst = std::ffi::CString::new(RUNTIME_BASE_DIR).expect("static"); + let opts = std::ffi::CString::new("mode=0700").expect("static"); + // SAFETY: all pointers are NUL-terminated static strings. + if unsafe { + libc::mount( + src.as_ptr(), + dst.as_ptr(), + src.as_ptr(), + libc::MS_NOSUID | libc::MS_NODEV, + opts.as_ptr().cast(), + ) + } != 0 + { + return Err(io::Error::last_os_error().into()); + } + } + fs::create_dir_all(RUNTIME_TLS_DIR)?; + fs::set_permissions(RUNTIME_TLS_DIR, fs::Permissions::from_mode(0o755))?; + + let container_root_mode = workload_root == Path::new("/"); + let runtime_root_dev = if container_root_mode { + 0 + } else { + kernel_dev(root_dev_raw) + }; + let runtime_sb_dev = kernel_dev(fs::metadata(RUNTIME_BASE_DIR)?.dev()); + let workload_root_dev = kernel_dev(fs::metadata(&workload_root)?.dev()); + if !container_root_mode && workload_root_dev == runtime_root_dev { + anyhow::bail!( + "workload root {} must reside on a separate mount from runtime root /", + workload_root.display() + ); + } + if runtime_sb_dev == workload_root_dev { + anyhow::bail!( + "runtime state dir {RUNTIME_BASE_DIR} must reside on a separate mount from workload root {}", + workload_root.display() + ); + } + + // Qualify cgroup.freeze before launching workload-hold. + let has_cgroup_v2 = Path::new("/sys/fs/cgroup/cgroup.controllers").exists(); + let standing_freeze = if has_cgroup_v2 { + qualify_cgroup_freezer() + } else { + false + }; + let (cgroup_sb_dev, freezer_cgroup_ino) = + if has_cgroup_v2 && let Ok(meta) = fs::metadata(WORKLOAD_CGROUP_DIR) { + (kernel_dev(meta.dev()), meta.ino()) + } else { + (0, 0) + }; + + // Measure init_net inode before launching workload-hold in CLONE_NEWNET. + #[allow(clippy::cast_possible_truncation)] + let init_net_inum = fs::metadata("/proc/self/ns/net")?.ino() as u32; + + // Spawn workload-hold in its dedicated mount, PID, cgroup, and net namespaces. + let placement = Arc::new( + PrivilegedPlacement::start(workload_root.clone(), has_cgroup_v2) + .map_err(|e| anyhow::anyhow!("start privileged workload namespaces: {e}"))?, + ); + let init_net_isolated = placement.workload_net_inum() != init_net_inum; + if !init_net_isolated { + anyhow::bail!("workload network namespace did not isolate from init_net"); + } + + // Arm and freeze the boot-once BPF LSM seal BEFORE starting any workload code. + let shim_tgid = std::process::id(); + let mut bpf_lsm = BpfLsmHandle::load_and_seal(SealConfig { + active: 1, + shim_tgid, + launcher_tgid: 0, + runtime_sb_dev, + runtime_root_dev, + init_net_inum, + freezer_cgroup_ino, + cgroup_sb_dev, + guest_parent_tgid: 0, + })?; + bpf_lsm.spawn_telemetry_reader()?; + + // Qualify seccomp_notify ADDFD support. + let seccomp_probe = crate::linux::seccomp_notify::probe_notification_api() + .map_err(|e| anyhow::anyhow!("seccomp_notify qualification failed: {e}"))?; + let seccomp_addfd_send = seccomp_probe.addfd_send(); + + // Start the networking-only seccomp_notify WorkloadLauncher (without + // PR_SET_NO_NEW_PRIVS) and attach our privileged placement. + let (launcher, listener) = + crate::linux::workload_launcher::start_privileged_networking() + .map_err(|e| anyhow::anyhow!("start privileged workload launcher: {e}"))?; + let launcher = launcher.with_privileged_placement(Arc::clone(&placement)); + + let broker = NetworkBroker::start(listener, protected_control_port) + .map_err(|e| anyhow::anyhow!("start privileged network broker: {e}"))?; + + let (kernel_release, native_architecture) = read_utsname(); + + let runtime = Arc::new(Self { + profile, + workload_root, + placement, + bpf_lsm: Mutex::new(bpf_lsm), + standing_freeze, + init_net_isolated, + seccomp_addfd_send, + kernel_release, + native_architecture, + }); + + Ok((runtime, launcher, broker)) + } + + #[must_use] + pub fn workload_root(&self) -> &Path { + &self.workload_root + } + + #[must_use] + pub fn placement(&self) -> &Arc { + &self.placement + } + + #[must_use] + pub const fn standing_freeze(&self) -> bool { + self.standing_freeze + } + + /// Apply or live-reload `filesystem_policy` and `process` rules in the BPF LSM maps. + pub fn apply_policy(&self, policy: &SandboxPolicy, workdir: &str) -> anyhow::Result { + let mut lsm = self + .bpf_lsm + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + lsm.apply_policy(&self.workload_root, policy, workdir) + } + + /// Write supervisor CA certificate and bundle into `/run/openshell/tls` + /// (visible read-only at `/etc/openshell-tls` inside the workload). + pub fn install_ca_material( + &self, + cert_pem: &[u8], + bundle_pem: &[u8], + ) -> io::Result<(PathBuf, PathBuf)> { + fs::create_dir_all(RUNTIME_TLS_DIR)?; + let cert_path = Path::new(RUNTIME_TLS_DIR).join("ca.crt"); + let bundle_path = Path::new(RUNTIME_TLS_DIR).join("ca-bundle.crt"); + write_atomic(&cert_path, cert_pem, 0o644)?; + write_atomic(&bundle_path, bundle_pem, 0o644)?; + Ok(( + Path::new(WORKLOAD_TLS_DIR).join("ca.crt"), + Path::new(WORKLOAD_TLS_DIR).join("ca-bundle.crt"), + )) + } + + /// Freeze the runtime-owned workload cgroup. Returns `true` if frozen. + pub fn freeze_workload(&self) -> bool { + if !self.standing_freeze { + return false; + } + let freeze_file = Path::new(WORKLOAD_CGROUP_DIR).join("cgroup.freeze"); + if fs::write(&freeze_file, "1\n").is_err() { + return false; + } + let deadline = Instant::now() + Duration::from_secs(2); + while Instant::now() < deadline { + if let Ok(events) = + fs::read_to_string(Path::new(WORKLOAD_CGROUP_DIR).join("cgroup.events")) + && events.lines().any(|line| line.trim() == "frozen 1") + { + return true; + } + std::thread::sleep(Duration::from_millis(10)); + } + false + } + + /// Thaw the runtime-owned workload cgroup. + pub fn thaw_workload(&self) { + if self.standing_freeze { + let _ = fs::write(Path::new(WORKLOAD_CGROUP_DIR).join("cgroup.freeze"), "0\n"); + } + } + + /// Kill every process in the workload cgroup (and terminate the holder). + pub fn kill_workload(&self) { + let kill_file = Path::new(WORKLOAD_CGROUP_DIR).join("cgroup.kill"); + if kill_file.exists() { + let _ = fs::write(&kill_file, "1\n"); + } + self.thaw_workload(); + self.placement.terminate_holder(); + } + + /// Build the confirmation audit evidence validated by the supervisor. + #[must_use] + pub fn audit_evidence(&self, broker_healthy: bool) -> PrivilegedSandboxAuditEvidence { + // SAFETY: PR_GET_DUMPABLE reads one scalar process property. + let dumpable = unsafe { libc::prctl(libc::PR_GET_DUMPABLE, 0, 0, 0, 0) } != 0; + // SAFETY: zeroed rlimit struct populated by getrlimit(RLIMIT_CORE). + let core_limit_zero = unsafe { + let mut rl: libc::rlimit = std::mem::zeroed(); + libc::getrlimit(libc::RLIMIT_CORE, &raw mut rl) == 0 && rl.rlim_cur == 0 + }; + PrivilegedSandboxAuditEvidence { + profile: self.profile, + runtime_uid: nix::unistd::geteuid().as_raw(), + workload_uid: 0, + sandbox_dumpable: dumpable, + core_limit_zero, + native_architecture: self.native_architecture.clone(), + kernel_release: self.kernel_release.clone(), + separate_workload_root: true, + bpf_lsm_sealed: true, + bpf_policy_enforced: true, + init_net_isolated: self.init_net_isolated, + vsock_blocked: true, + network_mediation: broker_healthy, + seccomp_addfd_send: self.seccomp_addfd_send, + standing_freeze: self.standing_freeze, + landlock_applied: false, + } + } +} + +fn write_atomic(path: &Path, content: &[u8], mode: u32) -> io::Result<()> { + let tmp = path.with_extension("tmp"); + let mut file = File::create(&tmp)?; + file.write_all(content)?; + file.sync_all()?; + fs::set_permissions(&tmp, fs::Permissions::from_mode(mode))?; + fs::rename(&tmp, path) +} + +fn read_utsname() -> (String, String) { + // SAFETY: zeroed utsname passed to libc::uname. + unsafe { + let mut uts: libc::utsname = std::mem::zeroed(); + if libc::uname(&raw mut uts) != 0 { + return ("unknown".to_string(), std::env::consts::ARCH.to_string()); + } + let to_str = |buf: &[libc::c_char]| { + let bytes: Vec = buf + .iter() + .take_while(|&&c| c != 0) + .map(|&c| c.to_ne_bytes()[0]) + .collect(); + String::from_utf8_lossy(&bytes).into_owned() + }; + (to_str(&uts.release), to_str(&uts.machine)) + } +} diff --git a/crates/openshell-sandbox/src/privileged/path_view.rs b/crates/openshell-sandbox/src/privileged/path_view.rs new file mode 100644 index 0000000000..2926da6783 --- /dev/null +++ b/crates/openshell-sandbox/src/privileged/path_view.rs @@ -0,0 +1,91 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Confined lookups inside the separate workload root using `openat2(RESOLVE_IN_ROOT)`. + +#![allow(unsafe_code)] + +use std::ffi::CString; +use std::fs::File; +use std::io; +use std::os::fd::{AsRawFd as _, FromRawFd as _, OwnedFd}; +use std::os::unix::ffi::OsStrExt as _; +use std::os::unix::fs::MetadataExt as _; +use std::path::Path; + +const RESOLVE_IN_ROOT: u64 = 0x10; + +#[repr(C)] +struct OpenHow { + flags: u64, + mode: u64, + resolve: u64, +} + +/// Open `guest_path` confined to `root` via `openat2(RESOLVE_IN_ROOT)`. +pub fn open_in_root(root: &Path, guest_path: &Path, flags: i32) -> io::Result { + let root_dir = File::open(root)?; + let relative = guest_path.strip_prefix("/").unwrap_or(guest_path); + let target = if relative.as_os_str().is_empty() { + CString::new(".").expect("static dot") + } else { + CString::new(relative.as_os_str().as_bytes()) + .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))? + }; + let how = OpenHow { + flags: u64::try_from(flags | libc::O_CLOEXEC).unwrap_or(0), + mode: 0, + resolve: RESOLVE_IN_ROOT, + }; + // SAFETY: `root_dir` is a valid open directory fd, `target` is NUL-terminated, + // and `how` matches Linux's `struct open_how`. + let fd = unsafe { + libc::syscall( + libc::SYS_openat2, + root_dir.as_raw_fd(), + target.as_ptr(), + &raw const how, + size_of::(), + ) + }; + if fd < 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: `fd` is a fresh open descriptor owned from here. + #[allow(clippy::cast_possible_truncation)] + Ok(unsafe { OwnedFd::from_raw_fd(fd as i32) }) +} + +/// Resolve a workload path to its `(st_dev, st_ino)` confined to `root`. +pub fn stat_in_root(root: &Path, guest_path: &Path) -> io::Result<(u64, u64)> { + let fd = open_in_root(root, guest_path, libc::O_PATH)?; + let file = File::from(fd); + let meta = file.metadata()?; + Ok((meta.dev(), meta.ino())) +} + +/// Read a bounded file inside `root` confined with `RESOLVE_IN_ROOT`. +pub fn read_to_string_in_root( + root: &Path, + guest_path: &Path, + max_bytes: usize, +) -> io::Result { + use std::io::Read as _; + let fd = open_in_root(root, guest_path, libc::O_RDONLY)?; + let file = File::from(fd); + let mut out = String::new(); + file.take(max_bytes as u64).read_to_string(&mut out)?; + Ok(out) +} + +/// Check whether `guest_path` is an executable regular file inside `root`. +pub fn is_executable_in_root(root: &Path, guest_path: &Path) -> bool { + let Ok(fd) = open_in_root(root, guest_path, libc::O_PATH) else { + return false; + }; + let file = File::from(fd); + let Ok(meta) = file.metadata() else { + return false; + }; + meta.is_file() && (meta.mode() & 0o111) != 0 +} diff --git a/crates/openshell-sandbox/src/privileged/placement.rs b/crates/openshell-sandbox/src/privileged/placement.rs new file mode 100644 index 0000000000..b8d24cd8ec --- /dev/null +++ b/crates/openshell-sandbox/src/privileged/placement.rs @@ -0,0 +1,786 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Placement of privileged (true guest root) workload processes. +//! +//! A long-lived `workload-hold` helper child holds the workload's dedicated +//! mount namespace (pivoted into the separate workload rootfs with +//! `MS_REC | MS_PRIVATE`), child PID namespace (where it is workload PID 1), +//! child cgroup namespace (under the runtime-owned freezer cgroup), and +//! loopback-only network namespace (`CLONE_NEWNET`, `lo` up). +//! +//! Every workload process (main, exec, PTY, SFTP) is spawned on the +//! `WorkloadLauncher` thread: +//! 1. The launcher switches `pid_ns_for_children` to `workload_pid_ns`, forks +//! the child into the workload PID namespace, and restores its own PID ns. +//! 2. Between `fork` and `exec` (`pre_exec`, async-signal-safe), the child +//! writes itself into the workload cgroup, enters the holder's cgroup, net, +//! and mount namespaces, stays guest `UID 0`, drops only kernel-escape +//! capabilities (`CAP_SYS_MODULE`, `CAP_SYS_RAWIO`, `CAP_SYS_BOOT`, +//! `CAP_BPF`, `CAP_PERFMON`), opens its session/PTY, `chdir`s to `workdir`, +//! and installs the minimal privileged seccomp filter (`io_uring` + nested +//! `NEW_LISTENER` blocked, no `PR_SET_NO_NEW_PRIVS`). + +#![allow(unsafe_code)] + +use std::ffi::CString; +use std::fs::File; +use std::io::{self, Read as _, Write as _}; +use std::os::fd::{AsRawFd, FromRawFd as _, OwnedFd, RawFd}; +use std::os::unix::fs::MetadataExt as _; +use std::os::unix::process::CommandExt as _; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::Mutex; + +use super::{ + RUNTIME_TLS_DIR, WORKLOAD_CGROUP_DIR, WORKLOAD_CGROUP_INIT_DIR, WORKLOAD_HOLD_ROLE, + WORKLOAD_TLS_DIR, +}; +use crate::linux::child_seccomp::{self, ChildHardeningProgram}; + +/// Kernel capabilities dropped from the workload bounding and active sets. +/// Everything else (`CAP_SYS_ADMIN`, `CAP_NET_ADMIN`, `CAP_SYS_PTRACE`, +/// `CAP_SETUID`, `CAP_SETGID`, `CAP_MKNOD`, `CAP_DAC_OVERRIDE`, ...) stays +/// available to guest root. +const DROPPED_CAPS: [u32; 5] = [ + 16, // CAP_SYS_MODULE + 17, // CAP_SYS_RAWIO + 22, // CAP_SYS_BOOT + 38, // CAP_PERFMON + 39, // CAP_BPF +]; + +const LINUX_CAPABILITY_VERSION_3: u32 = 0x2008_0522; + +#[repr(C)] +struct CapUserHeader { + version: u32, + pid: i32, +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct CapUserData { + effective: u32, + permitted: u32, + inheritable: u32, +} + +/// Drop `DROPPED_CAPS` from bounding, effective, permitted, and inheritable sets. +/// Async-signal-safe: only `prctl` and `capget`/`capset` syscalls. +fn drop_kernel_escape_capabilities() -> io::Result<()> { + for cap in DROPPED_CAPS { + // SAFETY: PR_CAPBSET_DROP takes scalar capability numbers. + let rc = unsafe { libc::prctl(libc::PR_CAPBSET_DROP, libc::c_ulong::from(cap), 0, 0, 0) }; + if rc != 0 { + let err = io::Error::last_os_error(); + if err.raw_os_error() != Some(libc::EINVAL) { + return Err(err); + } + } + } + let mut header = CapUserHeader { + version: LINUX_CAPABILITY_VERSION_3, + pid: 0, + }; + let mut data = [CapUserData::default(); 2]; + // SAFETY: `header` and `data` match Linux v3 capget/capset ABI. + if unsafe { libc::syscall(libc::SYS_capget, &raw mut header, data.as_mut_ptr()) } != 0 { + return Err(io::Error::last_os_error()); + } + for cap in DROPPED_CAPS { + let word = (cap / 32) as usize; + let bit = 1u32 << (cap % 32); + data[word].effective &= !bit; + data[word].permitted &= !bit; + data[word].inheritable &= !bit; + } + // SAFETY: `header` and `data` are valid v3 capability buffers. + if unsafe { libc::syscall(libc::SYS_capset, &raw mut header, data.as_mut_ptr()) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + +/// Bring up `lo` in the calling process's current network namespace. +pub fn loopback_up() -> io::Result<()> { + // SAFETY: AF_INET datagram socket used only for `lo` SIOCGIFFLAGS/SIOCSIFFLAGS. + unsafe { + let socket = libc::socket(libc::AF_INET, libc::SOCK_DGRAM | libc::SOCK_CLOEXEC, 0); + if socket < 0 { + return Err(io::Error::last_os_error()); + } + let mut request: libc::ifreq = std::mem::zeroed(); + for (slot, byte) in request.ifr_name.iter_mut().zip(b"lo\0") { + *slot = libc::c_char::from_ne_bytes([*byte]); + } + #[allow(clippy::cast_possible_truncation, trivial_numeric_casts)] + let mut rc = libc::ioctl(socket, libc::SIOCGIFFLAGS as libc::Ioctl, &raw mut request); + if rc == 0 { + #[allow(clippy::cast_possible_truncation)] + { + request.ifr_ifru.ifru_flags |= (libc::IFF_UP | libc::IFF_RUNNING) as libc::c_short; + } + #[allow(clippy::cast_possible_truncation, trivial_numeric_casts)] + { + rc = libc::ioctl( + socket, + libc::SIOCSIFFLAGS as libc::Ioctl, + &raw const request, + ); + } + } + let err = io::Error::last_os_error(); + libc::close(socket); + if rc != 0 { + return Err(err); + } + } + Ok(()) +} + +fn cstring(value: &str) -> io::Result { + CString::new(value).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e)) +} + +fn pipe_cloexec() -> io::Result<(OwnedFd, OwnedFd)> { + let mut fds = [0; 2]; + // SAFETY: pipe2 writes two fresh descriptors. + if unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) } != 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: descriptors are newly created and owned here. + Ok(unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) }) +} + +fn mount_call( + source: Option<&CString>, + target: &CString, + fstype: Option<&CString>, + flags: libc::c_ulong, + data: Option<&CString>, +) -> io::Result<()> { + let src = source.map_or(std::ptr::null(), |s| s.as_ptr()); + let fs = fstype.map_or(std::ptr::null(), |s| s.as_ptr()); + let d = data.map_or(std::ptr::null(), |s| s.as_ptr().cast()); + // SAFETY: all non-null pointers are NUL-terminated CStrings alive for the call. + if unsafe { libc::mount(src, target.as_ptr(), fs, flags, d) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + +fn components(path: &str) -> io::Result> { + path.trim_start_matches('/') + .split('/') + .map(|part| { + if part.is_empty() || part == "." || part == ".." { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("unsafe workload mount target {path}"), + )); + } + cstring(part) + }) + .collect() +} + +fn open_beneath_no_follow(root: RawFd, parts: &[CString], create: bool) -> io::Result { + let flags = libc::O_PATH | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC; + let mut current: Option = None; + for part in parts { + let parent = current.as_ref().map_or(root, AsRawFd::as_raw_fd); + // SAFETY: `parent` is an open directory fd and `part` is NUL-terminated. + let mut fd = unsafe { libc::openat(parent, part.as_ptr(), flags) }; + if fd < 0 && create && io::Error::last_os_error().raw_os_error() == Some(libc::ENOENT) { + // SAFETY: same. + unsafe { libc::mkdirat(parent, part.as_ptr(), 0o755) }; + // SAFETY: same. + fd = unsafe { libc::openat(parent, part.as_ptr(), flags) }; + } + if fd < 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: fresh descriptor. + let owned = unsafe { OwnedFd::from_raw_fd(fd) }; + // SAFETY: zeroed stat buffer for fstat. + let mut st: libc::stat = unsafe { std::mem::zeroed() }; + // SAFETY: `owned` is a live file descriptor and `st` is writable. + if unsafe { libc::fstat(owned.as_raw_fd(), &raw mut st) } != 0 { + return Err(io::Error::last_os_error()); + } + if st.st_mode & libc::S_IFMT != libc::S_IFDIR { + return Err(io::Error::from_raw_os_error(libc::ENOTDIR)); + } + current = Some(owned); + } + current.ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL)) +} + +fn bind_onto_pinned( + workload_root_fd: RawFd, + source: &str, + target_rel: &str, + read_only: bool, + recursive: bool, +) -> io::Result<()> { + let mut parts = components(target_rel)?; + let leaf = parts + .pop() + .ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))?; + let parent_fd = if parts.is_empty() { + None + } else { + Some(open_beneath_no_follow(workload_root_fd, &parts, true)?) + }; + let parent_raw = parent_fd + .as_ref() + .map_or(workload_root_fd, AsRawFd::as_raw_fd); + let src_meta = std::fs::symlink_metadata(source)?; + if src_meta.is_dir() { + // Ensure leaf directory exists without following symlinks. + let _leaf_fd = open_beneath_no_follow(parent_raw, std::slice::from_ref(&leaf), true)?; + } else { + // Ensure leaf file mountpoint exists without following symlinks. + // SAFETY: `parent_raw` is an open directory fd and `leaf` is NUL-terminated. + let fd = unsafe { + libc::openat( + parent_raw, + leaf.as_ptr(), + libc::O_CREAT | libc::O_WRONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC, + 0o644, + ) + }; + if fd < 0 { + let err = io::Error::last_os_error(); + if err.raw_os_error() != Some(libc::EEXIST) { + return Err(err); + } + } else { + // SAFETY: fresh descriptor. + unsafe { libc::close(fd) }; + } + } + let src = cstring(source)?; + // SAFETY: `fchdir` pins the parent directory by descriptor; mounting and + // remounting `leaf` by single path component operates on the newly stacked + // bind mount rather than the covered mountpoint dentry. + if unsafe { libc::fchdir(parent_raw) } != 0 { + return Err(io::Error::last_os_error()); + } + let bind_flags = if recursive { + libc::MS_BIND | libc::MS_REC + } else { + libc::MS_BIND + }; + mount_call(Some(&src), &leaf, None, bind_flags, None) + .map_err(|e| io::Error::new(e.kind(), format!("bind {source} -> {target_rel}: {e}")))?; + if read_only { + mount_call( + None, + &leaf, + None, + libc::MS_BIND | libc::MS_REMOUNT | libc::MS_RDONLY | libc::MS_NOSUID | libc::MS_NODEV, + None, + ) + .map_err(|e| io::Error::new(e.kind(), format!("remount-ro {target_rel}: {e}")))?; + } + Ok(()) +} + +fn unescape_mountinfo_path(raw: &str) -> String { + raw.replace("\\040", " ") + .replace("\\011", "\t") + .replace("\\012", "\n") + .replace("\\134", "\\") +} + +fn is_excluded_container_submount(path: &str) -> bool { + path == "/" + || path == "/proc" + || path.starts_with("/proc/") + || path == "/dev" + || path.starts_with("/dev/") + || path == "/sys" + || path.starts_with("/sys/") + || path == "/run/openshell" + || path.starts_with("/run/openshell/") + || path == "/.openshell" + || path.starts_with("/.openshell/") + || path == "/etc/openshell-tls" + || path.starts_with("/etc/openshell-tls/") +} + +/// Collect container submounts (such as `/etc/hosts`, `/etc/resolv.conf`, +/// `/etc/hostname`, `/sandbox`, and user volume mounts) from +/// `/proc/self/mountinfo` in mount order, excluding runtime-owned and +/// virtual-FS paths. +fn collect_container_submounts() -> io::Result> { + let text = std::fs::read_to_string("/proc/self/mountinfo")?; + let mut seen = std::collections::HashSet::new(); + let mut mounts = Vec::new(); + for line in text.lines() { + let mut fields = line.split(' '); + let Some(mp_raw) = fields.nth(4) else { + continue; + }; + let Some(opts) = fields.next() else { + continue; + }; + let mp = unescape_mountinfo_path(mp_raw); + if is_excluded_container_submount(&mp) || !seen.insert(mp.clone()) { + continue; + } + let read_only = opts.split(',').any(|opt| opt == "ro"); + mounts.push((mp, read_only)); + } + Ok(mounts) +} + +/// Entrypoint of the hidden `workload-hold` role. +/// +/// Runs as workload PID 1 inside its own PID, mount, cgroup, and loopback-only +/// network namespaces. Pivots into `--root`, mounts fresh `/proc`, `/dev/shm`, +/// and read-only `/etc/openshell-tls`, signals readiness on stdout (`"OK\n"`), +/// and reaps workload orphans until signaled to exit. +pub fn run_workload_hold(workload_root: &Path) -> io::Result<()> { + // Bring up loopback in the fresh CLONE_NEWNET namespace. + loopback_up()?; + + // Private mount propagation so nothing propagates back to PID 1's tree. + let slash = cstring("/")?; + mount_call(None, &slash, None, libc::MS_REC | libc::MS_PRIVATE, None)?; + + // Determine the target mount point for `pivot_root`. + // - Dedicated workload disk (VM driver): `workload_root` is e.g. `/newroot`, + // separate from the read-only runtime root `/`. + // - Container root (Kata Pod): `workload_root` is `/`; bind `/` (non-recursively, + // so runtime submounts under `/run/openshell` and `/.openshell` are excluded) + // onto `/run/openshell/workload` and pivot into it. + let container_root_mode = workload_root == Path::new("/"); + let container_submounts = if container_root_mode { + collect_container_submounts()? + } else { + Vec::new() + }; + let pivot_target: PathBuf = if container_root_mode { + let target = PathBuf::from("/run/openshell/workload"); + std::fs::create_dir_all(&target)?; + let target_c = cstring("/run/openshell/workload")?; + mount_call(Some(&slash), &target_c, None, libc::MS_BIND, None) + .map_err(|e| io::Error::new(e.kind(), format!("bind / -> workload root: {e}")))?; + target + } else { + let root_c = cstring(workload_root.to_str().ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "non-UTF-8 workload root") + })?)?; + mount_call( + Some(&root_c), + &root_c, + None, + libc::MS_BIND | libc::MS_REC, + None, + )?; + workload_root.to_path_buf() + }; + + let root_dir = File::open(&pivot_target)?; + let root_fd = root_dir.as_raw_fd(); + + // Bind /dev and /sys from host guest into the workload root, plus read-only + // CA bundle from runtime-owned /run/openshell/tls. + for path in ["/dev", "/sys"] { + bind_onto_pinned(root_fd, path, path, false, true)?; + } + if container_root_mode { + // Preserve non-runtime container submounts (kubelet /etc/hosts, + // /etc/resolv.conf, /etc/hostname, /sandbox PVC, user volume mounts) + // non-recursively in mount order so runtime mounts under /run/openshell + // and /.openshell never leak into the workload mount namespace. + for (mp, read_only) in &container_submounts { + bind_onto_pinned(root_fd, mp, mp, *read_only, false)?; + } + // Mask /.openshell with an empty read-only tmpfs so runtime binaries + // and bootstrap staging paths are inaccessible to workload processes. + if pivot_target.join(".openshell").is_dir() { + let parts = components("/.openshell")?; + let target_fd = open_beneath_no_follow(root_fd, &parts, false)?; + let tmpfs = cstring("tmpfs")?; + let dot = cstring(".")?; + let opts = cstring("size=4k,mode=0555")?; + // SAFETY: `fchdir` pins `/.openshell` inside the workload root. + if unsafe { libc::fchdir(target_fd.as_raw_fd()) } == 0 { + let _ = mount_call( + Some(&tmpfs), + &dot, + Some(&tmpfs), + libc::MS_RDONLY | libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC, + Some(&opts), + ); + } + } + } + if Path::new(RUNTIME_TLS_DIR).is_dir() { + bind_onto_pinned(root_fd, RUNTIME_TLS_DIR, WORKLOAD_TLS_DIR, true, true)?; + } + + // Pivot into workload_root and unmount the old runtime root completely so + // no runtime paths exist in the workload's mount namespace. + // SAFETY: `root_fd` is an open directory descriptor to the workload root. + if unsafe { libc::fchdir(root_fd) } != 0 { + return Err(io::Error::last_os_error()); + } + drop(root_dir); + let dot = cstring(".")?; + // SAFETY: `dot` is a valid NUL-terminated path for `pivot_root(".", ".")`. + if unsafe { libc::syscall(libc::SYS_pivot_root, dot.as_ptr(), dot.as_ptr()) } != 0 { + let e = io::Error::last_os_error(); + return Err(io::Error::new(e.kind(), format!("pivot_root: {e}"))); + } + // SAFETY: `dot` is a valid NUL-terminated path detaching the old root mount. + if unsafe { libc::umount2(dot.as_ptr(), libc::MNT_DETACH) } != 0 { + let e = io::Error::last_os_error(); + return Err(io::Error::new(e.kind(), format!("umount old root: {e}"))); + } + // SAFETY: `slash` is a valid NUL-terminated path `"/"`. + if unsafe { libc::chdir(slash.as_ptr()) } != 0 { + let e = io::Error::last_os_error(); + return Err(io::Error::new(e.kind(), format!("chdir /: {e}"))); + } + + // Mount a fresh /proc for this child PID namespace so guest PID 1 + // (openshell-sandbox) is completely invisible to workload processes. + let proc_t = cstring("/proc")?; + let proc_fs = cstring("proc")?; + let _ = std::fs::create_dir_all("/proc"); + mount_call( + Some(&proc_fs), + &proc_t, + Some(&proc_fs), + libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC, + None, + ) + .map_err(|e| io::Error::new(e.kind(), format!("mount /proc: {e}")))?; + + // Ensure /dev/pts, /dev/shm (needed by Chrome!), and /tmp are mounted. + let _ = std::fs::create_dir_all("/dev/pts"); + let _ = std::fs::create_dir_all("/dev/shm"); + let _ = std::fs::create_dir_all("/tmp"); + let devpts = cstring("devpts")?; + let devpts_t = cstring("/dev/pts")?; + let devpts_opts = cstring("newinstance,ptmxmode=0666,mode=0620")?; + let _ = mount_call( + Some(&devpts), + &devpts_t, + Some(&devpts), + libc::MS_NOSUID | libc::MS_NOEXEC, + Some(&devpts_opts), + ); + let tmpfs = cstring("tmpfs")?; + let shm_t = cstring("/dev/shm")?; + let shm_opts = cstring("mode=1777,size=512m")?; + let _ = mount_call( + Some(&tmpfs), + &shm_t, + Some(&tmpfs), + libc::MS_NOSUID | libc::MS_NODEV, + Some(&shm_opts), + ); + let cgroup2 = cstring("cgroup2")?; + let cgroup_t = cstring("/sys/fs/cgroup")?; + let _ = std::fs::create_dir_all("/sys/fs/cgroup"); + let _ = mount_call( + Some(&cgroup2), + &cgroup_t, + Some(&cgroup2), + libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC, + None, + ); + + // Signal readiness to openshell-sandbox on stdout, then stay alive as + // workload PID 1 reaping any orphaned descendants. + { + let mut out = io::stdout().lock(); + out.write_all(b"OK\n")?; + out.flush()?; + } + + loop { + let mut status = 0; + // SAFETY: waitpid(-1, ...) reaps any orphaned child in this PID namespace. + let pid = unsafe { libc::waitpid(-1, &raw mut status, 0) }; + if pid < 0 { + let err = io::Error::last_os_error(); + if err.raw_os_error() == Some(libc::ECHILD) { + std::thread::sleep(std::time::Duration::from_millis(200)); + } + } + } +} + +/// Session setup for a placed child process. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ChildSession { + Pipes, + Terminal, +} + +/// Manages the pinned workload namespaces and places every workload child. +pub struct PrivilegedPlacement { + workload_root: PathBuf, + holder: Mutex, + holder_pid: u32, + init_pid_ns: OwnedFd, + workload_pid_ns: OwnedFd, + workload_mnt_ns: OwnedFd, + workload_net_ns: OwnedFd, + workload_cgroup_ns: Option, + workload_cgroup_procs: Option, + workload_net_inum: u32, +} + +impl PrivilegedPlacement { + /// Start the `workload-hold` namespace holder and pin all workload namespace fds. + pub fn start(workload_root: PathBuf, has_cgroup_v2: bool) -> io::Result { + let exe = std::env::current_exe()?; + let init_pid_ns = File::open("/proc/self/ns/pid")?.into(); + + // Prepare cgroup v2 subtree if available: + // /sys/fs/cgroup/openshell-workload (freezer owned by shim) + // /sys/fs/cgroup/openshell-workload/init (workload's cgroupns root) + let cgroup_procs = if has_cgroup_v2 { + let _ = std::fs::create_dir_all(WORKLOAD_CGROUP_INIT_DIR); + // Enable controllers on the parent if possible (best effort). + let _ = std::fs::write( + Path::new(WORKLOAD_CGROUP_DIR).join("cgroup.subtree_control"), + "+cpu +memory +pids", + ); + Some(cstring(&format!( + "{WORKLOAD_CGROUP_INIT_DIR}/cgroup.procs" + ))?) + } else { + None + }; + + // Fork the holder into its own PID, mount, network, and cgroup namespaces. + // We unshare(CLONE_NEWPID) on a short-lived helper thread so the main + // runtime thread's `pid_ns_for_children` is never disturbed. + let root_arg = workload_root.clone(); + let cg_procs_clone = cgroup_procs.clone(); + let holder = std::thread::Builder::new() + .name("openshell-holder-spawn".to_string()) + .spawn(move || -> io::Result { + // SAFETY: unshare(CLONE_NEWPID) on this dedicated short-lived thread + // makes its immediate child PID 1 of the new PID namespace. + if unsafe { libc::unshare(libc::CLONE_NEWPID) } != 0 { + return Err(io::Error::last_os_error()); + } + let mut cmd = Command::new(&exe); + cmd.args([ + WORKLOAD_HOLD_ROLE, + "--root", + root_arg.to_str().ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "non-UTF-8 workload root") + })?, + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()); + + let cg_procs_pre = cg_procs_clone; + // SAFETY: pre_exec runs only async-signal-safe syscalls. + unsafe { + cmd.pre_exec(move || { + if let Some(ref procs_path) = cg_procs_pre { + let fd = + libc::open(procs_path.as_ptr(), libc::O_WRONLY | libc::O_CLOEXEC); + if fd >= 0 { + let _ = libc::write(fd, b"0\n".as_ptr().cast(), 2); + libc::close(fd); + } + } + let mut flags = libc::CLONE_NEWNS | libc::CLONE_NEWNET; + if cg_procs_pre.is_some() { + flags |= libc::CLONE_NEWCGROUP; + } + if libc::unshare(flags) != 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) + }); + } + cmd.spawn() + }) + .map_err(|e| io::Error::other(format!("spawn holder thread: {e}")))? + .join() + .map_err(|_| io::Error::other("holder spawn thread panicked"))??; + + let mut holder = holder; + let holder_pid = holder.id(); + + // Wait for "OK\n" from workload-hold so mount/net/proc setup is complete. + let mut stdout = holder + .stdout + .take() + .ok_or_else(|| io::Error::other("workload-hold stdout missing"))?; + let mut buf = [0u8; 3]; + stdout.read_exact(&mut buf).map_err(|e| { + let _ = holder.kill(); + let _ = holder.wait(); + io::Error::other(format!("workload-hold failed before ready: {e}")) + })?; + if &buf != b"OK\n" { + let _ = holder.kill(); + let _ = holder.wait(); + return Err(io::Error::other( + "workload-hold sent unexpected readiness token", + )); + } + + let workload_pid_ns: OwnedFd = File::open(format!("/proc/{holder_pid}/ns/pid"))?.into(); + let workload_mnt_ns: OwnedFd = File::open(format!("/proc/{holder_pid}/ns/mnt"))?.into(); + let net_file = File::open(format!("/proc/{holder_pid}/ns/net"))?; + #[allow(clippy::cast_possible_truncation)] + let workload_net_inum = net_file.metadata()?.ino() as u32; + let workload_net_ns: OwnedFd = net_file.into(); + let workload_cgroup_ns = has_cgroup_v2 + .then(|| File::open(format!("/proc/{holder_pid}/ns/cgroup")).map(Into::into)) + .transpose()?; + + Ok(Self { + workload_root, + holder: Mutex::new(holder), + holder_pid, + init_pid_ns, + workload_pid_ns, + workload_mnt_ns, + workload_net_ns, + workload_cgroup_ns, + workload_cgroup_procs: cgroup_procs, + workload_net_inum, + }) + } + + #[must_use] + pub fn workload_root(&self) -> &Path { + &self.workload_root + } + + #[must_use] + pub const fn holder_pid(&self) -> u32 { + self.holder_pid + } + + #[must_use] + pub const fn workload_net_inum(&self) -> u32 { + self.workload_net_inum + } + + /// Execute `spawn_fn` with `pid_ns_for_children` temporarily switched to the + /// workload's PID namespace (must be called on the single-threaded + /// `WorkloadLauncher` thread). + pub fn with_workload_pid_ns( + &self, + spawn_fn: impl FnOnce() -> io::Result, + ) -> io::Result { + // SAFETY: switching `pid_ns_for_children` on the serialized launcher + // thread puts the immediate forked child inside the workload PID ns. + if unsafe { libc::setns(self.workload_pid_ns.as_raw_fd(), libc::CLONE_NEWPID) } != 0 { + return Err(io::Error::last_os_error()); + } + let result = spawn_fn(); + // Always restore the launcher thread's `pid_ns_for_children`. + // SAFETY: `init_pid_ns` is the launcher's original PID namespace fd. + let _ = unsafe { libc::setns(self.init_pid_ns.as_raw_fd(), libc::CLONE_NEWPID) }; + result + } + + /// Install the async-signal-safe `pre_exec` placement hook onto `cmd`. + /// + /// Returns a `PlacementGate` whose `finish()` must be called after spawning. + pub fn install( + &self, + cmd: &mut Command, + workdir: &str, + session: ChildSession, + ) -> io::Result<()> { + let mut hardening: ChildHardeningProgram = child_seccomp::prepare_privileged()?; + let mnt_fd = self.workload_mnt_ns.as_raw_fd(); + let net_fd = self.workload_net_ns.as_raw_fd(); + let cgroup_fd = self.workload_cgroup_ns.as_ref().map(AsRawFd::as_raw_fd); + let cgroup_procs = self.workload_cgroup_procs.clone(); + let workdir_c = cstring(if workdir.is_empty() { "/" } else { workdir })?; + let slash_c = cstring("/")?; + + // SAFETY: Every operation inside `pre_exec` uses pre-allocated memory + // and async-signal-safe Linux syscalls. + unsafe { + cmd.pre_exec(move || { + // 1. Place child into the runtime-owned workload cgroup before + // entering the child's cgroup namespace. + if let Some(ref procs_path) = cgroup_procs { + let fd = libc::open(procs_path.as_ptr(), libc::O_WRONLY | libc::O_CLOEXEC); + if fd >= 0 { + let _ = libc::write(fd, b"0\n".as_ptr().cast(), 2); + libc::close(fd); + } + } + if let Some(cg_fd) = cgroup_fd + && libc::setns(cg_fd, libc::CLONE_NEWCGROUP) != 0 + { + return Err(io::Error::last_os_error()); + } + // 2. Enter the loopback-only workload network namespace and the + // pivoted workload mount namespace. + if libc::setns(net_fd, libc::CLONE_NEWNET) != 0 { + return Err(io::Error::last_os_error()); + } + if libc::setns(mnt_fd, libc::CLONE_NEWNS) != 0 { + return Err(io::Error::last_os_error()); + } + // 3. Session / controlling terminal setup. + if libc::setsid() < 0 { + return Err(io::Error::last_os_error()); + } + if session == ChildSession::Terminal { + #[allow(clippy::cast_possible_truncation, trivial_numeric_casts)] + if libc::ioctl(0, libc::TIOCSCTTY as libc::Ioctl, 0) < 0 { + return Err(io::Error::last_os_error()); + } + } + // 4. Switch to workdir (falling back to "/" if absent). + if libc::chdir(workdir_c.as_ptr()) != 0 { + let _ = libc::chdir(slash_c.as_ptr()); + } + // 5. Install the privileged seccomp filter (blocks io_uring and + // nested NEW_LISTENER) BEFORE dropping caps (no PR_SET_NO_NEW_PRIVS). + hardening.install_privileged()?; + // 6. Keep guest UID/GID 0, dropping only kernel-escape capabilities. + drop_kernel_escape_capabilities()?; + Ok(()) + }); + } + Ok(()) + } + + /// Terminate the workload namespace holder when shutting down. + pub fn terminate_holder(&self) { + if let Ok(mut holder) = self.holder.lock() { + let _ = holder.kill(); + let _ = holder.wait(); + } + } +} + +impl Drop for PrivilegedPlacement { + fn drop(&mut self) { + self.terminate_holder(); + } +} + +/// Also keep `pipe_cloexec` used for future readiness pipes if needed. +#[allow(dead_code)] +fn _unused_pipe_ref() { + let _ = pipe_cloexec; +} diff --git a/crates/openshell-sandbox/src/process.rs b/crates/openshell-sandbox/src/process.rs index 4967d20086..c1642b8bcd 100644 --- a/crates/openshell-sandbox/src/process.rs +++ b/crates/openshell-sandbox/src/process.rs @@ -436,15 +436,25 @@ fn parse_pids_max(contents: &str) -> RuntimePidLimitStatus { } } +/// Default `PATH` for privileged guest workloads when the driver's user +/// environment sets none. +pub(crate) const GUEST_WORKLOAD_PATH: &str = + "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; + #[cfg(target_os = "linux")] pub fn spawn_command_with_workload_launcher( launcher: &crate::linux::workload_launcher::WorkloadLauncher, mut cmd: Command, ) -> std::io::Result { let runtime = tokio::runtime::Handle::current(); + let placement = launcher.privileged_placement().cloned(); launcher.execute(move || { let _guard = runtime.enter(); - cmd.spawn() + if let Some(placement) = placement { + placement.with_workload_pid_ns(|| cmd.spawn()) + } else { + cmd.spawn() + } })? } @@ -453,7 +463,14 @@ pub fn spawn_std_command_with_workload_launcher( launcher: &crate::linux::workload_launcher::WorkloadLauncher, mut cmd: std::process::Command, ) -> std::io::Result { - launcher.execute(move || cmd.spawn())? + let placement = launcher.privileged_placement().cloned(); + launcher.execute(move || { + if let Some(placement) = placement { + placement.with_workload_pid_ns(|| cmd.spawn()) + } else { + cmd.spawn() + } + })? } /// Handle to a running process. @@ -603,6 +620,59 @@ impl ProcessHandle { cmd.current_dir(dir); } + #[cfg(target_os = "linux")] + if let Some(placement) = launcher.privileged_placement().cloned() { + let user_environment = configured_user_environment(); + if !user_environment.contains_key("SHELL") { + cmd.env( + "SHELL", + crate::privileged::detect_workload_login_shell(placement.workload_root()), + ); + } + if !user_environment.contains_key("PATH") { + cmd.env("PATH", GUEST_WORKLOAD_PATH); + } + if !user_environment.contains_key("USER") { + cmd.env("USER", "root"); + } + let session = if terminal_slave_fd.is_some() { + crate::privileged::placement::ChildSession::Terminal + } else { + crate::privileged::placement::ChildSession::Pipes + }; + placement + .install(cmd.as_std_mut(), workspace.root().unwrap_or("/"), session) + .into_diagnostic() + .wrap_err("prepare privileged workload placement")?; + let mut child_registry = managed_children::lock(); + let mut child = spawn_command_with_workload_launcher(launcher, cmd) + .into_diagnostic() + .wrap_err_with(|| { + format!("failed to spawn privileged sandbox entrypoint '{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, "Privileged workload process spawned"); + return Ok(Self { + child, + pid, + io: Some(io), + terminal: Arc::new(AtomicBool::new(false)), + signal_lock: Arc::new(std::sync::Mutex::new(())), + managed_child, + }); + } + // 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. diff --git a/crates/openshell-sdk/src/client.rs b/crates/openshell-sdk/src/client.rs index 7d11bf3e9c..126791a2b4 100644 --- a/crates/openshell-sdk/src/client.rs +++ b/crates/openshell-sdk/src/client.rs @@ -1841,6 +1841,7 @@ fn create_sandbox_request(spec: SandboxSpec) -> proto::CreateSandboxRequest { tty, service_exposures, restart_policy, + privileged, } = spec; let template = image.map(|image| proto::SandboxTemplate { image, @@ -1859,6 +1860,7 @@ fn create_sandbox_request(spec: SandboxSpec) -> proto::CreateSandboxRequest { command, tty, restart_policy: proto::SandboxRestartPolicy::from(restart_policy) as i32, + privileged, ..proto::SandboxSpec::default() }), name: name.unwrap_or_default(), diff --git a/crates/openshell-sdk/src/types.rs b/crates/openshell-sdk/src/types.rs index aaf6231dca..2d052cd683 100644 --- a/crates/openshell-sdk/src/types.rs +++ b/crates/openshell-sdk/src/types.rs @@ -325,6 +325,8 @@ pub struct SandboxSpec { pub service_exposures: Vec, /// Restart behavior after the canonical main process exits. pub restart_policy: SandboxRestartPolicy, + /// Request privileged (true guest root) mode on supported VM drivers. + pub privileged: bool, } /// A loopback HTTP service to expose during sandbox creation. diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index 8b2adb5570..1df18ceb3c 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -562,6 +562,8 @@ pub struct ComputeDriverInfoSnapshot { pub rootfs_tar_staging_dir: String, /// Maximum rootfs tar file size in bytes. pub rootfs_tar_max_bytes: u64, + /// Whether this driver supports `DriverSandboxSpec.privileged`. + pub supports_privileged: bool, } // Startup recovery owns persisted desired state before normal observations @@ -1467,6 +1469,7 @@ impl ComputeRuntime { resource_capabilities: capabilities.resource_capabilities, rootfs_tar_staging_dir: capabilities.rootfs_tar_staging_dir, rootfs_tar_max_bytes: capabilities.rootfs_tar_max_bytes, + supports_privileged: capabilities.supports_privileged, }; let default_image = capabilities.default_image; let rootfs_tar_staging = Arc::new(rootfs_tar::RootfsTarStagingRegistry::new( @@ -1840,6 +1843,11 @@ impl ComputeRuntime { self.driver_info.supports_sandbox_authentication } + #[must_use] + pub fn supports_privileged(&self) -> bool { + self.driver_info.supports_privileged + } + pub(crate) async fn authenticate_sandbox( &self, credential: &str, @@ -2104,6 +2112,13 @@ impl ComputeRuntime { .as_ref() .and_then(|spec| spec.template.as_ref()), )?; + if sandbox.spec.as_ref().is_some_and(|spec| spec.privileged) && !self.supports_privileged() + { + return Err(Status::failed_precondition(format!( + "privileged sandboxes are not supported by the '{}' compute driver", + self.driver_info.driver_name + ))); + } let sandbox_id = sandbox.object_id().to_string(); let mut sandbox = sandbox; let metadata = sandbox @@ -7882,6 +7897,7 @@ fn driver_sandbox_spec_from_public( }), launch_authentication: Vec::new(), isolation_backend: None, + privileged: spec.privileged, }) } @@ -9158,6 +9174,7 @@ impl ComputeDriver for NoopTestDriver { resource_capabilities: None, rootfs_tar_staging_dir: String::new(), rootfs_tar_max_bytes: 0, + supports_privileged: false, extension: Some(openshell_core::extension_protocol::extension_metadata( ExtensionFamily::Compute, "openshell/noop-test-driver", @@ -9373,6 +9390,7 @@ pub fn new_test_runtime_with_driver( resource_capabilities: None, rootfs_tar_staging_dir: String::new(), rootfs_tar_max_bytes: 0, + supports_privileged: false, }, telemetry_compute_driver: TelemetryComputeDriver::custom(), driver_process: None, @@ -10048,6 +10066,7 @@ mod tests { resource_capabilities: None, rootfs_tar_staging_dir: String::new(), rootfs_tar_max_bytes: 0, + supports_privileged: false, extension: (!self.omit_protocol_metadata).then(|| { let mut metadata = openshell_core::extension_protocol::extension_metadata( ExtensionFamily::Compute, @@ -10613,6 +10632,7 @@ mod tests { resource_capabilities: None, rootfs_tar_staging_dir: String::new(), rootfs_tar_max_bytes: 0, + supports_privileged: false, extension: Some(openshell_core::extension_protocol::extension_metadata( ExtensionFamily::Compute, "openshell/controlled-test-driver", @@ -10918,6 +10938,7 @@ mod tests { resource_capabilities: None, rootfs_tar_staging_dir: String::new(), rootfs_tar_max_bytes: 0, + supports_privileged: false, }, telemetry_compute_driver: TelemetryComputeDriver::custom(), driver_process: None, diff --git a/crates/openshell-server/src/test_support.rs b/crates/openshell-server/src/test_support.rs index 969e05928b..d145f45cc2 100644 --- a/crates/openshell-server/src/test_support.rs +++ b/crates/openshell-server/src/test_support.rs @@ -206,6 +206,7 @@ impl FakeComputeDriver { resource_capabilities: None, rootfs_tar_staging_dir: String::new(), rootfs_tar_max_bytes: 0, + supports_privileged: false, extension: Some(openshell_core::extension_protocol::extension_metadata( openshell_core::extension_protocol::ExtensionFamily::Compute, "openshell/fake-compute-driver", diff --git a/crates/openshell-supervisor/src/backend_setup/tests.rs b/crates/openshell-supervisor/src/backend_setup/tests.rs index 0f5b2ec5e2..9144ab8d56 100644 --- a/crates/openshell-supervisor/src/backend_setup/tests.rs +++ b/crates/openshell-supervisor/src/backend_setup/tests.rs @@ -724,6 +724,7 @@ fn standard_setup_decodes_native_descriptor_and_preserves_vm_identity() { b"test-evidence", ) .unwrap(), + privileged: None, }; for is_vm in [false, true] { if is_vm { diff --git a/deploy/helm/openshell/README.md b/deploy/helm/openshell/README.md index ad4dd9ce37..eefd1e6ed4 100644 --- a/deploy/helm/openshell/README.md +++ b/deploy/helm/openshell/README.md @@ -803,6 +803,7 @@ for peer identity policies, multi-node registrations, and authorization. | server.otlp.endpoint | string | `""` | OTLP/gRPC collector endpoint, conventionally port 4317. For an `http/protobuf` collector, also set protocol under gatewayConfig."openshell.gateway.otlp". | | server.otlp.serviceName | string | `""` | Gateway OpenTelemetry service name. Empty uses openshell-gateway. | | server.policyValidationFailureMode | string | `"fail_closed"` | Posture when a candidate sandbox policy fails validation. `fail_closed` deactivates the previous policy; `retain_last_valid` keeps it active. | +| server.privilegedRuntimeClassName | string | `""` | Kubernetes runtimeClassName for `--privileged` (true guest root + boot-once BPF LSM) sandbox pods, such as a hardened Kata Containers class. Empty (default) disables privileged sandboxes on Kubernetes. | | server.providerTokenGrants.spiffe.enabled | bool | `false` | Mount the SPIFFE Workload API socket into gateway and sandbox pods for dynamic provider token grants. | | server.providerTokenGrants.spiffe.workloadApiSocketPath | string | `"/spiffe-workload-api/spire-agent.sock"` | Path to the SPIFFE Workload API socket mounted into gateway and sandbox pods. | | server.sandboxGid | string | `""` | GID for sandbox pods (`sandbox_gid`). Empty (default) = same as sandboxUid. Must be an integer between 1 and 4294967294. | diff --git a/deploy/helm/openshell/templates/_helpers.tpl b/deploy/helm/openshell/templates/_helpers.tpl index d174315813..e7ba36051b 100644 --- a/deploy/helm/openshell/templates/_helpers.tpl +++ b/deploy/helm/openshell/templates/_helpers.tpl @@ -809,7 +809,7 @@ absent fields so every chart consumer observes the same configuration. {{- $imagePullSecrets := list -}}{{- range (get $legacyServer "sandboxImagePullSecrets" | default list) }}{{- if .name }}{{- $imagePullSecrets = append $imagePullSecrets .name }}{{- end }}{{- end -}} {{- if $imagePullSecrets }}{{- $_ := set $kubernetes "image_pull_secrets" $imagePullSecrets -}}{{- end -}} {{- end -}} -{{- range $legacyKey, $runtimeKey := dict "workspaceDefaultStorageSize" "workspace_default_storage_size" "workspaceStorageClass" "workspace_storage_class" "defaultRuntimeClassName" "default_runtime_class_name" -}} +{{- range $legacyKey, $runtimeKey := dict "workspaceDefaultStorageSize" "workspace_default_storage_size" "workspaceStorageClass" "workspace_storage_class" "defaultRuntimeClassName" "default_runtime_class_name" "privilegedRuntimeClassName" "privileged_runtime_class_name" -}} {{- if and (get $legacyServer $legacyKey) (not (hasKey $kubernetes $runtimeKey)) -}}{{- $_ := set $kubernetes $runtimeKey (get $legacyServer $legacyKey) -}}{{- end -}} {{- end -}} {{- if not (hasKey $kubernetes "sandbox_uid") -}} diff --git a/deploy/helm/openshell/values.yaml b/deploy/helm/openshell/values.yaml index 809f992703..123db8abda 100644 --- a/deploy/helm/openshell/values.yaml +++ b/deploy/helm/openshell/values.yaml @@ -549,6 +549,10 @@ server: # Set to a RuntimeClass name (e.g. "kata-containers", "nvidia") to apply it # to all sandboxes that don't explicitly override it. defaultRuntimeClassName: "" + # -- Kubernetes runtimeClassName for `--privileged` (true guest root + + # boot-once BPF LSM) sandbox pods, such as a hardened Kata Containers class. + # Empty (default) disables privileged sandboxes on Kubernetes. + privilegedRuntimeClassName: "" # -- UID for sandbox pods (`sandbox_uid`). Empty (default) = use the OpenShift # SCC namespace annotation if present, otherwise the driver default. Must be # an integer between 1 and 4294967294. diff --git a/e2e/rust/Cargo.toml b/e2e/rust/Cargo.toml index 2cf210ba66..e945b3a003 100644 --- a/e2e/rust/Cargo.toml +++ b/e2e/rust/Cargo.toml @@ -73,6 +73,11 @@ name = "vm_overlay" path = "tests/vm_overlay.rs" required-features = ["e2e-vm"] +[[test]] +name = "vm_privileged" +path = "tests/vm_privileged.rs" +required-features = ["e2e-vm"] + [[test]] name = "rootfs_tar" path = "tests/rootfs_tar.rs" diff --git a/e2e/rust/e2e-vm.sh b/e2e/rust/e2e-vm.sh index bafaadbc71..7dff3a4cb6 100755 --- a/e2e/rust/e2e-vm.sh +++ b/e2e/rust/e2e-vm.sh @@ -463,8 +463,10 @@ e2e_export_gateway_restart_metadata \ # preparation; allow 180s for slower CI runners. export OPENSHELL_PROVISION_TIMEOUT="${SANDBOX_PROVISION_TIMEOUT}" -OPENSHELL_TEST_PYTHON_IMAGE="${OPENSHELL_TEST_PYTHON_IMAGE:-${E2E_PULLABLE_PYTHON_IMAGE}}" \ - e2e_run_openshell_conformance "VM" +if [ "${OPENSHELL_E2E_SKIP_CONFORMANCE:-0}" != "1" ]; then + OPENSHELL_TEST_PYTHON_IMAGE="${OPENSHELL_TEST_PYTHON_IMAGE:-${E2E_PULLABLE_PYTHON_IMAGE}}" \ + e2e_run_openshell_conformance "VM" +fi if [ "${E2E_FEATURES}" = "e2e-conformance-only" ]; then echo "::notice::Skipping Rust e2e tests (e2e-conformance-only)" exit 0 @@ -496,6 +498,7 @@ else run_e2e_test ephemeral_cleanup run_e2e_test host_gateway_alias run_e2e_test vm_overlay + run_e2e_test vm_privileged run_e2e_test vm_bind_mount run_e2e_test vm_gateway_start run_e2e_test vm_corporate_proxy diff --git a/e2e/rust/tests/vm_privileged.rs b/e2e/rust/tests/vm_privileged.rs new file mode 100644 index 0000000000..13e1a04a02 --- /dev/null +++ b/e2e/rust/tests/vm_privileged.rs @@ -0,0 +1,298 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! VM privileged (true guest root + boot-once BPF LSM) workload E2E tests. +//! +//! Exercises real privileged workloads (Chromium and Bubblewrap) alongside +//! BPF LSM shim-seal, filesystem_policy, and network-mediation checks inside a +//! VM sandbox created with `openshell sandbox create --privileged` / `--priv`. + +use std::process::Command as StdCommand; + +use openshell_e2e::harness::cli::run_cli; +use openshell_e2e::harness::output::strip_ansi; +use openshell_e2e::harness::sandbox::{SandboxGuard, unique_sandbox_name}; + +const DEFAULT_PRIV_IMAGE: &str = "openshell-e2e-priv-workload:local"; + +fn ensure_privileged_workload_image() -> String { + if let Ok(image) = std::env::var("OPENSHELL_E2E_PRIV_IMAGE") + && !image.trim().is_empty() + { + return image; + } + + let inspect = StdCommand::new("docker") + .args(["image", "inspect", DEFAULT_PRIV_IMAGE]) + .output(); + if inspect.is_ok_and(|out| out.status.success()) { + return DEFAULT_PRIV_IMAGE.to_string(); + } + + let dockerfile = r#"FROM debian:bookworm-slim +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ + bubblewrap \ + ca-certificates \ + chromium \ + curl \ + iproute2 \ + python3 \ + strace \ + && rm -rf /var/lib/apt/lists/* +RUN mkdir -p /sandbox /etc/priv-ro-test && echo "sealed-content" > /etc/priv-ro-test/sentinel +"#; + let mut child = StdCommand::new("docker") + .args(["build", "-t", DEFAULT_PRIV_IMAGE, "-"]) + .stdin(std::process::Stdio::piped()) + .spawn() + .expect("spawn docker build for privileged workload image"); + { + use std::io::Write as _; + child + .stdin + .as_mut() + .expect("stdin") + .write_all(dockerfile.as_bytes()) + .expect("write Dockerfile"); + } + let status = child.wait().expect("wait for docker build"); + assert!( + status.success(), + "failed to build {DEFAULT_PRIV_IMAGE} workload image" + ); + DEFAULT_PRIV_IMAGE.to_string() +} + +fn privileged_policy() -> tempfile::NamedTempFile { + let file = tempfile::NamedTempFile::new().expect("temporary privileged policy"); + std::fs::write( + file.path(), + r#"version: 1 +filesystem_policy: + include_workdir: true + read_only: [/etc/priv-ro-test] + read_write: [/sandbox, /tmp, /dev/shm] +landlock: + compatibility: best_effort +network_policies: {} +"#, + ) + .expect("write privileged policy"); + file +} + +fn hard_landlock_policy() -> tempfile::NamedTempFile { + let file = tempfile::NamedTempFile::new().expect("temporary hard-landlock policy"); + std::fs::write( + file.path(), + r#"version: 1 +filesystem_policy: + include_workdir: true + read_only: [/usr, /etc] + read_write: [/sandbox, /tmp] +landlock: + compatibility: hard_requirement +network_policies: {} +"#, + ) + .expect("write hard-landlock policy"); + file +} + +#[tokio::test] +async fn vm_privileged_chrome_and_bubblewrap_workloads() { + let image = ensure_privileged_workload_image(); + let policy = privileged_policy(); + let policy_path = policy.path().to_str().expect("UTF-8 policy path"); + let name = unique_sandbox_name(); + + let mut sandbox = SandboxGuard::create_keep_with_args( + &[ + "--name", + &name, + "--privileged", + "--from", + &image, + "--policy", + policy_path, + ], + &["sh", "-c", "echo priv-vm-ready; exec sleep infinity"], + "priv-vm-ready", + ) + .await + .expect("privileged VM sandbox should start and become ready"); + + // 1. Verify true guest root and namespace isolation from the shim. + let identity_script = concat!( + "set -eu; ", + "test \"$(id -u)\" = \"0\"; ", + "test ! -e /run/openshell/bootstrap; ", + "! ps -eo comm | grep -qx openshell-sandbox; ", + "echo identity-isolation-ok", + ); + let out = sandbox + .exec(&["sh", "-c", identity_script]) + .await + .expect("guest root and namespace isolation check should succeed"); + assert!( + strip_ansi(&out).contains("identity-isolation-ok"), + "unexpected identity output:\n{out}" + ); + + // 2. Verify Bubblewrap (nested mount + PID + UTS namespaces) works cleanly. + let bwrap_script = concat!( + "set -eu; ", + "bwrap --ro-bind / / --dev /dev --proc /proc --tmpfs /tmp ", + "--unshare-pid --unshare-uts -- /bin/sh -c 'test \"$(id -u)\" = 0 && echo bwrap-ok'", + ); + let out = sandbox + .exec(&["sh", "-c", bwrap_script]) + .await + .expect("bubblewrap should run inside privileged VM sandbox"); + assert!( + strip_ansi(&out).contains("bwrap-ok"), + "bubblewrap output missing marker:\n{out}" + ); + + // 3. Verify Chromium starts cleanly both as guest root and as non-root with + // Chromium's own Linux namespace/seccomp sandbox enabled. + let chrome_script = concat!( + "set -eu; ", + "mkdir -p /tmp/chrome-root /tmp/chrome-user; ", + "chmod 1777 /tmp/chrome-root /tmp/chrome-user; ", + "HOME=/tmp/chrome-root chromium --no-sandbox --headless=new --disable-gpu ", + "--disable-software-rasterizer --dump-dom 'data:text/html,

chrome-root-ok

' ", + "| grep -q 'chrome-root-ok'; ", + "su -s /bin/sh sandbox -c 'HOME=/tmp/chrome-user chromium --headless=new --disable-gpu ", + "--disable-software-rasterizer --dump-dom \"data:text/html,

chrome-sandbox-ok

\"' ", + "| grep -q 'chrome-sandbox-ok'; ", + "echo chrome-both-ok", + ); + let out = sandbox + .exec(&["sh", "-c", chrome_script]) + .await + .expect("chromium should start in privileged VM sandbox"); + assert!( + strip_ansi(&out).contains("chrome-both-ok"), + "chromium output missing marker:\n{out}" + ); + + // 4. Verify BPF LSM shim seal, filesystem_policy, and network mediation + // hold even against guest UID 0. + let security_script = r#" +set -eu +python3 - <<'PY' +import ctypes, errno, os, socket, sys + +libc = ctypes.CDLL(None, use_errno=True) + +# Determine syscall numbers for arch (aarch64 vs x86_64) +import platform +arch = platform.machine() +if arch == "aarch64": + SYS_BPF = 280 + SYS_IO_URING_SETUP = 425 +elif arch == "x86_64": + SYS_BPF = 321 + SYS_IO_URING_SETUP = 425 +else: + raise RuntimeError(f"unsupported arch {arch}") + +# 4a. bpf() syscall must be denied by lsm/bpf even for guest UID 0 +buf = ctypes.create_string_buffer(128) +rc = libc.syscall(SYS_BPF, 0, buf, 64) +err = ctypes.get_errno() +assert rc == -1 and err in (errno.EPERM, errno.EACCES), f"expected bpf() denied, got rc={rc} errno={err}" + +# 4b. AF_VSOCK must be denied (by seccomp_notify and/or lsm/socket_create) +try: + s = socket.socket(40, socket.SOCK_STREAM, 0) + s.close() + raise AssertionError("AF_VSOCK socket unexpectedly succeeded") +except OSError as exc: + assert exc.errno in (errno.EPERM, errno.EACCES, errno.EAFNOSUPPORT), f"unexpected AF_VSOCK errno: {exc}" + +# 4c. io_uring_setup must be denied by privileged seccomp filter +rc = libc.syscall(SYS_IO_URING_SETUP, 8, buf) +err = ctypes.get_errno() +assert rc == -1 and err in (errno.EPERM, errno.ENOSYS), f"expected io_uring denied, got rc={rc} errno={err}" + +# 4d. filesystem_policy read_only path must reject writes from guest UID 0 +try: + with open("/etc/priv-ro-test/sentinel", "w") as f: + f.write("tampered\n") + raise AssertionError("write to read_only policy path unexpectedly succeeded") +except OSError as exc: + assert exc.errno in (errno.EACCES, errno.EPERM), f"unexpected RO write errno: {exc}" + +with open("/etc/priv-ro-test/sentinel") as f: + assert f.read().strip() == "sealed-content", "sentinel content was modified" + +# 4e. Writable policy path (/sandbox) must allow writes +with open("/sandbox/priv-rw-check", "w") as f: + f.write("rw-ok\n") + +# 4f. Policy-denied external TCP connection must fail closed +s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +s.settimeout(5) +try: + s.connect(("203.0.113.1", 80)) + raise AssertionError("external TCP connect unexpectedly succeeded") +except OSError: + pass +finally: + s.close() + +print("security-checks-ok") +PY +# 4g. Writable shadow mount over read_only policy path must be denied by lsm/sb_mount +if mount -t tmpfs tmpfs /etc/priv-ro-test 2>/dev/null; then + echo "ERROR: mount over read_only policy path unexpectedly succeeded" >&2 + exit 1 +fi +echo all-security-ok +"#; + let out = sandbox + .exec(&["sh", "-c", security_script]) + .await + .expect("privileged security checks should succeed"); + let clean = strip_ansi(&out); + assert!( + clean.contains("security-checks-ok") && clean.contains("all-security-ok"), + "privileged security assertions failed:\n{clean}" + ); + + sandbox.cleanup().await; +} + +#[tokio::test] +async fn vm_privileged_alias_and_hard_landlock_rejection() { + let policy = hard_landlock_policy(); + let policy_path = policy.path().to_str().expect("UTF-8 policy path"); + let name = unique_sandbox_name(); + + // --priv alias with hard_requirement Landlock must fail closed. + let (output, code) = run_cli(&[ + "sandbox", + "create", + "--name", + &name, + "--priv", + "--no-tty", + "--policy", + policy_path, + "--", + "true", + ]) + .await; + assert_ne!( + code, 0, + "privileged sandbox with landlock hard_requirement should fail closed:\n{output}" + ); + let clean = strip_ansi(&output); + assert!( + clean.contains("hard_requirement") || clean.contains("BPF LSM"), + "expected hard_requirement rejection reason, got:\n{clean}" + ); + let _ = run_cli(&["sandbox", "delete", &name]).await; +} diff --git a/proto/compute_driver.proto b/proto/compute_driver.proto index 88d090fc18..00f2ed1db9 100644 --- a/proto/compute_driver.proto +++ b/proto/compute_driver.proto @@ -157,6 +157,9 @@ message GetCapabilitiesResponse { // Gateways require an exact policy match before activating the driver. // Empty denotes a legacy driver and requires explicit admission opt-out. string resource_admission_policy = 13; + // Whether this driver supports `DriverSandboxSpec.privileged` (true guest + // root inside a hardened VM boundary). False by default. + bool supports_privileged = 14; } message AuthenticateSandboxRequest { @@ -263,6 +266,9 @@ message DriverSandboxSpec { // public sandbox spec or workload environment. Omitted for the built-in // runtime. Requires openshell.compute.isolation-backend. IsolationBackendRegistration isolation_backend = 17; + // Provision the sandbox in privileged (true guest root) mode. Drivers that + // do not support privileged mode must reject creation. + bool privileged = 18; } // Trusted operator registration delivered to the compute driver on every diff --git a/proto/openshell.proto b/proto/openshell.proto index 4212445623..795bb5d48e 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -1250,6 +1250,10 @@ message SandboxSpec { // Gateway-owned policy for replacing the sandbox runtime after the canonical // main process exits. Unspecified is normalized to Never before persistence. SandboxRestartPolicy restart_policy = 15; + // Run workload processes as true guest root inside a hardened VM sandbox + // sealed by boot-once BPF LSM. Requires a compute driver that advertises + // privileged support; unsupported drivers reject creation. + bool privileged = 16; } message ResourceRequirements { diff --git a/tasks/scripts/vm/build-libkrun.sh b/tasks/scripts/vm/build-libkrun.sh index 2e6f1d1138..a39ccdd966 100755 --- a/tasks/scripts/vm/build-libkrun.sh +++ b/tasks/scripts/vm/build-libkrun.sh @@ -67,7 +67,7 @@ install_deps() { if command -v apt-get &>/dev/null; then # Debian/Ubuntu - DEPS="build-essential git python3 python3-pip python3-pyelftools flex bison libelf-dev libssl-dev libcap-ng-dev bc curl libclang-dev cpio zstd jq" + DEPS="build-essential git python3 python3-pip python3-pyelftools flex bison libelf-dev libssl-dev libcap-ng-dev bc curl libclang-dev cpio zstd jq dwarves" MISSING="" for dep in $DEPS; do if ! dpkg -s "$dep" &>/dev/null; then @@ -214,6 +214,11 @@ if [ -f openshell.kconfig ]; then for opt in \ CONFIG_SECURITY \ CONFIG_SECURITY_LANDLOCK \ + CONFIG_SECURITY_LOCKDOWN_LSM \ + CONFIG_BPF_SYSCALL \ + CONFIG_BPF_JIT \ + CONFIG_BPF_LSM \ + CONFIG_DEBUG_INFO_BTF \ CONFIG_SECCOMP \ CONFIG_SECCOMP_FILTER \ CONFIG_HARDENED_USERCOPY \ @@ -228,17 +233,29 @@ if [ -f openshell.kconfig ]; then all_ok=false fi done - if grep -qx '# CONFIG_INIT_ON_FREE_DEFAULT_ON is not set' "${KERNEL_SOURCES}/.config"; then - echo " CONFIG_INIT_ON_FREE_DEFAULT_ON: disabled" - else - echo " WARNING: CONFIG_INIT_ON_FREE_DEFAULT_ON is not explicitly disabled after merge!" >&2 - all_ok=false - fi + for opt in \ + CONFIG_INIT_ON_FREE_DEFAULT_ON \ + CONFIG_MODULES \ + CONFIG_KEXEC \ + CONFIG_KEXEC_FILE \ + CONFIG_HIBERNATION \ + CONFIG_DEVMEM \ + CONFIG_DEVKMEM \ + CONFIG_PROC_KCORE \ + CONFIG_BLK_DEV_WRITE_MOUNTED \ + CONFIG_UPROBES; do + if grep -qx "# ${opt} is not set" "${KERNEL_SOURCES}/.config" || ! grep -q "^${opt}=" "${KERNEL_SOURCES}/.config"; then + echo " ${opt}: disabled" + else + echo " WARNING: ${opt} is enabled after merge!" >&2 + all_ok=false + fi + done lsm_order="$(grep '^CONFIG_LSM=' "${KERNEL_SOURCES}/.config" 2>/dev/null || true)" - if [[ "$lsm_order" == *landlock* ]]; then + if [[ "$lsm_order" == *landlock* ]] && [[ "$lsm_order" == *bpf* ]]; then echo " CONFIG_LSM: ${lsm_order#*=}" else - echo " WARNING: CONFIG_LSM does not activate Landlock: ${lsm_order:-unset}" >&2 + echo " WARNING: CONFIG_LSM does not activate Landlock and BPF: ${lsm_order:-unset}" >&2 all_ok=false fi if [ "$all_ok" = false ]; then diff --git a/tests/testkit/testkit/src/context.rs b/tests/testkit/testkit/src/context.rs index ad75be85e0..e54dde3806 100644 --- a/tests/testkit/testkit/src/context.rs +++ b/tests/testkit/testkit/src/context.rs @@ -604,6 +604,7 @@ fn grpc_create_request( tty, service_exposures: _, restart_policy, + privileged, } = spec; proto::CreateSandboxRequest { name: name.unwrap_or_default(), @@ -623,6 +624,7 @@ fn grpc_create_request( tty, policy, restart_policy: proto::SandboxRestartPolicy::from(restart_policy) as i32, + privileged, ..proto::SandboxSpec::default() }), ..proto::CreateSandboxRequest::default() From b270b64fb7eddb1e0155721f0b5c269b160e1bca Mon Sep 17 00:00:00 2001 From: Divesh Date: Mon, 30 Nov 2026 10:01:56 -0800 Subject: [PATCH 2/3] fix(sandbox): load privileged BPF LSM hooks on kernels with return value checks (#6077) Kernels 6.13+ reject BPF LSM programs unless every return is provably in [-4095, 0]. Each hook returned the earlier verdict read from the context, which is unbounded, so loading failed on newer guest kernels (for example Kata 6.18). Return -EPERM for an earlier denial instead. Also document the sandbox-attachable labels the privileged RuntimeClass needs. Refs #5925 Signed-off-by: Divesh Signed-off-by: Drew Newberry --- .../openshell-sandbox/bpf/openshell_lsm.bpf.c | 41 +++++++++++-------- deploy/helm/openshell/README.md | 2 +- deploy/helm/openshell/values.yaml | 2 + 3 files changed, 27 insertions(+), 18 deletions(-) diff --git a/crates/openshell-sandbox/bpf/openshell_lsm.bpf.c b/crates/openshell-sandbox/bpf/openshell_lsm.bpf.c index 4b55b07965..b2ccd17587 100644 --- a/crates/openshell-sandbox/bpf/openshell_lsm.bpf.c +++ b/crates/openshell-sandbox/bpf/openshell_lsm.bpf.c @@ -51,6 +51,13 @@ typedef __u16 umode_t; #define __type(name, val) typeof(val) *name #define __always_inline inline __attribute__((always_inline)) +// The verdict of earlier programs on this hook. Kernels with BPF LSM return +// value checks reject a program unless every return is provably in [-4095, 0], +// and the context value is unbounded, so an earlier denial becomes -EPERM. +static __always_inline int prior_verdict(unsigned long long raw) { + return (int)raw != 0 ? -EPERM : 0; +} + // Minimal CO-RE kernel struct definitions (relocated against /sys/kernel/btf/vmlinux). struct ns_common { unsigned int inum; @@ -500,7 +507,7 @@ static __always_inline int check_dentry_access(struct dentry *dentry, int is_wri SEC("lsm/bpf") int openshell_lsm_bpf(unsigned long long *ctx) { - int ret = (int)ctx[3]; + int ret = prior_verdict(ctx[3]); if (ret != 0) { return ret; } @@ -538,7 +545,7 @@ int openshell_lsm_bpf(unsigned long long *ctx) { SEC("lsm/ptrace_access_check") int openshell_lsm_ptrace(unsigned long long *ctx) { - int ret = (int)ctx[2]; + int ret = prior_verdict(ctx[2]); if (ret != 0) { return ret; } @@ -556,7 +563,7 @@ int openshell_lsm_ptrace(unsigned long long *ctx) { SEC("lsm/perf_event_alloc") int openshell_lsm_perf(unsigned long long *ctx) { - int ret = (int)ctx[1]; + int ret = prior_verdict(ctx[1]); if (ret != 0) { return ret; } @@ -570,7 +577,7 @@ int openshell_lsm_perf(unsigned long long *ctx) { SEC("lsm/task_kill") int openshell_lsm_task_kill(unsigned long long *ctx) { - int ret = (int)ctx[4]; + int ret = prior_verdict(ctx[4]); if (ret != 0) { return ret; } @@ -588,7 +595,7 @@ int openshell_lsm_task_kill(unsigned long long *ctx) { SEC("lsm/task_setrlimit") int openshell_lsm_task_setrlimit(unsigned long long *ctx) { - int ret = (int)ctx[3]; + int ret = prior_verdict(ctx[3]); if (ret != 0) { return ret; } @@ -606,7 +613,7 @@ int openshell_lsm_task_setrlimit(unsigned long long *ctx) { SEC("lsm/socket_create") int openshell_lsm_socket_create(unsigned long long *ctx) { - int ret = (int)ctx[4]; + int ret = prior_verdict(ctx[4]); if (ret != 0) { return ret; } @@ -635,7 +642,7 @@ int openshell_lsm_socket_create(unsigned long long *ctx) { SEC("lsm/sb_remount") int openshell_lsm_sb_remount(unsigned long long *ctx) { - int ret = (int)ctx[2]; + int ret = prior_verdict(ctx[2]); if (ret != 0) { return ret; } @@ -659,7 +666,7 @@ int openshell_lsm_sb_remount(unsigned long long *ctx) { SEC("lsm/sb_umount") int openshell_lsm_sb_umount(unsigned long long *ctx) { - int ret = (int)ctx[2]; + int ret = prior_verdict(ctx[2]); if (ret != 0) { return ret; } @@ -688,7 +695,7 @@ int openshell_lsm_sb_umount(unsigned long long *ctx) { SEC("lsm/locked_down") int openshell_lsm_locked_down(unsigned long long *ctx) { - int ret = (int)ctx[1]; + int ret = prior_verdict(ctx[1]); if (ret != 0) { return ret; } @@ -706,7 +713,7 @@ int openshell_lsm_locked_down(unsigned long long *ctx) { SEC("lsm/file_open") int openshell_lsm_file_open(unsigned long long *ctx) { - int ret = (int)ctx[1]; + int ret = prior_verdict(ctx[1]); if (ret != 0) { return ret; } @@ -726,7 +733,7 @@ int openshell_lsm_file_open(unsigned long long *ctx) { SEC("lsm/inode_create") int openshell_lsm_inode_create(unsigned long long *ctx) { - int ret = (int)ctx[3]; + int ret = prior_verdict(ctx[3]); if (ret != 0) { return ret; } @@ -736,7 +743,7 @@ int openshell_lsm_inode_create(unsigned long long *ctx) { SEC("lsm/inode_unlink") int openshell_lsm_inode_unlink(unsigned long long *ctx) { - int ret = (int)ctx[2]; + int ret = prior_verdict(ctx[2]); if (ret != 0) { return ret; } @@ -746,7 +753,7 @@ int openshell_lsm_inode_unlink(unsigned long long *ctx) { SEC("lsm/inode_rename") int openshell_lsm_inode_rename(unsigned long long *ctx) { - int ret = (int)ctx[4]; + int ret = prior_verdict(ctx[4]); if (ret != 0) { return ret; } @@ -761,7 +768,7 @@ int openshell_lsm_inode_rename(unsigned long long *ctx) { SEC("lsm/inode_setattr") int openshell_lsm_inode_setattr(unsigned long long *ctx) { - int ret = (int)ctx[3]; + int ret = prior_verdict(ctx[3]); if (ret != 0) { return ret; } @@ -771,7 +778,7 @@ int openshell_lsm_inode_setattr(unsigned long long *ctx) { SEC("lsm/sb_mount") int openshell_lsm_sb_mount(unsigned long long *ctx) { - int ret = (int)ctx[5]; + int ret = prior_verdict(ctx[5]); if (ret != 0) { return ret; } @@ -824,7 +831,7 @@ int openshell_lsm_sb_mount(unsigned long long *ctx) { SEC("lsm/bprm_check_security") int openshell_lsm_bprm_check(unsigned long long *ctx) { - int ret = (int)ctx[1]; + int ret = prior_verdict(ctx[1]); if (ret != 0) { return ret; } @@ -881,7 +888,7 @@ int openshell_lsm_bprm_check(unsigned long long *ctx) { SEC("lsm/task_alloc") int openshell_lsm_task_alloc(unsigned long long *ctx) { - int ret = (int)ctx[2]; + int ret = prior_verdict(ctx[2]); if (ret != 0) { return ret; } diff --git a/deploy/helm/openshell/README.md b/deploy/helm/openshell/README.md index eefd1e6ed4..73782c23c8 100644 --- a/deploy/helm/openshell/README.md +++ b/deploy/helm/openshell/README.md @@ -803,7 +803,7 @@ for peer identity policies, multi-node registrations, and authorization. | server.otlp.endpoint | string | `""` | OTLP/gRPC collector endpoint, conventionally port 4317. For an `http/protobuf` collector, also set protocol under gatewayConfig."openshell.gateway.otlp". | | server.otlp.serviceName | string | `""` | Gateway OpenTelemetry service name. Empty uses openshell-gateway. | | server.policyValidationFailureMode | string | `"fail_closed"` | Posture when a candidate sandbox policy fails validation. `fail_closed` deactivates the previous policy; `retain_last_valid` keeps it active. | -| server.privilegedRuntimeClassName | string | `""` | Kubernetes runtimeClassName for `--privileged` (true guest root + boot-once BPF LSM) sandbox pods, such as a hardened Kata Containers class. Empty (default) disables privileged sandboxes on Kubernetes. | +| server.privilegedRuntimeClassName | string | `""` | Kubernetes runtimeClassName for `--privileged` (true guest root + boot-once BPF LSM) sandbox pods, such as a hardened Kata Containers class. The RuntimeClass needs the `openshell.ai/sandbox-attachable=true` and `openshell.ai/sandbox-attachable-workspace=` labels. Empty (default) disables privileged sandboxes on Kubernetes. | | server.providerTokenGrants.spiffe.enabled | bool | `false` | Mount the SPIFFE Workload API socket into gateway and sandbox pods for dynamic provider token grants. | | server.providerTokenGrants.spiffe.workloadApiSocketPath | string | `"/spiffe-workload-api/spire-agent.sock"` | Path to the SPIFFE Workload API socket mounted into gateway and sandbox pods. | | server.sandboxGid | string | `""` | GID for sandbox pods (`sandbox_gid`). Empty (default) = same as sandboxUid. Must be an integer between 1 and 4294967294. | diff --git a/deploy/helm/openshell/values.yaml b/deploy/helm/openshell/values.yaml index 123db8abda..1e98fd3b6d 100644 --- a/deploy/helm/openshell/values.yaml +++ b/deploy/helm/openshell/values.yaml @@ -551,6 +551,8 @@ server: defaultRuntimeClassName: "" # -- Kubernetes runtimeClassName for `--privileged` (true guest root + # boot-once BPF LSM) sandbox pods, such as a hardened Kata Containers class. + # The RuntimeClass needs the `openshell.ai/sandbox-attachable=true` and + # `openshell.ai/sandbox-attachable-workspace=` labels. # Empty (default) disables privileged sandboxes on Kubernetes. privilegedRuntimeClassName: "" # -- UID for sandbox pods (`sandbox_uid`). Empty (default) = use the OpenShift From c153f758df4ca0d20fcc4fed5ca8ebd9cff529c5 Mon Sep 17 00:00:00 2001 From: Drew Newberry Date: Tue, 1 Dec 2026 20:42:06 -0800 Subject: [PATCH 3/3] feat(sandbox): replace VM bash init with thin openshell-sandbox vm-init PID 1 Signed-off-by: Drew Newberry --- .../scripts/openshell-vm-sandbox-init.sh | 797 --------- crates/openshell-driver-vm/src/driver.rs | 69 +- crates/openshell-driver-vm/src/main.rs | 5 +- crates/openshell-driver-vm/src/rootfs.rs | 188 +-- crates/openshell-driver-vm/src/runtime.rs | 10 +- crates/openshell-sandbox/src/lib.rs | 2 + crates/openshell-sandbox/src/main.rs | 14 + crates/openshell-sandbox/src/vm_init.rs | 1474 +++++++++++++++++ 8 files changed, 1515 insertions(+), 1044 deletions(-) delete mode 100644 crates/openshell-driver-vm/scripts/openshell-vm-sandbox-init.sh create mode 100644 crates/openshell-sandbox/src/vm_init.rs diff --git a/crates/openshell-driver-vm/scripts/openshell-vm-sandbox-init.sh b/crates/openshell-driver-vm/scripts/openshell-vm-sandbox-init.sh deleted file mode 100644 index 9e8383e893..0000000000 --- a/crates/openshell-driver-vm/scripts/openshell-vm-sandbox-init.sh +++ /dev/null @@ -1,797 +0,0 @@ -#!/bin/bash -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -# Minimal init for sandbox VMs. Runs as PID 1 inside the guest, mounts the -# essential filesystems, optionally loads NVIDIA GPU drivers, then execs the -# portable VM sandbox. Workload networking crosses the authenticated -# boundary channel; the VM does not receive a network interface. - -set -euo pipefail - -# libkrun consumes this driver-owned switch before exec'ing this script as -# PID 1. Do not leak the runtime control into the supervisor or workloads. -unset KRUN_INIT_PID1 - -BOOT_START=$(date +%s%3N 2>/dev/null || date +%s) -SANDBOX_OWNER_NORMALIZED_MARKER="/opt/openshell/.sandbox-owner-normalized" - -GPU_ENABLED="${GPU_ENABLED:-false}" - -ts() { - local now - now=$(date +%s%3N 2>/dev/null || date +%s) - local elapsed=$((now - BOOT_START)) - printf "[%d.%03ds] %s\n" $((elapsed / 1000)) $((elapsed % 1000)) "$*" -} - -mount_initial_fs() { - mount -t proc proc /proc 2>/dev/null || true - mount -t sysfs sysfs /sys 2>/dev/null || true - mount -t tmpfs tmpfs /tmp 2>/dev/null || true - mount -t tmpfs tmpfs /run 2>/dev/null || true - mount -t devtmpfs devtmpfs /dev 2>/dev/null || true -} - -bind_mount_into_newroot() { - local source="$1" - local target="/newroot${source}" - - mkdir -p "$target" 2>/dev/null || true - mount --rbind "$source" "$target" 2>/dev/null \ - || mount --bind "$source" "$target" 2>/dev/null \ - || true -} - -root_path() { - local path="$1" - printf '%s%s\n' "${ROOT_PREFIX:-}" "$path" -} - -sandbox_owner() { - sandbox_owner_from_passwd "$(root_path /etc/passwd)" -} - -sandbox_owner_for_root() { - local root="$1" - sandbox_owner_from_passwd "$root/etc/passwd" -} - -sandbox_owner_from_passwd() { - local passwd_path name uid gid rest - passwd_path="$1" - if [ -f "$passwd_path" ]; then - while IFS=: read -r name _ uid gid rest; do - _="${rest:-}" - if [ "$name" = "sandbox" ] \ - && [[ "$uid" =~ ^[0-9]+$ ]] \ - && [[ "$gid" =~ ^[0-9]+$ ]]; then - printf '%s:%s\n' "$uid" "$gid" - return - fi - done < "$passwd_path" - fi - - # New images use the conventional sandbox UID. Existing images retain the - # sandbox account read above, including the legacy 10001:10001 identity. - printf '1000:1000\n' -} - -source_overlay_env_if_present() { - local env_file="/overlay/upper/srv/openshell-env.sh" - if [ -f "$env_file" ]; then - # shellcheck source=/dev/null - source "$env_file" - fi -} - -ensure_target_runtime() { - local image_root="$1" - local sandbox_uid="${OPENSHELL_VM_SANDBOX_UID:-}" - local sandbox_gid="${OPENSHELL_VM_SANDBOX_GID:-}" - local replace_account=0 - - # An omitted identity means the image owns its sandbox account contract. - # Fall back to 1000 only when the image has no sandbox account at all. - if [ -n "$sandbox_uid" ] || [ -n "$sandbox_gid" ]; then - sandbox_uid="${sandbox_uid:-1000}" - sandbox_gid="${sandbox_gid:-$sandbox_uid}" - replace_account=1 - elif ! grep -q '^sandbox:' "$image_root/etc/passwd" 2>/dev/null; then - sandbox_uid=1000 - sandbox_gid=1000 - replace_account=1 - fi - - mkdir -p \ - "$image_root/srv" \ - "$image_root/opt/openshell/bin" \ - "$image_root/sandbox" \ - "$image_root/etc" - - cp /srv/openshell-vm-sandbox-init.sh "$image_root/srv/openshell-vm-sandbox-init.sh" - chmod 0755 "$image_root/srv/openshell-vm-sandbox-init.sh" - - if [ -x /opt/openshell/bin/openshell-sandbox ]; then - cp /opt/openshell/bin/openshell-sandbox "$image_root/opt/openshell/bin/openshell-sandbox" - chmod 0755 "$image_root/opt/openshell/bin/openshell-sandbox" - fi - if [ -x /opt/openshell/bin/openshell-vm-init ]; then - cp /opt/openshell/bin/openshell-vm-init "$image_root/opt/openshell/bin/openshell-vm-init" - chmod 0755 "$image_root/opt/openshell/bin/openshell-vm-init" - fi - - touch "$image_root/etc/passwd" "$image_root/etc/group" "$image_root/etc/shadow" "$image_root/etc/gshadow" - if [ "$replace_account" -eq 1 ]; then - if grep -q '^sandbox:' "$image_root/etc/group" 2>/dev/null; then - sed -i "s|^sandbox:.*|sandbox:x:${sandbox_gid}:|" "$image_root/etc/group" - else - printf 'sandbox:x:%s:\n' "$sandbox_gid" >> "$image_root/etc/group" - fi - if ! grep -q '^sandbox:' "$image_root/etc/gshadow" 2>/dev/null; then - printf 'sandbox:!::\n' >> "$image_root/etc/gshadow" - fi - if grep -q '^sandbox:' "$image_root/etc/passwd" 2>/dev/null; then - sed -i "s|^sandbox:.*|sandbox:x:${sandbox_uid}:${sandbox_gid}:OpenShell Sandbox:/sandbox:/bin/sh|" "$image_root/etc/passwd" - else - printf 'sandbox:x:%s:%s:OpenShell Sandbox:/sandbox:/bin/sh\n' "$sandbox_uid" "$sandbox_gid" >> "$image_root/etc/passwd" - fi - if ! grep -q '^sandbox:' "$image_root/etc/shadow" 2>/dev/null; then - printf 'sandbox:!:20123:0:99999:7:::\n' >> "$image_root/etc/shadow" - fi - fi - local owner - owner="$(sandbox_owner_for_root "$image_root")" - if ! chown -R "$owner" "$image_root/sandbox" 2>/dev/null; then - ts "FATAL: failed to apply sandbox image ownership (${owner})" - exit 1 - fi - chmod 0755 "$image_root/sandbox" -} - -prepare_guest_image_rootfs() { - local payload_dir="/overlay/config/openshell-image" - local image_root="/overlay/image-rootfs" - local partial_root="/overlay/image-rootfs.partial" - local source - - [ -d "$payload_dir" ] || return 0 - - source="$(cat "$payload_dir/source" 2>/dev/null || true)" - ts "preparing sandbox image rootfs in guest (${source:-unknown})" - - rm -rf "$image_root" "$partial_root" - - # Build the rootfs under $partial_root and rename it into place last. The - # host only caches a prepared disk that has $image_root, and guest exit - # codes do not reach the host, so $image_root must not exist until every - # step has succeeded. - case "$source" in - local-docker) - mkdir -p "$partial_root" - tar -xpf "$payload_dir/source-rootfs.tar" -C "$partial_root" - ;; - oci-layout) - if [ ! -x /opt/openshell/bin/umoci ]; then - ts "FATAL: umoci not found in VM bootstrap image" - exit 1 - fi - # `umoci raw unpack` extracts the image filesystem directly into - # the target directory; unlike `umoci unpack`, it does not create - # a bundle with a rootfs/ subdirectory. - /opt/openshell/bin/umoci raw unpack \ - --image "$payload_dir/oci:openshell" \ - "$partial_root" - if [ ! -d "$partial_root" ]; then - ts "FATAL: umoci unpack did not produce a rootfs directory" - exit 1 - fi - ;; - *) - ts "FATAL: unknown guest image payload source: ${source:-missing}" - exit 1 - ;; - esac - - ensure_target_runtime "$partial_root" - if [ -f "$payload_dir/identity" ]; then - cp "$payload_dir/identity" "$partial_root/.openshell-rootfs-variant" - fi - rm -rf "$payload_dir" - mv "$partial_root" "$image_root" -} - -exec_supervisor_in_newroot() { - local chroot_bin - local supervisor="/.openshell-bootstrap/opt/openshell/bin/openshell-sandbox" - - for chroot_bin in /usr/sbin/chroot /usr/bin/chroot /sbin/chroot /bin/chroot; do - [ -x "$chroot_bin" ] || continue - - if [ -x "/newroot${supervisor}" ]; then - exec "$chroot_bin" /newroot "$supervisor" "$@" - fi - done - - ts "FATAL: unable to exec openshell-sandbox in guest rootfs" - exit 1 -} - -setup_overlay_root() { - ts "setting up writable overlay root" - mount_initial_fs - - if [ ! -b /dev/vdb ]; then - ts "FATAL: writable overlay disk /dev/vdb not found" - exit 1 - fi - - mkdir -p /overlay /lower /newroot /image-cache - mount -o remount,ro / 2>/dev/null || true - mount -t ext4 -o rw /dev/vdb /overlay - mkdir -p /overlay/upper /overlay/work - source_overlay_env_if_present - - if [ "${OPENSHELL_VM_INIT_MODE:-sandbox}" = "image-prep" ]; then - prepare_guest_image_rootfs - sync - if ! umount /overlay; then - ts "FATAL: failed to unmount /overlay cleanly after image-prep; refusing to produce a dirty image-cache disk" - exit 1 - fi - ts "image-prep complete" - exit 0 - fi - - mount --bind / /lower - mount -o remount,bind,ro /lower 2>/dev/null || true - - local lower_root="/lower" - if [ -b /dev/vdc ]; then - mount -t ext4 -o ro,noload /dev/vdc /image-cache - if [ -d /image-cache/image-rootfs ]; then - lower_root="/image-cache/image-rootfs" - ts "using prepared image rootfs lowerdir" - else - ts "FATAL: prepared image disk missing /image-rootfs" - exit 1 - fi - fi - - # Privileged mode uses an ephemeral root overlay across boots: wipe any - # mutated non-workspace entries in /overlay/upper while preserving /sandbox - # and the driver-injected /.openshell bootstrap staging directory. - if [ "${OPENSHELL_VM_PRIVILEGED:-0}" = "1" ]; then - for entry in /overlay/upper/* /overlay/upper/.[!.]* /overlay/upper/..?*; do - [ -e "$entry" ] || [ -L "$entry" ] || continue - base="$(basename "$entry")" - case "$base" in - sandbox|.openshell) ;; - *) rm -rf "$entry" ;; - esac - done - fi - - # The host makes upper under the gateway's umask and uid, and it becomes /. - chown 0:0 /overlay/upper - chmod 0755 /overlay/upper - - mount -t overlay overlay \ - -o lowerdir="$lower_root",upperdir=/overlay/upper,workdir=/overlay/work \ - /newroot - mkdir -p /newroot/.openshell-bootstrap - mount --bind /lower /newroot/.openshell-bootstrap - - # GPU setup runs against the bootstrap runtime and its mounted /dev, /proc, - # and /run before those filesystems are mirrored into the target root. - if [ "${GPU_ENABLED}" = "true" ]; then - setup_gpu || ts "WARNING: GPU init failed; continuing without GPU" - fi - - if [ "${OPENSHELL_VM_PRIVILEGED:-0}" != "1" ]; then - bind_mount_into_newroot /proc - bind_mount_into_newroot /sys - bind_mount_into_newroot /tmp - bind_mount_into_newroot /dev - bind_mount_into_newroot /run - fi - - ROOT_PREFIX="/newroot" - run_post_overlay_setup -} - -create_gpu_device_nodes_mknod() { - # Mode 666 is intentional: single-tenant microVM with the VM itself as the - # isolation boundary. The sandbox user is the only non-root user. - local nv_major - nv_major=$(awk '$2 == "nvidia" {print $1}' /proc/devices 2>/dev/null || true) - if [ -n "$nv_major" ]; then - mknod -m 666 /dev/nvidiactl c "$nv_major" 255 2>/dev/null || true - - local gpu_count=0 - if [ -d /proc/driver/nvidia/gpus ]; then - for gpu_dir in /proc/driver/nvidia/gpus/*/; do - [ -d "$gpu_dir" ] || continue - mknod -m 666 "/dev/nvidia${gpu_count}" c "$nv_major" "$gpu_count" 2>/dev/null || true - gpu_count=$((gpu_count + 1)) - done - fi - if [ "$gpu_count" -eq 0 ]; then - mknod -m 666 /dev/nvidia0 c "$nv_major" 0 2>/dev/null || true - fi - - local modeset_major - modeset_major=$(awk '$2 == "nvidia-modeset" {print $1}' /proc/devices 2>/dev/null || true) - if [ -n "$modeset_major" ]; then - mknod -m 666 /dev/nvidia-modeset c "$modeset_major" 254 2>/dev/null || true - fi - - local uvm_major - uvm_major=$(awk '$2 == "nvidia-uvm" {print $1}' /proc/devices 2>/dev/null || true) - if [ -n "$uvm_major" ]; then - mknod -m 666 /dev/nvidia-uvm c "$uvm_major" 0 2>/dev/null || true - mknod -m 666 /dev/nvidia-uvm-tools c "$uvm_major" 1 2>/dev/null || true - fi - - local caps_major - caps_major=$(awk '$2 == "nvidia-caps" {print $1}' /proc/devices 2>/dev/null || true) - if [ -n "$caps_major" ]; then - mkdir -p /dev/nvidia-caps 2>/dev/null || true - mknod -m 666 /dev/nvidia-caps/nvidia-cap1 c "$caps_major" 1 2>/dev/null || true - mknod -m 666 /dev/nvidia-caps/nvidia-cap2 c "$caps_major" 2 2>/dev/null || true - fi - - ts "GPU device nodes created via mknod (${gpu_count} GPU(s), major=${nv_major})" - else - ts "WARNING: 'nvidia' not in /proc/devices; device nodes unavailable" - fi -} - -setup_gpu() { - ts "GPU_ENABLED=true — initializing GPU passthrough" - - if ! command -v modprobe >/dev/null 2>&1; then - ts "FATAL: modprobe not found; cannot load nvidia kernel modules" - return 1 - fi - - # Stage GSP firmware to tmpfs so module loading reads it from a stable - # early-boot path. - if [ -d /lib/firmware/nvidia ]; then - ts "staging GPU firmware to tmpfs" - mkdir -p /run/firmware/nvidia - cp -a /lib/firmware/nvidia/* /run/firmware/nvidia/ 2>/dev/null || true - if [ -e /sys/module/firmware_class/parameters/path ]; then - echo /run/firmware > /sys/module/firmware_class/parameters/path - fi - fi - - ts "loading nvidia kernel modules" - modprobe nvidia || { ts "FATAL: modprobe nvidia failed"; return 1; } - modprobe nvidia_uvm 2>/dev/null || true - modprobe nvidia_modeset 2>/dev/null || true - - rm -rf /run/firmware 2>/dev/null || true - - if command -v nvidia-smi >/dev/null 2>&1; then - ts "running nvidia-smi to create device nodes and validate GPU" - local smi_rc=0 - nvidia-smi >/dev/null 2>&1 || smi_rc=$? - if [ "$smi_rc" -eq 0 ]; then - nvidia-smi -L 2>/dev/null | while read -r line; do ts " $line"; done - ts "GPU initialization successful" - else - ts "WARNING: nvidia-smi failed (exit ${smi_rc}); falling back to mknod" - create_gpu_device_nodes_mknod - fi - else - ts "nvidia-smi not found; creating device nodes via mknod" - create_gpu_device_nodes_mknod - fi -} - -reconcile_sandbox_account() { - local sandbox_uid="${OPENSHELL_VM_SANDBOX_UID:-}" - local sandbox_gid="${OPENSHELL_VM_SANDBOX_GID:-}" - local etc - - [ -n "$sandbox_uid" ] && [ -n "$sandbox_gid" ] || return 0 - [[ "$sandbox_uid" =~ ^[0-9]+$ ]] && [[ "$sandbox_gid" =~ ^[0-9]+$ ]] || { - ts "FATAL: invalid requested sandbox identity" - exit 1 - } - etc="$(root_path /etc)" - mkdir -p "$etc" - touch "$etc/passwd" "$etc/group" "$etc/shadow" "$etc/gshadow" - if grep -q '^sandbox:' "$etc/group"; then - if ! awk -F: -v OFS=: -v gid="$sandbox_gid" \ - '$1 == "sandbox" { $3 = gid } { print }' \ - "$etc/group" >"$etc/group.openshell"; then - rm -f "$etc/group.openshell" - ts "FATAL: failed to reconcile sandbox group" - exit 1 - fi - mv "$etc/group.openshell" "$etc/group" - else - printf 'sandbox:x:%s:\n' "$sandbox_gid" >> "$etc/group" - fi - if grep -q '^sandbox:' "$etc/passwd"; then - # Preserve image-owned account metadata (home, shell, and description) - # while restoring the UID/GID contract recorded for this overlay. - if ! awk -F: -v OFS=: -v uid="$sandbox_uid" -v gid="$sandbox_gid" \ - '$1 == "sandbox" { $3 = uid; $4 = gid } { print }' \ - "$etc/passwd" >"$etc/passwd.openshell"; then - rm -f "$etc/passwd.openshell" - ts "FATAL: failed to reconcile sandbox account" - exit 1 - fi - mv "$etc/passwd.openshell" "$etc/passwd" - else - printf 'sandbox:x:%s:%s:OpenShell Sandbox:/sandbox:/bin/sh\n' "$sandbox_uid" "$sandbox_gid" >> "$etc/passwd" - fi - grep -q '^sandbox:' "$etc/gshadow" || printf 'sandbox:!::\n' >> "$etc/gshadow" - grep -q '^sandbox:' "$etc/shadow" || printf 'sandbox:!:20123:0:99999:7:::\n' >> "$etc/shadow" - ts "reconciled sandbox account (${sandbox_uid}:${sandbox_gid})" -} - -setup_sandbox_workdir() { - local sandbox_dir - local owner - local current_owner - sandbox_dir="$(root_path /sandbox)" - owner="$(sandbox_owner)" - mkdir -p "$sandbox_dir" - current_owner="$(stat -c '%u:%g' "$sandbox_dir" 2>/dev/null || true)" - if [ "$owner" = "10001:10001" ]; then - ts "preserving legacy sandbox ownership (10001:10001)" - fi - if [ "$current_owner" != "$owner" ]; then - if ! chown -R "$owner" "$sandbox_dir" 2>/dev/null; then - ts "FATAL: failed to apply sandbox ownership (${owner})" - exit 1 - fi - fi - chmod 0755 "$sandbox_dir" - ts "prepared /sandbox ownership (${owner})" -} - -configure_hostname() { - local sandbox_hostname="${OPENSHELL_SANDBOX:-openshell-sandbox-vm}" - sandbox_hostname="$(printf '%s' "$sandbox_hostname" | tr -c 'A-Za-z0-9.-' '-')" - sandbox_hostname="$(printf '%s' "$sandbox_hostname" | sed 's/^[.-][.-]*//; s/[.-][.-]*$//')" - sandbox_hostname="$(printf '%.63s' "$sandbox_hostname")" - if [ -z "$sandbox_hostname" ]; then - sandbox_hostname="openshell-sandbox-vm" - fi - - hostname "$sandbox_hostname" 2>/dev/null || true - printf '%s\n' "$sandbox_hostname" >"$(root_path /etc/hostname)" 2>/dev/null || true - ts "hostname=${sandbox_hostname}" -} - -# OCI images commonly ship an empty /etc/hosts and rely on the container -# runtime to bind-mount a generated one. No runtime does that here, and /etc is -# read-only once the supervisor applies policy, so init supplies the loopback -# names when the file is missing or empty. A non-empty file is the image -# author's and is kept as is. Without these entries `localhost` fails to -# resolve: the guest resolver is the loopback relay, which has no record for it. -configure_hosts() { - local hosts_file - hosts_file="$(root_path /etc/hosts)" - - # An absolute symlink target resolves against init's own root, not the - # workload root, so following one could write outside the workload. Leave - # an image-authored link alone. - if [ -L "$hosts_file" ]; then - ts "WARN: ${hosts_file} is a symlink; leaving it unchanged" - return 0 - fi - if [ -s "$hosts_file" ]; then - return 0 - fi - - # Missing loopback names degrade the workload but do not make the sandbox - # unsafe, so a write failure is reported and boot continues. The shell's - # own error stays visible on the console to explain the failure. - if ! printf '%s\n' \ - '127.0.0.1 localhost' \ - '::1 localhost ip6-localhost ip6-loopback' \ - >"$hosts_file"; then - ts "WARN: could not write ${hosts_file}; localhost will not resolve" - return 0 - fi - ts "populated empty /etc/hosts with loopback names" -} - -run_openshell_init_dropins() { - # Run executable drop-ins from /opt/openshell/init.d in deterministic - # ASCII-sorted order. Drop-ins are *executed* in a child shell rather - # than sourced, so they cannot mutate parent shell state or exit the - # caller. They inherit `OPENSHELL_VM_INIT_PHASE`, `ROOT_PREFIX`, and - # any `OPENSHELL_VM_DATA_*` env vars set by lifecycle extensions. - # - # Security: this runs as root before the supervisor enforces policy, so - # it executes *only* the drop-ins the VM driver explicitly injected this - # launch, as enumerated in the driver-authored manifest. Anything else - # found under init.d (e.g. files baked into a user-controlled guest - # image) is ignored. The manifest lives in the overlay upperdir, which - # the driver owns, so a guest image cannot forge or shadow it. A missing - # manifest is treated as "run nothing" (fail-closed). - local init_dir manifest - init_dir="$(root_path /opt/openshell/init.d)" - manifest="$(root_path /opt/openshell/init.d.manifest)" - - if [ ! -f "$manifest" ]; then - if [ -d "$init_dir" ]; then - ts "no OpenShell VM init drop-in manifest present; skipping init.d" - fi - return 0 - fi - - export OPENSHELL_VM_INIT_PHASE="before-supervisor" - export ROOT_PREFIX="${ROOT_PREFIX:-}" - - # Fail closed on any inconsistency: every drop-in below is trusted, - # required setup the driver injected on purpose, so we abort the boot - # rather than run a half-configured sandbox. Aborting exits this init - # non-zero; the VM helper then exits and the driver runs - # lifecycle-extension cleanup, so a failed init does not leak resources. - # The loop runs in the main shell (process substitution, not a pipe), so - # `exit` here terminates init as intended. - local name dropin rc - while IFS= read -r name; do - [ -n "$name" ] || continue - # Manifest entries are bare file names that the driver already - # validated. A separator or traversal here means the manifest was - # tampered with after the driver wrote it. - case "$name" in - */* | . | ..) - ts "FATAL: unsafe init drop-in manifest entry '${name}'" - exit 1 - ;; - esac - - # The driver writes each entry's file and marks it 0755 in the same - # operation, so a missing or non-executable entry means the overlay - # was tampered with or provisioning is broken. - dropin="${init_dir}/${name}" - if [ ! -f "$dropin" ]; then - ts "FATAL: init drop-in '${name}' listed in manifest but not found" - exit 1 - fi - if [ ! -x "$dropin" ]; then - ts "FATAL: init drop-in '${name}' is not executable" - exit 1 - fi - - ts "running OpenShell VM init drop-in ${name}" - rc=0 - set +e - "$dropin" - rc=$? - set -e - if [ "$rc" -ne 0 ]; then - ts "FATAL: OpenShell VM init drop-in ${name} failed with exit code ${rc}" - exit 1 - fi - done < <(LC_ALL=C sort -u "$manifest") -} - -# Create a virtiofs mount point under ROOT_PREFIX without following symlinks, -# so an image cannot redirect a validated target onto another guest path. -# Directories created under /sandbox are handed to the sandbox user. -prepare_virtiofs_target() { - local target="$1" owner="$2" - local path="${ROOT_PREFIX:-}" component - local -a components - IFS=/ read -r -a components <<<"${target#/}" - for component in "${components[@]}"; do - [ -n "$component" ] || continue - path="${path}/${component}" - if [ -L "$path" ]; then - ts >&2 "FATAL: virtiofs mount target ${target} traverses symlink ${path#"${ROOT_PREFIX:-}"}" - exit 1 - fi - if [ ! -e "$path" ]; then - if ! mkdir "$path"; then - ts >&2 "FATAL: failed to create virtiofs mount point ${target}" - exit 1 - fi - case "${path#"${ROOT_PREFIX:-}"}" in - /sandbox/*) - if ! chown "$owner" "$path"; then - ts >&2 "FATAL: failed to hand virtiofs mount point parent ${path#"${ROOT_PREFIX:-}"} to ${owner}" - exit 1 - fi - ;; - esac - elif [ ! -d "$path" ]; then - ts >&2 "FATAL: virtiofs mount target ${target} is not a directory" - exit 1 - fi - done - printf '%s\n' "$path" -} - -# Runs after every /sandbox ownership fixup and the root-run init drop-ins so -# nothing in init walks into host-backed shares. -mount_virtiofs_shares() { - local manifest - manifest="$(root_path /.openshell/mounts.manifest)" - # The driver always writes the manifest; it is empty without mounts. - [ -s "$manifest" ] || return 0 - - ts "mounting virtiofs shares" - local tag target mode mount_opts guest_target owner - owner="$(sandbox_owner)" - while IFS=$'\t' read -r tag target mode; do - [ -n "$tag" ] || continue - case "$mode" in - ro) mount_opts="-o ro" ;; - rw) mount_opts="" ;; - *) - ts "FATAL: unknown virtiofs mount mode '${mode}' for tag ${tag}" - exit 1 - ;; - esac - guest_target="$(prepare_virtiofs_target "$target" "$owner")" || exit 1 - # shellcheck disable=SC2086 - if mount -t virtiofs $mount_opts "$tag" "$guest_target"; then - ts " mounted virtiofs ${tag} -> ${target} (${mode})" - else - ts "FATAL: failed to mount virtiofs ${tag} at ${target}" - exit 1 - fi - done < "$manifest" -} - -run_post_overlay_setup() { - # Source QEMU-injected environment variables if present. The file lives in - # the overlay upperdir so the cached bootstrap rootfs remains immutable. - local env_file - env_file="$(root_path /srv/openshell-env.sh)" - if [ -f "$env_file" ]; then - # shellcheck source=/dev/null - source "$env_file" - fi - - if [ -z "${ROOT_PREFIX:-}" ]; then - mount -t proc proc /proc 2>/dev/null & - mount -t sysfs sysfs /sys 2>/dev/null & - mount -t tmpfs tmpfs /tmp 2>/dev/null & - mount -t tmpfs tmpfs /run 2>/dev/null & - mount -t devtmpfs devtmpfs /dev 2>/dev/null & - wait - fi - - if [ "${OPENSHELL_VM_PRIVILEGED:-0}" = "1" ]; then - mkdir -p /sys/fs/cgroup - mount -t cgroup2 cgroup2 /sys/fs/cgroup 2>/dev/null || true - fi - mkdir -p "$(root_path /dev/pts)" "$(root_path /dev/shm)" "$(root_path /sys/fs/cgroup)" - mount -t devpts devpts "$(root_path /dev/pts)" 2>/dev/null & - mount -t tmpfs tmpfs "$(root_path /dev/shm)" 2>/dev/null & - mount -t cgroup2 cgroup2 "$(root_path /sys/fs/cgroup)" 2>/dev/null & - wait - - reconcile_sandbox_account - setup_sandbox_workdir - - configure_hostname - configure_hosts - if ! /opt/openshell/bin/openshell-vm-init prepare-network; then - ts "FATAL: failed to bring up the loopback interface" - exit 1 - fi - - # The capability-free sandbox owns a loopback-only DNS relay. Guest init - # grants the low port before handing control to the zero-capability UID. - if ! echo 0 > /proc/sys/net/ipv4/ip_unprivileged_port_start; then - ts "FATAL: failed to permit the unprivileged DNS relay to bind port 53" - exit 1 - fi - cat >"$(root_path /etc/resolv.conf)" <<'EOF' -nameserver 127.0.0.53 -options timeout:2 attempts:2 -EOF - -# The boundary transport mediates network and DNS requests. Only loopback is -# configured in the guest; no public resolver or guest NIC is needed. - -export HOME=/sandbox -export USER=sandbox - -# Fix /sandbox ownership. The host-side CLI extracts OCI layers as a non-root -# user (e.g. UID 501 on macOS), so /sandbox may be owned by the host UID. -# -# On macOS (Hypervisor.framework), guest root has real root privileges and -# chown succeeds. On Linux non-root hosts with virtiofs, guest root maps to -# the host user, so chown is denied — this is non-fatal because the -# supervisor's own filesystem preparation handles the paths that matter. -if [ -d /sandbox ]; then - _sb_uid=$(id -u sandbox 2>/dev/null || true) - _sb_gid=$(id -g sandbox 2>/dev/null || true) - if [ -n "$_sb_uid" ] && [ -n "$_sb_gid" ]; then - _cur_uid=$(stat -c '%u' /sandbox 2>/dev/null || true) - if [ -n "$_cur_uid" ] && [ "$_cur_uid" != "$_sb_uid" ]; then - ts "fixing /sandbox ownership (was uid=${_cur_uid}, setting to sandbox=${_sb_uid}:${_sb_gid})" - chown -R "${_sb_uid}:${_sb_gid}" /sandbox 2>/dev/null || \ - ts "chown /sandbox denied (virtiofs rootless host), continuing" - fi - fi -fi - -run_openshell_init_dropins - -mount_virtiofs_shares - -if [ -n "${OPENSHELL_SANDBOX_ID:-}" ]; then - ts "OPENSHELL_SANDBOX_ID=${OPENSHELL_SANDBOX_ID}" -fi - -ts "starting OpenShell VM sandbox" -_sandbox_bootstrap_guest="${OPENSHELL_VM_SANDBOX_BOOTSTRAP:-/.openshell/state/bootstrap.json}" -_sandbox_bootstrap="$(root_path "$_sandbox_bootstrap_guest")" -_sandbox_state_dir="${_sandbox_bootstrap%/*}" -if [ ! -f "$_sandbox_bootstrap" ]; then - ts "FATAL: sandbox bootstrap is missing" - exit 1 -fi - -if [ "${OPENSHELL_VM_PRIVILEGED:-0}" = "1" ]; then - # Stage bootstrap and TLS material into runtime-private tmpfs on the - # read-only runtime root and remove them from the workload overlay so - # guest-root workloads never see bootstrap secrets. - mkdir -p /run/openshell/bootstrap /run/openshell/tls - chmod 0700 /run/openshell /run/openshell/bootstrap - chmod 0755 /run/openshell/tls - for _sandbox_private_file in "$_sandbox_state_dir"/*; do - [ -f "$_sandbox_private_file" ] || continue - _dst="/run/openshell/bootstrap/$(basename "$_sandbox_private_file")" - cp "$_sandbox_private_file" "$_dst" - chmod 0600 "$_dst" - done - rm -rf "$_sandbox_state_dir" - # Ensure the workload root has no bootstrap mount exposing the runtime root. - umount /newroot/.openshell-bootstrap 2>/dev/null || true - rmdir /newroot/.openshell-bootstrap 2>/dev/null || true - _priv_bootstrap="/run/openshell/bootstrap/$(basename "$_sandbox_bootstrap")" - ts "exec openshell-sandbox --privileged (workload root: ${ROOT_PREFIX:-/newroot})" - exec /opt/openshell/bin/openshell-sandbox \ - --bootstrap "$_priv_bootstrap" \ - --privileged \ - --workload-root "${ROOT_PREFIX:-/newroot}" -fi - -_sandbox_owner="$(sandbox_owner)" -_sandbox_uid="${_sandbox_owner%%:*}" -_sandbox_gid="${_sandbox_owner##*:}" -chown "${_sandbox_uid}:${_sandbox_gid}" "$_sandbox_state_dir" -chmod 0700 "$_sandbox_state_dir" -for _sandbox_private_file in "$_sandbox_state_dir"/*; do - [ -f "$_sandbox_private_file" ] || continue - chown "${_sandbox_uid}:${_sandbox_gid}" "$_sandbox_private_file" - chmod 0600 "$_sandbox_private_file" -done -if [ "${OPENSHELL_VM_INIT_MODE:-sandbox}" = "capability-probe" ]; then - ts "starting capability-free VM qualification as ${_sandbox_uid}:${_sandbox_gid}" - if [ "${ROOT_PREFIX:-}" = "/newroot" ]; then - exec_supervisor_in_newroot capability-probe-launch "$_sandbox_uid" "$_sandbox_gid" - fi - exec /opt/openshell/bin/openshell-sandbox \ - capability-probe-launch "$_sandbox_uid" "$_sandbox_gid" -fi -if [ "${ROOT_PREFIX:-}" = "/newroot" ]; then - exec_supervisor_in_newroot \ - launch-capability-free "$_sandbox_uid" "$_sandbox_gid" "$_sandbox_bootstrap_guest" -fi -exec /opt/openshell/bin/openshell-sandbox \ - launch-capability-free "$_sandbox_uid" "$_sandbox_gid" "$_sandbox_bootstrap_guest" -} - -if [ "${1:-}" != "--post-overlay" ]; then - setup_overlay_root -fi - -shift || true -run_post_overlay_setup diff --git a/crates/openshell-driver-vm/src/driver.rs b/crates/openshell-driver-vm/src/driver.rs index 9c5af6538c..4ae7799d03 100644 --- a/crates/openshell-driver-vm/src/driver.rs +++ b/crates/openshell-driver-vm/src/driver.rs @@ -22,9 +22,9 @@ use crate::rootfs::{ clone_or_copy_sparse_file, create_ext4_image_from_dir_with_size, create_rootfs_image_from_dir, ext4_image_has_directory, extract_host_supervisor, extract_rootfs_archive_to, prepare_sandbox_rootfs_from_image_root, recover_rootfs_image, remove_rootfs_image_file, - sandbox_guest_init_path, sandbox_guest_runtime_identity, sandbox_guest_user_ids_from_image, - sandbox_guest_user_ids_from_overlay_image, set_rootfs_image_file_mode, - validate_host_supervisor, write_rootfs_image_file, + sandbox_guest_init_arg, sandbox_guest_init_path, sandbox_guest_runtime_identity, + sandbox_guest_user_ids_from_image, sandbox_guest_user_ids_from_overlay_image, + set_rootfs_image_file_mode, validate_host_supervisor, write_rootfs_image_file, }; use crate::runtime::VmBackend; use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD}; @@ -262,7 +262,7 @@ const IMAGE_REFERENCE_FILE: &str = "image-reference"; const IMAGE_PREP_INIT_MODE: &str = "image-prep"; const IMAGE_PREP_CONSOLE_LOG: &str = "image-prep-console.log"; /// Directory the guest image-prep init writes at the root of the prepared disk -/// once preparation succeeds (`image_root` in `openshell-vm-sandbox-init.sh`). +/// once preparation succeeds (`image_root` in `openshell-sandbox vm-init`). pub(crate) const PREPARED_IMAGE_ROOTFS_DIR: &str = "/image-rootfs"; static IMAGE_CACHE_BUILD_COUNTER: AtomicU64 = AtomicU64::new(0); static OWNER_STATE_WRITE_COUNTER: AtomicU64 = AtomicU64::new(0); @@ -2171,6 +2171,7 @@ impl VmDriver { command.arg("--vm-image-disk").arg(image_disk); } command.arg("--vm-exec").arg(sandbox_guest_init_path()); + command.arg("--vm-arg").arg(sandbox_guest_init_arg()); command.arg("--vm-workdir").arg("/"); command.arg("--vm-console-output").arg(&console_output); command.arg("--vm-vcpus").arg(plan.vcpus.to_string()); @@ -4660,6 +4661,7 @@ impl VmDriver { command.arg("--vm-root-disk").arg(bootstrap_root_disk); command.arg("--vm-overlay-disk").arg(prep_disk); command.arg("--vm-exec").arg(sandbox_guest_init_path()); + command.arg("--vm-arg").arg(sandbox_guest_init_arg()); command.arg("--vm-workdir").arg("/"); command.arg("--vm-console-output").arg(&console_output); command.arg("--vm-vcpus").arg(self.config.vcpus.to_string()); @@ -15027,65 +15029,6 @@ while :; do sleep 0.05; done"#, )); } - /// Runs `prepare_virtiofs_target` from the guest init script against a - /// host directory standing in for the guest root. - #[cfg(unix)] - fn run_prepare_virtiofs_target(root: &Path, target: &str) -> std::process::Output { - let script = include_str!("../scripts/openshell-vm-sandbox-init.sh"); - let start = script - .find("prepare_virtiofs_target() {") - .expect("init script defines prepare_virtiofs_target"); - let end = start + script[start..].find("\n}\n").expect("function end") + 3; - let program = format!( - "set -euo pipefail\nts() {{ echo \"$@\"; }}\n{}\nprepare_virtiofs_target \"$1\" \"$(id -u):$(id -g)\"\n", - &script[start..end] - ); - std::process::Command::new("bash") - .args(["-c", &program, "test", target]) - .env("ROOT_PREFIX", root) - .output() - .unwrap() - } - - #[cfg(unix)] - #[test] - fn vm_init_prepare_virtiofs_target_creates_missing_directories() { - let root = tempfile::tempdir().unwrap(); - fs::create_dir(root.path().join("sandbox")).unwrap(); - let output = run_prepare_virtiofs_target(root.path(), "/sandbox/a/b"); - assert!(output.status.success(), "{output:?}"); - let expected = root.path().join("sandbox/a/b"); - assert!(expected.is_dir()); - assert_eq!( - String::from_utf8_lossy(&output.stdout).trim(), - expected.display().to_string() - ); - } - - #[cfg(unix)] - #[test] - fn vm_init_prepare_virtiofs_target_refuses_symlinks() { - let root = tempfile::tempdir().unwrap(); - let elsewhere = tempfile::tempdir().unwrap(); - fs::create_dir(root.path().join("sandbox")).unwrap(); - std::os::unix::fs::symlink(elsewhere.path(), root.path().join("sandbox/link")).unwrap(); - let output = run_prepare_virtiofs_target(root.path(), "/sandbox/link/x"); - assert!(!output.status.success()); - assert!(String::from_utf8_lossy(&output.stderr).contains("traverses symlink")); - assert!(!elsewhere.path().join("x").exists()); - } - - #[cfg(unix)] - #[test] - fn vm_init_prepare_virtiofs_target_refuses_non_directory() { - let root = tempfile::tempdir().unwrap(); - fs::create_dir(root.path().join("sandbox")).unwrap(); - fs::write(root.path().join("sandbox/file"), b"").unwrap(); - let output = run_prepare_virtiofs_target(root.path(), "/sandbox/file/x"); - assert!(!output.status.success()); - assert!(String::from_utf8_lossy(&output.stderr).contains("is not a directory")); - } - fn mounts_driver_config(source: &str, target: &str) -> Struct { let string = |s: &str| Value { kind: Some(Kind::StringValue(s.to_string())), diff --git a/crates/openshell-driver-vm/src/main.rs b/crates/openshell-driver-vm/src/main.rs index 407ad3e150..b344c59a51 100644 --- a/crates/openshell-driver-vm/src/main.rs +++ b/crates/openshell-driver-vm/src/main.rs @@ -56,6 +56,9 @@ struct Args { #[arg(long, hide = true)] vm_exec: Option, + #[arg(long = "vm-arg", hide = true)] + vm_arg: Vec, + #[arg(long, hide = true, default_value = "/")] vm_workdir: String, @@ -511,7 +514,7 @@ fn build_vm_launch_config(args: &Args) -> std::result::Result &'static str { SANDBOX_GUEST_INIT_PATH } +pub const fn sandbox_guest_init_arg() -> &'static str { + SANDBOX_GUEST_INIT_ARG +} + /// Identity of every embedded artifact materialized into a bootstrap rootfs. /// /// Including this in the image-cache key makes local, uncommitted guest-sandbox @@ -45,7 +50,6 @@ pub fn sandbox_guest_runtime_identity() -> String { hasher.update(SANDBOX); hasher.update(VM_INIT); hasher.update(UMOCI); - hasher.update(include_bytes!("../scripts/openshell-vm-sandbox-init.sh")); format!("{:x}", hasher.finalize()) } @@ -550,23 +554,6 @@ fn prepare_sandbox_rootfs( remove_rootfs_path(rootfs, relative)?; } - let init_path = rootfs.join("srv/openshell-vm-sandbox-init.sh"); - if let Some(parent) = init_path.parent() { - create_guest_dir_all(parent)?; - } - fs::write( - &init_path, - include_str!("../scripts/openshell-vm-sandbox-init.sh"), - ) - .map_err(|e| format!("write {}: {e}", init_path.display()))?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt as _; - - fs::set_permissions(&init_path, fs::Permissions::from_mode(0o755)) - .map_err(|e| format!("chmod {}: {e}", init_path.display()))?; - } - ensure_supervisor_binary(rootfs)?; ensure_vm_init_binary(rootfs)?; ensure_umoci_binary(rootfs)?; @@ -586,22 +573,9 @@ fn prepare_sandbox_rootfs( } pub fn validate_sandbox_rootfs(rootfs: &Path) -> Result<(), String> { - require_rootfs_path(rootfs, SANDBOX_GUEST_INIT_PATH)?; require_rootfs_path(rootfs, SANDBOX_SUPERVISOR_PATH)?; require_rootfs_path(rootfs, SANDBOX_VM_INIT_PATH)?; require_rootfs_path(rootfs, SANDBOX_UMOCI_PATH)?; - require_any_rootfs_path(rootfs, &["/bin/bash"])?; - require_any_rootfs_path(rootfs, &["/bin/mount", "/usr/bin/mount"])?; - require_any_rootfs_path( - rootfs, - &[ - "/usr/sbin/chroot", - "/usr/bin/chroot", - "/sbin/chroot", - "/bin/chroot", - ], - )?; - require_any_rootfs_path(rootfs, &["/bin/sed", "/usr/bin/sed"])?; Ok(()) } @@ -1213,20 +1187,6 @@ fn require_rootfs_path(rootfs: &Path, relative: &str) -> Result<(), String> { } } -fn require_any_rootfs_path(rootfs: &Path, candidates: &[&str]) -> Result<(), String> { - if candidates - .iter() - .any(|candidate| rootfs.join(candidate.trim_start_matches('/')).exists()) - { - Ok(()) - } else { - Err(format!( - "prepared rootfs is missing one of: {}", - candidates.join(", ") - )) - } -} - fn remove_rootfs_path(rootfs: &Path, relative: &str) -> Result<(), String> { let path = rootfs.join(relative); if !path.exists() { @@ -1303,33 +1263,9 @@ mod tests { prepare_sandbox_rootfs(&rootfs, Some(uid), Some(uid)).expect("prepare sandbox rootfs"); validate_sandbox_rootfs(&rootfs).expect("validate sandbox rootfs"); - assert!(rootfs.join("srv/openshell-vm-sandbox-init.sh").is_file()); + assert!(rootfs.join("opt/openshell/bin/openshell-sandbox").is_file()); assert!(rootfs.join("opt/openshell/bin/umoci").is_file()); assert!(rootfs.join("opt/openshell/bin/openshell-vm-init").is_file()); - let init_script = fs::read_to_string(rootfs.join("srv/openshell-vm-sandbox-init.sh")) - .expect("read guest init"); - assert!( - init_script.contains( - "launch-capability-free \"$_sandbox_uid\" \"$_sandbox_gid\" \"$_sandbox_bootstrap_guest\"" - ) - ); - assert!(init_script.contains("OPENSHELL_VM_SANDBOX_BOOTSTRAP")); - // The shell script is embedded verbatim in the guest rootfs, so these - // assertions pin its launch contract at the packaging boundary. - assert!(init_script.contains("exec \"$chroot_bin\" /newroot \"$supervisor\" \"$@\"")); - assert!(!init_script.contains("--library-path")); - assert!(!init_script.contains("\"$loader\"")); - assert!(!init_script.contains("ld-linux")); - assert!(init_script.contains(" reconcile_sandbox_account\n setup_sandbox_workdir")); - assert!( - init_script - .contains("chown \"${_sandbox_uid}:${_sandbox_gid}\" \"$_sandbox_state_dir\"") - ); - assert!(init_script.contains("chmod 0700 \"$_sandbox_state_dir\"")); - assert!(!init_script.contains("--backend-name=in-pod")); - assert!(!init_script.contains("@ISOLATION_INTERFACE_VERSION@")); - assert!(!init_script.contains("8.8.8.8")); - assert!(!init_script.contains("VM_NET_")); assert!(rootfs.join("sandbox").is_dir()); assert!(rootfs.join("image-cache").is_dir()); assert!(rootfs.join("lower").is_dir()); @@ -1357,103 +1293,6 @@ mod tests { let _ = fs::remove_dir_all(&dir); } - /// Runs the shipped guest init's `configure_hosts` against `root`. - /// - /// The function is cut out of the real script so the test exercises the - /// shell that boots the guest rather than a Rust reimplementation of it. - fn run_guest_configure_hosts(root: &Path) -> std::process::Output { - let script = include_str!("../scripts/openshell-vm-sandbox-init.sh"); - let start = script - .find("configure_hosts() {\n") - .expect("guest init defines configure_hosts"); - let tail = &script[start..]; - let end = tail - .find("\n}\n") - .expect("configure_hosts closes at column zero") - + "\n}\n".len(); - let program = format!( - "set -euo pipefail\n\ - ts() {{ :; }}\n\ - root_path() {{ printf '%s%s\\n' \"${{ROOT_PREFIX:-}}\" \"$1\"; }}\n\ - {}\n\ - configure_hosts\n", - &tail[..end] - ); - Command::new("bash") - .arg("-c") - .arg(program) - .env("ROOT_PREFIX", root) - .output() - .expect("run configure_hosts") - } - - #[test] - fn guest_init_populates_missing_or_empty_hosts_and_keeps_image_hosts() { - let dir = unique_temp_dir(); - let etc = dir.join("etc"); - fs::create_dir_all(&etc).expect("create etc"); - let hosts = etc.join("hosts"); - let loopback = "127.0.0.1 localhost\n::1 localhost ip6-localhost ip6-loopback\n"; - - // An image that ships no hosts file at all. - let output = run_guest_configure_hosts(&dir); - assert!(output.status.success(), "{output:?}"); - assert_eq!(fs::read_to_string(&hosts).expect("read hosts"), loopback); - - // The usual OCI placeholder: present but empty. - fs::write(&hosts, "").expect("write empty hosts"); - let output = run_guest_configure_hosts(&dir); - assert!(output.status.success(), "{output:?}"); - assert_eq!(fs::read_to_string(&hosts).expect("read hosts"), loopback); - - // A hosts file authored by the image is not rewritten. - let authored = "10.1.2.3 build-host\n"; - fs::write(&hosts, authored).expect("write authored hosts"); - let output = run_guest_configure_hosts(&dir); - assert!(output.status.success(), "{output:?}"); - assert_eq!(fs::read_to_string(&hosts).expect("read hosts"), authored); - - // An image-authored symlink is left alone, and an absolute target - // outside the workload root is never written through. - let outside = dir.join("outside-hosts"); - fs::write(&outside, "").expect("write outside hosts"); - fs::remove_file(&hosts).expect("remove hosts"); - std::os::unix::fs::symlink(&outside, &hosts).expect("link hosts"); - let output = run_guest_configure_hosts(&dir); - assert!(output.status.success(), "{output:?}"); - assert_eq!(fs::read_to_string(&outside).expect("read outside"), ""); - assert!( - fs::symlink_metadata(&hosts) - .expect("stat hosts") - .file_type() - .is_symlink() - ); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn guest_init_boot_path_configures_hosts_after_the_account_and_before_networking() { - // The step only helps if the boot function itself calls it, so look at - // the lines of `run_post_overlay_setup` rather than anywhere in the file. - let script = include_str!("../scripts/openshell-vm-sandbox-init.sh"); - let start = script - .find("run_post_overlay_setup() {\n") - .expect("guest init defines run_post_overlay_setup"); - let boot = &script[start..]; - let network = boot - .find("openshell-vm-init prepare-network") - .expect("boot function brings up the loopback interface"); - let lines: Vec<&str> = boot[..network].lines().map(str::trim).collect(); - let position = |call: &str| lines.iter().position(|line| *line == call); - let account = position("reconcile_sandbox_account").expect("account reconciled"); - let hosts = position("configure_hosts").expect("boot function calls configure_hosts"); - assert!( - account < hosts, - "hosts are written after the root is set up" - ); - } - #[cfg(unix)] #[test] fn guest_dirs_are_traversable_under_a_private_umask() { @@ -1484,19 +1323,6 @@ mod tests { let _ = fs::remove_dir_all(&dir); } - #[test] - fn guest_init_normalizes_the_overlay_root_before_mounting_it() { - // Overlayfs takes the root's owner and mode from upper, which the host - // creates under the gateway's umask. A private umask would make / 0700 - // and unreadable to the sandbox user. - let script = include_str!("../scripts/openshell-vm-sandbox-init.sh"); - let position = |needle: &str| script.find(needle).unwrap_or_else(|| panic!("{needle}")); - let chown = position("chown 0:0 /overlay/upper"); - let chmod = position("chmod 0755 /overlay/upper"); - let mount = position("mount -t overlay overlay"); - assert!(chown < mount && chmod < mount); - } - #[test] fn prepare_sandbox_rootfs_preserves_image_workdir_contents_in_rootfs() { let dir = unique_temp_dir(); diff --git a/crates/openshell-driver-vm/src/runtime.rs b/crates/openshell-driver-vm/src/runtime.rs index ad300d98cf..2f2c42edd3 100644 --- a/crates/openshell-driver-vm/src/runtime.rs +++ b/crates/openshell-driver-vm/src/runtime.rs @@ -271,6 +271,10 @@ fn build_kernel_cmdline(config: &VmLaunchConfig) -> String { if config.gpu_bdf.is_some() { parts.push("firmware_class.path=/lib/firmware".to_string()); } + if !config.args.is_empty() { + parts.push("--".to_string()); + parts.extend(config.args.iter().cloned()); + } parts.join(" ") } @@ -811,8 +815,8 @@ mod tests { kernel_image: None, vcpus: 2, mem_mib: 2048, - exec_path: "/srv/openshell-vm-sandbox-init.sh".to_string(), - args: Vec::new(), + exec_path: "/opt/openshell/bin/openshell-sandbox".to_string(), + args: vec!["vm-init".to_string()], env: vec!["OPENSHELL_ENDPOINT=http://10.0.128.1:8080".to_string()], workdir: "/".to_string(), log_level: 0, @@ -881,6 +885,8 @@ mod tests { assert!(cmdline.contains(" ro")); assert!(!cmdline.contains("ip=")); assert!(cmdline.contains("firmware_class.path=/lib/firmware")); + assert!(cmdline.contains("init=/opt/openshell/bin/openshell-sandbox")); + assert!(cmdline.ends_with(" -- vm-init")); assert!(!cmdline.contains("VM_NET_IP=")); assert!(!cmdline.contains("VM_NET_GW=")); assert!(!cmdline.contains("VM_NET_DNS=")); diff --git a/crates/openshell-sandbox/src/lib.rs b/crates/openshell-sandbox/src/lib.rs index 910003ab55..5c486f10fa 100644 --- a/crates/openshell-sandbox/src/lib.rs +++ b/crates/openshell-sandbox/src/lib.rs @@ -43,6 +43,8 @@ mod pty; pub mod sandbox; #[cfg(target_os = "linux")] pub mod sftp; +#[cfg(target_os = "linux")] +pub mod vm_init; /// Results of actively qualifying the admitted workload runtime before the /// sandbox consumes protected bootstrap material. diff --git a/crates/openshell-sandbox/src/main.rs b/crates/openshell-sandbox/src/main.rs index a29b65533a..e1c7cbeb70 100644 --- a/crates/openshell-sandbox/src/main.rs +++ b/crates/openshell-sandbox/src/main.rs @@ -43,6 +43,7 @@ const CAPABILITY_PROBE_LAUNCH_SUBCOMMAND: &str = "capability-probe-launch"; const CAPABILITY_SOCKET_CHILD_SUBCOMMAND: &str = "capability-socket-child"; const CAPABILITY_LANDLOCK_CHILD_SUBCOMMAND: &str = "capability-landlock-child"; const CAPABILITY_FREE_LAUNCH_SUBCOMMAND: &str = "launch-capability-free"; +const VM_INIT_SUBCOMMAND: &str = "vm-init"; #[cfg(target_os = "linux")] const PROBE_DENIED_TCP_PEER: &str = "203.0.113.1:9"; #[cfg(target_os = "linux")] @@ -1847,6 +1848,16 @@ fn run_privileged_boundary( )) } +#[cfg(target_os = "linux")] +fn run_vm_init() -> Result<()> { + openshell_sandbox::vm_init::run_vm_init() +} + +#[cfg(not(target_os = "linux"))] +fn run_vm_init() -> Result<()> { + Err(miette::miette!("openshell-sandbox vm-init requires Linux")) +} + fn run_privileged_role(role: &str, args: &[String]) -> Option> { #[cfg(target_os = "linux")] { @@ -1923,6 +1934,9 @@ fn main() -> Result<()> { if raw_args.get(1).map(String::as_str) == Some(CAPABILITY_FREE_LAUNCH_SUBCOMMAND) { return launch_capability_free(&raw_args[2..]); } + if raw_args.get(1).map(String::as_str) == Some(VM_INIT_SUBCOMMAND) { + return run_vm_init(); + } if let Some(role) = raw_args.get(1) && let Some(result) = run_privileged_role(role, &raw_args[2..]) { diff --git a/crates/openshell-sandbox/src/vm_init.rs b/crates/openshell-sandbox/src/vm_init.rs new file mode 100644 index 0000000000..3c4fe25b5d --- /dev/null +++ b/crates/openshell-sandbox/src/vm_init.rs @@ -0,0 +1,1474 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Thin guest PID 1 (`openshell-sandbox vm-init`) for VM-backed sandboxes. +//! +//! Runs directly as guest PID 1 inside libkrun (`KRUN_INIT_PID1=1`) and QEMU +//! (`init=/opt/openshell/bin/openshell-sandbox -- vm-init`), mounts the overlay +//! rootfs and system filesystems, stages bootstrap material, forks and execs +//! `openshell-sandbox` as PID 2, reaps orphans until PID 2 exits, then syncs, +//! unmounts `/overlay`, and triggers a clean guest reboot (`RB_AUTOBOOT`) to +//! terminate the VMM without a kernel panic. + +#![allow(unsafe_code)] + +use std::collections::BTreeSet; +use std::ffi::{CStr, CString}; +use std::fs; +use std::io; +use std::os::unix::ffi::OsStrExt as _; +use std::os::unix::fs::{FileTypeExt as _, MetadataExt as _, PermissionsExt as _}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::atomic::{AtomicI32, Ordering}; +use std::time::{Duration, Instant}; + +const SANDBOX_BINARY_PATH: &str = "/opt/openshell/bin/openshell-sandbox"; +const SANDBOX_BINARY_IN_CHROOT: &str = "/.openshell-bootstrap/opt/openshell/bin/openshell-sandbox"; +const UMOCI_BINARY_PATH: &str = "/opt/openshell/bin/umoci"; +const DEFAULT_SANDBOX_UID: u32 = 1000; +const DEFAULT_SANDBOX_GID: u32 = 1000; +const DEFAULT_HOSTNAME: &str = "openshell-sandbox-vm"; +const DEFAULT_BOOTSTRAP_PATH: &str = "/.openshell/state/bootstrap.json"; +const LOOPBACK_HOSTS: &str = "127.0.0.1 localhost\n::1 localhost ip6-localhost ip6-loopback\n"; +const RESOLV_CONF: &str = "nameserver 127.0.0.53\noptions timeout:2 attempts:2\n"; + +static SANDBOX_CHILD_PID: AtomicI32 = AtomicI32::new(0); + +struct Logger { + start: Instant, +} + +impl Logger { + fn new() -> Self { + Self { + start: Instant::now(), + } + } + + fn log(&self, msg: &str) { + let elapsed = self.start.elapsed(); + let secs = elapsed.as_secs(); + let millis = elapsed.subsec_millis(); + println!("[{secs}.{millis:03}s] {msg}"); + } +} + +struct ChildLaunchSpec { + chroot_dir: Option, + exec_path: CString, + argv: Vec, +} + +/// Entrypoint for `openshell-sandbox vm-init`. +pub fn run_vm_init() -> miette::Result<()> { + // libkrun consumes this driver-owned switch before exec'ing us as PID 1. + // Remove it before spawning any children. + // SAFETY: vm-init is single-threaded at startup. + unsafe { + std::env::remove_var("KRUN_INIT_PID1"); + } + + let log = Logger::new(); + // SAFETY: `getpid` has no preconditions and never fails. + let is_pid1 = unsafe { libc::getpid() } == 1; + + match run_vm_init_inner(&log, is_pid1) { + Ok(exit_code) => { + if is_pid1 { + shutdown_and_reboot(&log, exit_code); + } + if exit_code == 0 { + Ok(()) + } else { + std::process::exit(exit_code); + } + } + Err(err) => { + log.log(&format!("FATAL: {err}")); + if is_pid1 { + shutdown_and_reboot(&log, 1); + } + Err(miette::miette!("{err}")) + } + } +} + +fn run_vm_init_inner(log: &Logger, is_pid1: bool) -> Result { + log.log("setting up writable overlay root"); + mount_initial_fs(); + + if !is_block_device(Path::new("/dev/vdb")) { + return Err("writable overlay disk /dev/vdb not found".to_string()); + } + + for dir in ["/overlay", "/lower", "/newroot", "/image-cache"] { + fs::create_dir_all(dir).map_err(|e| format!("mkdir {dir}: {e}"))?; + } + let _ = mount_call( + None, + Path::new("/"), + None, + libc::MS_REMOUNT | libc::MS_RDONLY, + None, + ); + mount_call( + Some("/dev/vdb"), + Path::new("/overlay"), + Some("ext4"), + 0, + None, + ) + .map_err(|e| format!("mount /dev/vdb -> /overlay: {e}"))?; + fs::create_dir_all("/overlay/upper").map_err(|e| format!("mkdir /overlay/upper: {e}"))?; + fs::create_dir_all("/overlay/work").map_err(|e| format!("mkdir /overlay/work: {e}"))?; + + load_env_file_if_present(Path::new("/overlay/upper/srv/openshell-env.sh")); + + let init_mode = env_or_default("OPENSHELL_VM_INIT_MODE", "sandbox"); + if init_mode == "image-prep" { + prepare_guest_image_rootfs(log)?; + // SAFETY: `sync` has no preconditions. + unsafe { + libc::sync(); + } + umount_call(Path::new("/overlay"), 0).map_err(|e| { + format!( + "failed to unmount /overlay cleanly after image-prep; refusing to produce a dirty image-cache disk: {e}" + ) + })?; + log.log("image-prep complete"); + return Ok(0); + } + + mount_call(Some("/"), Path::new("/lower"), None, libc::MS_BIND, None) + .map_err(|e| format!("bind-mount / -> /lower: {e}"))?; + let _ = mount_call( + None, + Path::new("/lower"), + None, + libc::MS_REMOUNT | libc::MS_BIND | libc::MS_RDONLY, + None, + ); + + let mut lower_root = PathBuf::from("/lower"); + if is_block_device(Path::new("/dev/vdc")) { + mount_call( + Some("/dev/vdc"), + Path::new("/image-cache"), + Some("ext4"), + libc::MS_RDONLY, + Some("noload"), + ) + .map_err(|e| format!("mount /dev/vdc -> /image-cache: {e}"))?; + let candidate = PathBuf::from("/image-cache/image-rootfs"); + if candidate.is_dir() { + lower_root = candidate; + log.log("using prepared image rootfs lowerdir"); + } else { + return Err("prepared image disk missing /image-rootfs".to_string()); + } + } + + let privileged = std::env::var("OPENSHELL_VM_PRIVILEGED").as_deref() == Ok("1"); + if privileged { + wipe_privileged_overlay_upper(Path::new("/overlay/upper"))?; + } + + // Overlayfs takes the root's owner and mode from upper, which the host + // creates under the gateway's umask. Normalize before mounting overlayfs. + chown_path(Path::new("/overlay/upper"), 0, 0) + .map_err(|e| format!("chown /overlay/upper: {e}"))?; + chmod_path(Path::new("/overlay/upper"), 0o755) + .map_err(|e| format!("chmod /overlay/upper: {e}"))?; + + let overlay_opts = format!( + "lowerdir={},upperdir=/overlay/upper,workdir=/overlay/work", + lower_root.display() + ); + mount_call( + Some("overlay"), + Path::new("/newroot"), + Some("overlay"), + 0, + Some(&overlay_opts), + ) + .map_err(|e| format!("mount overlay -> /newroot: {e}"))?; + + let bootstrap_mp = Path::new("/newroot/.openshell-bootstrap"); + fs::create_dir_all(bootstrap_mp) + .map_err(|e| format!("mkdir {}: {e}", bootstrap_mp.display()))?; + mount_call(Some("/lower"), bootstrap_mp, None, libc::MS_BIND, None) + .map_err(|e| format!("bind-mount /lower -> {}: {e}", bootstrap_mp.display()))?; + + if std::env::var("GPU_ENABLED").as_deref() == Ok("true") + && let Err(err) = setup_gpu(log) + { + log.log(&format!( + "WARNING: GPU init failed ({err}); continuing without GPU" + )); + } + + let root = Path::new("/newroot"); + if privileged { + let _ = fs::create_dir_all("/sys/fs/cgroup"); + let _ = mount_call( + Some("cgroup2"), + Path::new("/sys/fs/cgroup"), + Some("cgroup2"), + 0, + None, + ); + } else { + for path in ["/proc", "/sys", "/tmp", "/dev", "/run"] { + bind_mount_into_root(Path::new(path), root); + } + } + + for (rel, fstype) in [ + ("dev/pts", "devpts"), + ("dev/shm", "tmpfs"), + ("sys/fs/cgroup", "cgroup2"), + ] { + let target = root.join(rel); + let _ = fs::create_dir_all(&target); + let _ = mount_call(Some(fstype), &target, Some(fstype), 0, None); + } + + reconcile_sandbox_account_from_env(root, log)?; + setup_sandbox_workdir(root, log)?; + configure_hostname(root, log); + configure_hosts(root, log); + + crate::privileged::placement::loopback_up() + .map_err(|e| format!("failed to bring up the loopback interface: {e}"))?; + + fs::write("/proc/sys/net/ipv4/ip_unprivileged_port_start", b"0\n") + .map_err(|e| format!("failed to permit the unprivileged DNS relay to bind port 53: {e}"))?; + fs::write(root.join("etc/resolv.conf"), RESOLV_CONF) + .map_err(|e| format!("write /etc/resolv.conf: {e}"))?; + + // SAFETY: single-threaded prior to spawning child processes. + unsafe { + std::env::set_var("HOME", "/sandbox"); + std::env::set_var("USER", "sandbox"); + } + + run_openshell_init_dropins(root, log)?; + mount_virtiofs_shares(root, log)?; + + if let Ok(sandbox_id) = std::env::var("OPENSHELL_SANDBOX_ID") + && !sandbox_id.is_empty() + { + log.log(&format!("OPENSHELL_SANDBOX_ID={sandbox_id}")); + } + + log.log("starting OpenShell VM sandbox"); + let bootstrap_guest = env_or_default("OPENSHELL_VM_SANDBOX_BOOTSTRAP", DEFAULT_BOOTSTRAP_PATH); + let bootstrap_in_root = root_path(root, &bootstrap_guest); + if !bootstrap_in_root.is_file() { + return Err("sandbox bootstrap is missing".to_string()); + } + let state_dir_in_root = bootstrap_in_root + .parent() + .ok_or_else(|| format!("bootstrap path '{bootstrap_guest}' has no parent"))?; + + let launch = if privileged { + prepare_privileged_launch(root, &bootstrap_in_root, state_dir_in_root, log)? + } else { + prepare_capability_free_launch(root, &init_mode, &bootstrap_guest, state_dir_in_root, log)? + }; + + let sandbox_pid = spawn_sandbox_child(&launch)?; + if is_pid1 { + SANDBOX_CHILD_PID.store(sandbox_pid, Ordering::Release); + install_signal_forwarders(); + } + + let exit_code = reap_until_child_exits(sandbox_pid); + SANDBOX_CHILD_PID.store(0, Ordering::Release); + Ok(exit_code) +} + +fn prepare_privileged_launch( + root: &Path, + bootstrap_in_root: &Path, + state_dir_in_root: &Path, + log: &Logger, +) -> Result { + let run_dir = Path::new("/run/openshell"); + let bootstrap_dir = run_dir.join("bootstrap"); + let tls_dir = run_dir.join("tls"); + fs::create_dir_all(&bootstrap_dir) + .map_err(|e| format!("mkdir {}: {e}", bootstrap_dir.display()))?; + fs::create_dir_all(&tls_dir).map_err(|e| format!("mkdir {}: {e}", tls_dir.display()))?; + chmod_path(run_dir, 0o700).map_err(|e| format!("chmod /run/openshell: {e}"))?; + chmod_path(&bootstrap_dir, 0o700) + .map_err(|e| format!("chmod /run/openshell/bootstrap: {e}"))?; + chmod_path(&tls_dir, 0o755).map_err(|e| format!("chmod /run/openshell/tls: {e}"))?; + + for entry in fs::read_dir(state_dir_in_root) + .map_err(|e| format!("read {}: {e}", state_dir_in_root.display()))? + { + let entry = entry.map_err(|e| format!("read dir entry: {e}"))?; + let src = entry.path(); + if !src.is_file() { + continue; + } + let dst = bootstrap_dir.join(entry.file_name()); + fs::copy(&src, &dst) + .map_err(|e| format!("copy {} -> {}: {e}", src.display(), dst.display()))?; + chmod_path(&dst, 0o600).map_err(|e| format!("chmod {}: {e}", dst.display()))?; + } + fs::remove_dir_all(state_dir_in_root) + .map_err(|e| format!("remove {}: {e}", state_dir_in_root.display()))?; + + let bootstrap_mp = root.join(".openshell-bootstrap"); + let _ = umount_call(&bootstrap_mp, 0); + let _ = fs::remove_dir(&bootstrap_mp); + + let bootstrap_file_name = bootstrap_in_root + .file_name() + .ok_or_else(|| "bootstrap path has no file name".to_string())?; + let priv_bootstrap = bootstrap_dir.join(bootstrap_file_name); + log.log(&format!( + "spawning openshell-sandbox --privileged (workload root: {})", + root.display() + )); + + let argv = [ + SANDBOX_BINARY_PATH, + "--bootstrap", + priv_bootstrap + .to_str() + .ok_or_else(|| "non-UTF-8 bootstrap path".to_string())?, + "--privileged", + "--workload-root", + root.to_str() + .ok_or_else(|| "non-UTF-8 workload root".to_string())?, + ] + .into_iter() + .map(to_cstring) + .collect::, _>>()?; + + Ok(ChildLaunchSpec { + chroot_dir: None, + exec_path: to_cstring(SANDBOX_BINARY_PATH)?, + argv, + }) +} + +fn prepare_capability_free_launch( + root: &Path, + init_mode: &str, + bootstrap_guest: &str, + state_dir_in_root: &Path, + log: &Logger, +) -> Result { + let (uid, gid) = sandbox_owner_for_root(root); + chown_path(state_dir_in_root, uid, gid) + .map_err(|e| format!("chown {}: {e}", state_dir_in_root.display()))?; + chmod_path(state_dir_in_root, 0o700) + .map_err(|e| format!("chmod {}: {e}", state_dir_in_root.display()))?; + + for entry in fs::read_dir(state_dir_in_root) + .map_err(|e| format!("read {}: {e}", state_dir_in_root.display()))? + { + let entry = entry.map_err(|e| format!("read dir entry: {e}"))?; + let path = entry.path(); + if !path.is_file() { + continue; + } + chown_path(&path, uid, gid).map_err(|e| format!("chown {}: {e}", path.display()))?; + chmod_path(&path, 0o600).map_err(|e| format!("chmod {}: {e}", path.display()))?; + } + + let uid_str = uid.to_string(); + let gid_str = gid.to_string(); + let argv = if init_mode == "capability-probe" { + log.log(&format!( + "starting capability-free VM qualification as {uid}:{gid}" + )); + vec![ + to_cstring(SANDBOX_BINARY_IN_CHROOT)?, + to_cstring("capability-probe-launch")?, + to_cstring(&uid_str)?, + to_cstring(&gid_str)?, + ] + } else { + vec![ + to_cstring(SANDBOX_BINARY_IN_CHROOT)?, + to_cstring("launch-capability-free")?, + to_cstring(&uid_str)?, + to_cstring(&gid_str)?, + to_cstring(bootstrap_guest)?, + ] + }; + + Ok(ChildLaunchSpec { + chroot_dir: Some(to_cstring( + root.to_str() + .ok_or_else(|| "non-UTF-8 chroot dir".to_string())?, + )?), + exec_path: to_cstring(SANDBOX_BINARY_IN_CHROOT)?, + argv, + }) +} + +fn spawn_sandbox_child(spec: &ChildLaunchSpec) -> Result { + let mut argv_ptrs: Vec<*const libc::c_char> = spec.argv.iter().map(|s| s.as_ptr()).collect(); + argv_ptrs.push(std::ptr::null()); + let slash = CString::new("/").map_err(|e| format!("cstring /: {e}"))?; + + // SAFETY: vm-init is single-threaded here; child performs only async-signal-safe + // syscalls (chroot, chdir, execv, _exit) using pre-allocated CStrings. + let pid = unsafe { libc::fork() }; + if pid < 0 { + return Err(format!( + "fork sandbox child: {}", + io::Error::last_os_error() + )); + } + if pid == 0 { + if let Some(chroot_dir) = &spec.chroot_dir { + // SAFETY: chroot_dir and slash are valid NUL-terminated paths. + let ok = unsafe { + libc::chroot(chroot_dir.as_ptr()) == 0 && libc::chdir(slash.as_ptr()) == 0 + }; + if !ok { + // SAFETY: immediate termination in forked child on setup failure. + unsafe { libc::_exit(127) }; + } + } + // SAFETY: exec_path and argv_ptrs are valid NUL-terminated C strings. + unsafe { + libc::execv(spec.exec_path.as_ptr(), argv_ptrs.as_ptr()); + libc::_exit(127); + } + } + Ok(pid) +} + +extern "C" fn forward_signal_to_sandbox(sig: libc::c_int) { + let pid = SANDBOX_CHILD_PID.load(Ordering::Acquire); + if pid > 0 { + // SAFETY: `kill` is async-signal-safe and `pid > 0` targets only the sandbox child. + unsafe { + libc::kill(pid, sig); + } + } +} + +fn install_signal_forwarders() { + for sig in [libc::SIGTERM, libc::SIGINT] { + // SAFETY: `forward_signal_to_sandbox` only performs an atomic load and `kill(2)`. + unsafe { + let mut action: libc::sigaction = std::mem::zeroed(); + action.sa_sigaction = forward_signal_to_sandbox as *const () as libc::sighandler_t; + libc::sigemptyset(&raw mut action.sa_mask); + action.sa_flags = libc::SA_RESTART; + libc::sigaction(sig, &raw const action, std::ptr::null_mut()); + } + } +} + +fn reap_until_child_exits(sandbox_pid: libc::pid_t) -> i32 { + loop { + let mut status: libc::c_int = 0; + // SAFETY: `waitpid(-1, ...)` reaps any child or adopted orphan. + let pid = unsafe { libc::waitpid(-1, &raw mut status, 0) }; + if pid == sandbox_pid { + if libc::WIFEXITED(status) { + return libc::WEXITSTATUS(status); + } + if libc::WIFSIGNALED(status) { + return 128 + libc::WTERMSIG(status); + } + return 1; + } + if pid < 0 { + let err = io::Error::last_os_error(); + if err.raw_os_error() == Some(libc::EINTR) { + continue; + } + if err.raw_os_error() == Some(libc::ECHILD) { + return 0; + } + } + } +} + +fn shutdown_and_reboot(log: &Logger, exit_code: i32) -> ! { + // Signal any remaining guest processes, wait briefly, then SIGKILL stragglers. + // SAFETY: PID 1 shutting down the guest VM. + unsafe { + libc::kill(-1, libc::SIGTERM); + } + let deadline = Instant::now() + Duration::from_millis(500); + while Instant::now() < deadline { + let mut status: libc::c_int = 0; + // SAFETY: non-blocking waitpid drains exited processes during shutdown. + let pid = unsafe { libc::waitpid(-1, &raw mut status, libc::WNOHANG) }; + if pid < 0 && io::Error::last_os_error().raw_os_error() == Some(libc::ECHILD) { + break; + } + if pid <= 0 { + std::thread::sleep(Duration::from_millis(25)); + } + } + // SAFETY: PID 1 final termination sweep before unmounting and rebooting. + unsafe { + libc::kill(-1, libc::SIGKILL); + let mut status: libc::c_int = 0; + while libc::waitpid(-1, &raw mut status, libc::WNOHANG) > 0 {} + libc::sync(); + } + + let _ = umount_call(Path::new("/newroot"), libc::MNT_DETACH); + if umount_call(Path::new("/overlay"), 0).is_err() { + let _ = umount_call(Path::new("/overlay"), libc::MNT_DETACH); + } + // SAFETY: final sync + guest reboot (`RB_AUTOBOOT`) terminates libkrun and QEMU `-no-reboot`. + unsafe { + libc::sync(); + libc::reboot(libc::RB_AUTOBOOT); + } + log.log(&format!( + "reboot() returned unexpectedly (exit_code={exit_code})" + )); + std::process::exit(exit_code); +} + +fn mount_initial_fs() { + for (source, target, fstype) in [ + ("proc", "/proc", "proc"), + ("sysfs", "/sys", "sysfs"), + ("tmpfs", "/tmp", "tmpfs"), + ("tmpfs", "/run", "tmpfs"), + ("devtmpfs", "/dev", "devtmpfs"), + ] { + let _ = mount_call(Some(source), Path::new(target), Some(fstype), 0, None); + } +} + +fn bind_mount_into_root(source: &Path, newroot: &Path) { + let rel = source.strip_prefix("/").unwrap_or(source); + let target = newroot.join(rel); + let _ = fs::create_dir_all(&target); + let Some(src_str) = source.to_str() else { + return; + }; + if mount_call( + Some(src_str), + &target, + None, + libc::MS_BIND | libc::MS_REC, + None, + ) + .is_err() + { + let _ = mount_call(Some(src_str), &target, None, libc::MS_BIND, None); + } +} + +fn wipe_privileged_overlay_upper(upper: &Path) -> Result<(), String> { + for entry in fs::read_dir(upper).map_err(|e| format!("read {}: {e}", upper.display()))? { + let entry = entry.map_err(|e| format!("read dir entry: {e}"))?; + let name = entry.file_name(); + if name == "sandbox" || name == ".openshell" { + continue; + } + let path = entry.path(); + let meta = + fs::symlink_metadata(&path).map_err(|e| format!("lstat {}: {e}", path.display()))?; + if meta.file_type().is_dir() { + fs::remove_dir_all(&path) + .map_err(|e| format!("remove_dir_all {}: {e}", path.display()))?; + } else { + fs::remove_file(&path).map_err(|e| format!("remove_file {}: {e}", path.display()))?; + } + } + Ok(()) +} + +fn prepare_guest_image_rootfs(log: &Logger) -> Result<(), String> { + let payload_dir = Path::new("/overlay/config/openshell-image"); + if !payload_dir.is_dir() { + return Ok(()); + } + let image_root = Path::new("/overlay/image-rootfs"); + let partial_root = Path::new("/overlay/image-rootfs.partial"); + let source = fs::read_to_string(payload_dir.join("source")) + .unwrap_or_default() + .trim() + .to_string(); + + log.log(&format!( + "preparing sandbox image rootfs in guest ({})", + if source.is_empty() { + "unknown" + } else { + &source + } + )); + + for dir in [image_root, partial_root] { + if dir.exists() { + fs::remove_dir_all(dir).map_err(|e| format!("remove {}: {e}", dir.display()))?; + } + } + + match source.as_str() { + "local-docker" => { + fs::create_dir_all(partial_root) + .map_err(|e| format!("mkdir {}: {e}", partial_root.display()))?; + let status = Command::new("tar") + .arg("-xpf") + .arg(payload_dir.join("source-rootfs.tar")) + .arg("-C") + .arg(partial_root) + .status() + .map_err(|e| format!("exec tar: {e}"))?; + if !status.success() { + return Err(format!("tar extract failed with {status}")); + } + } + "oci-layout" => { + if !Path::new(UMOCI_BINARY_PATH).is_file() { + return Err("umoci not found in VM bootstrap image".to_string()); + } + let image_arg = format!("{}:openshell", payload_dir.join("oci").display()); + let status = Command::new(UMOCI_BINARY_PATH) + .args(["raw", "unpack", "--image", &image_arg]) + .arg(partial_root) + .status() + .map_err(|e| format!("exec umoci: {e}"))?; + if !status.success() { + return Err(format!("umoci raw unpack failed with {status}")); + } + if !partial_root.is_dir() { + return Err("umoci unpack did not produce a rootfs directory".to_string()); + } + } + _ => { + return Err(format!( + "unknown guest image payload source: {}", + if source.is_empty() { + "missing" + } else { + &source + } + )); + } + } + + ensure_target_runtime(partial_root)?; + let identity_src = payload_dir.join("identity"); + if identity_src.is_file() { + fs::copy( + &identity_src, + partial_root.join(".openshell-rootfs-variant"), + ) + .map_err(|e| format!("copy identity: {e}"))?; + } + fs::remove_dir_all(payload_dir) + .map_err(|e| format!("remove {}: {e}", payload_dir.display()))?; + fs::rename(partial_root, image_root).map_err(|e| format!("rename prepared rootfs: {e}"))?; + Ok(()) +} + +fn ensure_target_runtime(image_root: &Path) -> Result<(), String> { + for rel in ["srv", "opt/openshell/bin", "sandbox", "etc"] { + fs::create_dir_all(image_root.join(rel)) + .map_err(|e| format!("mkdir {}/{rel}: {e}", image_root.display()))?; + } + + if Path::new(SANDBOX_BINARY_PATH).is_file() { + let dst = image_root.join("opt/openshell/bin/openshell-sandbox"); + fs::copy(SANDBOX_BINARY_PATH, &dst) + .map_err(|e| format!("copy openshell-sandbox -> {}: {e}", dst.display()))?; + chmod_path(&dst, 0o755).map_err(|e| format!("chmod {}: {e}", dst.display()))?; + } + + let requested_user_id = parse_optional_env_u32("OPENSHELL_VM_SANDBOX_UID")?; + let requested_group_id = parse_optional_env_u32("OPENSHELL_VM_SANDBOX_GID")?; + let passwd_path = image_root.join("etc/passwd"); + let has_sandbox_account = fs::read_to_string(&passwd_path) + .is_ok_and(|s| s.lines().any(|line| line.starts_with("sandbox:"))); + + if requested_user_id.is_some() || requested_group_id.is_some() { + let uid = requested_user_id.unwrap_or(DEFAULT_SANDBOX_UID); + let gid = requested_group_id.unwrap_or(uid); + reconcile_sandbox_account(image_root, uid, gid, false)?; + } else if !has_sandbox_account { + reconcile_sandbox_account(image_root, DEFAULT_SANDBOX_UID, DEFAULT_SANDBOX_GID, false)?; + } + + let (uid, gid) = sandbox_owner_for_root(image_root); + let sandbox_dir = image_root.join("sandbox"); + chown_recursive(&sandbox_dir, uid, gid) + .map_err(|e| format!("failed to apply sandbox image ownership ({uid}:{gid}): {e}"))?; + chmod_path(&sandbox_dir, 0o755).map_err(|e| format!("chmod {}: {e}", sandbox_dir.display()))?; + Ok(()) +} + +fn setup_gpu(log: &Logger) -> Result<(), String> { + log.log("GPU_ENABLED=true — initializing GPU passthrough"); + + let fw_src = Path::new("/lib/firmware/nvidia"); + if fw_src.is_dir() { + log.log("staging GPU firmware to tmpfs"); + let fw_dst = Path::new("/run/firmware/nvidia"); + fs::create_dir_all(fw_dst).map_err(|e| format!("mkdir {}: {e}", fw_dst.display()))?; + copy_dir_contents(fw_src, fw_dst)?; + let fw_param = Path::new("/sys/module/firmware_class/parameters/path"); + if fw_param.exists() { + let _ = fs::write(fw_param, b"/run/firmware"); + } + } + + log.log("loading nvidia kernel modules"); + let status = Command::new("modprobe") + .arg("nvidia") + .status() + .map_err(|e| format!("modprobe nvidia: {e}"))?; + if !status.success() { + return Err(format!("modprobe nvidia exited with {status}")); + } + let _ = Command::new("modprobe").arg("nvidia_uvm").status(); + let _ = Command::new("modprobe").arg("nvidia_modeset").status(); + let _ = fs::remove_dir_all("/run/firmware"); + + match Command::new("nvidia-smi").output() { + Ok(out) if out.status.success() => { + log.log("GPU initialization successful"); + } + Ok(out) => { + log.log(&format!( + "WARNING: nvidia-smi failed ({}); falling back to mknod", + out.status + )); + create_gpu_device_nodes_mknod(log); + } + Err(_) => { + log.log("nvidia-smi not found; creating device nodes via mknod"); + create_gpu_device_nodes_mknod(log); + } + } + Ok(()) +} + +fn create_gpu_device_nodes_mknod(log: &Logger) { + let devices = fs::read_to_string("/proc/devices").unwrap_or_default(); + let find_major = |name: &str| -> Option { + devices.lines().find_map(|line| { + let mut parts = line.split_whitespace(); + let major = parts.next()?.parse::().ok()?; + let dev = parts.next()?; + (dev == name).then_some(major) + }) + }; + + let Some(nv_major) = find_major("nvidia") else { + log.log("WARNING: 'nvidia' not in /proc/devices; device nodes unavailable"); + return; + }; + let _ = mknod_char(Path::new("/dev/nvidiactl"), nv_major, 255, 0o666); + + let mut gpu_count = 0u32; + if let Ok(entries) = fs::read_dir("/proc/driver/nvidia/gpus") { + for entry in entries.flatten() { + if entry.path().is_dir() { + let _ = mknod_char( + Path::new(&format!("/dev/nvidia{gpu_count}")), + nv_major, + gpu_count, + 0o666, + ); + gpu_count += 1; + } + } + } + if gpu_count == 0 { + let _ = mknod_char(Path::new("/dev/nvidia0"), nv_major, 0, 0o666); + } + if let Some(modeset_major) = find_major("nvidia-modeset") { + let _ = mknod_char(Path::new("/dev/nvidia-modeset"), modeset_major, 254, 0o666); + } + if let Some(uvm_major) = find_major("nvidia-uvm") { + let _ = mknod_char(Path::new("/dev/nvidia-uvm"), uvm_major, 0, 0o666); + let _ = mknod_char(Path::new("/dev/nvidia-uvm-tools"), uvm_major, 1, 0o666); + } + if let Some(caps_major) = find_major("nvidia-caps") { + let _ = fs::create_dir_all("/dev/nvidia-caps"); + let _ = mknod_char( + Path::new("/dev/nvidia-caps/nvidia-cap1"), + caps_major, + 1, + 0o666, + ); + let _ = mknod_char( + Path::new("/dev/nvidia-caps/nvidia-cap2"), + caps_major, + 2, + 0o666, + ); + } + log.log(&format!( + "GPU device nodes created via mknod ({gpu_count} GPU(s), major={nv_major})" + )); +} + +fn mknod_char(path: &Path, major: u32, minor: u32, mode: u32) -> io::Result<()> { + let cpath = CString::new(path.as_os_str().as_bytes()) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "NUL in path"))?; + let dev = libc::makedev(major, minor); + // SAFETY: cpath is a valid NUL-terminated path; mknod creates a char device node. + if unsafe { libc::mknod(cpath.as_ptr(), libc::S_IFCHR | mode, dev) } != 0 { + Err(io::Error::last_os_error()) + } else { + Ok(()) + } +} + +fn reconcile_sandbox_account_from_env(root: &Path, log: &Logger) -> Result<(), String> { + let uid = parse_optional_env_u32("OPENSHELL_VM_SANDBOX_UID")?; + let gid = parse_optional_env_u32("OPENSHELL_VM_SANDBOX_GID")?; + let (Some(uid), Some(gid)) = (uid, gid) else { + return Ok(()); + }; + reconcile_sandbox_account(root, uid, gid, true)?; + log.log(&format!("reconciled sandbox account ({uid}:{gid})")); + Ok(()) +} + +fn reconcile_sandbox_account( + root: &Path, + uid: u32, + gid: u32, + preserve_passwd_metadata: bool, +) -> Result<(), String> { + let etc = root.join("etc"); + fs::create_dir_all(&etc).map_err(|e| format!("mkdir {}: {e}", etc.display()))?; + + let group_path = etc.join("group"); + let group_content = fs::read_to_string(&group_path).unwrap_or_default(); + let new_group = update_colon_record(&group_content, "sandbox", |fields| { + if fields.len() >= 3 { + let mut updated: Vec = fields.iter().map(|s| (*s).to_string()).collect(); + updated[2] = gid.to_string(); + updated.join(":") + } else { + format!("sandbox:x:{gid}:") + } + }) + .unwrap_or_else(|| append_line(&group_content, &format!("sandbox:x:{gid}:"))); + write_file_atomic(&group_path, &new_group)?; + + let passwd_path = etc.join("passwd"); + let passwd_content = fs::read_to_string(&passwd_path).unwrap_or_default(); + let default_passwd_line = format!("sandbox:x:{uid}:{gid}:OpenShell Sandbox:/sandbox:/bin/sh"); + let new_passwd = update_colon_record(&passwd_content, "sandbox", |fields| { + if preserve_passwd_metadata && fields.len() >= 4 { + let mut updated: Vec = fields.iter().map(|s| (*s).to_string()).collect(); + updated[2] = uid.to_string(); + updated[3] = gid.to_string(); + updated.join(":") + } else { + default_passwd_line.clone() + } + }) + .unwrap_or_else(|| append_line(&passwd_content, &default_passwd_line)); + write_file_atomic(&passwd_path, &new_passwd)?; + + for (file, default_line) in [ + ("gshadow", "sandbox:!::"), + ("shadow", "sandbox:!:20123:0:99999:7:::"), + ] { + let path = etc.join(file); + let content = fs::read_to_string(&path).unwrap_or_default(); + if !content.lines().any(|line| line.starts_with("sandbox:")) { + write_file_atomic(&path, &append_line(&content, default_line))?; + } + } + Ok(()) +} + +fn update_colon_record(content: &str, name: &str, rewrite: F) -> Option +where + F: Fn(&[&str]) -> String, +{ + let mut found = false; + let mut out = String::with_capacity(content.len() + 32); + for line in content.lines() { + let fields: Vec<&str> = line.split(':').collect(); + if fields.first().copied() == Some(name) { + found = true; + out.push_str(&rewrite(&fields)); + } else { + out.push_str(line); + } + out.push('\n'); + } + found.then_some(out) +} + +fn append_line(content: &str, line: &str) -> String { + let mut out = content.to_string(); + if !out.is_empty() && !out.ends_with('\n') { + out.push('\n'); + } + out.push_str(line); + out.push('\n'); + out +} + +fn write_file_atomic(path: &Path, content: &str) -> Result<(), String> { + let tmp = path.with_extension("openshell"); + fs::write(&tmp, content).map_err(|e| format!("write {}: {e}", tmp.display()))?; + fs::rename(&tmp, path) + .map_err(|e| format!("rename {} -> {}: {e}", tmp.display(), path.display())) +} + +fn sandbox_owner_for_root(root: &Path) -> (u32, u32) { + sandbox_owner_from_passwd(&root.join("etc/passwd")) +} + +fn sandbox_owner_from_passwd(passwd_path: &Path) -> (u32, u32) { + if let Ok(content) = fs::read_to_string(passwd_path) { + for line in content.lines() { + let mut fields = line.split(':'); + if fields.next() == Some("sandbox") + && fields.next().is_some() + && let Some(uid) = fields.next().and_then(|v| v.parse::().ok()) + && let Some(gid) = fields.next().and_then(|v| v.parse::().ok()) + { + return (uid, gid); + } + } + } + (DEFAULT_SANDBOX_UID, DEFAULT_SANDBOX_GID) +} + +fn setup_sandbox_workdir(root: &Path, log: &Logger) -> Result<(), String> { + let sandbox_dir = root.join("sandbox"); + let (uid, gid) = sandbox_owner_for_root(root); + fs::create_dir_all(&sandbox_dir) + .map_err(|e| format!("mkdir {}: {e}", sandbox_dir.display()))?; + if uid == 10001 && gid == 10001 { + log.log("preserving legacy sandbox ownership (10001:10001)"); + } + let meta = + fs::metadata(&sandbox_dir).map_err(|e| format!("stat {}: {e}", sandbox_dir.display()))?; + if meta.uid() != uid || meta.gid() != gid { + chown_recursive(&sandbox_dir, uid, gid) + .map_err(|e| format!("failed to apply sandbox ownership ({uid}:{gid}): {e}"))?; + } + chmod_path(&sandbox_dir, 0o755).map_err(|e| format!("chmod {}: {e}", sandbox_dir.display()))?; + log.log(&format!("prepared /sandbox ownership ({uid}:{gid})")); + Ok(()) +} + +fn sanitize_hostname(raw: &str) -> String { + let replaced: String = raw + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '.' || c == '-' { + c + } else { + '-' + } + }) + .collect(); + let trimmed = replaced.trim_matches(|c| c == '.' || c == '-'); + let truncated: String = trimmed.chars().take(63).collect(); + if truncated.is_empty() { + DEFAULT_HOSTNAME.to_string() + } else { + truncated + } +} + +fn configure_hostname(root: &Path, log: &Logger) { + let raw = std::env::var("OPENSHELL_SANDBOX").unwrap_or_else(|_| DEFAULT_HOSTNAME.to_string()); + let hostname = sanitize_hostname(&raw); + // SAFETY: hostname bytes are valid UTF-8/ASCII and length matches buffer. + let _ = unsafe { libc::sethostname(hostname.as_ptr().cast(), hostname.len()) }; + let _ = fs::write(root.join("etc/hostname"), format!("{hostname}\n")); + log.log(&format!("hostname={hostname}")); +} + +fn configure_hosts(root: &Path, log: &Logger) { + let hosts_file = root.join("etc/hosts"); + if let Ok(meta) = fs::symlink_metadata(&hosts_file) { + if meta.file_type().is_symlink() { + log.log(&format!( + "WARN: {} is a symlink; leaving it unchanged", + hosts_file.display() + )); + return; + } + if meta.len() > 0 { + return; + } + } + if let Err(err) = fs::write(&hosts_file, LOOPBACK_HOSTS) { + log.log(&format!( + "WARN: could not write {} ({err}); localhost will not resolve", + hosts_file.display() + )); + return; + } + log.log("populated empty /etc/hosts with loopback names"); +} + +fn validate_dropin_name(name: &str) -> Result<(), String> { + if name.is_empty() || name == "." || name == ".." || name.contains('/') { + return Err(format!("unsafe init drop-in manifest entry '{name}'")); + } + Ok(()) +} + +fn run_openshell_init_dropins(root: &Path, log: &Logger) -> Result<(), String> { + let init_dir = root.join("opt/openshell/init.d"); + let manifest = root.join("opt/openshell/init.d.manifest"); + if !manifest.is_file() { + if init_dir.is_dir() { + log.log("no OpenShell VM init drop-in manifest present; skipping init.d"); + } + return Ok(()); + } + + let content = + fs::read_to_string(&manifest).map_err(|e| format!("read {}: {e}", manifest.display()))?; + let mut names = BTreeSet::new(); + for line in content.lines() { + if line.is_empty() { + continue; + } + validate_dropin_name(line)?; + names.insert(line.to_string()); + } + + let root_str = root + .to_str() + .ok_or_else(|| "non-UTF-8 ROOT_PREFIX".to_string())?; + for name in names { + let dropin = init_dir.join(&name); + let meta = fs::metadata(&dropin) + .map_err(|_| format!("init drop-in '{name}' listed in manifest but not found"))?; + if !meta.is_file() { + return Err(format!( + "init drop-in '{name}' listed in manifest but not found" + )); + } + if meta.permissions().mode() & 0o111 == 0 { + return Err(format!("init drop-in '{name}' is not executable")); + } + log.log(&format!("running OpenShell VM init drop-in {name}")); + let status = Command::new(&dropin) + .env("OPENSHELL_VM_INIT_PHASE", "before-supervisor") + .env("ROOT_PREFIX", root_str) + .status() + .map_err(|e| format!("exec OpenShell VM init drop-in {name}: {e}"))?; + if !status.success() { + return Err(format!( + "OpenShell VM init drop-in {name} failed with exit code {}", + status.code().unwrap_or(1) + )); + } + } + Ok(()) +} + +/// Create a virtiofs mount point under `root` without following symlinks, +/// so an image cannot redirect a validated target onto another guest path. +/// Directories created under `/sandbox` are handed to `(owner_uid, owner_gid)`. +fn prepare_virtiofs_target( + root: &Path, + target: &str, + uid: u32, + gid: u32, +) -> Result { + let mut path = root.to_path_buf(); + let mut rel = String::new(); + for component in target.trim_start_matches('/').split('/') { + if component.is_empty() { + continue; + } + if component == "." || component == ".." { + return Err(format!("virtiofs mount target {target} contains traversal")); + } + path.push(component); + rel.push('/'); + rel.push_str(component); + match fs::symlink_metadata(&path) { + Ok(meta) => { + if meta.file_type().is_symlink() { + return Err(format!( + "virtiofs mount target {target} traverses symlink {rel}" + )); + } + if !meta.file_type().is_dir() { + return Err(format!("virtiofs mount target {target} is not a directory")); + } + } + Err(err) if err.kind() == io::ErrorKind::NotFound => { + fs::create_dir(&path) + .map_err(|e| format!("failed to create virtiofs mount point {target}: {e}"))?; + if rel.starts_with("/sandbox/") { + chown_path(&path, uid, gid).map_err(|e| { + format!( + "failed to hand virtiofs mount point parent {rel} to {uid}:{gid}: {e}" + ) + })?; + } + } + Err(err) => { + return Err(format!( + "failed to stat virtiofs mount point {target}: {err}" + )); + } + } + } + Ok(path) +} + +fn mount_virtiofs_shares(root: &Path, log: &Logger) -> Result<(), String> { + let manifest = root.join(".openshell/mounts.manifest"); + let content = match fs::read_to_string(&manifest) { + Ok(c) if !c.trim().is_empty() => c, + _ => return Ok(()), + }; + + log.log("mounting virtiofs shares"); + let (uid, gid) = sandbox_owner_for_root(root); + for line in content.lines() { + let mut fields = line.split('\t'); + let Some(tag) = fields.next() else { + continue; + }; + if tag.is_empty() { + continue; + } + let target = fields + .next() + .ok_or_else(|| format!("malformed mounts.manifest entry for tag {tag}"))?; + let mode = fields + .next() + .ok_or_else(|| format!("missing mode in mounts.manifest for tag {tag}"))?; + let flags = match mode { + "ro" => libc::MS_RDONLY, + "rw" => 0, + other => { + return Err(format!( + "unknown virtiofs mount mode '{other}' for tag {tag}" + )); + } + }; + let guest_target = prepare_virtiofs_target(root, target, uid, gid)?; + mount_call(Some(tag), &guest_target, Some("virtiofs"), flags, None) + .map_err(|e| format!("failed to mount virtiofs {tag} at {target}: {e}"))?; + log.log(&format!(" mounted virtiofs {tag} -> {target} ({mode})")); + } + Ok(()) +} + +/// Parse QEMU-injected `export KEY="VALUE"` environment lines produced by +/// `openshell-driver-vm::runtime::write_guest_env_file`. +fn parse_env_file(content: &str) -> Vec<(String, String)> { + let mut vars = Vec::new(); + for line in content.lines() { + let trimmed = line.trim(); + let Some(rest) = trimmed.strip_prefix("export ") else { + continue; + }; + let Some((key, raw_val)) = rest.split_once('=') else { + continue; + }; + let key = key.trim(); + if key.is_empty() { + continue; + } + let value = raw_val + .strip_prefix('"') + .and_then(|s| s.strip_suffix('"')) + .map_or_else(|| raw_val.to_string(), unescape_shell_double_quoted); + vars.push((key.to_string(), value)); + } + vars +} + +fn unescape_shell_double_quoted(input: &str) -> String { + let mut out = String::with_capacity(input.len()); + let mut chars = input.chars(); + while let Some(c) = chars.next() { + if c == '\\' { + match chars.next() { + Some('n') => out.push('\n'), + Some('r') => out.push('\r'), + Some(other) => out.push(other), + None => out.push('\\'), + } + } else { + out.push(c); + } + } + out +} + +fn load_env_file_if_present(path: &Path) { + let Ok(content) = fs::read_to_string(path) else { + return; + }; + for (key, value) in parse_env_file(&content) { + // SAFETY: vm-init is single-threaded. + unsafe { + std::env::set_var(key, value); + } + } +} + +fn parse_optional_env_u32(name: &str) -> Result, String> { + match std::env::var(name) { + Ok(val) if !val.is_empty() => val + .parse::() + .map(Some) + .map_err(|_| format!("invalid requested sandbox identity in {name}")), + _ => Ok(None), + } +} + +fn env_or_default(name: &str, default: &str) -> String { + match std::env::var(name) { + Ok(val) if !val.is_empty() => val, + _ => default.to_string(), + } +} + +fn root_path(root: &Path, guest_path: &str) -> PathBuf { + root.join(guest_path.trim_start_matches('/')) +} + +fn is_block_device(path: &Path) -> bool { + fs::metadata(path).is_ok_and(|m| m.file_type().is_block_device()) +} + +fn to_cstring(s: &str) -> Result { + CString::new(s).map_err(|e| format!("invalid C string '{s}': {e}")) +} + +fn mount_call( + source: Option<&str>, + target: &Path, + fstype: Option<&str>, + flags: libc::c_ulong, + data: Option<&str>, +) -> io::Result<()> { + let source_c = source + .map(CString::new) + .transpose() + .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "NUL in mount source"))?; + let target_c = CString::new(target.as_os_str().as_bytes()) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "NUL in mount target"))?; + let fstype_c = fstype + .map(CString::new) + .transpose() + .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "NUL in mount fstype"))?; + let data_c = data + .map(CString::new) + .transpose() + .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "NUL in mount data"))?; + + let src_ptr = source_c.as_deref().map_or(std::ptr::null(), CStr::as_ptr); + let fs_ptr = fstype_c.as_deref().map_or(std::ptr::null(), CStr::as_ptr); + let data_ptr = data_c + .as_deref() + .map_or(std::ptr::null(), |c| c.as_ptr().cast::()); + + // SAFETY: all non-null pointers reference valid NUL-terminated CStrings for the duration of mount(2). + if unsafe { libc::mount(src_ptr, target_c.as_ptr(), fs_ptr, flags, data_ptr) } != 0 { + Err(io::Error::last_os_error()) + } else { + Ok(()) + } +} + +fn umount_call(target: &Path, flags: libc::c_int) -> io::Result<()> { + let target_c = CString::new(target.as_os_str().as_bytes()) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "NUL in umount target"))?; + // SAFETY: target_c is a valid NUL-terminated path for umount2(2). + if unsafe { libc::umount2(target_c.as_ptr(), flags) } != 0 { + Err(io::Error::last_os_error()) + } else { + Ok(()) + } +} + +fn chown_path(path: &Path, uid: u32, gid: u32) -> io::Result<()> { + let cpath = CString::new(path.as_os_str().as_bytes()) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "NUL in chown path"))?; + // SAFETY: cpath is a valid NUL-terminated path; lchown avoids following symlinks. + if unsafe { libc::lchown(cpath.as_ptr(), uid, gid) } != 0 { + Err(io::Error::last_os_error()) + } else { + Ok(()) + } +} + +fn chown_recursive(path: &Path, uid: u32, gid: u32) -> io::Result<()> { + chown_path(path, uid, gid)?; + let meta = fs::symlink_metadata(path)?; + if meta.file_type().is_dir() { + for entry in fs::read_dir(path)? { + let entry = entry?; + chown_recursive(&entry.path(), uid, gid)?; + } + } + Ok(()) +} + +fn chmod_path(path: &Path, mode: u32) -> io::Result<()> { + fs::set_permissions(path, fs::Permissions::from_mode(mode)) +} + +fn copy_dir_contents(src: &Path, dst: &Path) -> Result<(), String> { + for entry in fs::read_dir(src).map_err(|e| format!("read {}: {e}", src.display()))? { + let entry = entry.map_err(|e| format!("read dir entry: {e}"))?; + let from = entry.path(); + let to = dst.join(entry.file_name()); + if from.is_dir() { + fs::create_dir_all(&to).map_err(|e| format!("mkdir {}: {e}", to.display()))?; + copy_dir_contents(&from, &to)?; + } else if from.is_file() { + fs::copy(&from, &to) + .map_err(|e| format!("copy {} -> {}: {e}", from.display(), to.display()))?; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn configure_hosts_populates_missing_or_empty_and_keeps_image_hosts_and_symlinks() { + let dir = tempfile::tempdir().unwrap(); + let etc = dir.path().join("etc"); + fs::create_dir_all(&etc).unwrap(); + let hosts = etc.join("hosts"); + let log = Logger::new(); + + // Missing hosts file. + configure_hosts(dir.path(), &log); + assert_eq!(fs::read_to_string(&hosts).unwrap(), LOOPBACK_HOSTS); + + // Empty hosts file. + fs::write(&hosts, "").unwrap(); + configure_hosts(dir.path(), &log); + assert_eq!(fs::read_to_string(&hosts).unwrap(), LOOPBACK_HOSTS); + + // Image-authored hosts file is preserved. + let authored = "10.1.2.3 build-host\n"; + fs::write(&hosts, authored).unwrap(); + configure_hosts(dir.path(), &log); + assert_eq!(fs::read_to_string(&hosts).unwrap(), authored); + + // Symlink is left untouched and target outside root is not written. + let outside = dir.path().join("outside-hosts"); + fs::write(&outside, "").unwrap(); + fs::remove_file(&hosts).unwrap(); + std::os::unix::fs::symlink(&outside, &hosts).unwrap(); + configure_hosts(dir.path(), &log); + assert_eq!(fs::read_to_string(&outside).unwrap(), ""); + assert!( + fs::symlink_metadata(&hosts) + .unwrap() + .file_type() + .is_symlink() + ); + } + + #[test] + fn prepare_virtiofs_target_creates_dirs_and_rejects_symlinks_and_files() { + let root = tempfile::tempdir().unwrap(); + let elsewhere = tempfile::tempdir().unwrap(); + fs::create_dir(root.path().join("sandbox")).unwrap(); + let uid = unsafe { libc::geteuid() }; + let gid = unsafe { libc::getegid() }; + + let created = prepare_virtiofs_target(root.path(), "/sandbox/a/b", uid, gid).unwrap(); + assert!(created.is_dir()); + assert_eq!(created, root.path().join("sandbox/a/b")); + + std::os::unix::fs::symlink(elsewhere.path(), root.path().join("sandbox/link")).unwrap(); + let err = prepare_virtiofs_target(root.path(), "/sandbox/link/x", uid, gid).unwrap_err(); + assert!(err.contains("traverses symlink"), "{err}"); + assert!(!elsewhere.path().join("x").exists()); + + fs::write(root.path().join("sandbox/file"), b"").unwrap(); + let err = prepare_virtiofs_target(root.path(), "/sandbox/file/x", uid, gid).unwrap_err(); + assert!(err.contains("is not a directory"), "{err}"); + } + + #[test] + fn parse_env_file_round_trips_shell_escaped_values() { + let content = "\ +export GPU_ENABLED=\"true\" +export OPENSHELL_MSG=\"hello \\\"world\\\" \\$1 \\\\path\\nline2\" +"; + let vars = parse_env_file(content); + assert_eq!( + vars, + vec![ + ("GPU_ENABLED".to_string(), "true".to_string()), + ( + "OPENSHELL_MSG".to_string(), + "hello \"world\" $1 \\path\nline2".to_string() + ), + ] + ); + } + + #[test] + fn sanitize_hostname_matches_rfc1123_rules() { + assert_eq!(sanitize_hostname("my_sandbox!"), "my-sandbox"); + assert_eq!(sanitize_hostname("..."), DEFAULT_HOSTNAME); + assert_eq!(sanitize_hostname(&"a".repeat(80)).len(), 63); + } + + #[test] + fn reconcile_sandbox_account_updates_and_preserves_metadata() { + let dir = tempfile::tempdir().unwrap(); + let etc = dir.path().join("etc"); + fs::create_dir_all(&etc).unwrap(); + fs::write( + etc.join("passwd"), + "root:x:0:0:root:/root:/bin/sh\nsandbox:x:1000:1000:Custom:/home/sb:/bin/bash\n", + ) + .unwrap(); + fs::write(etc.join("group"), "root:x:0:\nsandbox:x:1000:\n").unwrap(); + + reconcile_sandbox_account(dir.path(), 20001, 20002, true).unwrap(); + assert_eq!(sandbox_owner_for_root(dir.path()), (20001, 20002)); + let passwd = fs::read_to_string(etc.join("passwd")).unwrap(); + assert!(passwd.contains("sandbox:x:20001:20002:Custom:/home/sb:/bin/bash")); + } + + #[test] + fn wipe_privileged_overlay_upper_preserves_sandbox_and_openshell() { + let upper = tempfile::tempdir().unwrap(); + fs::create_dir_all(upper.path().join("sandbox")).unwrap(); + fs::create_dir_all(upper.path().join(".openshell/state")).unwrap(); + fs::create_dir_all(upper.path().join("etc")).unwrap(); + fs::write(upper.path().join("etc/shadow"), b"mutated").unwrap(); + fs::write(upper.path().join(".hidden"), b"tmp").unwrap(); + + wipe_privileged_overlay_upper(upper.path()).unwrap(); + assert!(upper.path().join("sandbox").is_dir()); + assert!(upper.path().join(".openshell/state").is_dir()); + assert!(!upper.path().join("etc").exists()); + assert!(!upper.path().join(".hidden").exists()); + } +}