From e3bffdae61204311d405e78cc76635f81c38364d Mon Sep 17 00:00:00 2001 From: Drew Newberry Date: Mon, 23 Nov 2026 22:30:03 -0800 Subject: [PATCH] feat(sandbox): add privileged VM sandbox mode with BPF LSM seal Signed-off-by: Drew Newberry --- Cargo.lock | 42 +- 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, 4488 insertions(+), 129 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 f76c9c406f..71b4b8f503 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" @@ -4646,6 +4682,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", ] @@ -5510,6 +5549,7 @@ version = "0.0.0" dependencies = [ "anyhow", "async-trait", + "aya", "base64 0.22.1", "bytes", "clap", @@ -6396,7 +6436,7 @@ checksum = "9cd31dcfdbbd7431a807ef4df6edd6473228e94d5c805e8cf671227a21bad068" dependencies = [ "anyhow", "clap", - "itertools 0.14.0", + "itertools 0.15.0", "proc-macro2", "quote", "rand 0.8.6", diff --git a/crates/openshell-cli/src/main.rs b/crates/openshell-cli/src/main.rs index bc624aa604..55e5af25ee 100644 --- a/crates/openshell-cli/src/main.rs +++ b/crates/openshell-cli/src/main.rs @@ -1675,6 +1675,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, @@ -3586,6 +3592,7 @@ async fn run_async() -> Result<()> { env_from, no_credential_warnings, approval_mode, + privileged, output, command, } => { @@ -3674,6 +3681,7 @@ async fn run_async() -> Result<()> { suppress_credential_warnings: no_credential_warnings, restart_policy: &restart_policy, provision_timeout_secs: timeout.map(std::num::NonZeroU32::get), + privileged, }, &cli.workspace, &tls, diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index 507c649617..0070913f0b 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -435,6 +435,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>, @@ -463,6 +464,7 @@ pub struct SandboxCreateConfig<'a> { pub suppress_credential_warnings: bool, pub restart_policy: &'a str, pub provision_timeout_secs: Option, + pub privileged: bool, } impl Default for SandboxCreateConfig<'_> { @@ -495,6 +497,7 @@ impl Default for SandboxCreateConfig<'_> { suppress_credential_warnings: false, restart_policy: "never", provision_timeout_secs: None, + privileged: false, } } } @@ -535,6 +538,7 @@ pub async fn sandbox_create( suppress_credential_warnings, restart_policy, provision_timeout_secs, + privileged, } = config; if editor.is_some() && !command.is_empty() { @@ -699,6 +703,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 a012b69aaf..0d99acf416 100644 --- a/crates/openshell-driver-docker/src/lib.rs +++ b/crates/openshell-driver-docker/src/lib.rs @@ -1132,6 +1132,7 @@ impl DockerComputeDriver { Vec::new() }, )), + supports_privileged: false, } } @@ -1156,6 +1157,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 63621d01e1..67c9e8dbfa 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -1328,6 +1328,7 @@ impl KubernetesComputeDriver { .to_string(), ], )), + supports_privileged: !self.config.privileged_runtime_class_name.is_empty(), }) } @@ -2154,6 +2155,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() }; @@ -2570,6 +2573,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 @@ -2653,6 +2663,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, @@ -2673,6 +2685,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) @@ -3113,6 +3128,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!( @@ -3191,7 +3207,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)) @@ -3208,19 +3230,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") @@ -3268,7 +3292,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() @@ -3835,6 +3872,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, @@ -3842,6 +3896,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(|| { @@ -3945,6 +4000,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()))?; @@ -7378,6 +7434,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"; @@ -7492,20 +7550,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!([])) @@ -7570,24 +7639,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!([{ @@ -7828,6 +7921,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. @@ -7852,6 +7947,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, @@ -8039,15 +8136,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(), @@ -8064,9 +8166,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 284ef2c913..911a450597 100644 --- a/crates/openshell-driver-podman/src/driver.rs +++ b/crates/openshell-driver-podman/src/driver.rs @@ -746,6 +746,7 @@ impl PodmanComputeDriver { openshell_core::VERSION, [], )), + supports_privileged: false, }) } @@ -1089,6 +1090,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 37fb7bfa59..7bf916dcee 100644 --- a/crates/openshell-driver-vm/src/driver.rs +++ b/crates/openshell-driver-vm/src/driver.rs @@ -1582,6 +1582,7 @@ impl VmDriver { .into_owned(), rootfs_tar_max_bytes: self.config.rootfs_tar_max_bytes(), extension: Some(extension), + supports_privileged: true, } } @@ -2106,6 +2107,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 @@ -2120,12 +2127,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()))?; @@ -6763,6 +6771,9 @@ fn build_guest_environment(sandbox: &Sandbox, config: &VmDriverConfig) -> Vec>(); pairs.sort_by(|left, right| left.0.cmp(&right.0)); pairs @@ -7635,7 +7646,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)?; } @@ -7668,6 +7689,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 0db379981f..e571f12796 100644 --- a/crates/openshell-sandbox-backend/src/runtime/test_support.rs +++ b/crates/openshell-sandbox-backend/src/runtime/test_support.rs @@ -748,6 +748,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 d95ce62e4c..352083b911 100644 --- a/crates/openshell-sandbox/src/boundary_exec.rs +++ b/crates/openshell-sandbox/src/boundary_exec.rs @@ -127,9 +127,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(), @@ -162,15 +170,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 { @@ -235,21 +256,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")] @@ -373,19 +413,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")] @@ -466,6 +523,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 038708c654..68fea883ca 100644 --- a/crates/openshell-sandbox/src/boundary_server.rs +++ b/crates/openshell-sandbox/src/boundary_server.rs @@ -255,6 +255,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, @@ -304,6 +310,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, @@ -2569,6 +2659,7 @@ mod linux { network_broker: NetworkBroker, workload_launcher: crate::linux::workload_launcher::WorkloadLauncher, qualification: crate::RuntimeQualification, + privileged: Option>, } #[derive(Clone)] @@ -2879,9 +2970,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); @@ -2904,7 +3004,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, @@ -3128,6 +3236,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, @@ -3229,13 +3340,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" @@ -3254,8 +3372,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); @@ -3333,6 +3456,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; @@ -3440,7 +3566,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, @@ -3748,6 +3874,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()) { @@ -3859,6 +4012,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), @@ -3981,6 +4154,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), @@ -5597,6 +5835,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(), @@ -5700,6 +5939,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")); @@ -5814,6 +6054,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)); } @@ -5898,6 +6139,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, @@ -6371,6 +6613,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, @@ -6891,6 +7134,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(); @@ -7071,6 +7315,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", @@ -7727,6 +7972,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"); @@ -8024,6 +8270,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, @@ -8333,6 +8580,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, @@ -8751,6 +8999,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, @@ -8971,6 +9220,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, @@ -10391,6 +10641,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, @@ -10821,6 +11072,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, @@ -10964,3 +11216,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 51b3af629e..256d299277 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 @@ -68,6 +88,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)); @@ -75,7 +107,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); @@ -108,6 +140,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 c329cfc439..06403613d5 100644 --- a/crates/openshell-sdk/src/client.rs +++ b/crates/openshell-sdk/src/client.rs @@ -1499,6 +1499,7 @@ fn create_sandbox_request(spec: SandboxSpec) -> proto::CreateSandboxRequest { tty, service_exposures, restart_policy, + privileged, } = spec; let template = image.map(|image| proto::SandboxTemplate { image, @@ -1517,6 +1518,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 97c1fc7574..a9e9daa98f 100644 --- a/crates/openshell-sdk/src/types.rs +++ b/crates/openshell-sdk/src/types.rs @@ -299,6 +299,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 da516927a6..369f559531 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -522,6 +522,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 @@ -1040,6 +1042,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( @@ -1409,6 +1412,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, @@ -1673,6 +1681,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 @@ -7321,6 +7336,7 @@ fn driver_sandbox_spec_from_public( }), launch_authentication: Vec::new(), isolation_backend: None, + privileged: spec.privileged, }) } @@ -8597,6 +8613,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", @@ -8812,6 +8829,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, @@ -9293,6 +9311,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, @@ -9849,6 +9868,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", @@ -10150,6 +10170,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 6bb58c1e76..53afad249a 100644 --- a/deploy/helm/openshell/README.md +++ b/deploy/helm/openshell/README.md @@ -781,6 +781,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 05aab6f705..3fc4af800c 100644 --- a/deploy/helm/openshell/values.yaml +++ b/deploy/helm/openshell/values.yaml @@ -531,6 +531,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 6b0f5d5d1e..fa406fa6b9 100644 --- a/e2e/rust/Cargo.toml +++ b/e2e/rust/Cargo.toml @@ -78,6 +78,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 = "service_bearer_passthrough" path = "tests/service_bearer_passthrough.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 c01e88daf3..b7e30eb938 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -1248,6 +1248,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 da6e84abee..172c60545c 100644 --- a/tests/testkit/testkit/src/context.rs +++ b/tests/testkit/testkit/src/context.rs @@ -595,6 +595,7 @@ fn grpc_create_request( tty, service_exposures: _, restart_policy, + privileged, } = spec; proto::CreateSandboxRequest { name: name.unwrap_or_default(), @@ -614,6 +615,7 @@ fn grpc_create_request( tty, policy, restart_policy: proto::SandboxRestartPolicy::from(restart_policy) as i32, + privileged, ..proto::SandboxSpec::default() }), ..proto::CreateSandboxRequest::default()