diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 2ed378e..0000000 --- a/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -third_party/mxc/patches/*.patch text eol=lf -whitespace diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4b43272..d8a659d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,11 +15,9 @@ env: MXC_REPOSITORY: https://github.com/microsoft/mxc # Linux lxc-exec: MXC v1.0.0. MXC_REF: 7bf210247986cb73b1b314df60c2f1109c479c0b - # Windows wxc-exec stays on an older MXC revision with the AXIS patches in - # third_party/mxc until MXC BaseContainer can run least-privilege - # AppContainer children without DACL mutation: - # https://github.com/microsoft/mxc/issues/1496 - MXC_WINDOWS_REF: 1736b48398c3fe4d1315b2311c0951cc893eb3ae + # Windows wxc-exec: MXC v1.0.1, unpatched. MXC 1.x BaseContainer has no + # least-privilege (LPAC) option: https://github.com/microsoft/mxc/issues/1496 + MXC_WINDOWS_REF: fda29ac63bc306b7f97f3b86b4b63d44f7f40cf2 permissions: contents: read @@ -366,8 +364,6 @@ jobs: $mxcDir = Join-Path $env:RUNNER_TEMP "mxc" git clone --filter=blob:none $env:MXC_REPOSITORY $mxcDir git -C $mxcDir checkout $env:MXC_WINDOWS_REF - Get-ChildItem (Join-Path $env:GITHUB_WORKSPACE "third_party\mxc\patches\*.patch") | - Sort-Object Name | ForEach-Object { git -C $mxcDir apply --whitespace=error $_.FullName } Push-Location (Join-Path $mxcDir "src") cargo build --release -p wxc --no-default-features --locked Pop-Location diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 3626c45..1b30287 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -19,11 +19,9 @@ env: MXC_REPOSITORY: https://github.com/microsoft/mxc # Linux lxc-exec: MXC v1.0.0. MXC_REF: 7bf210247986cb73b1b314df60c2f1109c479c0b - # Windows wxc-exec stays on an older MXC revision with the AXIS patches in - # third_party/mxc until MXC BaseContainer can run least-privilege - # AppContainer children without DACL mutation: - # https://github.com/microsoft/mxc/issues/1496 - MXC_WINDOWS_REF: 1736b48398c3fe4d1315b2311c0951cc893eb3ae + # Windows wxc-exec: MXC v1.0.1, unpatched. MXC 1.x BaseContainer has no + # least-privilege (LPAC) option: https://github.com/microsoft/mxc/issues/1496 + MXC_WINDOWS_REF: fda29ac63bc306b7f97f3b86b4b63d44f7f40cf2 SYFT_VERSION: 1.46.0 SYFT_LINUX_AMD64_SHA256: d654f678b709eb53c393d38519d5ed7d2e57205529404018614cfefa0fb2b5ca @@ -205,8 +203,6 @@ jobs: $mxcDir = Join-Path $env:RUNNER_TEMP "mxc" git clone --filter=blob:none $env:MXC_REPOSITORY $mxcDir git -C $mxcDir checkout $env:MXC_WINDOWS_REF - Get-ChildItem (Join-Path $env:GITHUB_WORKSPACE "third_party\mxc\patches\*.patch") | - Sort-Object Name | ForEach-Object { git -C $mxcDir apply --whitespace=error $_.FullName } Push-Location (Join-Path $mxcDir "src") cargo build --release -p wxc --no-default-features --locked --target ${{ matrix.target }} Pop-Location @@ -306,9 +302,7 @@ jobs: Copy-Item -LiteralPath (Join-Path "$targetDir" "axis.exe") -Destination "$packageDir" Copy-Item -LiteralPath (Join-Path "$targetDir" "axisd.exe") -Destination "$packageDir" Copy-Item -LiteralPath (Join-Path "$targetDir" "wxc-exec.exe") -Destination "$packageDir" - Copy-Item -LiteralPath (Join-Path "$targetDir" "axis-wfp-broker.exe") -Destination "$packageDir" Copy-Item -LiteralPath (Join-Path "$targetDir" "axis-ssh-proxy.exe") -Destination "$packageDir" - Copy-Item -LiteralPath "scripts/install_windows_wfp_broker.ps1" -Destination "$packageDir" Copy-Item -Path "policies\*.yaml" -Destination "$packageDir" Copy-Item -LiteralPath "LICENSE" -Destination "$packageDir" Copy-Item -LiteralPath "install.ps1" -Destination "$packageDir" @@ -346,9 +340,7 @@ jobs: --require axis.exe --require axisd.exe --require wxc-exec.exe - --require axis-wfp-broker.exe --require axis-ssh-proxy.exe - --require install_windows_wfp_broker.ps1 --require REPRODUCIBILITY.json - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ed706e7..5733f19 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,11 +20,9 @@ env: MXC_REPOSITORY: https://github.com/microsoft/mxc # Linux lxc-exec: MXC v1.0.0. MXC_REF: 7bf210247986cb73b1b314df60c2f1109c479c0b - # Windows wxc-exec stays on an older MXC revision with the AXIS patches in - # third_party/mxc until MXC BaseContainer can run least-privilege - # AppContainer children without DACL mutation: - # https://github.com/microsoft/mxc/issues/1496 - MXC_WINDOWS_REF: 1736b48398c3fe4d1315b2311c0951cc893eb3ae + # Windows wxc-exec: MXC v1.0.1, unpatched. MXC 1.x BaseContainer has no + # least-privilege (LPAC) option: https://github.com/microsoft/mxc/issues/1496 + MXC_WINDOWS_REF: fda29ac63bc306b7f97f3b86b4b63d44f7f40cf2 SYFT_VERSION: 1.46.0 SYFT_LINUX_AMD64_SHA256: d654f678b709eb53c393d38519d5ed7d2e57205529404018614cfefa0fb2b5ca @@ -200,8 +198,6 @@ jobs: $mxcDir = Join-Path $env:RUNNER_TEMP "mxc" git clone --filter=blob:none $env:MXC_REPOSITORY $mxcDir git -C $mxcDir checkout $env:MXC_WINDOWS_REF - Get-ChildItem (Join-Path $env:GITHUB_WORKSPACE "third_party\mxc\patches\*.patch") | - Sort-Object Name | ForEach-Object { git -C $mxcDir apply --whitespace=error $_.FullName } Push-Location (Join-Path $mxcDir "src") cargo build --release -p wxc --no-default-features --locked --target ${{ matrix.target }} Pop-Location @@ -298,9 +294,7 @@ jobs: Copy-Item -LiteralPath (Join-Path "$targetDir" "axis.exe") -Destination "$packageDir" Copy-Item -LiteralPath (Join-Path "$targetDir" "axisd.exe") -Destination "$packageDir" Copy-Item -LiteralPath (Join-Path "$targetDir" "wxc-exec.exe") -Destination "$packageDir" - Copy-Item -LiteralPath (Join-Path "$targetDir" "axis-wfp-broker.exe") -Destination "$packageDir" Copy-Item -LiteralPath (Join-Path "$targetDir" "axis-ssh-proxy.exe") -Destination "$packageDir" - Copy-Item -LiteralPath "scripts/install_windows_wfp_broker.ps1" -Destination "$packageDir" Copy-Item -Path "policies\*.yaml" -Destination "$packageDir" Copy-Item -LiteralPath "README.md" -Destination "$packageDir" Copy-Item -LiteralPath "LICENSE" -Destination "$packageDir" @@ -339,9 +333,7 @@ jobs: --require axis.exe --require axisd.exe --require wxc-exec.exe - --require axis-wfp-broker.exe --require axis-ssh-proxy.exe - --require install_windows_wfp_broker.ps1 --require REPRODUCIBILITY.json - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index d52a976..99ab163 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -224,7 +224,7 @@ Test Result, and treat a red push or weekly run on `main` like any other broken `main` build. Some tests need privileges, hardware, or kernels that hosted runners do not have -(privileged Linux tiers, Windows BaseContainer and the WFP broker, newer +(privileged Linux tiers, Windows BaseContainer and its strict proxy, newer Landlock ABIs, GPU, vxn). They skip on such hosts, and **a skipped test is not a passing test**. PRs in these areas include a run on a capable host in the Test Result ([Security Test Tiers](docs/security-test-tiers.md)). diff --git a/README.md b/README.md index 4a35754..2ac3977 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ platform backend is available: |---|---|---|---| | Process | MXC Bubblewrap process backend with AXIS seccomp; native Landlock/seccomp retained | Experimental: MXC ProcessContainer (BaseContainer) with AXIS-owned lifecycle cleanup | Seatbelt (sandbox-exec) | | Filesystem | MXC Bubblewrap mounts or native Landlock LSM | MXC ProcessContainer path allowlists | Seatbelt profile (subpath rules) | -| Network | block mode, MXC cooperative proxy, or strict native netns proxy | MXC allow/block plus BaseContainer strict proxy through the installed AXIS WFP broker | Seatbelt network deny + proxy | +| Network | block mode, MXC cooperative proxy, or strict native netns proxy | MXC allow/block plus BaseContainer strict proxy through MXC's loopback proxy mapping | Seatbelt network deny + proxy | | GPU | Optional HIP Remote artifacts | Optional HIP Remote artifacts | Optional HIP Remote artifacts | | Inference | Local LLM via llama.cpp or vLLM | Same | Same | @@ -50,6 +50,10 @@ invoked as `pwsh`. irm 'https://raw.githubusercontent.com/ROCm/axis/main/install.ps1' | iex ``` +On Windows too, run `gh auth login` (or set `GH_TOKEN`) before the installer. +On networks that intercept TLS, `gh` can fail with certificate errors and the +installer then stops; check that `gh auth status` works first. + **Windows support is experimental.** The Windows sandbox uses MXC BaseContainer, which needs Windows 11 x64 at or above one of these builds (see MXC's [OS version support](https://github.com/microsoft/mxc/blob/main/docs/backends/process-container/os-version-support.md)): @@ -65,8 +69,9 @@ Run `winver` to check your build. Windows 10, Windows Server and earlier Windows 11 builds are not supported: on them every sandboxed launch fails instead of running with weaker isolation. A supported build is necessary but not sufficient. Hosted CI runners lack BaseContainer, so the Windows sandbox is -not exercised in CI, and known MXC issues still prevent some common tools, such -as git, Node.js and Git Bash, from starting inside it. +not exercised in CI. Some common tools start only with an opt-in policy field: +PowerShell and Git for Windows need `process.windows_win32k`, and Node.js needs +`filesystem.windows_enumerate_ancestors` (see [Windows](#windows-mxc-processcontainer-experimental)). ```bash # Nightly builds @@ -93,12 +98,11 @@ narrower privileged path. Windows release archives include the pinned MXC `wxc-exec.exe` beside `axis.exe`. Windows `runtime.provider: auto` and `mxc` use ProcessContainer; the incomplete legacy `axis_native` host-spawn path is disabled and never used -as a fallback. Proxy-mode policies also need the AXIS WFP broker service, which -the installer does not register. Install it once from an elevated PowerShell -session in a source checkout with `scripts\install_windows_wfp_broker.ps1` (see -[Setup And Install](docs/setup-and-install.md)); the copy of that script in the -release archive expects a source tree and cannot yet install the bundled -`axis-wfp-broker.exe`. +as a fallback. Proxy-mode policies need no extra service: the packaged executor +routes the sandbox to the AXIS proxy through MXC's loopback proxy mapping (see +[Setup And Install](docs/setup-and-install.md)). Blocked bypass attempts are not +recorded on Windows, so every proxy-mode launch prints a warning; set +`network.bypass_audit: hard_requirement` to refuse such launches instead. The Linux default MXC process backend also needs the host `bubblewrap` runtime and unprivileged user namespaces enabled. Allow-mode policies also need @@ -140,6 +144,11 @@ cross-platform dependency and package boundary, see axis run -- python3 -c "print('Hello from AXIS sandbox')" ``` +```powershell +# Windows: python3 is often only the Microsoft Store placeholder there +axis run -- cmd.exe /c echo Hello from AXIS sandbox +``` + That's it. The default `minimal` policy is intentionally quickstart-friendly on Linux: MXC Bubblewrap process isolation, AXIS seccomp syscall filtering, block-mode network denial, and no requested cgroup/resource limits. It does not @@ -158,6 +167,9 @@ axis list axis destroy ``` +The daemon commands (`axisd`, `axis create`, `list`, `exec`, `destroy`) do not +work on Windows yet: axisd there cannot create sandboxes. Use `axis run`. + On Linux, policies that request CPU, memory, or process limits require writable cgroups v2 or a documented fallback. `network.mode: proxy` uses an AXIS-owned strict proxy boundary and needs native `CAP_NET_ADMIN` support or the optional @@ -229,29 +241,52 @@ Windows process policies default to the packaged MXC `wxc-exec.exe` backend. AXIS translates the shared policy into MXC JSON, clears the executor environment, rejects secrets and unsupported surfaces before launch, and places the executor in a kill-on-close Job Object for timeout and teardown cleanup. AXIS requires -MXC BaseContainer by default, enables its least-privilege token mode, and fails -closed rather than silently selecting another ProcessContainer tier. +MXC BaseContainer and fails closed rather than silently selecting another +ProcessContainer tier. The supported slice now includes filesystem read-only/read-write allowlists, BaseContainer-default-deny normalization for non-overlapping deny rules, a physical managed Windows profile, child-tree process/aggregate-memory/CPU limits, default allow/block networking, and BaseContainer strict proxy routing through -the installed AXIS WFP broker. The broker installs an exact proxy permit plus -IPv4/IPv6 default-deny filters against the SID read from the suspended child; -direct TCP, UDP, DNS, and QUIC bypasses remain blocked. Nested deny rules and -GPU/AMD policies still reject instead of weakening the policy. Scoped SSH is -supported through BaseContainer strict proxy mode when every projected key has -the same literal host set and that set exactly matches port-22 network rules. +MXC's `runtimeConfig.networkProxy` mapping, which limits egress to the AXIS +loopback proxy; direct TCP, UDP, DNS, and QUIC bypasses remain blocked. Nested +deny rules and GPU/AMD policies still reject instead of weakening the policy. + +The pinned MXC 1.x BaseContainer has no least-privilege (LPAC) token mode. The +child cannot read the user's files outside its grants, but it keeps the +caller's user SID inside the container, so system locations and the user's +registry hive stay readable, and `process.identity: isolated` is rejected. In +strict proxy mode MXC also requires inbound connections to be allowed, so +whether private-network peers can reach a listener in the sandbox depends on +the host firewall. [Windows MXC 1.x Backend](docs/windows-mxc-1.md) records the +trade-offs and the evidence. + +Two opt-in policy fields widen access for tools that need it. Both are off by +default and printed at launch when on: + +- `process.windows_win32k: true` lets the sandbox make Win32k (USER32/GDI) + calls, which PowerShell and Git for Windows need to start. +- `filesystem.windows_enumerate_ancestors: true` lets the sandbox list the + folders above its grants, which Node.js needs to resolve paths. It exposes + the names, sizes and times of files below those folders, not their contents. + +Scoped SSH is supported through BaseContainer strict proxy mode when every +projected key has the same literal host set and that set exactly matches +port-22 network rules. Managed inference, streaming, host-side provider credential injection, and conservative token-budget reservation are supported through BaseContainer strict proxy mode; token-budget exhaustion currently supports the exact `reject` action only. -Interactive ConPTY is unsupported through BaseContainer on Windows build 26300 -because its creation API rejects pseudoconsole startup handles with -`ERROR_INVALID_HANDLE`. AXIS does not force the older AppContainer/DACL tier to -obtain terminal support. AppContainer/DACL fallback remains disabled in the MXC -configuration, so an unavailable BaseContainer is a launch failure. +Run from a terminal, the sandboxed command reads and writes that terminal +directly. BaseContainer cannot give it a pseudoconsole (its creation API rejects +pseudoconsole startup handles with `ERROR_INVALID_HANDLE`), so full-screen +programs that need one may not render correctly, and AXIS does not force the +older AppContainer/DACL tier to obtain one. The sandbox cannot write to the +terminal's input buffer. A `.cmd` or `.bat` file launched directly fails inside +BaseContainer with "Access is denied"; run it as `cmd.exe /c script.cmd`. +AppContainer/DACL fallback remains disabled in the MXC configuration, so an +unavailable BaseContainer is a launch failure. The pinned MXC project is an early preview and does not claim its profiles are security boundaries; AXIS therefore treats unsupported or unavailable behavior as a launch failure, not as permission to execute on the host. @@ -349,7 +384,7 @@ axis/ ├── gui/ # Desktop apps (shared web UI plus Linux, macOS and Windows shells) ├── benches/ # Performance benchmarks ├── e2e/ # End-to-end tests -└── third_party/mxc/ # Patches applied to the pinned MXC revision +└── third_party/mxc/ # Notes on the pinned MXC revisions (no patches) ``` ## Performance diff --git a/crates/axis-cli/src/main.rs b/crates/axis-cli/src/main.rs index 5e27297..a7410bd 100644 --- a/crates/axis-cli/src/main.rs +++ b/crates/axis-cli/src/main.rs @@ -639,6 +639,29 @@ async fn main() -> Result<()> { policy.network.mode, policy.network.policies.len(), ); + if matches!(policy.network.mode, axis_core::policy::NetworkMode::Proxy) { + println!( + " Bypass audit: {}", + match policy.network.bypass_audit { + axis_core::policy::Compatibility::BestEffort => { + "best_effort (Windows ProcessContainer blocks bypass attempts but does not record them)" + } + axis_core::policy::Compatibility::HardRequirement => { + "hard_requirement (refuse backends that cannot record bypass attempts)" + } + }, + ); + } + if policy.process.windows_win32k { + println!( + " Windows: process.windows_win32k on (the sandbox can make Win32k system calls)" + ); + } + if policy.filesystem.windows_enumerate_ancestors { + println!( + " Windows: filesystem.windows_enumerate_ancestors on (file names, sizes and times below grant ancestors are visible)" + ); + } println!(" Inference: {} routes", policy.inference.routes.len()); if policy.gpu.enabled { println!( @@ -1501,6 +1524,7 @@ mod tests { filesystem: FilesystemPolicy::default(), process: ProcessPolicy::default(), network: NetworkPolicy { + bypass_audit: Default::default(), mode: network_mode, policies: Vec::new(), }, diff --git a/crates/axis-core/src/capability.rs b/crates/axis-core/src/capability.rs index 23b117a..15797f0 100644 --- a/crates/axis-core/src/capability.rs +++ b/crates/axis-core/src/capability.rs @@ -8,7 +8,7 @@ //! the planner decides whether an AXIS policy can be enforced without knowing //! about operating-system primitives. -use crate::policy::{NetworkMode, Policy}; +use crate::policy::{Compatibility, NetworkMode, Policy}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; @@ -254,9 +254,12 @@ pub trait RuntimeCapabilityProbe { fn snapshot(&self, backend: &BackendCapabilities) -> RuntimeProbeSnapshot; } +pub const BYPASS_EVIDENCE_REQUIREMENT: &str = "audit.bypass_evidence"; + #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct PlannerOptions { accepted_weaker_surfaces: BTreeSet, + accepted_weaker_requirements: BTreeSet<&'static str>, } impl PlannerOptions { @@ -264,13 +267,35 @@ impl PlannerOptions { Self::default() } + /// Options carrying the weaker behavior a policy accepts itself. Only + /// `network.bypass_audit: best_effort` (the default) does so, and only for + /// a bypass audit trail; every other weaker surface still has to be + /// accepted by the caller. + pub fn for_policy(policy: &Policy) -> Self { + let options = Self::new(); + match policy.network.bypass_audit { + Compatibility::BestEffort => { + options.accept_weaker_requirement(BYPASS_EVIDENCE_REQUIREMENT) + } + Compatibility::HardRequirement => options, + } + } + pub fn accept_weaker_surface(mut self, surface: PolicySurface) -> Self { self.accepted_weaker_surfaces.insert(surface); self } - fn accepts_weaker(&self, surface: PolicySurface) -> bool { - self.accepted_weaker_surfaces.contains(&surface) + pub fn accept_weaker_requirement(mut self, requirement: &'static str) -> Self { + self.accepted_weaker_requirements.insert(requirement); + self + } + + fn accepts_weaker(&self, reason: &PlanReason) -> bool { + self.accepted_weaker_surfaces.contains(&reason.surface) + || self + .accepted_weaker_requirements + .contains(reason.requirement) } } @@ -310,9 +335,12 @@ pub enum BackendPlanOutcome { ExactWithHostDependency { dependencies: Vec, }, + /// Accepting the weaker behavior does not waive host dependencies: a + /// launch still needs every dependency of the other requirements. WeakerOnly { accepted: bool, reasons: Vec, + dependencies: Vec, }, Unsupported { reasons: Vec, @@ -335,7 +363,11 @@ impl BackendPolicyPlan { BackendPlanOutcome::ExactWithHostDependency { dependencies } => { dependencies.iter().all(|dependency| dependency.present) } - BackendPlanOutcome::WeakerOnly { accepted, .. } => *accepted, + BackendPlanOutcome::WeakerOnly { + accepted, + dependencies, + .. + } => *accepted && dependencies.iter().all(|dependency| dependency.present), BackendPlanOutcome::Unsupported { .. } => false, } } @@ -344,34 +376,15 @@ impl BackendPolicyPlan { match &self.outcome { BackendPlanOutcome::Exact => None, BackendPlanOutcome::ExactWithHostDependency { dependencies } => { - let missing = dependencies - .iter() - .filter(|dependency| !dependency.present) - .map(|dependency| { - if matches!(dependency.state, DependencyState::Missing) { - format!( - "{} requires missing host dependency '{}'", - dependency.requirement, dependency.dependency - ) - } else { - format!( - "{} requires host dependency '{}' but probe reported {}", - dependency.requirement, - dependency.dependency, - dependency.state.failure_label() - ) - } - }) - .collect::>(); - if missing.is_empty() { - None - } else { - Some(missing.join("; ")) - } + missing_dependencies_error(dependencies) } - BackendPlanOutcome::WeakerOnly { accepted, reasons } => { + BackendPlanOutcome::WeakerOnly { + accepted, + reasons, + dependencies, + } => { if *accepted { - None + missing_dependencies_error(dependencies) } else { Some(format!( "backend offers only weaker behavior: {}", @@ -385,6 +398,45 @@ impl BackendPolicyPlan { )), } } + + /// Weaker behavior the launch accepted, to be reported to the user. + pub fn accepted_weaker_reasons(&self) -> &[PlanReason] { + match &self.outcome { + BackendPlanOutcome::WeakerOnly { + accepted: true, + reasons, + .. + } => reasons, + _ => &[], + } + } +} + +fn missing_dependencies_error(dependencies: &[DependencyDecision]) -> Option { + let missing = dependencies + .iter() + .filter(|dependency| !dependency.present) + .map(|dependency| { + if matches!(dependency.state, DependencyState::Missing) { + format!( + "{} requires missing host dependency '{}'", + dependency.requirement, dependency.dependency + ) + } else { + format!( + "{} requires host dependency '{}' but probe reported {}", + dependency.requirement, + dependency.dependency, + dependency.state.failure_label() + ) + } + }) + .collect::>(); + if missing.is_empty() { + None + } else { + Some(missing.join("; ")) + } } pub fn plan_backend_policy( @@ -462,10 +514,11 @@ pub fn plan_backend_requirements( } else if !weaker_reasons.is_empty() { let accepted = weaker_reasons .iter() - .all(|reason| options.accepts_weaker(reason.surface)); + .all(|reason| options.accepts_weaker(reason)); BackendPlanOutcome::WeakerOnly { accepted, reasons: weaker_reasons, + dependencies: dependency_decisions, } } else if !dependency_decisions.is_empty() { BackendPlanOutcome::ExactWithHostDependency { @@ -831,7 +884,7 @@ fn requirements_for_policy( push( &mut requirements, PolicySurface::Audit, - "audit.bypass_evidence", + BYPASS_EVIDENCE_REQUIREMENT, &backend.audit.bypass_evidence, ); } @@ -968,6 +1021,7 @@ mod tests { deny: Vec::new(), compatibility: Default::default(), workspace_read_only: false, + windows_enumerate_ancestors: false, }, process: ProcessPolicy { max_processes: 0, @@ -978,8 +1032,10 @@ mod tests { identity: Default::default(), child_processes: Default::default(), timeout_sec: None, + windows_win32k: false, }, network: NetworkPolicy { + bypass_audit: Default::default(), mode, policies: Vec::new(), }, @@ -1088,6 +1144,7 @@ mod tests { requirement: "network.strict_proxy", reason: "cooperative proxy environment variables only".into(), }], + dependencies: Vec::new(), } ); assert!(!plan.spawn_allowed()); @@ -1126,6 +1183,7 @@ mod tests { BackendPlanOutcome::WeakerOnly { accepted: false, ref reasons, + .. } if reasons.len() == 2 ), "accepting only {surface:?} must not accept the plan: {:?}", @@ -1147,6 +1205,116 @@ mod tests { assert!(accepted.spawn_allowed()); } + fn unrecorded_bypass_backend() -> BackendCapabilities { + let mut backend = exact_backend(); + backend.audit.bypass_evidence = CapabilitySupport::weaker("bypass blocked, not recorded"); + backend + } + + #[test] + fn bypass_audit_best_effort_launches_and_reports_the_missing_trail() { + let backend = unrecorded_bypass_backend(); + let policy = minimal_policy(NetworkMode::Proxy); + assert!(matches!( + policy.network.bypass_audit, + Compatibility::BestEffort + )); + + let plan = plan_backend_policy( + &policy, + &backend, + &RuntimeProbeSnapshot::new(), + &PlannerOptions::for_policy(&policy), + ); + + assert!(plan.spawn_allowed(), "{:?}", plan.pre_spawn_error()); + assert_eq!( + plan.accepted_weaker_reasons(), + [PlanReason { + surface: PolicySurface::Audit, + requirement: BYPASS_EVIDENCE_REQUIREMENT, + reason: "bypass blocked, not recorded".into(), + }] + ); + } + + #[test] + fn bypass_audit_hard_requirement_refuses_an_unrecorded_trail() { + let backend = unrecorded_bypass_backend(); + let mut policy = minimal_policy(NetworkMode::Proxy); + policy.network.bypass_audit = Compatibility::HardRequirement; + + let plan = plan_backend_policy( + &policy, + &backend, + &RuntimeProbeSnapshot::new(), + &PlannerOptions::for_policy(&policy), + ); + + assert!(!plan.spawn_allowed()); + let error = plan.pre_spawn_error().unwrap(); + assert!(error.contains(BYPASS_EVIDENCE_REQUIREMENT), "{error}"); + assert!(plan.accepted_weaker_reasons().is_empty()); + } + + #[test] + fn bypass_audit_best_effort_accepts_nothing_else() { + let policy = minimal_policy(NetworkMode::Proxy); + let options = PlannerOptions::for_policy(&policy); + + let mut other_weaker = unrecorded_bypass_backend(); + other_weaker.audit.denials = CapabilitySupport::weaker("denials not recorded"); + let plan = plan_backend_policy( + &policy, + &other_weaker, + &RuntimeProbeSnapshot::new(), + &options, + ); + assert!(!plan.spawn_allowed()); + assert!(plan.pre_spawn_error().unwrap().contains("audit.denials")); + + let mut unsupported = exact_backend(); + unsupported.audit.bypass_evidence = CapabilitySupport::unsupported("no bypass control"); + let plan = plan_backend_policy( + &policy, + &unsupported, + &RuntimeProbeSnapshot::new(), + &options, + ); + assert!(matches!( + plan.outcome, + BackendPlanOutcome::Unsupported { .. } + )); + assert!(!plan.spawn_allowed()); + } + + #[test] + fn accepted_weaker_plan_still_requires_host_dependencies() { + let mut backend = unrecorded_bypass_backend(); + backend.network.strict_proxy = CapabilitySupport::with_dependency("proxy-boundary"); + let policy = minimal_policy(NetworkMode::Proxy); + let options = PlannerOptions::for_policy(&policy); + + let missing = + plan_backend_policy(&policy, &backend, &RuntimeProbeSnapshot::new(), &options); + assert!(!missing.spawn_allowed()); + assert!( + missing + .pre_spawn_error() + .unwrap() + .contains("requires missing host dependency 'proxy-boundary'") + ); + + let present = plan_backend_policy( + &policy, + &backend, + &RuntimeProbeSnapshot::new() + .with_dependency("proxy-boundary", DependencyState::Present), + &options, + ); + assert!(present.spawn_allowed(), "{:?}", present.pre_spawn_error()); + } + #[test] fn binary_restricted_endpoint_requires_attribution() { let mut backend = exact_backend(); diff --git a/crates/axis-core/src/capability_map.rs b/crates/axis-core/src/capability_map.rs index eaddea0..d9c2b60 100644 --- a/crates/axis-core/src/capability_map.rs +++ b/crates/axis-core/src/capability_map.rs @@ -42,7 +42,6 @@ pub mod host_dependency { pub const WINDOWS_JOBOBJECT: &str = "windows.job_object"; pub const WINDOWS_LOW_INTEGRITY: &str = "windows.low_integrity"; pub const WINDOWS_PROCESS_CONTAINER: &str = "windows.processcontainer"; - pub const WINDOWS_WFP_BROKER: &str = "windows.axis_wfp_broker"; pub const WINDOWS_SANDBOX: &str = "windows.windows_sandbox"; pub const WINDOWS_WHP: &str = "windows.whp"; pub const WINDOWS_WSL2: &str = "windows.wsl2"; @@ -1019,7 +1018,6 @@ fn mxc_windows_processcontainer() -> BackendCapabilities { host_dependency::MXC_EXECUTOR, host_dependency::WINDOWS_PROCESS_CONTAINER, host_dependency::WINDOWS_JOBOBJECT, - host_dependency::WINDOWS_WFP_BROKER, ]), filesystem: FilesystemCapabilities { read_only: processcontainer.clone(), @@ -1037,7 +1035,9 @@ fn mxc_windows_processcontainer() -> BackendCapabilities { user_identity: CapabilitySupport::unsupported( "MXC ProcessContainer cannot map a caller-named host account", ), - isolated_identity: processcontainer.clone(), + isolated_identity: CapabilitySupport::unsupported( + "MXC 1.x BaseContainer has no LPAC token option, so the process keeps the caller's user SID", + ), syscall_filtering: CapabilitySupport::unsupported( "ProcessContainer does not provide AXIS seccomp-style syscall filtering", ), @@ -1049,10 +1049,14 @@ fn mxc_windows_processcontainer() -> BackendCapabilities { network: NetworkCapabilities { allow: processcontainer.clone(), block: processcontainer.clone(), + // MXC 1.x scopes per-container WFP egress to the single + // `runtimeConfig.networkProxy` loopback endpoint, but only with + // `ingress.default: allow`, which adds privateNetworkClientServer. + // Inbound connections from private-network peers then depend on + // the host firewall; see docs/windows-mxc-1.md. strict_proxy: deps_support([ host_dependency::MXC_EXECUTOR, host_dependency::WINDOWS_PROCESS_CONTAINER, - host_dependency::WINDOWS_WFP_BROKER, ]), cooperative_proxy: CapabilitySupport::weaker( "cooperative proxy environment variables cannot prevent direct socket bypass", @@ -1081,7 +1085,9 @@ fn mxc_windows_processcontainer() -> BackendCapabilities { audit: AuditCapabilities { denials: CapabilitySupport::AxisOwned, dependency_reasons: CapabilitySupport::AxisOwned, - bypass_evidence: dep_support(host_dependency::WINDOWS_WFP_BROKER), + bypass_evidence: CapabilitySupport::weaker( + "MXC's per-container WFP filters block direct bypass attempts, but neither MXC nor AXIS records them", + ), }, } } @@ -1523,9 +1529,6 @@ fn host_dependency_for(name: &'static str) -> HostDependency { host_dependency::WINDOWS_JOBOBJECT => "Windows Job Object resource enforcement", host_dependency::WINDOWS_LOW_INTEGRITY => "Windows low-integrity token support", host_dependency::WINDOWS_PROCESS_CONTAINER => "Windows ProcessContainer support", - host_dependency::WINDOWS_WFP_BROKER => { - "installed AXIS WFP broker service with a reachable lease pipe" - } host_dependency::WINDOWS_SANDBOX => "Windows Sandbox optional feature", host_dependency::WINDOWS_WHP => "Windows Hypervisor Platform feature", host_dependency::WINDOWS_WSL2 => "Windows Subsystem for Linux 2 feature", @@ -1953,6 +1956,7 @@ mod tests { deny: Vec::new(), compatibility: Default::default(), workspace_read_only: false, + windows_enumerate_ancestors: false, }, process: ProcessPolicy { max_processes: 0, @@ -1963,8 +1967,10 @@ mod tests { identity: Default::default(), child_processes: Default::default(), timeout_sec: None, + windows_win32k: false, }, network: NetworkPolicy { + bypass_audit: Default::default(), mode, policies: Vec::new(), }, diff --git a/crates/axis-core/src/container_backend.rs b/crates/axis-core/src/container_backend.rs index f33af02..f50983d 100644 --- a/crates/axis-core/src/container_backend.rs +++ b/crates/axis-core/src/container_backend.rs @@ -1156,6 +1156,7 @@ mod tests { deny: Vec::new(), compatibility: Default::default(), workspace_read_only: false, + windows_enumerate_ancestors: false, }, process: ProcessPolicy { max_processes: 0, @@ -1164,6 +1165,7 @@ mod tests { ..Default::default() }, network: NetworkPolicy { + bypass_audit: Default::default(), mode, policies: Vec::new(), }, diff --git a/crates/axis-core/src/mxc_config.rs b/crates/axis-core/src/mxc_config.rs index 8b0afc6..691c815 100644 --- a/crates/axis-core/src/mxc_config.rs +++ b/crates/axis-core/src/mxc_config.rs @@ -32,15 +32,21 @@ pub const MXC_CONFIG_VERSION: &str = "1.0.0"; /// include; AXIS already treats those backends as opt-in. pub const MXC_DEV_CONFIG_VERSION: &str = "1.1.0-alpha"; -/// Contract emitted for Windows MXC backends. -/// -/// The Windows executor stays on an older pinned MXC revision because MXC 1.x -/// BaseContainer cannot launch least-privilege (LPAC) AppContainer children -/// without host DACL mutation, and cannot route ProcessContainer traffic to an -/// unpackaged loopback proxy without opening inbound access. See -/// . +/// Contract emitted for the Windows WSLc, Isolation Session and VM-style config +/// builders. The pinned MXC 1.x executor rejects it; those backends have no +/// launch path yet. pub const MXC_WINDOWS_CONFIG_VERSION: &str = "0.6.0-alpha"; +/// Contract emitted for the Windows ProcessContainer (BaseContainer) backend. +/// +/// MXC 1.x BaseContainer has no least-privilege (LPAC) token option +/// (), so AXIS emits +/// `leastPrivilege: false` and the child token keeps ALL APPLICATION PACKAGES. +/// Strict proxy uses the unpackaged loopback proxy mapping, which requires +/// `ingress.default` and `ingress.hostLoopback` to be allowed while WFP scopes +/// egress to the single proxy endpoint. +pub const MXC_WINDOWS_PROCESS_CONFIG_VERSION: &str = "1.0.0"; + #[derive(Debug, Error, PartialEq, Eq)] pub enum MxcConfigError { #[error("MXC process command line must not be empty")] @@ -154,7 +160,10 @@ pub struct MxcProcessConfigOptions { pub cooperative_proxy_configured_by_mxc: bool, pub resource_limits_enforced_by_axis: bool, pub proxy_url: Option, - pub axis_wfp: Option, + /// Windows only: emit `ui.disable: false` (Win32k allowed). + pub windows_win32k: bool, + /// Windows only: paths the child may query/list without reading content. + pub windows_enumerate_paths: Vec, } #[derive(Debug, Clone, Default, PartialEq, Eq)] @@ -214,6 +223,27 @@ pub struct MxcProcessWireConfig { pub fallback: Option, #[serde(skip_serializing_if = "Option::is_none")] pub seatbelt: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ui: Option, + #[serde( + rename = "runtimeConfig", + default, + skip_serializing_if = "Option::is_none" + )] + pub runtime_config: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct MxcUiConfig { + pub disable: bool, + pub clipboard: String, + pub injection: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct MxcRuntimeConfig { + #[serde(rename = "networkProxy")] + pub network_proxy: String, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -292,6 +322,21 @@ impl MxcNetworkConfig { ingress: MxcNetworkIngress::DENY, } } + + /// Windows ProcessContainer client of an unpackaged loopback proxy. MXC + /// requires ingress and host loopback to be allowed for this mapping; WFP + /// then permits egress only to `runtimeConfig.networkProxy`. + pub const fn windows_loopback_proxy_client() -> Self { + Self { + egress: MxcNetworkEgress { + default: MxcNetworkAction::Deny, + }, + ingress: MxcNetworkIngress { + default: MxcNetworkAction::Allow, + host_loopback: MxcNetworkAction::Allow, + }, + } + } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -399,27 +444,18 @@ pub struct MxcProcessContainerConfig { pub least_privilege: bool, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub capabilities: Vec, - pub resources: MxcProcessResourceConfig, - #[serde(rename = "axisWfp", skip_serializing_if = "Option::is_none")] - pub axis_wfp: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct MxcAxisWfpConfig { - #[serde(rename = "pipeName")] - pub pipe_name: String, - #[serde(rename = "leaseId")] - pub lease_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub filesystem: Option, } #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct MxcProcessResourceConfig { - #[serde(rename = "maxProcesses")] - pub max_processes: u32, - #[serde(rename = "maxMemoryMb")] - pub max_memory_mb: u64, - #[serde(rename = "cpuRatePercent")] - pub cpu_rate_percent: u32, +pub struct MxcProcessContainerFilesystem { + #[serde( + rename = "enumeratePaths", + default, + skip_serializing_if = "Vec::is_empty" + )] + pub enumerate_paths: Vec, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -576,31 +612,50 @@ pub fn build_mxc_process_config( process_container: None, fallback: None, seatbelt: None, + ui: None, + runtime_config: None, }), - ProcessBackendConfigFormat::MxcWindowsProcessContainer => Ok(MxcProcessWireConfig { - version: MXC_WINDOWS_CONFIG_VERSION.into(), - container_id: options.container_id, - containment: MxcContainment::ProcessContainer, - platform: Some(MxcPlatform::Windows), - process, - filesystem, - network: legacy_network(network_policy, options.proxy_url.clone()), - lifecycle, - process_container: Some(MxcProcessContainerConfig { - least_privilege: true, - capabilities: Vec::new(), - resources: MxcProcessResourceConfig { - max_processes: spec.resources.max_processes, - max_memory_mb: spec.resources.max_memory_mb, - cpu_rate_percent: spec.resources.cpu_rate_percent, - }, - axis_wfp: options.axis_wfp, - }), - fallback: Some(MxcFallbackConfig { - allow_dacl_mutation: false, - }), - seatbelt: None, - }), + ProcessBackendConfigFormat::MxcWindowsProcessContainer => { + let (network, runtime_config) = match (spec.network.mode, options.proxy_url.clone()) { + (ProcessBackendNetworkMode::StrictProxy, Some(url)) => ( + MxcNetworkConfig::windows_loopback_proxy_client(), + Some(MxcRuntimeConfig { network_proxy: url }), + ), + (ProcessBackendNetworkMode::StrictProxy, None) => { + return Err(MxcConfigError::StrictProxyRequiresAxisLayer); + } + _ => (network_policy.directional(), None), + }; + Ok(MxcProcessWireConfig { + version: MXC_WINDOWS_PROCESS_CONFIG_VERSION.into(), + container_id: options.container_id, + containment: MxcContainment::ProcessContainer, + platform: None, + process, + filesystem, + network: MxcNetworkSection::Directional(network), + lifecycle, + process_container: Some(MxcProcessContainerConfig { + least_privilege: false, + capabilities: Vec::new(), + filesystem: (!options.windows_enumerate_paths.is_empty()).then(|| { + MxcProcessContainerFilesystem { + enumerate_paths: options.windows_enumerate_paths.clone(), + } + }), + }), + fallback: Some(MxcFallbackConfig { + allow_dacl_mutation: false, + }), + seatbelt: None, + ui: options.windows_win32k.then(|| MxcUiConfig { + disable: false, + clipboard: "none".into(), + injection: false, + }), + runtime_config, + }) + } ProcessBackendConfigFormat::MxcMacosSeatbeltProfile => Ok(MxcProcessWireConfig { version: MXC_CONFIG_VERSION.into(), container_id: options.container_id, @@ -613,6 +668,8 @@ pub fn build_mxc_process_config( process_container: None, fallback: None, seatbelt: Some(MxcSeatbeltConfig::default()), + ui: None, + runtime_config: None, }), ProcessBackendConfigFormat::AxisNativeLinux | ProcessBackendConfigFormat::AxisNativeMacosSeatbeltProfile @@ -791,14 +848,7 @@ fn validate_process_resources( spec: &ProcessBackendExecutionSpec, options: &MxcProcessConfigOptions, ) -> Result<(), MxcConfigError> { - let emitted_to_windows_processcontainer = matches!( - spec.config_format, - ProcessBackendConfigFormat::MxcWindowsProcessContainer - ); - if process_resources_requested(spec) - && !emitted_to_windows_processcontainer - && !options.resource_limits_enforced_by_axis - { + if process_resources_requested(spec) && !options.resource_limits_enforced_by_axis { return Err(MxcConfigError::ProcessResourceLimitsRequireAxisLayer); } Ok(()) @@ -1323,27 +1373,54 @@ mod tests { .unwrap(); let json = serde_json::to_value(&config).unwrap(); - assert_eq!(json["version"], MXC_WINDOWS_CONFIG_VERSION); + assert_eq!(json["version"], MXC_WINDOWS_PROCESS_CONFIG_VERSION); assert_eq!(json["containment"], "processcontainer"); - assert_eq!(json["platform"], "windows"); - assert_eq!(json["network"]["defaultPolicy"], "allow"); - assert_eq!(json["processContainer"]["leastPrivilege"], true); + assert!(json.get("platform").is_none()); + assert!(json["network"].get("defaultPolicy").is_none()); + assert_eq!(json["processContainer"]["leastPrivilege"], false); assert!(json["processContainer"].get("capabilities").is_none()); - assert_eq!( - json["processContainer"]["resources"], - serde_json::json!({ - "maxProcesses": 0, - "maxMemoryMb": 0, - "cpuRatePercent": 0 - }) - ); + assert!(json["processContainer"].get("resources").is_none()); + assert!(json["processContainer"].get("filesystem").is_none()); + assert!(json["processContainer"].get("axisWfp").is_none()); assert_eq!(json["fallback"]["allowDaclMutation"], false); + assert!(json.get("ui").is_none()); + assert!(json.get("runtimeConfig").is_none()); assert!(json.get("experimental").is_none()); } #[test] - fn windows_strict_proxy_serializes_axis_wfp_pre_resume_contract() { + fn windows_win32k_and_enumerate_paths_serialize_for_mxc_1() { + let spec = process_execution_spec( + BackendCapabilityMapId::MxcWindowsProcessContainer, + NetworkMode::Block, + ) + .unwrap(); + let config = build_mxc_process_config( + "agent --version", + &spec, + MxcProcessConfigOptions { + container_id: Some("axis-windows".into()), + windows_win32k: true, + windows_enumerate_paths: vec![r"C:\Users".into(), r"C:\".into()], + ..Default::default() + }, + ) + .unwrap(); + let json = serde_json::to_value(config).unwrap(); + + assert_eq!( + json["ui"], + serde_json::json!({ "disable": false, "clipboard": "none", "injection": false }) + ); + assert_eq!( + json["processContainer"]["filesystem"]["enumeratePaths"], + serde_json::json!([r"C:\Users", r"C:\"]) + ); + } + + #[test] + fn windows_strict_proxy_is_a_loopback_only_client_of_the_axis_proxy() { let spec = process_execution_spec( BackendCapabilityMapId::MxcWindowsProcessContainer, NetworkMode::Proxy, @@ -1356,27 +1433,44 @@ mod tests { container_id: Some("axis-windows-proxy".into()), strict_proxy_enforced_by_axis: true, proxy_url: Some("http://127.0.0.1:31280".into()), - axis_wfp: Some(MxcAxisWfpConfig { - pipe_name: r"\\.\pipe\axis-wfp-broker-v1".into(), - lease_id: "d5406689-f871-42e0-ae5b-eb4b5720ad2a".into(), - }), ..Default::default() }, ) .unwrap(); let json = serde_json::to_value(config).unwrap(); - assert_eq!(json["version"], MXC_WINDOWS_CONFIG_VERSION); - - assert_eq!(json["network"]["defaultPolicy"], "allow"); - assert_eq!(json["network"]["proxy"]["url"], "http://127.0.0.1:31280"); + assert_eq!(json["version"], MXC_WINDOWS_PROCESS_CONFIG_VERSION); assert_eq!( - json["processContainer"]["axisWfp"], + json["network"], serde_json::json!({ - "pipeName": r"\\.\pipe\axis-wfp-broker-v1", - "leaseId": "d5406689-f871-42e0-ae5b-eb4b5720ad2a" + "egress": { "default": "deny" }, + "ingress": { "default": "allow", "hostLoopback": "allow" } }) ); + assert_eq!( + json["runtimeConfig"], + serde_json::json!({ "networkProxy": "http://127.0.0.1:31280" }) + ); + assert!(json["processContainer"].get("axisWfp").is_none()); + } + + #[test] + fn windows_strict_proxy_without_an_endpoint_is_refused() { + let spec = process_execution_spec( + BackendCapabilityMapId::MxcWindowsProcessContainer, + NetworkMode::Proxy, + ) + .unwrap(); + let err = build_mxc_process_config( + "agent --version", + &spec, + MxcProcessConfigOptions { + strict_proxy_enforced_by_axis: true, + ..Default::default() + }, + ) + .unwrap_err(); + assert!(matches!(err, MxcConfigError::StrictProxyRequiresAxisLayer)); } #[test] @@ -1702,12 +1796,10 @@ mod tests { let json = serde_json::to_value(config).unwrap(); assert_eq!( - json["network"], - serde_json::json!({ - "defaultPolicy": "allow", - "proxy": { "url": "http://127.0.0.1:31280" } - }) + json["runtimeConfig"]["networkProxy"], + "http://127.0.0.1:31280" ); + assert_eq!(json["network"]["egress"]["default"], "deny"); } #[test] @@ -1844,7 +1936,7 @@ mod tests { } #[test] - fn windows_process_resource_limits_are_emitted_for_mxc_inner_job() { + fn windows_process_resource_limits_stay_out_of_the_mxc_1_config() { let mut spec = process_execution_spec( BackendCapabilityMapId::MxcWindowsProcessContainer, NetworkMode::Allow, @@ -1854,20 +1946,30 @@ mod tests { spec.resources.max_memory_mb = 1024; spec.resources.cpu_rate_percent = 50; + let err = build_mxc_process_config( + "agent --version", + &spec, + MxcProcessConfigOptions { + container_id: Some("axis-windows".into()), + ..Default::default() + }, + ) + .unwrap_err(); + assert_eq!(err, MxcConfigError::ProcessResourceLimitsRequireAxisLayer); + let config = build_mxc_process_config( "agent --version", &spec, MxcProcessConfigOptions { container_id: Some("axis-windows".into()), - resource_limits_enforced_by_axis: false, + resource_limits_enforced_by_axis: true, ..Default::default() }, ) .unwrap(); - let resources = &config.process_container.unwrap().resources; - assert_eq!(resources.max_processes, 32); - assert_eq!(resources.max_memory_mb, 1024); - assert_eq!(resources.cpu_rate_percent, 50); + let json = serde_json::to_value(&config).unwrap(); + assert!(json["processContainer"].get("resources").is_none()); + assert_eq!(json["processContainer"]["leastPrivilege"], false); } #[test] @@ -2543,7 +2645,7 @@ mod tests { id, process_launch(), &present_runtime_for_backend(id), - &PlannerOptions::new(), + &PlannerOptions::for_policy(&policy), ) } @@ -2569,6 +2671,7 @@ mod tests { deny: vec!["/home/user/.ssh".into()], compatibility: Default::default(), workspace_read_only: false, + windows_enumerate_ancestors: false, }, process: ProcessPolicy { max_processes: 0, @@ -2577,6 +2680,7 @@ mod tests { ..Default::default() }, network: NetworkPolicy { + bypass_audit: Default::default(), mode, policies: Vec::new(), }, @@ -2610,6 +2714,7 @@ mod tests { deny: Vec::new(), compatibility: Default::default(), workspace_read_only: false, + windows_enumerate_ancestors: false, }, process: ProcessPolicy { max_processes: 0, @@ -2618,6 +2723,7 @@ mod tests { ..Default::default() }, network: NetworkPolicy { + bypass_audit: Default::default(), mode, policies: Vec::new(), }, @@ -2639,6 +2745,7 @@ mod tests { deny: Vec::new(), compatibility: Default::default(), workspace_read_only: false, + windows_enumerate_ancestors: false, }, process: ProcessPolicy { max_processes: 0, @@ -2647,6 +2754,7 @@ mod tests { ..Default::default() }, network: NetworkPolicy { + bypass_audit: Default::default(), mode, policies: Vec::new(), }, @@ -2665,6 +2773,7 @@ mod tests { deny: Vec::new(), compatibility: Default::default(), workspace_read_only: false, + windows_enumerate_ancestors: false, }; policy } diff --git a/crates/axis-core/src/policy.rs b/crates/axis-core/src/policy.rs index 9b36aa4..16f8980 100644 --- a/crates/axis-core/src/policy.rs +++ b/crates/axis-core/src/policy.rs @@ -493,6 +493,14 @@ pub struct FilesystemPolicy { #[serde(default)] pub workspace_read_only: bool, + /// Windows MXC 1.x only: let the sandbox enumerate every ancestor of a + /// grant, which path canonicalization (Node's JS `realpath`) needs. MXC + /// applies enumeration to the whole subtree, so an ancestor such as `C:\` + /// exposes the names, sizes and times of every file below it that NTFS + /// does not separately deny. Contents stay unreadable. Off by default. + #[serde(default)] + pub windows_enumerate_ancestors: bool, + #[serde(default = "default_compatibility")] pub compatibility: Compatibility, } @@ -545,6 +553,14 @@ pub struct ProcessPolicy { /// Maximum wall-clock time in seconds before auto-destroy. None = no timeout. #[serde(default)] pub timeout_sec: Option, + + /// Windows only: allow Win32k system calls inside the BaseContainer. + /// USER32 initialization needs them, so PowerShell, Git for Windows, + /// `whoami` and most GUI-linked console tools fail with + /// STATUS_DLL_INIT_FAILED without this. Clipboard access and synthetic + /// input injection stay denied. + #[serde(default)] + pub windows_win32k: bool, } impl Default for ProcessPolicy { @@ -558,6 +574,7 @@ impl Default for ProcessPolicy { identity: ProcessIdentity::default(), child_processes: ChildProcessPolicy::default(), timeout_sec: None, + windows_win32k: false, } } } @@ -617,6 +634,14 @@ pub struct NetworkPolicy { #[serde(default)] pub policies: Vec, + + /// Proxy mode on a backend that blocks bypass attempts but cannot record + /// them (Windows ProcessContainer). `best_effort` launches and warns that + /// no bypass audit trail is kept; `hard_requirement` refuses to launch. + /// Backends that record bypass attempts, or cannot block them, are not + /// affected. + #[serde(default)] + pub bypass_audit: Compatibility, } impl Default for NetworkPolicy { @@ -624,6 +649,7 @@ impl Default for NetworkPolicy { Self { mode: default_network_mode(), policies: Vec::new(), + bypass_audit: Compatibility::default(), } } } diff --git a/crates/axis-core/src/process_backend.rs b/crates/axis-core/src/process_backend.rs index 3cafd3e..1959ead 100644 --- a/crates/axis-core/src/process_backend.rs +++ b/crates/axis-core/src/process_backend.rs @@ -136,6 +136,10 @@ pub struct ProcessBackendExecutionSpec { pub capture_output: bool, #[serde(default)] pub timeout_ms: Option, + /// Weaker behavior the plan accepted, as `requirement: reason`. Adapters + /// report these to the user before launch. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub accepted_weaker: Vec, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -346,6 +350,12 @@ pub fn build_process_backend_execution_spec( .timeout_sec .or(policy.process.timeout_sec) .map(|seconds| seconds.saturating_mul(1000)), + accepted_weaker: plan + .policy_plan + .accepted_weaker_reasons() + .iter() + .map(|reason| format!("{}: {}", reason.requirement, reason.reason)) + .collect(), }) } @@ -699,7 +709,7 @@ mod tests { } #[test] - fn process_execution_spec_for_windows_mxc_accepts_proxy_with_wfp_dependencies() { + fn process_execution_spec_for_windows_mxc_accepts_strict_proxy() { let runtime = present_runtime_for_backend(BackendCapabilityMapId::MxcWindowsProcessContainer); let mut policy = process_policy(NetworkMode::Proxy); @@ -712,7 +722,7 @@ mod tests { BackendCapabilityMapId::MxcWindowsProcessContainer, launch_options(), &runtime, - &PlannerOptions::new(), + &PlannerOptions::for_policy(&policy), ) .unwrap(); @@ -1075,7 +1085,7 @@ mod tests { } #[test] - fn windows_processcontainer_requires_wfp_for_proxy_and_bypass_evidence() { + fn windows_processcontainer_strict_proxy_needs_only_mxc_dependencies() { let runtime = RuntimeProbeSnapshot::new() .with_dependency(host_dependency::MXC_EXECUTOR, DependencyState::Present) .with_dependency( @@ -1091,41 +1101,106 @@ mod tests { &policy, BackendCapabilityMapId::MxcWindowsProcessContainer, &runtime, - &PlannerOptions::new(), + &PlannerOptions::for_policy(&policy), ) .unwrap(); - assert!(matches!( - plan.policy_plan.outcome, - BackendPlanOutcome::ExactWithHostDependency { .. } - )); - assert!(!plan.spawn_allowed()); - let error = plan.pre_spawn_error().unwrap(); - assert!(error.contains(host_dependency::WINDOWS_WFP_BROKER)); - + assert!(plan.spawn_allowed(), "{:?}", plan.pre_spawn_error()); let strict_proxy = plan .policy_plan .decisions .iter() .find(|decision| decision.requirement == "network.strict_proxy") .unwrap(); - assert!(matches!( + assert_eq!( strict_proxy.support, - CapabilitySupport::ExactWithHostDependency { .. } - )); + CapabilitySupport::with_dependencies([ + host_dependency::MXC_EXECUTOR, + host_dependency::WINDOWS_PROCESS_CONTAINER, + ]) + ); + } - let runtime = runtime.with_dependency( - host_dependency::WINDOWS_WFP_BROKER, - DependencyState::Present, + #[test] + fn windows_proxy_bypass_audit_warns_by_default_and_refuses_when_required() { + let mut policy = process_policy(NetworkMode::Proxy); + policy.filesystem.deny.clear(); + let plan = |policy: &Policy, runtime: &RuntimeProbeSnapshot| { + plan_process_backend_policy( + policy, + BackendCapabilityMapId::MxcWindowsProcessContainer, + runtime, + &PlannerOptions::for_policy(policy), + ) + .unwrap() + .policy_plan + }; + let present = + present_runtime_for_backend(BackendCapabilityMapId::MxcWindowsProcessContainer); + + let default = plan(&policy, &present); + assert!(default.spawn_allowed(), "{:?}", default.pre_spawn_error()); + assert_eq!( + default + .accepted_weaker_reasons() + .iter() + .map(|reason| reason.requirement) + .collect::>(), + [crate::capability::BYPASS_EVIDENCE_REQUIREMENT] ); - let plan = plan_process_backend_policy( + + let without_executor = plan( &policy, - BackendCapabilityMapId::MxcWindowsProcessContainer, - &runtime, - &PlannerOptions::new(), - ) - .unwrap(); - assert!(plan.spawn_allowed(), "{:?}", plan.pre_spawn_error()); + &present + .clone() + .with_dependency(host_dependency::MXC_EXECUTOR, DependencyState::Missing), + ); + assert!(!without_executor.spawn_allowed()); + assert!( + without_executor + .pre_spawn_error() + .unwrap() + .contains(host_dependency::MXC_EXECUTOR) + ); + + policy.network.bypass_audit = crate::policy::Compatibility::HardRequirement; + let required = plan(&policy, &present); + assert!(!required.spawn_allowed()); + assert!( + required + .pre_spawn_error() + .unwrap() + .contains(crate::capability::BYPASS_EVIDENCE_REQUIREMENT) + ); + } + + #[test] + fn linux_proxy_backends_ignore_bypass_audit_setting() { + for id in [ + BackendCapabilityMapId::AxisNativeLinux, + BackendCapabilityMapId::MxcLinuxBubblewrap, + ] { + let runtime = present_runtime_for_backend(id); + let mut outcomes = Vec::new(); + for setting in [ + crate::policy::Compatibility::BestEffort, + crate::policy::Compatibility::HardRequirement, + ] { + let mut policy = process_policy(NetworkMode::Proxy); + policy.network.bypass_audit = setting; + let plan = plan_process_backend_policy( + &policy, + id, + &runtime, + &PlannerOptions::for_policy(&policy), + ) + .unwrap() + .policy_plan; + assert!(plan.accepted_weaker_reasons().is_empty(), "{id:?}"); + outcomes.push(plan.outcome); + } + assert_eq!(outcomes[0], outcomes[1], "{id:?}"); + } } #[test] @@ -1264,6 +1339,7 @@ mod tests { deny: vec!["~/.ssh".into()], compatibility: Default::default(), workspace_read_only: false, + windows_enumerate_ancestors: false, }, process: ProcessPolicy { max_processes: 0, @@ -1274,8 +1350,10 @@ mod tests { identity: Default::default(), child_processes: Default::default(), timeout_sec: None, + windows_win32k: false, }, network: NetworkPolicy { + bypass_audit: Default::default(), mode, policies: Vec::new(), }, diff --git a/crates/axis-core/src/vm_backend.rs b/crates/axis-core/src/vm_backend.rs index 6e9ca91..bdb8bad 100644 --- a/crates/axis-core/src/vm_backend.rs +++ b/crates/axis-core/src/vm_backend.rs @@ -1501,6 +1501,7 @@ mod tests { deny: Vec::new(), compatibility: Default::default(), workspace_read_only: false, + windows_enumerate_ancestors: false, }, process: ProcessPolicy { max_processes: 0, @@ -1511,8 +1512,10 @@ mod tests { identity: Default::default(), child_processes: Default::default(), timeout_sec: None, + windows_win32k: false, }, network: NetworkPolicy { + bypass_audit: Default::default(), mode, policies: Vec::new(), }, @@ -1531,6 +1534,7 @@ mod tests { deny: Vec::new(), compatibility: Default::default(), workspace_read_only: false, + windows_enumerate_ancestors: false, }; policy } diff --git a/crates/axis-daemon/src/sandbox_mgr.rs b/crates/axis-daemon/src/sandbox_mgr.rs index f439779..05c38b6 100644 --- a/crates/axis-daemon/src/sandbox_mgr.rs +++ b/crates/axis-daemon/src/sandbox_mgr.rs @@ -2225,6 +2225,7 @@ mod tests { filesystem: FilesystemPolicy::default(), process: ProcessPolicy::default(), network: NetworkPolicy { + bypass_audit: Default::default(), mode: network_mode, policies: Vec::new(), }, diff --git a/crates/axis-sandbox/Cargo.toml b/crates/axis-sandbox/Cargo.toml index 0ce2220..6b17339 100644 --- a/crates/axis-sandbox/Cargo.toml +++ b/crates/axis-sandbox/Cargo.toml @@ -24,15 +24,11 @@ libc = { workspace = true } windows = { version = "0.62", features = [ "Win32_Foundation", "Win32_Globalization", - "Win32_NetworkManagement_WindowsFilteringPlatform", "Win32_Security", "Win32_Security_Authorization", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", - "Win32_System_Pipes", - "Win32_System_Rpc", - "Win32_System_Services", "Win32_System_Threading", "Win32_System_Memory", "Win32_Storage_FileSystem", diff --git a/crates/axis-sandbox/src/bin/axis-wfp-broker.rs b/crates/axis-sandbox/src/bin/axis-wfp-broker.rs deleted file mode 100644 index 4e48390..0000000 --- a/crates/axis-sandbox/src/bin/axis-wfp-broker.rs +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright 2026 Advanced Micro Devices, Inc. -// SPDX-License-Identifier: Apache-2.0 - -#[cfg(not(target_os = "windows"))] -fn main() { - eprintln!("axis-wfp-broker is available only on Windows"); - std::process::exit(2); -} - -#[cfg(target_os = "windows")] -fn main() { - if let Err(error) = windows_main() { - eprintln!("axis-wfp-broker: {error}"); - std::process::exit(1); - } -} - -#[cfg(target_os = "windows")] -fn windows_main() -> Result<(), String> { - use axis_sandbox::windows::wfp::{BrokerConfig, serve}; - use std::sync::Arc; - use std::sync::atomic::AtomicBool; - - let mut args = std::env::args_os(); - let _program = args.next(); - let command = args - .next() - .and_then(|value| value.into_string().ok()) - .unwrap_or_else(|| "run".into()); - if args.next().is_some() { - return Err("usage: axis-wfp-broker [run|service|probe]".into()); - } - - match command.as_str() { - "run" => serve(BrokerConfig::default(), Arc::new(AtomicBool::new(false))), - "service" => service::dispatch(), - "probe" => probe(), - _ => Err("usage: axis-wfp-broker [run|service|probe]".into()), - } -} - -#[cfg(target_os = "windows")] -fn probe() -> Result<(), String> { - use windows::Win32::Foundation::HANDLE; - use windows::Win32::NetworkManagement::WindowsFilteringPlatform::{ - FWPM_SESSION_FLAG_DYNAMIC, FWPM_SESSION0, FwpmEngineClose0, FwpmEngineOpen0, - }; - use windows::Win32::System::Rpc::RPC_C_AUTHN_WINNT; - use windows::core::PCWSTR; - - let mut engine = HANDLE::default(); - let session = FWPM_SESSION0 { - flags: FWPM_SESSION_FLAG_DYNAMIC, - txnWaitTimeoutInMSec: 1_000, - ..Default::default() - }; - let status = unsafe { - FwpmEngineOpen0( - PCWSTR::null(), - RPC_C_AUTHN_WINNT, - None, - Some(&session), - &mut engine, - ) - }; - if status != 0 { - return Err(format!( - "Windows Filtering Platform engine unavailable: 0x{status:08X}" - )); - } - unsafe { - let _ = FwpmEngineClose0(engine); - } - println!("AXIS_WFP_BROKER_PROBE_OK"); - Ok(()) -} - -#[cfg(target_os = "windows")] -mod service { - use axis_sandbox::windows::wfp::{BrokerConfig, DEFAULT_PIPE_NAME, serve}; - use std::fs::OpenOptions; - use std::sync::atomic::{AtomicBool, Ordering}; - use std::sync::{Arc, OnceLock}; - use windows::Win32::System::Services::{ - RegisterServiceCtrlHandlerExW, SERVICE_ACCEPT_SHUTDOWN, SERVICE_ACCEPT_STOP, - SERVICE_CONTROL_SHUTDOWN, SERVICE_CONTROL_STOP, SERVICE_RUNNING, SERVICE_START_PENDING, - SERVICE_STATUS, SERVICE_STATUS_HANDLE, SERVICE_STOP_PENDING, SERVICE_STOPPED, - SERVICE_TABLE_ENTRYW, SERVICE_WIN32_OWN_PROCESS, SetServiceStatus, - StartServiceCtrlDispatcherW, - }; - use windows::core::{PWSTR, w}; - - const SERVICE_NAME: windows::core::PCWSTR = w!("AxisWfpBroker"); - static STOP: OnceLock> = OnceLock::new(); - static STATUS: OnceLock = OnceLock::new(); - - pub(super) fn dispatch() -> Result<(), String> { - let mut name = "AxisWfpBroker\0".encode_utf16().collect::>(); - let entries = [ - SERVICE_TABLE_ENTRYW { - lpServiceName: PWSTR(name.as_mut_ptr()), - lpServiceProc: Some(service_main), - }, - SERVICE_TABLE_ENTRYW::default(), - ]; - unsafe { StartServiceCtrlDispatcherW(entries.as_ptr()) } - .map_err(|e| format!("StartServiceCtrlDispatcherW failed: {e}")) - } - - unsafe extern "system" fn service_main(_argc: u32, _argv: *mut PWSTR) { - let handle = match unsafe { - RegisterServiceCtrlHandlerExW(SERVICE_NAME, Some(control_handler), None) - } { - Ok(handle) => handle, - Err(_) => return, - }; - let _ = STATUS.set(handle.0 as usize); - report(SERVICE_START_PENDING, 0, 10_000); - - let stop = Arc::new(AtomicBool::new(false)); - let _ = STOP.set(stop.clone()); - report( - SERVICE_RUNNING, - SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN, - 0, - ); - let exit_code = match serve(BrokerConfig::default(), stop) { - Ok(()) => 0, - Err(_) => 1, - }; - report(SERVICE_STOPPED, 0, 0); - if exit_code != 0 { - // SCM observes the nonzero service-specific result in the final - // status reported below on a future extension; for now the broker - // audit log carries the actionable error without exposing secrets. - } - } - - unsafe extern "system" fn control_handler( - control: u32, - _event_type: u32, - _event_data: *mut core::ffi::c_void, - _context: *mut core::ffi::c_void, - ) -> u32 { - if control == SERVICE_CONTROL_STOP || control == SERVICE_CONTROL_SHUTDOWN { - report(SERVICE_STOP_PENDING, 0, 5_000); - if let Some(stop) = STOP.get() { - stop.store(true, Ordering::Release); - } - // Wake a blocking ConnectNamedPipe. The server loop observes STOP - // before creating the next instance; this connection is rejected - // in its worker and disappears with process shutdown. - let _ = OpenOptions::new() - .read(true) - .write(true) - .open(DEFAULT_PIPE_NAME); - } - 0 - } - - fn report( - state: windows::Win32::System::Services::SERVICE_STATUS_CURRENT_STATE, - accepted: u32, - wait_hint: u32, - ) { - let Some(raw) = STATUS.get().copied() else { - return; - }; - let status = SERVICE_STATUS { - dwServiceType: SERVICE_WIN32_OWN_PROCESS, - dwCurrentState: state, - dwControlsAccepted: accepted, - dwWaitHint: wait_hint, - ..Default::default() - }; - unsafe { - let _ = SetServiceStatus(SERVICE_STATUS_HANDLE(raw as *mut _), &status); - } - } -} diff --git a/crates/axis-sandbox/src/linux/mod.rs b/crates/axis-sandbox/src/linux/mod.rs index 44cedc5..de369bb 100644 --- a/crates/axis-sandbox/src/linux/mod.rs +++ b/crates/axis-sandbox/src/linux/mod.rs @@ -4151,6 +4151,7 @@ mod tests { filesystem: FilesystemPolicy::default(), process: ProcessPolicy::default(), network: NetworkPolicy { + bypass_audit: Default::default(), mode: NetworkMode::Allow, policies: Vec::new(), }, @@ -4164,6 +4165,7 @@ mod tests { fn binary_restricted_proxy_policy() -> Policy { let mut policy = test_policy(); policy.network = NetworkPolicy { + bypass_audit: Default::default(), mode: NetworkMode::Proxy, policies: vec![EndpointPolicy { name: "api".into(), diff --git a/crates/axis-sandbox/src/linux/mxc.rs b/crates/axis-sandbox/src/linux/mxc.rs index 25b1827..2a95edb 100644 --- a/crates/axis-sandbox/src/linux/mxc.rs +++ b/crates/axis-sandbox/src/linux/mxc.rs @@ -3900,6 +3900,7 @@ mod tests { filesystem: FilesystemPolicy::default(), process: ProcessPolicy::default(), network: NetworkPolicy { + bypass_audit: Default::default(), mode: network_mode, policies: Vec::new(), }, @@ -5187,6 +5188,7 @@ mod tests { ], compatibility: Compatibility::BestEffort, workspace_read_only: false, + windows_enumerate_ancestors: false, }; let spec = translate_sandbox_config(&config(policy, workspace.clone())).unwrap(); @@ -5440,6 +5442,7 @@ mod tests { deny: vec![denied.to_string_lossy().into_owned()], compatibility: Compatibility::HardRequirement, workspace_read_only: false, + windows_enumerate_ancestors: false, }; let err = MxcExecutionSpec::from_sandbox_config(&config(policy, workspace)).unwrap_err(); @@ -5492,6 +5495,7 @@ mod tests { deny: vec![denied.to_string_lossy().into_owned()], compatibility: Compatibility::HardRequirement, workspace_read_only: false, + windows_enumerate_ancestors: false, }; let err = MxcExecutionSpec::from_sandbox_config(&config(policy, workspace)).unwrap_err(); diff --git a/crates/axis-sandbox/src/linux/resources.rs b/crates/axis-sandbox/src/linux/resources.rs index 8487547..52b2678 100644 --- a/crates/axis-sandbox/src/linux/resources.rs +++ b/crates/axis-sandbox/src/linux/resources.rs @@ -357,6 +357,7 @@ mod tests { identity: Default::default(), child_processes: Default::default(), timeout_sec: None, + windows_win32k: false, } } diff --git a/crates/axis-sandbox/src/linux/strategy.rs b/crates/axis-sandbox/src/linux/strategy.rs index d6a7b19..d26e8d6 100644 --- a/crates/axis-sandbox/src/linux/strategy.rs +++ b/crates/axis-sandbox/src/linux/strategy.rs @@ -707,6 +707,7 @@ mod tests { filesystem: FilesystemPolicy::default(), process: ProcessPolicy::default(), network: NetworkPolicy { + bypass_audit: Default::default(), mode, policies: Vec::new(), }, diff --git a/crates/axis-sandbox/src/linux/vxn.rs b/crates/axis-sandbox/src/linux/vxn.rs index b4e3605..0fb7d01 100644 --- a/crates/axis-sandbox/src/linux/vxn.rs +++ b/crates/axis-sandbox/src/linux/vxn.rs @@ -646,6 +646,7 @@ mod tests { filesystem: FilesystemPolicy::default(), process, network: NetworkPolicy { + bypass_audit: Default::default(), mode, policies: Vec::new(), }, diff --git a/crates/axis-sandbox/src/sandbox.rs b/crates/axis-sandbox/src/sandbox.rs index 3d970a1..f459f2d 100644 --- a/crates/axis-sandbox/src/sandbox.rs +++ b/crates/axis-sandbox/src/sandbox.rs @@ -144,6 +144,12 @@ fn ensure_daemon_token_hidden(config: &SandboxConfig) -> Result<(), SandboxError } } +/// A Unix-only grant (`/usr`) on Windows. The Windows backend skips it, or +/// refuses it under `hard_requirement`, so it never grants anything there. +fn is_ignored_unix_path(path: &str) -> bool { + cfg!(target_os = "windows") && path.starts_with('/') +} + /// The first of the workspace and the policy's grants that contains or lies /// inside `token_dir`. A grant that cannot be resolved counts as covering. #[cfg(not(target_os = "macos"))] @@ -168,7 +174,7 @@ fn grant_covering( .chain(&filesystem.read_write) .find(|grant| { // {tmpdir} expands to a fresh per-sandbox directory. - if grant.contains("{tmpdir}") { + if grant.contains("{tmpdir}") || is_ignored_unix_path(grant) { return false; } let mut grant = grant.replace("{workspace}", &workspace); @@ -637,6 +643,9 @@ fn reject_unmanaged_home_grants( guard: &ManagedHomeGrantGuard<'_>, ) -> Result<(), String> { for path in paths { + if is_ignored_unix_path(path) { + continue; + } let expanded = expand_managed_home_guard_path(path, guard.raw_workspace, guard.lexical_home)?; if paths_overlap(&expanded, guard.private_setup) { @@ -1128,6 +1137,9 @@ mod tests { ), None ); + // Skipped on Windows, where the backend ignores it; elsewhere it is + // a real path outside the token dir. + assert_eq!(covering(&["/usr".into()], &[], &workspace), None); for unresolvable in ["relative/path", "~other/dir"] { assert_eq!( covering(&[unresolvable.into()], &[], &workspace), @@ -1178,6 +1190,7 @@ mod tests { filesystem: FilesystemPolicy::default(), process: ProcessPolicy::default(), network: NetworkPolicy { + bypass_audit: Default::default(), mode: NetworkMode::Allow, policies: Vec::new(), }, @@ -1310,6 +1323,43 @@ mod tests { }); } + #[cfg(target_os = "windows")] + #[test] + fn windows_mxc_managed_home_accepts_bundled_policies_with_unix_paths() { + let home = tempfile::tempdir().unwrap(); + let workspace = tempfile::tempdir().unwrap(); + + with_home(home.path(), || { + for (name, yaml) in [ + ("minimal", include_str!("../../../policies/minimal.yaml")), + ( + "coding-agent", + include_str!("../../../policies/coding-agent.yaml"), + ), + ] { + let mut config = test_config(); + config.policy = Policy::from_yaml(yaml).unwrap(); + config.workspace_dir = workspace.path().to_path_buf(); + assert!( + config + .policy + .filesystem + .read_only + .iter() + .any(|path| path.starts_with('/')), + "{name} no longer has a Unix-only path to test" + ); + + prepare_managed_agent_workspace( + &mut config, + true, + PlatformBackendSelection::WindowsMxc, + ) + .unwrap_or_else(|err| panic!("{name}: {err}")); + } + }); + } + #[cfg(target_os = "linux")] #[test] fn process_runtime_provider_selects_linux_backend() { diff --git a/crates/axis-sandbox/src/windows/job_object.rs b/crates/axis-sandbox/src/windows/job_object.rs index 650a59d..9b4264f 100644 --- a/crates/axis-sandbox/src/windows/job_object.rs +++ b/crates/axis-sandbox/src/windows/job_object.rs @@ -13,7 +13,6 @@ use windows::Win32::System::Threading::{ ALL_PROCESSOR_GROUPS, GetActiveProcessorCount, OpenProcess, }; use windows::Win32::System::Threading::{PROCESS_SET_QUOTA, PROCESS_TERMINATE}; -use windows::core::HSTRING; /// Wrapper around a Win32 Job Object handle. pub struct JobHandle { @@ -33,32 +32,30 @@ impl Drop for JobHandle { } } -/// Create a Job Object with resource limits. -pub fn create_job_object( - name: &str, +/// Kill-on-close Job Object that also carries the sandbox resource limits. +/// Breakaway is not permitted, so every descendant (including the MXC +/// BaseContainer child) is accounted here. A zero value leaves that limit off. +/// The job is unnamed: `CreateJobObjectW` opens an existing job of the same +/// name, which another process could create and hold open. +pub fn create_limited_kill_on_close_job( max_processes: u32, max_memory_mb: u64, cpu_rate_percent: u32, ) -> Result { - let job_name = HSTRING::from(name); - - let handle = unsafe { CreateJobObjectW(None, &job_name) } + let handle = unsafe { CreateJobObjectW(None, None) } .map_err(|e| format!("CreateJobObjectW failed: {e}"))?; - - // Set extended limit information. let job = JobHandle { handle }; let mut ext_info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default(); + let mut flags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; if max_processes > 0 { + flags |= JOB_OBJECT_LIMIT_ACTIVE_PROCESS; ext_info.BasicLimitInformation.ActiveProcessLimit = max_processes; } - ext_info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_ACTIVE_PROCESS - | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE - // NOTE: DIE_ON_UNHANDLED_EXCEPTION removed — V8/Node.js uses SEH for - // stack guards and GC, so this flag kills Node-based agents immediately. - // | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION - | JOB_OBJECT_LIMIT_PROCESS_MEMORY; - ext_info.ProcessMemoryLimit = (max_memory_mb * 1024 * 1024) as usize; - + if max_memory_mb > 0 { + flags |= JOB_OBJECT_LIMIT_JOB_MEMORY; + ext_info.JobMemoryLimit = (max_memory_mb * 1024 * 1024) as usize; + } + ext_info.BasicLimitInformation.LimitFlags = flags; unsafe { SetInformationJobObject( job.handle, @@ -68,19 +65,15 @@ pub fn create_job_object( ) } .map_err(|e| format!("SetInformationJobObject (limits) failed: {e}"))?; - - // Set CPU rate control. if cpu_rate_percent > 0 { let mut cpu_info = JOBOBJECT_CPU_RATE_CONTROL_INFORMATION { ControlFlags: JOB_OBJECT_CPU_RATE_CONTROL_ENABLE | JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP, ..Default::default() }; - // CpuRate is in hundredths of a percent (100 = 1%, 10000 = 100%). let processors = unsafe { GetActiveProcessorCount(ALL_PROCESSOR_GROUPS) }.max(1); cpu_info.Anonymous.CpuRate = (cpu_rate_percent * 100) .div_ceil(processors) .clamp(1, 10_000); - unsafe { SetInformationJobObject( job.handle, @@ -91,38 +84,45 @@ pub fn create_job_object( } .map_err(|e| format!("SetInformationJobObject (CPU) failed: {e}"))?; } - - tracing::info!( - "job object '{name}': max_procs={max_processes}, max_mem={max_memory_mb}MB, cpu={cpu_rate_percent}%" - ); - Ok(job) } -/// Create a Job Object used only as a fail-closed process-tree lifetime guard. -/// Resource limits are added separately once their accounting semantics have -/// been proven for the selected backend. -pub fn create_kill_on_close_job(name: &str) -> Result { - let job_name = HSTRING::from(name); - let handle = unsafe { CreateJobObjectW(None, &job_name) } - .map_err(|e| format!("CreateJobObjectW failed: {e}"))?; - let job = JobHandle { handle }; - let mut ext_info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default(); - // MXC's BaseContainer child may explicitly break away before it is placed - // in MXC's child-only resource Job. Silent breakaway remains disabled, so - // ordinary descendants cannot escape this lifecycle boundary. - ext_info.BasicLimitInformation.LimitFlags = - JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_BREAKAWAY_OK; +/// Resume every thread of a process created with CREATE_SUSPENDED. +pub fn resume_process(pid: u32) -> Result<(), String> { + use windows::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, + }; + use windows::Win32::System::Threading::{OpenThread, ResumeThread, THREAD_SUSPEND_RESUME}; + + let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) } + .map_err(|e| format!("CreateToolhelp32Snapshot failed: {e}"))?; + let mut entry = THREADENTRY32 { + dwSize: std::mem::size_of::() as u32, + ..Default::default() + }; + let mut resumed = 0; + let mut more = unsafe { Thread32First(snapshot, &mut entry) }.is_ok(); + while more { + if entry.th32OwnerProcessID == pid + && let Ok(thread) = + unsafe { OpenThread(THREAD_SUSPEND_RESUME, false, entry.th32ThreadID) } + { + if unsafe { ResumeThread(thread) } != u32::MAX { + resumed += 1; + } + unsafe { + let _ = CloseHandle(thread); + } + } + more = unsafe { Thread32Next(snapshot, &mut entry) }.is_ok(); + } unsafe { - SetInformationJobObject( - job.handle, - JobObjectExtendedLimitInformation, - &ext_info as *const _ as *const std::ffi::c_void, - std::mem::size_of::() as u32, - ) + let _ = CloseHandle(snapshot); } - .map_err(|e| format!("SetInformationJobObject (lifetime guard) failed: {e}"))?; - Ok(job) + if resumed == 0 { + return Err(format!("no suspended thread resumed for pid {pid}")); + } + Ok(()) } /// Assign a process to a Job Object by PID. diff --git a/crates/axis-sandbox/src/windows/mod.rs b/crates/axis-sandbox/src/windows/mod.rs index 51f9cac..f8c36d1 100644 --- a/crates/axis-sandbox/src/windows/mod.rs +++ b/crates/axis-sandbox/src/windows/mod.rs @@ -13,4 +13,3 @@ pub mod etw; pub mod job_object; pub(crate) mod mxc; pub mod restricted; -pub mod wfp; diff --git a/crates/axis-sandbox/src/windows/mxc.rs b/crates/axis-sandbox/src/windows/mxc.rs index 946d926..adb4477 100644 --- a/crates/axis-sandbox/src/windows/mxc.rs +++ b/crates/axis-sandbox/src/windows/mxc.rs @@ -8,7 +8,9 @@ //! rejected before the executor is resolved or user code is spawned. use crate::sandbox::{BackendPreflight, SandboxConfig, SandboxError, SandboxImpl}; -use axis_core::capability::{DependencyState, PlannerOptions, RuntimeProbeSnapshot}; +use axis_core::capability::{ + BYPASS_EVIDENCE_REQUIREMENT, DependencyState, PlannerOptions, RuntimeProbeSnapshot, +}; use axis_core::capability_map::{BackendCapabilityMapId, host_dependency}; use axis_core::mxc_config::{self, MxcProcessWireConfig}; use axis_core::policy::{Compatibility, NetworkMode}; @@ -106,7 +108,7 @@ impl MxcWindowsExecutor { let mut file = tempfile::Builder::new() .prefix("axis-mxc-windows-") .suffix(".json") - .tempfile() + .tempfile_in(private_config_dir(&config.filesystem.readwrite_paths)?) .map_err(|err| MxcWindowsError::Config(err.to_string()))?; file.write_all(&json) .and_then(|()| file.flush()) @@ -170,6 +172,64 @@ pub(crate) struct MxcWindowsSandbox { workspace_dir: PathBuf, capture_output: bool, timeout_sec: Option, + max_processes: u32, + max_memory_mb: u64, + cpu_rate_percent: u32, + tmpdir: Option, + tmpdir_active: bool, +} + +/// The executor config lives under the axisd token directory. Sandbox creation +/// refuses any grant that covers that directory, so neither this sandbox nor a +/// concurrent one can edit the config before `wxc-exec` reads it. The check +/// is repeated here against this sandbox's grants; a path that cannot be +/// canonicalized counts as covering the directory. +fn private_config_dir(writable: &[String]) -> Result { + let token_dir = axis_core::daemon_auth::token_dir().ok_or_else(|| { + MxcWindowsError::Config( + "cannot locate the AXIS state directory for the executor config".into(), + ) + })?; + let dir = token_dir.join("mxc-config"); + fs::create_dir_all(&dir).map_err(|err| { + MxcWindowsError::Config(format!( + "cannot create the executor config directory {}: {err}", + dir.display() + )) + })?; + let canonical = |path: &Path| { + normalize_absolute_windows_path(path) + .and_then(|lexical| canonicalize_with_nonexistent_suffix(&lexical)) + }; + let dir = canonical(&dir).map_err(|err| MxcWindowsError::Config(err.to_string()))?; + for grant in writable { + let covers = canonical(Path::new(grant)) + .map(|grant| path_within(&dir, &grant) || path_within(&grant, &dir)) + .unwrap_or(true); + if covers { + return Err(MxcWindowsError::Config(format!( + "read-write grant {grant:?} could reach the executor config directory {}", + dir.display() + ))); + } + } + Ok(dir) +} + +fn path_within(path: &Path, root: &Path) -> bool { + let path = path.to_string_lossy().to_ascii_lowercase(); + let root = root.to_string_lossy().to_ascii_lowercase(); + Path::new(path.trim_end_matches(['\\', '/'])).starts_with(root.trim_end_matches(['\\', '/'])) +} + +fn policy_uses_tmpdir(config: &SandboxConfig) -> bool { + let filesystem = &config.policy.filesystem; + filesystem + .read_only + .iter() + .chain(filesystem.read_write.iter()) + .chain(filesystem.deny.iter()) + .any(|path| path.contains("{tmpdir}")) } enum MxcExecutorChild { @@ -206,10 +266,21 @@ impl MxcExecutorChild { impl MxcWindowsSandbox { pub(crate) fn new(config: &SandboxConfig) -> Result { - let wire_config = build_windows_processcontainer_config(config) + let (wire_config, accepted_weaker) = build_windows_processcontainer_launch(config) .map_err(|err| SandboxError::IsolationFailed(err.to_string()))?; let executor = MxcWindowsExecutor::resolve() .map_err(|err| SandboxError::IsolationFailed(err.to_string()))?; + // Interactive `axis run` filters tracing to errors, so the user would + // not see a tracing warning. + for weaker in &accepted_weaker { + if weaker.starts_with(BYPASS_EVIDENCE_REQUIREMENT) { + eprintln!( + "axis: warning: {weaker}; set network.bypass_audit: hard_requirement to refuse such launches" + ); + } else { + eprintln!("axis: warning: {weaker}"); + } + } if config.backend_preflight == BackendPreflight::DryRun { executor .dry_run(&wire_config, Duration::from_secs(5)) @@ -234,7 +305,38 @@ impl MxcWindowsSandbox { workspace_dir: config.workspace_dir.clone(), capture_output: config.capture_output, timeout_sec: config.timeout_sec.or(config.policy.process.timeout_sec), + max_processes: config.policy.process.effective_max_processes(), + max_memory_mb: config.policy.process.max_memory_mb, + cpu_rate_percent: config.policy.process.cpu_rate_percent, + tmpdir: policy_uses_tmpdir(config).then(|| config.workspace_dir.join(".axis-tmp")), + tmpdir_active: false, + } + } + + fn create_tmpdir(&mut self) -> Result<(), SandboxError> { + let Some(tmpdir) = &self.tmpdir else { + return Ok(()); + }; + std::fs::create_dir(tmpdir).map_err(|err| { + SandboxError::IsolationFailed(format!( + "cannot create exclusive tmpdir {}: {err}", + tmpdir.display() + )) + })?; + self.tmpdir_active = true; + Ok(()) + } + + fn cleanup_tmpdir(&mut self) { + if !self.tmpdir_active { + return; + } + if let Some(tmpdir) = &self.tmpdir + && let Err(err) = std::fs::remove_dir_all(tmpdir) + { + tracing::warn!("sandbox {}: tmpdir cleanup failed: {err}", self.id); } + self.tmpdir_active = false; } #[cfg(test)] @@ -251,6 +353,7 @@ impl MxcWindowsSandbox { // Closing the Job Object is the final process-tree kill boundary. self.job.take(); self.config_file.take(); + self.cleanup_tmpdir(); } fn terminate_tree(&mut self) -> Result<(), SandboxError> { @@ -261,6 +364,7 @@ impl MxcWindowsSandbox { let _ = child.wait()?; } self.config_file.take(); + self.cleanup_tmpdir(); Ok(()) } } @@ -272,46 +376,12 @@ impl SandboxImpl for MxcWindowsSandbox { "Windows MXC backend is already started".into(), )); } - let config = self - .executor - .write_private_config(&self.wire_config) - .map_err(|err| SandboxError::IsolationFailed(err.to_string()))?; - let job = super::job_object::create_kill_on_close_job(&format!("axis-mxc-{}", self.id)) - .map_err(|err| SandboxError::IsolationFailed(format!("MXC Job Object: {err}")))?; - let mut command = Command::new(&self.executor.path); - configure_executor_invocation(&mut command, config.path(), false); - command.current_dir(&self.workspace_dir); - configure_executor_environment(&mut command, &self.executor.path); - if self.capture_output { - command.stdin(Stdio::null()); - let stdout = File::create(self.workspace_dir.join("stdout.log")) - .map_err(|err| SandboxError::SpawnFailed(format!("stdout log: {err}")))?; - let stderr = File::create(self.workspace_dir.join("stderr.log")) - .map_err(|err| SandboxError::SpawnFailed(format!("stderr log: {err}")))?; - command - .stdout(Stdio::from(stdout)) - .stderr(Stdio::from(stderr)); + self.create_tmpdir()?; + let result = self.launch(); + if result.is_err() { + self.cleanup_tmpdir(); } - let mut child = - MxcExecutorChild::Standard(command.spawn().map_err(|err| { - SandboxError::SpawnFailed(format!("Windows MXC executor: {err}")) - })?); - let pid = child.id(); - if let Err(err) = super::job_object::assign_process_to_job(&job, pid) { - let _ = child.kill(); - let _ = child.wait(); - return Err(SandboxError::IsolationFailed(format!( - "MXC Job Object assignment: {err}" - ))); - } - self.config_file = Some(config); - self.job = Some(job); - self.child = Some(child); - tracing::info!( - "sandbox {} started via MXC ProcessContainer, pid={pid}", - self.id - ); - Ok(pid) + result } fn wait( @@ -373,12 +443,87 @@ impl SandboxImpl for MxcWindowsSandbox { } } +impl MxcWindowsSandbox { + fn launch(&mut self) -> Result { + let config = self + .executor + .write_private_config(&self.wire_config) + .map_err(|err| SandboxError::IsolationFailed(err.to_string()))?; + // The executor itself occupies one process slot in the job. + let job = super::job_object::create_limited_kill_on_close_job( + if self.max_processes > 0 { + self.max_processes + 1 + } else { + 0 + }, + self.max_memory_mb, + self.cpu_rate_percent, + ) + .map_err(|err| SandboxError::IsolationFailed(format!("MXC Job Object: {err}")))?; + let mut command = Command::new(&self.executor.path); + { + use std::os::windows::process::CommandExt; + const CREATE_SUSPENDED: u32 = 0x0000_0004; + command.creation_flags(CREATE_SUSPENDED); + } + configure_executor_invocation(&mut command, config.path(), false); + command.current_dir(&self.workspace_dir); + configure_executor_environment(&mut command, &self.executor.path); + if self.capture_output { + command.stdin(Stdio::null()); + let stdout = File::create(self.workspace_dir.join("stdout.log")) + .map_err(|err| SandboxError::SpawnFailed(format!("stdout log: {err}")))?; + let stderr = File::create(self.workspace_dir.join("stderr.log")) + .map_err(|err| SandboxError::SpawnFailed(format!("stderr log: {err}")))?; + command + .stdout(Stdio::from(stdout)) + .stderr(Stdio::from(stderr)); + } + let mut child = + MxcExecutorChild::Standard(command.spawn().map_err(|err| { + SandboxError::SpawnFailed(format!("Windows MXC executor: {err}")) + })?); + let pid = child.id(); + if let Err(err) = super::job_object::assign_process_to_job(&job, pid) { + let _ = child.kill(); + let _ = child.wait(); + return Err(SandboxError::IsolationFailed(format!( + "MXC Job Object assignment: {err}" + ))); + } + if let Err(err) = super::job_object::resume_process(pid) { + let _ = child.kill(); + let _ = child.wait(); + return Err(SandboxError::IsolationFailed(format!( + "MXC executor resume: {err}" + ))); + } + self.config_file = Some(config); + self.job = Some(job); + self.child = Some(child); + tracing::info!( + "sandbox {} started via MXC ProcessContainer, pid={pid}", + self.id + ); + Ok(pid) + } +} + +#[cfg(test)] fn build_windows_processcontainer_config( config: &SandboxConfig, ) -> Result { + build_windows_processcontainer_launch(config).map(|(wire, _)| wire) +} + +/// The executor config plus the weaker behavior the launch accepted, including +/// the opt-in Windows access the policy turned on. +fn build_windows_processcontainer_launch( + config: &SandboxConfig, +) -> Result<(MxcProcessWireConfig, Vec), MxcWindowsError> { validate_unproven_policy_surfaces(config)?; - validate_tier_policy(config.interactive_terminal)?; let translated_filesystem = translate_filesystem_policy(config)?; + let denied = translated_filesystem.deny.clone(); let filesystem = normalize_basecontainer_filesystem(translated_filesystem)?; let mut effective_policy = config.policy.clone(); effective_policy.filesystem.read_only = filesystem.read_only.clone(); @@ -386,7 +531,32 @@ fn build_windows_processcontainer_config( // BaseContainer keeps its stronger default-deny boundary, so redundant // denies are removed after overlap validation. effective_policy.filesystem.deny.clear(); - let environment = sanitized_environment(&config.env)?; + let mut environment = sanitized_environment(&config.env)?; + let search_path = environment + .iter() + .find(|(key, _)| key.eq_ignore_ascii_case("PATH")) + .map(|(_, value)| OsString::from(value)) + .or_else(|| std::env::var_os("PATH")); + // MXC 1.x uses a supplied environment verbatim and refuses to launch + // without these. AXIS always supplies one so the child's environment block + // is not built from the user's persisted variables. Those stay readable + // through HKCU without LPAC; this only controls what is inherited. + for key in ["SYSTEMROOT", "LOCALAPPDATA"] { + if !environment + .keys() + .any(|existing| existing.eq_ignore_ascii_case(key)) + && let Some(value) = std::env::var_os(key).and_then(|value| value.into_string().ok()) + { + environment.insert(key.into(), value); + } + } + let enumerate_paths = if config.policy.filesystem.windows_enumerate_ancestors { + let ancestors = grant_ancestors(&filesystem)?; + reject_denies_under_enumerated_ancestors(&ancestors, &denied)?; + ancestors + } else { + Vec::new() + }; let working_dir = path_string( config .working_dir @@ -403,20 +573,13 @@ fn build_windows_processcontainer_config( } else { None }; - let wfp_dependency = - if crate::windows::wfp::broker_available(crate::windows::wfp::DEFAULT_PIPE_NAME) { - DependencyState::Present - } else { - DependencyState::Missing - }; let runtime = RuntimeProbeSnapshot::new() .with_dependency(host_dependency::MXC_EXECUTOR, DependencyState::Present) .with_dependency( host_dependency::WINDOWS_PROCESS_CONTAINER, DependencyState::Present, ) - .with_dependency(host_dependency::WINDOWS_JOBOBJECT, DependencyState::Present) - .with_dependency(host_dependency::WINDOWS_WFP_BROKER, wfp_dependency); + .with_dependency(host_dependency::WINDOWS_JOBOBJECT, DependencyState::Present); let mut spec = build_process_backend_execution_spec( &effective_policy, BackendCapabilityMapId::MxcWindowsProcessContainer, @@ -429,34 +592,154 @@ fn build_windows_processcontainer_config( timeout_sec: config.timeout_sec, }, &runtime, - &PlannerOptions::new(), + &PlannerOptions::for_policy(&effective_policy), ) .map_err(|err| MxcWindowsError::UnsupportedPolicy(err.to_string()))?; + let mut accepted_weaker = spec.accepted_weaker.clone(); + if config.policy.process.windows_win32k { + accepted_weaker.push( + "process.windows_win32k: the sandbox can make Win32k (USER32/GDI) system calls".into(), + ); + } + if !enumerate_paths.is_empty() { + accepted_weaker.push(format!( + "filesystem.windows_enumerate_ancestors: file names, sizes and times below {} are visible to the sandbox", + enumerate_paths.join(", ") + )); + } spec.filesystem = filesystem; + let command = resolve_bare_command(&config.command, search_path.as_deref()); + reject_batch_metacharacters(&command, &config.args)?; let wire = mxc_config::build_mxc_process_config( - windows_command_line(&config.command, &config.args), + windows_command_line(&command, &config.args), &spec, mxc_config::MxcProcessConfigOptions { container_id: Some(format!("axis-{}", config.id)), strict_proxy_enforced_by_axis: strict_proxy, proxy_url: proxy_addr.map(|addr| format!("http://{addr}")), - axis_wfp: strict_proxy.then(|| mxc_config::MxcAxisWfpConfig { - pipe_name: crate::windows::wfp::DEFAULT_PIPE_NAME.into(), - lease_id: config.id.0.to_string(), - }), + resource_limits_enforced_by_axis: true, + windows_win32k: config.policy.process.windows_win32k, + windows_enumerate_paths: enumerate_paths, ..Default::default() }, ) .map_err(|err| MxcWindowsError::Config(err.to_string()))?; - Ok(wire) + Ok((wire, accepted_weaker)) } -fn validate_tier_policy(interactive_terminal: bool) -> Result<(), MxcWindowsError> { - if interactive_terminal { - return Err(MxcWindowsError::UnsupportedPolicy( - "interactive ConPTY is unsupported because Experimental_CreateProcessInSandbox rejects PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE with ERROR_INVALID_HANDLE on supported BaseContainer builds; AXIS does not downgrade to AppContainer/DACL to obtain terminal support" - .into(), - )); +/// CreateProcess runs `.cmd` and `.bat` files through `cmd.exe`, which treats +/// these characters as operators or variable references even inside quotes. +const BATCH_METACHARACTERS: &[char] = &['&', '|', '<', '>', '^', '%', '!', '"', '\r', '\n']; + +fn reject_batch_metacharacters(command: &str, args: &[String]) -> Result<(), MxcWindowsError> { + let is_batch = Path::new(command) + .extension() + .and_then(OsStr::to_str) + .is_some_and(|extension| { + extension.eq_ignore_ascii_case("cmd") || extension.eq_ignore_ascii_case("bat") + }); + if !is_batch { + return Ok(()); + } + match std::iter::once(command) + .chain(args.iter().map(String::as_str)) + .find(|argument| argument.contains(BATCH_METACHARACTERS)) + { + Some(argument) => Err(MxcWindowsError::UnsupportedPolicy(format!( + "{command:?} runs through cmd.exe, which would interpret the characters in {argument:?}; run the underlying executable instead, for example node.exe with the script path" + ))), + None => Ok(()), + } +} + +/// CreateProcess searches the executor's own directory first for a bare name, +/// and that directory is not granted to the container, so the launch fails +/// with ERROR_ACCESS_DENIED. Resolve bare names against the sandbox PATH first, +/// falling back to the host PATH when the caller does not set one. Relative +/// PATH entries are skipped: they would resolve against AXIS's working +/// directory, not the sandbox's. +fn resolve_bare_command(command: &str, search_path: Option<&OsStr>) -> String { + if command.contains(['\\', '/', ':']) { + return command.into(); + } + let has_extension = Path::new(command).extension().is_some(); + let extensions: Vec = if has_extension { + vec![String::new()] + } else { + std::env::var("PATHEXT") + .unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".into()) + .split(';') + .filter(|extension| !extension.is_empty()) + .map(str::to_owned) + .collect() + }; + let Some(path) = search_path else { + return command.into(); + }; + for directory in std::env::split_paths(path).filter(|directory| directory.is_absolute()) { + for extension in &extensions { + let candidate = directory.join(format!("{command}{extension}")); + if candidate.is_file() { + return candidate.to_string_lossy().into_owned(); + } + } + } + command.into() +} + +/// Every proper ancestor of a filesystem grant, so path canonicalization +/// (Node's JS `realpath`, `GetFinalPathNameByHandle` callers) can `lstat` the +/// chain. MXC applies enumeration to each path's whole subtree: names and +/// attributes below it become visible, file contents do not. +/// An ancestor inside another grant is left out: MXC lets an enumerate entry +/// replace that grant's access on the path, so `{tmpdir}` would otherwise turn +/// a read-write `{workspace}` into list-only. +fn grant_ancestors( + filesystem: &ProcessBackendFilesystemSpec, +) -> Result, MxcWindowsError> { + let grants: Vec<&String> = filesystem + .read_only + .iter() + .chain(filesystem.read_write.iter()) + .collect(); + let covered = |path: &Path| { + grants + .iter() + .any(|grant| path.starts_with(Path::new(grant.as_str()))) + }; + let mut seen = HashSet::new(); + let mut ancestors = Vec::new(); + for grant in &grants { + let mut current = Path::new(grant.as_str()).parent(); + while let Some(path) = current { + let rendered = path_string(path)?; + if rendered.is_empty() { + break; + } + if !covered(path) && seen.insert(rendered.to_ascii_lowercase()) { + ancestors.push(rendered); + } + current = path.parent(); + } + } + Ok(ancestors) +} + +/// Enumeration covers an ancestor's whole subtree, so a denied path below one +/// would have its file names listed. +fn reject_denies_under_enumerated_ancestors( + ancestors: &[String], + denied: &[String], +) -> Result<(), MxcWindowsError> { + for ancestor in ancestors { + let ancestor_key = windows_path_key(ancestor)?; + for deny in denied { + if component_prefix(&ancestor_key, &windows_path_key(deny)?) { + return Err(MxcWindowsError::UnsupportedPolicy(format!( + "filesystem.windows_enumerate_ancestors would list names under {ancestor:?}, which contains the denied path {deny:?}; remove the deny or turn the option off" + ))); + } + } } Ok(()) } @@ -488,7 +771,7 @@ fn validate_unproven_policy_surfaces(config: &SandboxConfig) -> Result<(), MxcWi } if config.policy.process.run_as_user.is_some() { return Err(MxcWindowsError::UnsupportedPolicy( - "process.run_as_user names a host/Unix account and has no sound BaseContainer mapping; use process.identity: isolated for portable identity intent" + "process.run_as_user names a host/Unix account and has no sound BaseContainer mapping; MXC 1.x BaseContainer also has no LPAC token, so process.identity: isolated is unavailable on Windows" .into(), )); } @@ -1015,35 +1298,273 @@ mod tests { let wire = build_windows_processcontainer_config(&config).unwrap(); let json = serde_json::to_value(wire).unwrap(); assert_eq!(json["containment"], "processcontainer"); - assert_eq!(json["version"], mxc_config::MXC_WINDOWS_CONFIG_VERSION); - assert_eq!(json["platform"], "windows"); - assert_eq!(json["processContainer"]["leastPrivilege"], true); + assert_eq!( + json["version"], + mxc_config::MXC_WINDOWS_PROCESS_CONFIG_VERSION + ); + assert!(json.get("platform").is_none()); + assert_eq!(json["processContainer"]["leastPrivilege"], false); assert_eq!(json["fallback"]["allowDaclMutation"], false); - assert_eq!(json["network"]["defaultPolicy"], "block"); + assert_eq!(json["network"]["egress"]["default"], "deny"); + assert!(json.get("ui").is_none()); assert_eq!( json["filesystem"]["readwritePaths"][0], root.path().to_string_lossy().as_ref() ); - assert_eq!( - json["process"]["env"], - serde_json::json!(["PATH=safe-path"]) + let env: Vec<&str> = json["process"]["env"] + .as_array() + .unwrap() + .iter() + .map(|entry| entry.as_str().unwrap()) + .collect(); + assert!(env.contains(&"PATH=safe-path")); + assert!(!env.iter().any(|entry| entry.contains("secret"))); + for required in ["SYSTEMROOT=", "LOCALAPPDATA="] { + assert!( + env.iter().any(|entry| entry.starts_with(required)), + "{required}" + ); + } + assert_eq!(env.len(), 3); + } + + #[test] + fn strict_proxy_reports_the_missing_bypass_audit_trail_unless_required() { + let root = tempfile::tempdir().unwrap(); + let mut config = sandbox_config(root.path()); + config.policy.network.mode = NetworkMode::Proxy; + config.proxy_addr = Some("127.0.0.1:31280".parse().unwrap()); + + let (_, accepted_weaker) = build_windows_processcontainer_launch(&config).unwrap(); + assert_eq!(accepted_weaker.len(), 1, "{accepted_weaker:?}"); + assert!(accepted_weaker[0].starts_with("audit.bypass_evidence: ")); + + config.policy.network.mode = NetworkMode::Block; + let (_, accepted_weaker) = build_windows_processcontainer_launch(&config).unwrap(); + assert!(accepted_weaker.is_empty(), "{accepted_weaker:?}"); + + config.policy.process.windows_win32k = true; + config.policy.filesystem.windows_enumerate_ancestors = true; + let (_, accepted_weaker) = build_windows_processcontainer_launch(&config).unwrap(); + assert_eq!(accepted_weaker.len(), 2, "{accepted_weaker:?}"); + assert!(accepted_weaker[0].starts_with("process.windows_win32k: ")); + assert!(accepted_weaker[1].starts_with("filesystem.windows_enumerate_ancestors: ")); + config.policy.process.windows_win32k = false; + config.policy.filesystem.windows_enumerate_ancestors = false; + + config.policy.network.mode = NetworkMode::Proxy; + config.policy.network.bypass_audit = Compatibility::HardRequirement; + let error = build_windows_processcontainer_launch(&config).unwrap_err(); + assert!( + error.to_string().contains("audit.bypass_evidence"), + "{error}" ); } #[test] - fn processcontainer_serializes_child_only_job_resources() { + fn processcontainer_limits_go_to_the_outer_job_not_the_mxc_1_config() { let root = tempfile::tempdir().unwrap(); let mut config = sandbox_config(root.path()); config.policy.process.max_processes = 8; config.policy.process.max_memory_mb = 512; config.policy.process.cpu_rate_percent = 25; + let executor_path = root.path().join("fake-mxc.cmd"); + write_fake_executor(&executor_path, &root.path().join("unused.json")); + let executor = MxcWindowsExecutor::from_test_path(&executor_path).unwrap(); - let wire = build_windows_processcontainer_config(&config).unwrap(); - let json = serde_json::to_value(wire).unwrap(); + let sandbox = MxcWindowsSandbox::new_with_executor(&config, executor).unwrap(); + let json = serde_json::to_value(&sandbox.wire_config).unwrap(); + + assert!(json["processContainer"].get("resources").is_none()); + assert_eq!(sandbox.max_processes, 8); + assert_eq!(sandbox.max_memory_mb, 512); + assert_eq!(sandbox.cpu_rate_percent, 25); + } + + #[test] + fn win32k_policy_enables_ui_without_clipboard_or_injection() { + let root = tempfile::tempdir().unwrap(); + let mut config = sandbox_config(root.path()); + config.policy.process.windows_win32k = true; + + let json = + serde_json::to_value(build_windows_processcontainer_config(&config).unwrap()).unwrap(); + + assert_eq!( + json["ui"], + serde_json::json!({ "disable": false, "clipboard": "none", "injection": false }) + ); + } + + #[test] + fn ancestor_enumeration_is_opt_in() { + let root = tempfile::tempdir().unwrap(); + let mut config = sandbox_config(root.path()); + + let json = + serde_json::to_value(build_windows_processcontainer_config(&config).unwrap()).unwrap(); + assert!(json["processContainer"].get("filesystem").is_none()); + + config.policy.filesystem.windows_enumerate_ancestors = true; + let json = + serde_json::to_value(build_windows_processcontainer_config(&config).unwrap()).unwrap(); + let paths = json["processContainer"]["filesystem"]["enumeratePaths"] + .as_array() + .unwrap(); + assert!( + paths + .iter() + .any(|path| root.path().starts_with(path.as_str().unwrap())) + ); + } + + #[test] + fn ancestor_enumeration_refuses_a_denied_sibling() { + let root = tempfile::tempdir().unwrap(); + let workspace = root.path().join("ws"); + let secret = root.path().join("secret"); + fs::create_dir_all(&workspace).unwrap(); + fs::create_dir_all(&secret).unwrap(); + let mut config = sandbox_config(&workspace); + config.policy.filesystem.deny = vec![secret.to_string_lossy().into_owned()]; + + build_windows_processcontainer_config(&config).unwrap(); + + config.policy.filesystem.windows_enumerate_ancestors = true; + let error = build_windows_processcontainer_config(&config).unwrap_err(); + assert!( + error + .to_string() + .contains("filesystem.windows_enumerate_ancestors"), + "{error}" + ); + } + + #[test] + fn grant_ancestors_skip_paths_inside_another_grant() { + let filesystem = ProcessBackendFilesystemSpec { + read_only: vec![r"C:\Program Files\Git".into()], + read_write: vec![r"C:\work\lease".into(), r"C:\work\lease\.axis-tmp".into()], + deny: Vec::new(), + }; + + let ancestors = grant_ancestors(&filesystem).unwrap(); + + assert!(ancestors.contains(&r"C:\Program Files".to_string())); + assert!(ancestors.contains(&r"C:\work".to_string())); + assert!( + !ancestors + .iter() + .any(|path| path.eq_ignore_ascii_case(r"C:\work\lease")) + ); + } + + #[test] + fn path_within_ignores_case_and_trailing_separators() { + assert!(path_within( + Path::new(r"C:\Work\Lease\.axis-tmp"), + Path::new(r"c:\work\lease\") + )); + assert!(path_within( + Path::new(r"C:\work\lease"), + Path::new(r"C:\work\lease") + )); + assert!(!path_within( + Path::new(r"C:\work\lease2"), + Path::new(r"C:\work\lease") + )); + } - assert_eq!(json["processContainer"]["resources"]["maxProcesses"], 8); - assert_eq!(json["processContainer"]["resources"]["maxMemoryMb"], 512); - assert_eq!(json["processContainer"]["resources"]["cpuRatePercent"], 25); + #[test] + fn private_config_dir_is_under_the_hidden_state_dir_and_fails_closed() { + let dir = private_config_dir(&[]).unwrap(); + let token_dir = fs::canonicalize(axis_core::daemon_auth::token_dir().unwrap()).unwrap(); + assert!(path_within(&dir, &token_dir), "{}", dir.display()); + + let temp = std::env::temp_dir().to_string_lossy().into_owned(); + private_config_dir(std::slice::from_ref(&temp)).unwrap(); + + let parent = token_dir.parent().unwrap().to_string_lossy().into_owned(); + let inside = dir.join("nested").to_string_lossy().into_owned(); + for grant in [parent, inside, r"relative\grant".to_string()] { + let error = private_config_dir(std::slice::from_ref(&grant)).unwrap_err(); + assert!( + error + .to_string() + .contains("could reach the executor config"), + "{grant}: {error}" + ); + } + } + + #[test] + fn bare_command_resolves_against_supplied_search_path() { + let root = tempfile::tempdir().unwrap(); + let tool = root.path().join("axis-test-tool.exe"); + File::create(&tool).unwrap(); + + let resolved = resolve_bare_command("axis-test-tool", Some(root.path().as_os_str())); + + assert!(resolved.eq_ignore_ascii_case(&tool.to_string_lossy())); + assert_eq!( + resolve_bare_command("axis-test-tool", Some(OsStr::new(""))), + "axis-test-tool" + ); + assert_eq!( + resolve_bare_command(r"C:\x\tool.exe", None), + r"C:\x\tool.exe" + ); + } + + #[test] + fn bare_command_skips_relative_search_path_entries() { + let relative = format!("axis-relative-path-{}", std::process::id()); + let dir = std::env::current_dir().unwrap().join(&relative); + fs::create_dir_all(&dir).unwrap(); + File::create(dir.join("axis-relative-tool.exe")).unwrap(); + + let resolved = resolve_bare_command("axis-relative-tool", Some(OsStr::new(&relative))); + + fs::remove_dir_all(&dir).unwrap(); + assert_eq!(resolved, "axis-relative-tool"); + } + + #[test] + fn batch_files_refuse_arguments_cmd_would_interpret() { + for (command, argument) in [ + (r"C:\tools\npm.cmd", "a&b"), + (r"C:\tools\npm.CMD", "100%"), + (r"C:\tools\build.bat", "say \"hi\""), + (r"C:\tools\build.bat", "line\nnext"), + ] { + let error = + reject_batch_metacharacters(command, &["run".into(), argument.into()]).unwrap_err(); + assert!( + error.to_string().contains("cmd.exe"), + "{command} {argument}" + ); + } + reject_batch_metacharacters(r"C:\tools\npm.cmd", &["install".into(), "left-pad".into()]) + .unwrap(); + reject_batch_metacharacters(r"C:\tools\tool.exe", &["a&b".into()]).unwrap(); + } + + #[test] + fn tmpdir_is_created_exclusively_and_removed_after_stop() { + let root = tempfile::tempdir().unwrap(); + let mut config = sandbox_config(root.path()); + config.policy.filesystem.read_write.push("{tmpdir}".into()); + let executor_path = root.path().join("fake-mxc.cmd"); + write_fake_executor(&executor_path, &root.path().join("unused.json")); + let executor = MxcWindowsExecutor::from_test_path(&executor_path).unwrap(); + let mut sandbox = MxcWindowsSandbox::new_with_executor(&config, executor).unwrap(); + let tmpdir = root.path().join(".axis-tmp"); + + sandbox.create_tmpdir().unwrap(); + assert!(tmpdir.is_dir()); + assert!(sandbox.create_tmpdir().is_err()); + sandbox.cleanup_tmpdir(); + assert!(!tmpdir.exists()); } #[test] @@ -1054,14 +1575,23 @@ mod tests { config.policy.process.child_processes = ChildProcessPolicy::Deny; config.policy.process.max_processes = 32; - let wire = build_windows_processcontainer_config(&config).unwrap(); - let json = serde_json::to_value(wire).unwrap(); - assert_eq!(json["processContainer"]["leastPrivilege"], true); - assert_eq!(json["processContainer"]["resources"]["maxProcesses"], 1); + let error = build_windows_processcontainer_config(&config).unwrap_err(); + assert!(error.to_string().contains("LPAC"), "{error}"); + + config.policy.process.identity = Default::default(); + assert_eq!(config.policy.process.effective_max_processes(), 1); + let json = + serde_json::to_value(build_windows_processcontainer_config(&config).unwrap()).unwrap(); + assert_eq!(json["processContainer"]["leastPrivilege"], false); config.policy.process.run_as_user = Some("sandbox-user".into()); let error = build_windows_processcontainer_config(&config).unwrap_err(); - assert!(error.to_string().contains("process.identity: isolated")); + assert!( + error + .to_string() + .contains("process.identity: isolated is unavailable on Windows"), + "{error}" + ); } #[test] @@ -1168,11 +1698,16 @@ mod tests { } #[test] - fn interactive_terminal_rejects_instead_of_downgrading() { - let error = validate_tier_policy(true).unwrap_err(); - assert!(error.to_string().contains("ERROR_INVALID_HANDLE")); - assert!(error.to_string().contains("AppContainer/DACL")); - validate_tier_policy(false).unwrap(); + fn terminal_launch_runs_without_a_pseudoconsole() { + let root = tempfile::tempdir().unwrap(); + let mut config = sandbox_config(root.path()); + let detached = + serde_json::to_value(build_windows_processcontainer_config(&config).unwrap()).unwrap(); + config.interactive_terminal = true; + let terminal = + serde_json::to_value(build_windows_processcontainer_config(&config).unwrap()).unwrap(); + assert_eq!(terminal["process"], detached["process"]); + assert_eq!(terminal["ui"], detached["ui"]); } #[test] @@ -1193,7 +1728,6 @@ mod tests { config.policy.network.mode = NetworkMode::Proxy; validate_unproven_policy_surfaces(&config).unwrap(); - validate_tier_policy(false).unwrap(); } #[test] @@ -1292,7 +1826,7 @@ mod tests { let json: serde_json::Value = serde_json::from_slice(&fs::read(config_copy).unwrap()).unwrap(); assert_eq!(json["containment"], "processcontainer"); - assert_eq!(json["network"]["defaultPolicy"], "block"); + assert_eq!(json["network"]["egress"]["default"], "deny"); assert!(!serde_json::to_string(&json).unwrap().contains("secret")); } @@ -1365,6 +1899,7 @@ mod tests { deny: Vec::new(), compatibility: Compatibility::BestEffort, workspace_read_only: false, + windows_enumerate_ancestors: false, }, process: ProcessPolicy { max_processes: 0, @@ -1375,8 +1910,10 @@ mod tests { identity: Default::default(), child_processes: Default::default(), timeout_sec: None, + windows_win32k: false, }, network: NetworkPolicy { + bypass_audit: Default::default(), mode: NetworkMode::Block, policies: Vec::new(), }, diff --git a/crates/axis-sandbox/src/windows/wfp.rs b/crates/axis-sandbox/src/windows/wfp.rs deleted file mode 100644 index 61ba8dc..0000000 --- a/crates/axis-sandbox/src/windows/wfp.rs +++ /dev/null @@ -1,1428 +0,0 @@ -// Copyright 2026 Advanced Micro Devices, Inc. -// SPDX-License-Identifier: Apache-2.0 - -//! Privileged Windows Filtering Platform broker for strict proxy leases. -//! -//! The broker deliberately exposes one fixed operation: constrain the actual -//! AppContainer identity of a suspended child to one TCP proxy endpoint. It -//! does not accept caller-provided SIDs, filter keys, layers, actions, or -//! arbitrary conditions. - -use serde::{Deserialize, Serialize}; -use std::ffi::c_void; -use std::fs::{File, OpenOptions}; -use std::io::{Read, Write}; -use std::mem::{MaybeUninit, size_of}; -use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; -use std::os::windows::io::{FromRawHandle, IntoRawHandle}; -use std::path::{Path, PathBuf}; -use std::ptr::NonNull; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex, OnceLock}; -use std::time::{SystemTime, UNIX_EPOCH}; -use uuid::Uuid; -use windows::Win32::Foundation::{ - CloseHandle, ERROR_ALREADY_EXISTS, ERROR_BROKEN_PIPE, ERROR_PIPE_CONNECTED, FILETIME, - FWP_E_FILTER_NOT_FOUND, FWP_E_SUBLAYER_NOT_FOUND, GetLastError, HANDLE, HLOCAL, - INVALID_HANDLE_VALUE, LocalFree, -}; -use windows::Win32::NetworkManagement::WindowsFilteringPlatform::{ - FWP_ACTION_BLOCK, FWP_ACTION_PERMIT, FWP_CONDITION_VALUE0, FWP_CONDITION_VALUE0_0, - FWP_IP_VERSION_V4, FWP_IP_VERSION_V6, FWP_MATCH_EQUAL, FWP_SID, FWP_UINT8, FWP_UINT16, - FWP_UINT32, FWP_UINT64, FWP_V4_ADDR_AND_MASK, FWP_V4_ADDR_MASK, FWP_V6_ADDR_AND_MASK, - FWP_V6_ADDR_MASK, FWP_VALUE0, FWP_VALUE0_0, FWPM_ACTION0, FWPM_CONDITION_ALE_PACKAGE_ID, - FWPM_CONDITION_IP_PROTOCOL, FWPM_CONDITION_IP_REMOTE_ADDRESS, FWPM_CONDITION_IP_REMOTE_PORT, - FWPM_DISPLAY_DATA0, FWPM_ENGINE_COLLECT_NET_EVENTS, FWPM_FILTER_CONDITION0, - FWPM_FILTER_FLAG_CLEAR_ACTION_RIGHT, FWPM_FILTER0, FWPM_LAYER_ALE_AUTH_CONNECT_V4, - FWPM_LAYER_ALE_AUTH_CONNECT_V6, FWPM_NET_EVENT_FLAG_IP_PROTOCOL_SET, - FWPM_NET_EVENT_FLAG_IP_VERSION_SET, FWPM_NET_EVENT_FLAG_REMOTE_ADDR_SET, - FWPM_NET_EVENT_FLAG_REMOTE_PORT_SET, FWPM_NET_EVENT_SUBSCRIPTION0, - FWPM_NET_EVENT_TYPE_CLASSIFY_DROP, FWPM_NET_EVENT5, FWPM_SESSION_FLAG_DYNAMIC, FWPM_SESSION0, - FWPM_SUBLAYER0, FwpmEngineClose0, FwpmEngineGetOption0, FwpmEngineOpen0, FwpmEngineSetOption0, - FwpmFilterAdd0, FwpmFilterDeleteByKey0, FwpmFreeMemory0, FwpmNetEventSubscribe4, - FwpmNetEventUnsubscribe0, FwpmSubLayerAdd0, FwpmSubLayerDeleteByKey0, FwpmTransactionAbort0, - FwpmTransactionBegin0, FwpmTransactionCommit0, -}; -use windows::Win32::Security::Authorization::{ - ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1, -}; -use windows::Win32::Security::{ - GetLengthSid, GetTokenInformation, PSECURITY_DESCRIPTOR, PSID, TOKEN_APPCONTAINER_INFORMATION, - TOKEN_QUERY, TokenAppContainerSid, TokenIsAppContainer, -}; -use windows::Win32::Storage::FileSystem::PIPE_ACCESS_DUPLEX; -use windows::Win32::System::Diagnostics::ToolHelp::{ - CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW, TH32CS_SNAPPROCESS, -}; -use windows::Win32::System::Pipes::{ - ConnectNamedPipe, CreateNamedPipeW, DisconnectNamedPipe, GetNamedPipeClientProcessId, - PIPE_READMODE_BYTE, PIPE_REJECT_REMOTE_CLIENTS, PIPE_TYPE_BYTE, PIPE_WAIT, WaitNamedPipeW, -}; -use windows::Win32::System::Rpc::RPC_C_AUTHN_WINNT; -use windows::Win32::System::Threading::{ - CreateMutexW, GetCurrentProcessId, GetProcessTimes, OpenProcess, OpenProcessToken, - PROCESS_ACCESS_RIGHTS, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION, - PROCESS_TERMINATE, QueryFullProcessImageNameW, TerminateProcess, WaitForSingleObject, -}; -use windows::core::{GUID, PCWSTR, PWSTR}; - -pub const PROTOCOL_VERSION: u32 = 1; -pub const DEFAULT_PIPE_NAME: &str = r"\\.\pipe\axis-wfp-broker-v1"; -const MAX_MESSAGE_BYTES: usize = 64 * 1024; -const PIPE_BUFFER_BYTES: u32 = 64 * 1024; -const IPPROTO_TCP: u8 = 6; -static AUDIT_WRITE_LOCK: OnceLock> = OnceLock::new(); - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct LeaseRequest { - pub version: u32, - pub lease_id: Uuid, - pub child_pid: u32, - pub proxy_address: IpAddr, - pub proxy_port: u16, -} - -impl LeaseRequest { - pub fn validate(&self) -> Result<(), String> { - if self.version != PROTOCOL_VERSION { - return Err(format!( - "unsupported WFP broker protocol version {}", - self.version - )); - } - if self.lease_id.is_nil() { - return Err("leaseId must not be nil".into()); - } - if self.child_pid == 0 { - return Err("childPid must not be zero".into()); - } - if self.proxy_port == 0 { - return Err("proxyPort must not be zero".into()); - } - if self.proxy_address.is_unspecified() || self.proxy_address.is_multicast() { - return Err("proxyAddress must be a concrete unicast address".into()); - } - Ok(()) - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct LeaseResponse { - pub version: u32, - pub lease_id: Uuid, - pub accepted: bool, - pub app_container_sid: Option, - pub filter_count: u32, - pub error: Option, -} - -impl LeaseResponse { - fn accepted(request: &LeaseRequest, sid: String, filter_count: u32) -> Self { - Self { - version: PROTOCOL_VERSION, - lease_id: request.lease_id, - accepted: true, - app_container_sid: Some(sid), - filter_count, - error: None, - } - } - - fn rejected(lease_id: Uuid, error: impl Into) -> Self { - Self { - version: PROTOCOL_VERSION, - lease_id, - accepted: false, - app_container_sid: None, - filter_count: 0, - error: Some(error.into()), - } - } -} - -#[derive(Debug, Clone)] -pub struct BrokerConfig { - pub pipe_name: String, - pub audit_log: PathBuf, - pub lease_dir: PathBuf, -} - -impl Default for BrokerConfig { - fn default() -> Self { - let root = std::env::var_os("ProgramData") - .map(PathBuf::from) - .unwrap_or_else(|| PathBuf::from(r"C:\ProgramData")); - Self { - pipe_name: DEFAULT_PIPE_NAME.into(), - audit_log: root.join("axis").join("logs").join("wfp-broker.jsonl"), - lease_dir: root.join("axis").join("wfp-leases"), - } - } -} - -/// Non-mutating availability probe used by policy planning. It does not open -/// a lease or consume a pipe instance. -pub fn broker_available(pipe_name: &str) -> bool { - let pipe_name = wide(pipe_name); - unsafe { WaitNamedPipeW(PCWSTR(pipe_name.as_ptr()), 250) }.as_bool() -} - -struct NetEventCollectionGuard { - engine: HANDLE, - restore_disabled: bool, -} - -unsafe impl Send for NetEventCollectionGuard {} - -struct FwpmAllocatedValue(NonNull); - -impl FwpmAllocatedValue { - fn from_raw(value: *mut FWP_VALUE0) -> Result { - NonNull::new(value) - .map(Self) - .ok_or_else(|| "FwpmEngineGetOption0 returned a null value".into()) - } - - fn get(&self) -> &FWP_VALUE0 { - // SAFETY: a successful FwpmEngineGetOption0 call returns an allocated - // FWP_VALUE0 that remains readable until FwpmFreeMemory0 releases it. - unsafe { self.0.as_ref() } - } -} - -impl Drop for FwpmAllocatedValue { - fn drop(&mut self) { - let mut value = self.0.as_ptr(); - unsafe { - FwpmFreeMemory0((&mut value as *mut *mut FWP_VALUE0).cast()); - } - } -} - -impl NetEventCollectionGuard { - fn enable() -> Result { - let mut engine = HANDLE::default(); - check_wfp( - unsafe { FwpmEngineOpen0(PCWSTR::null(), RPC_C_AUTHN_WINNT, None, None, &mut engine) }, - "FwpmEngineOpen0(audit)", - )?; - - let mut current = MaybeUninit::<*mut FWP_VALUE0>::uninit(); - let get_result = check_wfp( - unsafe { - FwpmEngineGetOption0(engine, FWPM_ENGINE_COLLECT_NET_EVENTS, current.as_mut_ptr()) - }, - "FwpmEngineGetOption0(net events)", - ); - if let Err(error) = get_result { - unsafe { - let _ = FwpmEngineClose0(engine); - } - return Err(error); - } - // SAFETY: FwpmEngineGetOption0 initializes the out parameter on success. - let current = unsafe { current.assume_init() }; - let current = match FwpmAllocatedValue::from_raw(current) { - Ok(current) => current, - Err(error) => { - unsafe { - let _ = FwpmEngineClose0(engine); - } - return Err(error); - } - }; - let value = current.get(); - let was_enabled = unsafe { value.r#type == FWP_UINT32 && value.Anonymous.uint32 != 0 }; - drop(current); - - if !was_enabled && let Err(error) = set_net_event_collection(engine, true) { - unsafe { - let _ = FwpmEngineClose0(engine); - } - return Err(error); - } - Ok(Self { - engine, - restore_disabled: !was_enabled, - }) - } -} - -impl Drop for NetEventCollectionGuard { - fn drop(&mut self) { - if self.restore_disabled { - let _ = set_net_event_collection(self.engine, false); - } - unsafe { - let _ = FwpmEngineClose0(self.engine); - } - } -} - -fn set_net_event_collection(engine: HANDLE, enabled: bool) -> Result<(), String> { - let value = FWP_VALUE0 { - r#type: FWP_UINT32, - Anonymous: FWP_VALUE0_0 { - uint32: u32::from(enabled), - }, - }; - check_wfp( - unsafe { FwpmEngineSetOption0(engine, FWPM_ENGINE_COLLECT_NET_EVENTS, &value) }, - "FwpmEngineSetOption0(net events)", - ) -} - -struct BrokerInstanceGuard(HANDLE); - -impl BrokerInstanceGuard { - fn acquire() -> Result { - let handle = unsafe { - CreateMutexW( - None, - false, - PCWSTR(wide(r"Global\AxisWfpBrokerV1").as_ptr()), - ) - } - .map_err(|e| format!("create broker singleton mutex: {e}"))?; - if unsafe { GetLastError() } == ERROR_ALREADY_EXISTS { - unsafe { - let _ = CloseHandle(handle); - } - return Err("another AXIS WFP broker instance is already running".into()); - } - Ok(Self(handle)) - } -} - -impl Drop for BrokerInstanceGuard { - fn drop(&mut self) { - unsafe { - let _ = CloseHandle(self.0); - } - } -} - -/// Serve lease requests until `stop` becomes true. -/// -/// Each accepted connection owns one dynamic WFP engine. The connection is -/// held open by `wxc-exec` for the complete sandbox lifetime, so disconnect, -/// executor crash, broker process exit, or service stop removes every filter -/// in the lease without a persistent recovery journal. -pub fn serve(config: BrokerConfig, stop: Arc) -> Result<(), String> { - let _instance = BrokerInstanceGuard::acquire()?; - let _net_event_collection = NetEventCollectionGuard::enable()?; - reap_stale_leases(&config.lease_dir, &config.audit_log)?; - while !stop.load(Ordering::Acquire) { - let pipe = create_pipe(&config.pipe_name)?; - let connected = unsafe { ConnectNamedPipe(pipe, None) }; - if connected.is_err() { - let err = unsafe { GetLastError() }; - if err != ERROR_PIPE_CONNECTED { - unsafe { - let _ = CloseHandle(pipe); - } - if stop.load(Ordering::Acquire) { - return Ok(()); - } - return Err(format!("ConnectNamedPipe failed: {err:?}")); - } - } - - let child_config = config.clone(); - let raw_pipe = pipe.0 as usize; - std::thread::spawn(move || { - // SAFETY: ownership of the connected handle moves into File and is - // released exactly once at the end of this worker. - let mut stream = unsafe { File::from_raw_handle(raw_pipe as *mut c_void) }; - if let Err(error) = handle_connection(&mut stream, &child_config) { - let _ = append_audit( - &child_config.audit_log, - serde_json::json!({ - "event": "lease_error", - "error": error, - }), - ); - } - let raw = stream.into_raw_handle(); - unsafe { - let handle = HANDLE(raw); - let _ = DisconnectNamedPipe(handle); - let _ = CloseHandle(handle); - } - }); - } - Ok(()) -} - -fn handle_connection(stream: &mut File, config: &BrokerConfig) -> Result<(), String> { - let caller_pid = pipe_client_pid(stream)?; - let request_bytes = read_frame(stream)?; - let parsed: Result = serde_json::from_slice(&request_bytes); - let request = match parsed { - Ok(request) => request, - Err(error) => { - let response = - LeaseResponse::rejected(Uuid::nil(), format!("invalid request: {error}")); - write_frame( - stream, - &serde_json::to_vec(&response).map_err(|e| e.to_string())?, - )?; - return Err(response.error.unwrap_or_default()); - } - }; - - let result = (|| { - request.validate()?; - validate_executor_and_child(caller_pid, request.child_pid)?; - let identity = read_app_container_identity(request.child_pid)?; - let lease = WfpLease::install( - &request, - &identity.sid_bytes, - &config.audit_log, - &config.lease_dir, - )?; - Ok::<_, String>((identity.sid_string, lease)) - })(); - - match result { - Ok((sid, lease)) => { - let response = LeaseResponse::accepted(&request, sid.clone(), lease.filter_count); - write_frame( - stream, - &serde_json::to_vec(&response).map_err(|e| e.to_string())?, - )?; - append_audit( - &config.audit_log, - serde_json::json!({ - "event": "lease_installed", - "leaseId": request.lease_id, - "callerPid": caller_pid, - "childPid": request.child_pid, - "appContainerSid": sid, - "proxyAddress": request.proxy_address, - "proxyPort": request.proxy_port, - "filterCount": lease.filter_count, - }), - )?; - - // The executor writes no more data. EOF is the lease-release signal. - let mut discard = [0u8; 128]; - match stream.read(&mut discard) { - Ok(_) => {} - Err(error) if error.raw_os_error() == Some(ERROR_BROKEN_PIPE.0 as i32) => {} - Err(error) => return Err(format!("lease pipe read failed: {error}")), - } - drop(lease); - append_audit( - &config.audit_log, - serde_json::json!({ - "event": "lease_removed", - "leaseId": request.lease_id, - "childPid": request.child_pid, - }), - )?; - Ok(()) - } - Err(error) => { - let response = LeaseResponse::rejected(request.lease_id, error.clone()); - write_frame( - stream, - &serde_json::to_vec(&response).map_err(|e| e.to_string())?, - )?; - append_audit( - &config.audit_log, - serde_json::json!({ - "event": "lease_rejected", - "leaseId": request.lease_id, - "callerPid": caller_pid, - "childPid": request.child_pid, - "error": error, - }), - )?; - Err(response.error.unwrap_or_default()) - } - } -} - -fn create_pipe(name: &str) -> Result { - let wide_name = wide(name); - // Deny AppContainer clients explicitly. Authenticated host callers may - // connect, after which process-image, parent, and child-token validation - // narrow the accepted operation. - let sddl = wide("D:P(D;;GA;;;AC)(A;;GA;;;SY)(A;;GA;;;BA)(A;;GRGW;;;AU)"); - let mut descriptor = PSECURITY_DESCRIPTOR::default(); - unsafe { - ConvertStringSecurityDescriptorToSecurityDescriptorW( - PCWSTR(sddl.as_ptr()), - SDDL_REVISION_1, - &mut descriptor, - None, - ) - .map_err(|e| format!("pipe security descriptor: {e}"))?; - } - let attributes = windows::Win32::Security::SECURITY_ATTRIBUTES { - nLength: size_of::() as u32, - lpSecurityDescriptor: descriptor.0, - bInheritHandle: false.into(), - }; - let pipe = unsafe { - CreateNamedPipeW( - PCWSTR(wide_name.as_ptr()), - PIPE_ACCESS_DUPLEX, - PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS, - 255, - PIPE_BUFFER_BYTES, - PIPE_BUFFER_BYTES, - 0, - Some(&attributes), - ) - }; - unsafe { - let _ = LocalFree(Some(HLOCAL(descriptor.0))); - } - if pipe == INVALID_HANDLE_VALUE { - Err(format!("CreateNamedPipeW failed: {:?}", unsafe { - GetLastError() - })) - } else { - Ok(pipe) - } -} - -fn pipe_client_pid(stream: &File) -> Result { - use std::os::windows::io::AsRawHandle; - let mut pid = 0; - let handle = HANDLE(stream.as_raw_handle()); - unsafe { GetNamedPipeClientProcessId(handle, &mut pid) } - .map_err(|e| format!("GetNamedPipeClientProcessId failed: {e}"))?; - if pid == 0 { - Err("named-pipe client PID was zero".into()) - } else { - Ok(pid) - } -} - -fn validate_executor_and_child(caller_pid: u32, child_pid: u32) -> Result<(), String> { - if caller_pid == unsafe { GetCurrentProcessId() } || caller_pid == child_pid { - return Err("invalid executor/child PID relationship".into()); - } - let image = process_image(caller_pid)?; - let basename = Path::new(&image) - .file_name() - .and_then(|value| value.to_str()) - .unwrap_or_default(); - if !basename.eq_ignore_ascii_case("wxc-exec.exe") { - return Err(format!( - "broker caller image must be wxc-exec.exe (got {basename:?})" - )); - } - let parent = process_parent_pid(child_pid)?; - if parent != caller_pid { - return Err(format!( - "suspended child PID {child_pid} is not owned by executor PID {caller_pid}" - )); - } - Ok(()) -} - -fn process_image(pid: u32) -> Result { - let process = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) } - .map_err(|e| format!("OpenProcess({pid}) failed: {e}"))?; - let mut buffer = vec![0u16; 32_768]; - let mut len = buffer.len() as u32; - let result = unsafe { - QueryFullProcessImageNameW( - process, - PROCESS_NAME_WIN32, - PWSTR(buffer.as_mut_ptr()), - &mut len, - ) - }; - unsafe { - let _ = CloseHandle(process); - } - result.map_err(|e| format!("QueryFullProcessImageNameW({pid}) failed: {e}"))?; - Ok(String::from_utf16_lossy(&buffer[..len as usize])) -} - -fn process_parent_pid(pid: u32) -> Result { - let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) } - .map_err(|e| format!("CreateToolhelp32Snapshot failed: {e}"))?; - let mut entry = PROCESSENTRY32W { - dwSize: size_of::() as u32, - ..Default::default() - }; - let mut found = None; - if unsafe { Process32FirstW(snapshot, &mut entry) }.is_ok() { - loop { - if entry.th32ProcessID == pid { - found = Some(entry.th32ParentProcessID); - break; - } - if unsafe { Process32NextW(snapshot, &mut entry) }.is_err() { - break; - } - } - } - unsafe { - let _ = CloseHandle(snapshot); - } - found.ok_or_else(|| format!("child PID {pid} not found in process snapshot")) -} - -struct AppContainerIdentity { - sid_bytes: Vec, - sid_string: String, -} - -fn read_app_container_identity(pid: u32) -> Result { - let process = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) } - .map_err(|e| format!("OpenProcess({pid}) failed: {e}"))?; - let mut token = HANDLE::default(); - let token_result = unsafe { OpenProcessToken(process, TOKEN_QUERY, &mut token) }; - unsafe { - let _ = CloseHandle(process); - } - token_result.map_err(|e| format!("OpenProcessToken({pid}) failed: {e}"))?; - - let result = (|| { - let mut is_app_container = 0u32; - let mut returned = 0u32; - unsafe { - GetTokenInformation( - token, - TokenIsAppContainer, - Some((&mut is_app_container as *mut u32).cast()), - size_of::() as u32, - &mut returned, - ) - } - .map_err(|e| format!("GetTokenInformation(TokenIsAppContainer): {e}"))?; - if is_app_container == 0 { - return Err("target child is not running with an AppContainer token".into()); - } - - let mut required = 0u32; - let _ = unsafe { GetTokenInformation(token, TokenAppContainerSid, None, 0, &mut required) }; - if required < size_of::() as u32 { - return Err(format!( - "TokenAppContainerSid reported an invalid buffer size {required}" - )); - } - let words = (required as usize).div_ceil(size_of::()); - let mut info_buffer = vec![0usize; words]; - unsafe { - GetTokenInformation( - token, - TokenAppContainerSid, - Some(info_buffer.as_mut_ptr().cast()), - required, - &mut returned, - ) - } - .map_err(|e| format!("GetTokenInformation(TokenAppContainerSid): {e}"))?; - let info = unsafe { - &*(info_buffer - .as_ptr() - .cast::()) - }; - if info.TokenAppContainer.is_invalid() { - return Err("AppContainer token returned a null package SID".into()); - } - - let sid_len = unsafe { GetLengthSid(info.TokenAppContainer) } as usize; - if sid_len == 0 { - return Err("GetLengthSid returned zero".into()); - } - let sid_bytes = unsafe { - std::slice::from_raw_parts(info.TokenAppContainer.0.cast::(), sid_len).to_vec() - }; - let mut sid_text = PWSTR::null(); - unsafe { ConvertSidToStringSidW(info.TokenAppContainer, &mut sid_text) } - .map_err(|e| format!("ConvertSidToStringSidW failed: {e}"))?; - let sid_string = unsafe { sid_text.to_string() } - .map_err(|e| format!("AppContainer SID was not valid UTF-16: {e}"))?; - unsafe { - let _ = LocalFree(Some(HLOCAL(sid_text.0.cast()))); - } - Ok(AppContainerIdentity { - sid_bytes, - sid_string, - }) - })(); - unsafe { - let _ = CloseHandle(token); - } - result -} - -#[derive(Debug, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct LeaseJournal { - version: u32, - lease_id: Uuid, - child_pid: u32, - child_creation_time: u64, -} - -fn write_lease_journal(directory: &Path, journal: &LeaseJournal) -> Result { - std::fs::create_dir_all(directory) - .map_err(|e| format!("create WFP lease journal directory: {e}"))?; - let path = directory.join(format!("{}.json", journal.lease_id)); - let mut file = OpenOptions::new() - .write(true) - .create_new(true) - .open(&path) - .map_err(|e| format!("create WFP lease journal {}: {e}", path.display()))?; - serde_json::to_writer(&mut file, journal) - .map_err(|e| format!("write WFP lease journal {}: {e}", path.display()))?; - file.write_all(b"\n") - .and_then(|_| file.sync_all()) - .map_err(|e| format!("flush WFP lease journal {}: {e}", path.display()))?; - Ok(path) -} - -fn process_creation_time(pid: u32) -> Result { - let process = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) } - .map_err(|e| format!("OpenProcess({pid}) for creation time failed: {e}"))?; - let mut creation = FILETIME::default(); - let mut exit = FILETIME::default(); - let mut kernel = FILETIME::default(); - let mut user = FILETIME::default(); - let result = - unsafe { GetProcessTimes(process, &mut creation, &mut exit, &mut kernel, &mut user) }; - unsafe { - let _ = CloseHandle(process); - } - result.map_err(|e| format!("GetProcessTimes({pid}) failed: {e}"))?; - Ok((u64::from(creation.dwHighDateTime) << 32) | u64::from(creation.dwLowDateTime)) -} - -fn reap_stale_leases(directory: &Path, audit_log: &Path) -> Result<(), String> { - std::fs::create_dir_all(directory) - .map_err(|e| format!("create WFP lease journal directory: {e}"))?; - let mut journals = Vec::new(); - for entry in std::fs::read_dir(directory) - .map_err(|e| format!("read WFP lease journal directory: {e}"))? - { - let entry = entry.map_err(|e| format!("read WFP lease journal entry: {e}"))?; - if entry.path().extension().and_then(|value| value.to_str()) != Some("json") { - continue; - } - let bytes = std::fs::read(entry.path()) - .map_err(|e| format!("read WFP lease journal {}: {e}", entry.path().display()))?; - let journal: LeaseJournal = serde_json::from_slice(&bytes) - .map_err(|e| format!("parse WFP lease journal {}: {e}", entry.path().display()))?; - if journal.version != 1 - || entry.file_name().to_string_lossy() != format!("{}.json", journal.lease_id) - { - return Err(format!( - "invalid WFP lease journal identity in {}", - entry.path().display() - )); - } - journals.push((entry.path(), journal)); - } - if journals.is_empty() { - return Ok(()); - } - - let mut engine = HANDLE::default(); - check_wfp( - unsafe { FwpmEngineOpen0(PCWSTR::null(), RPC_C_AUTHN_WINNT, None, None, &mut engine) }, - "FwpmEngineOpen0(recovery)", - )?; - let result = (|| { - for (path, journal) in journals { - terminate_matching_process(&journal)?; - cleanup_persistent_blocks(engine, journal.lease_id)?; - std::fs::remove_file(&path) - .map_err(|e| format!("remove recovered WFP journal {}: {e}", path.display()))?; - append_audit( - audit_log, - serde_json::json!({ - "event": "stale_lease_reaped", - "leaseId": journal.lease_id, - "childPid": journal.child_pid, - }), - )?; - } - Ok(()) - })(); - unsafe { - let _ = FwpmEngineClose0(engine); - } - result -} - -fn terminate_matching_process(journal: &LeaseJournal) -> Result<(), String> { - let process = match unsafe { - OpenProcess( - PROCESS_QUERY_LIMITED_INFORMATION - | PROCESS_TERMINATE - | PROCESS_ACCESS_RIGHTS(0x0010_0000), - false, - journal.child_pid, - ) - } { - Ok(process) => process, - Err(_) => return Ok(()), - }; - let current_creation = process_creation_time(journal.child_pid); - if current_creation == Ok(journal.child_creation_time) { - unsafe { - let _ = TerminateProcess(process, u32::MAX); - let _ = WaitForSingleObject(process, 5_000); - } - } - unsafe { - let _ = CloseHandle(process); - } - current_creation.map(|_| ()) -} - -fn cleanup_persistent_blocks(engine: HANDLE, lease_id: Uuid) -> Result<(), String> { - for discriminator in [10, 11] { - let status = unsafe { FwpmFilterDeleteByKey0(engine, &guid_for(lease_id, discriminator)) }; - if status != 0 && status != FWP_E_FILTER_NOT_FOUND.0 as u32 { - return Err(format!( - "FwpmFilterDeleteByKey0(recovery) failed with 0x{status:08X}" - )); - } - } - let status = unsafe { FwpmSubLayerDeleteByKey0(engine, &guid_for(lease_id, 0)) }; - if status != 0 && status != FWP_E_SUBLAYER_NOT_FOUND.0 as u32 { - return Err(format!( - "FwpmSubLayerDeleteByKey0(recovery) failed with 0x{status:08X}" - )); - } - Ok(()) -} - -struct WfpLease { - persistent_engine: HANDLE, - dynamic_engine: HANDLE, - filter_count: u32, - block_filter_ids: Vec, - sublayer_key: GUID, - lease_id: Uuid, - event_handle: HANDLE, - audit_context: Option>, - journal_path: Option, -} - -unsafe impl Send for WfpLease {} - -impl Drop for WfpLease { - fn drop(&mut self) { - if !self.event_handle.is_invalid() { - unsafe { - let _ = FwpmNetEventUnsubscribe0(self.persistent_engine, self.event_handle); - } - self.event_handle = HANDLE::default(); - } - self.audit_context.take(); - // Remove the proxy permit first. If cleanup is interrupted after this - // point, the persistent blocks leave the ephemeral identity fail-closed. - if !self.dynamic_engine.is_invalid() { - unsafe { - let _ = FwpmEngineClose0(self.dynamic_engine); - } - self.dynamic_engine = HANDLE::default(); - } - if !self.persistent_engine.is_invalid() { - let cleanup = cleanup_persistent_blocks(self.persistent_engine, self.lease_id); - unsafe { - let _ = FwpmEngineClose0(self.persistent_engine); - } - self.persistent_engine = HANDLE::default(); - if cleanup.is_ok() - && let Some(path) = self.journal_path.take() - { - let _ = std::fs::remove_file(path); - } - } - } -} - -impl WfpLease { - fn install( - request: &LeaseRequest, - sid_bytes: &[u8], - audit_log: &Path, - lease_dir: &Path, - ) -> Result { - let mut persistent_engine = HANDLE::default(); - check_wfp( - unsafe { - FwpmEngineOpen0( - PCWSTR::null(), - RPC_C_AUTHN_WINNT, - None, - None, - &mut persistent_engine, - ) - }, - "FwpmEngineOpen0(persistent blocks)", - )?; - let sublayer_key = guid_for(request.lease_id, 0); - let mut lease = Self { - persistent_engine, - dynamic_engine: HANDLE::default(), - filter_count: 0, - block_filter_ids: Vec::with_capacity(2), - sublayer_key, - lease_id: request.lease_id, - event_handle: HANDLE::default(), - audit_context: None, - journal_path: None, - }; - - let journal = LeaseJournal { - version: 1, - lease_id: request.lease_id, - child_pid: request.child_pid, - child_creation_time: process_creation_time(request.child_pid)?, - }; - lease.journal_path = Some(write_lease_journal(lease_dir, &journal)?); - - check_wfp( - unsafe { FwpmTransactionBegin0(lease.persistent_engine, 0) }, - "FwpmTransactionBegin0(persistent blocks)", - )?; - match lease.install_persistent_blocks(request, sid_bytes) { - Ok(()) => { - if let Err(error) = check_wfp( - unsafe { FwpmTransactionCommit0(lease.persistent_engine) }, - "FwpmTransactionCommit0(persistent blocks)", - ) { - unsafe { - let _ = FwpmTransactionAbort0(lease.persistent_engine); - } - return Err(error); - } - } - Err(error) => { - unsafe { - let _ = FwpmTransactionAbort0(lease.persistent_engine); - } - return Err(error); - } - } - - let session_name = wide(&format!("AXIS strict proxy permit {}", request.lease_id)); - let session = FWPM_SESSION0 { - displayData: FWPM_DISPLAY_DATA0 { - name: PWSTR(session_name.as_ptr() as *mut u16), - description: PWSTR::null(), - }, - flags: FWPM_SESSION_FLAG_DYNAMIC, - txnWaitTimeoutInMSec: 10_000, - ..Default::default() - }; - check_wfp( - unsafe { - FwpmEngineOpen0( - PCWSTR::null(), - RPC_C_AUTHN_WINNT, - None, - Some(&session), - &mut lease.dynamic_engine, - ) - }, - "FwpmEngineOpen0(dynamic permit)", - )?; - check_wfp( - unsafe { FwpmTransactionBegin0(lease.dynamic_engine, 0) }, - "FwpmTransactionBegin0(dynamic permit)", - )?; - if let Err(error) = lease.install_dynamic_allow(request, sid_bytes) { - unsafe { - let _ = FwpmTransactionAbort0(lease.dynamic_engine); - } - return Err(error); - } - if let Err(error) = check_wfp( - unsafe { FwpmTransactionCommit0(lease.dynamic_engine) }, - "FwpmTransactionCommit0(dynamic permit)", - ) { - unsafe { - let _ = FwpmTransactionAbort0(lease.dynamic_engine); - } - return Err(error); - } - lease.filter_count = 3; - lease.subscribe_to_block_events(request, audit_log)?; - Ok(lease) - } - - fn install_persistent_blocks( - &mut self, - request: &LeaseRequest, - sid_bytes: &[u8], - ) -> Result<(), String> { - let sublayer_name = wide(&format!("AXIS lease {}", request.lease_id)); - let sublayer = FWPM_SUBLAYER0 { - subLayerKey: self.sublayer_key, - displayData: FWPM_DISPLAY_DATA0 { - name: PWSTR(sublayer_name.as_ptr() as *mut u16), - description: PWSTR::null(), - }, - weight: u16::MAX - 1, - ..Default::default() - }; - check_wfp( - unsafe { FwpmSubLayerAdd0(self.persistent_engine, &sublayer, None) }, - "FwpmSubLayerAdd0", - )?; - - let mut sid = sid_bytes.to_vec(); - let sid_ptr = PSID(sid.as_mut_ptr().cast()); - let block_v4 = self.add_block( - request, - self.sublayer_key, - sid_ptr, - FWPM_LAYER_ALE_AUTH_CONNECT_V4, - 10, - )?; - self.block_filter_ids.push(block_v4); - let block_v6 = self.add_block( - request, - self.sublayer_key, - sid_ptr, - FWPM_LAYER_ALE_AUTH_CONNECT_V6, - 11, - )?; - self.block_filter_ids.push(block_v6); - Ok(()) - } - - fn install_dynamic_allow( - &self, - request: &LeaseRequest, - sid_bytes: &[u8], - ) -> Result<(), String> { - let permit_sublayer_key = guid_for(request.lease_id, 3); - let name = wide(&format!("AXIS proxy permit {}", request.lease_id)); - let sublayer = FWPM_SUBLAYER0 { - subLayerKey: permit_sublayer_key, - displayData: FWPM_DISPLAY_DATA0 { - name: PWSTR(name.as_ptr() as *mut u16), - description: PWSTR::null(), - }, - weight: u16::MAX, - ..Default::default() - }; - check_wfp( - unsafe { FwpmSubLayerAdd0(self.dynamic_engine, &sublayer, None) }, - "FwpmSubLayerAdd0(dynamic permit)", - )?; - let mut sid = sid_bytes.to_vec(); - let sid_ptr = PSID(sid.as_mut_ptr().cast()); - match request.proxy_address { - IpAddr::V4(address) => { - self.add_allow_v4(request, permit_sublayer_key, sid_ptr, address.octets())?; - } - IpAddr::V6(address) => { - self.add_allow_v6(request, permit_sublayer_key, sid_ptr, address.octets())?; - } - } - Ok(()) - } - - fn add_allow_v4( - &self, - request: &LeaseRequest, - sublayer_key: GUID, - sid: PSID, - address: [u8; 4], - ) -> Result { - let mut addr = FWP_V4_ADDR_AND_MASK { - addr: u32::from_be_bytes(address), - mask: u32::MAX, - }; - let mut conditions = common_allow_conditions(sid, request.proxy_port); - conditions.push(FWPM_FILTER_CONDITION0 { - fieldKey: FWPM_CONDITION_IP_REMOTE_ADDRESS, - matchType: FWP_MATCH_EQUAL, - conditionValue: FWP_CONDITION_VALUE0 { - r#type: FWP_V4_ADDR_MASK, - Anonymous: FWP_CONDITION_VALUE0_0 { - v4AddrMask: &mut addr, - }, - }, - }); - let _ = self.add_filter( - self.dynamic_engine, - request, - sublayer_key, - FWPM_LAYER_ALE_AUTH_CONNECT_V4, - 1, - u64::MAX, - FWP_ACTION_PERMIT, - &mut conditions, - )?; - Ok(1) - } - - fn add_allow_v6( - &self, - request: &LeaseRequest, - sublayer_key: GUID, - sid: PSID, - address: [u8; 16], - ) -> Result { - let mut addr = FWP_V6_ADDR_AND_MASK { - addr: address, - prefixLength: 128, - }; - let mut conditions = common_allow_conditions(sid, request.proxy_port); - conditions.push(FWPM_FILTER_CONDITION0 { - fieldKey: FWPM_CONDITION_IP_REMOTE_ADDRESS, - matchType: FWP_MATCH_EQUAL, - conditionValue: FWP_CONDITION_VALUE0 { - r#type: FWP_V6_ADDR_MASK, - Anonymous: FWP_CONDITION_VALUE0_0 { - v6AddrMask: &mut addr, - }, - }, - }); - let _ = self.add_filter( - self.dynamic_engine, - request, - sublayer_key, - FWPM_LAYER_ALE_AUTH_CONNECT_V6, - 2, - u64::MAX, - FWP_ACTION_PERMIT, - &mut conditions, - )?; - Ok(1) - } - - fn add_block( - &self, - request: &LeaseRequest, - sublayer_key: GUID, - sid: PSID, - layer: GUID, - discriminator: u8, - ) -> Result { - let mut conditions = vec![sid_condition(sid)]; - self.add_filter( - self.persistent_engine, - request, - sublayer_key, - layer, - discriminator, - 1, - FWP_ACTION_BLOCK, - &mut conditions, - ) - } - - #[allow(clippy::too_many_arguments)] - fn add_filter( - &self, - engine: HANDLE, - request: &LeaseRequest, - sublayer_key: GUID, - layer: GUID, - discriminator: u8, - mut weight_value: u64, - action_type: windows::Win32::NetworkManagement::WindowsFilteringPlatform::FWP_ACTION_TYPE, - conditions: &mut [FWPM_FILTER_CONDITION0], - ) -> Result { - let name = wide(&format!( - "AXIS lease {} filter {discriminator}", - request.lease_id - )); - let filter = FWPM_FILTER0 { - filterKey: guid_for(request.lease_id, discriminator), - displayData: FWPM_DISPLAY_DATA0 { - name: PWSTR(name.as_ptr() as *mut u16), - description: PWSTR::null(), - }, - flags: FWPM_FILTER_FLAG_CLEAR_ACTION_RIGHT, - layerKey: layer, - subLayerKey: sublayer_key, - weight: FWP_VALUE0 { - r#type: FWP_UINT64, - Anonymous: FWP_VALUE0_0 { - uint64: &mut weight_value, - }, - }, - numFilterConditions: conditions.len() as u32, - filterCondition: conditions.as_mut_ptr(), - action: FWPM_ACTION0 { - r#type: action_type, - ..Default::default() - }, - ..Default::default() - }; - let mut id = 0u64; - check_wfp( - unsafe { FwpmFilterAdd0(engine, &filter, None, Some(&mut id)) }, - "FwpmFilterAdd0", - )?; - Ok(id) - } - - fn subscribe_to_block_events( - &mut self, - request: &LeaseRequest, - audit_log: &Path, - ) -> Result<(), String> { - if self.block_filter_ids.len() != 2 { - return Err("strict-proxy lease did not retain both block-filter IDs".into()); - } - let mut context = Box::new(WfpAuditContext { - audit_log: audit_log.to_path_buf(), - lease_id: request.lease_id, - child_pid: request.child_pid, - block_filter_ids: [self.block_filter_ids[0], self.block_filter_ids[1]], - }); - let subscription = FWPM_NET_EVENT_SUBSCRIPTION0::default(); - let mut event_handle = HANDLE::default(); - check_wfp( - unsafe { - FwpmNetEventSubscribe4( - self.persistent_engine, - &subscription, - Some(wfp_net_event_callback), - Some((&mut *context as *mut WfpAuditContext).cast()), - &mut event_handle, - ) - }, - "FwpmNetEventSubscribe4", - )?; - self.event_handle = event_handle; - self.audit_context = Some(context); - Ok(()) - } -} - -struct WfpAuditContext { - audit_log: PathBuf, - lease_id: Uuid, - child_pid: u32, - block_filter_ids: [u64; 2], -} - -unsafe extern "system" fn wfp_net_event_callback( - context: *mut c_void, - event: *const FWPM_NET_EVENT5, -) { - if context.is_null() || event.is_null() { - return; - } - let context = unsafe { &*(context.cast::()) }; - let event = unsafe { &*event }; - if event.r#type != FWPM_NET_EVENT_TYPE_CLASSIFY_DROP { - return; - } - let drop_event = unsafe { event.Anonymous.classifyDrop }; - if drop_event.is_null() { - return; - } - let filter_id = unsafe { (*drop_event).filterId }; - if !context.block_filter_ids.contains(&filter_id) { - return; - } - - let header = &event.header; - let remote_address = if header.flags & FWPM_NET_EVENT_FLAG_REMOTE_ADDR_SET == 0 { - None - } else if header.ipVersion == FWP_IP_VERSION_V4 { - let value = unsafe { header.Anonymous2.remoteAddrV4 }; - Some(IpAddr::V4(Ipv4Addr::from(value.to_be_bytes()))) - } else if header.ipVersion == FWP_IP_VERSION_V6 { - let value = unsafe { header.Anonymous2.remoteAddrV6.byteArray16 }; - Some(IpAddr::V6(Ipv6Addr::from(value))) - } else { - None - }; - let remote_port = - (header.flags & FWPM_NET_EVENT_FLAG_REMOTE_PORT_SET != 0).then_some(header.remotePort); - let protocol = - (header.flags & FWPM_NET_EVENT_FLAG_IP_PROTOCOL_SET != 0).then_some(header.ipProtocol); - let ip_version = (header.flags & FWPM_NET_EVENT_FLAG_IP_VERSION_SET != 0).then(|| { - if header.ipVersion == FWP_IP_VERSION_V4 { - 4 - } else if header.ipVersion == FWP_IP_VERSION_V6 { - 6 - } else { - 0 - } - }); - - let _ = append_audit( - &context.audit_log, - serde_json::json!({ - "event": "connection_blocked", - "leaseId": context.lease_id, - "childPid": context.child_pid, - "filterId": filter_id, - "ipVersion": ip_version, - "protocol": protocol, - "remoteAddress": remote_address, - "remotePort": remote_port, - }), - ); -} - -fn common_allow_conditions(sid: PSID, port: u16) -> Vec { - vec![ - sid_condition(sid), - FWPM_FILTER_CONDITION0 { - fieldKey: FWPM_CONDITION_IP_PROTOCOL, - matchType: FWP_MATCH_EQUAL, - conditionValue: FWP_CONDITION_VALUE0 { - r#type: FWP_UINT8, - Anonymous: FWP_CONDITION_VALUE0_0 { uint8: IPPROTO_TCP }, - }, - }, - FWPM_FILTER_CONDITION0 { - fieldKey: FWPM_CONDITION_IP_REMOTE_PORT, - matchType: FWP_MATCH_EQUAL, - conditionValue: FWP_CONDITION_VALUE0 { - r#type: FWP_UINT16, - Anonymous: FWP_CONDITION_VALUE0_0 { uint16: port }, - }, - }, - ] -} - -fn sid_condition(sid: PSID) -> FWPM_FILTER_CONDITION0 { - FWPM_FILTER_CONDITION0 { - fieldKey: FWPM_CONDITION_ALE_PACKAGE_ID, - matchType: FWP_MATCH_EQUAL, - conditionValue: FWP_CONDITION_VALUE0 { - r#type: FWP_SID, - Anonymous: FWP_CONDITION_VALUE0_0 { sid: sid.0.cast() }, - }, - } -} - -fn guid_for(lease_id: Uuid, discriminator: u8) -> GUID { - let mut bytes = *lease_id.as_bytes(); - bytes[15] ^= discriminator; - GUID::from_u128(u128::from_be_bytes(bytes)) -} - -fn check_wfp(status: u32, operation: &str) -> Result<(), String> { - if status == 0 { - Ok(()) - } else { - Err(format!("{operation} failed with WFP status 0x{status:08X}")) - } -} - -fn read_frame(stream: &mut File) -> Result, String> { - let mut length = [0u8; 4]; - stream - .read_exact(&mut length) - .map_err(|e| format!("read request length: {e}"))?; - let length = u32::from_le_bytes(length) as usize; - if length == 0 || length > MAX_MESSAGE_BYTES { - return Err(format!("invalid request length {length}")); - } - let mut payload = vec![0u8; length]; - stream - .read_exact(&mut payload) - .map_err(|e| format!("read request payload: {e}"))?; - Ok(payload) -} - -fn write_frame(stream: &mut File, payload: &[u8]) -> Result<(), String> { - if payload.is_empty() || payload.len() > MAX_MESSAGE_BYTES { - return Err(format!("invalid response length {}", payload.len())); - } - stream - .write_all(&(payload.len() as u32).to_le_bytes()) - .and_then(|_| stream.write_all(payload)) - .and_then(|_| stream.flush()) - .map_err(|e| format!("write response: {e}")) -} - -fn append_audit(path: &Path, mut event: serde_json::Value) -> Result<(), String> { - let _guard = AUDIT_WRITE_LOCK - .get_or_init(|| Mutex::new(())) - .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()); - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent).map_err(|e| format!("create WFP audit directory: {e}"))?; - } - if let Some(object) = event.as_object_mut() { - object.insert( - "timestampUnixMs".into(), - serde_json::Value::from( - SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default() - .as_millis() as u64, - ), - ); - } - let mut file = OpenOptions::new() - .create(true) - .append(true) - .open(path) - .map_err(|e| format!("open WFP audit log: {e}"))?; - let mut line = - serde_json::to_vec(&event).map_err(|e| format!("encode WFP audit event: {e}"))?; - line.push(b'\n'); - // One append write prevents records from separate broker generations from - // interleaving during a service restart. - file.write_all(&line) - .map_err(|e| format!("write WFP audit event: {e}")) -} - -fn wide(value: &str) -> Vec { - value.encode_utf16().chain(Some(0)).collect() -} - -#[cfg(test)] -mod tests { - use super::*; - - fn request() -> LeaseRequest { - LeaseRequest { - version: PROTOCOL_VERSION, - lease_id: Uuid::new_v4(), - child_pid: 123, - proxy_address: "127.0.0.1".parse().unwrap(), - proxy_port: 31_280, - } - } - - #[test] - fn lease_request_accepts_only_concrete_nonzero_endpoint() { - request().validate().unwrap(); - for address in ["0.0.0.0", "::", "224.0.0.1", "ff02::1"] { - let mut invalid = request(); - invalid.proxy_address = address.parse().unwrap(); - assert!(invalid.validate().is_err(), "{address}"); - } - let mut invalid = request(); - invalid.proxy_port = 0; - assert!(invalid.validate().is_err()); - } - - #[test] - fn protocol_rejects_unknown_fields() { - let mut value = serde_json::to_value(request()).unwrap(); - value["arbitraryFilter"] = serde_json::json!("permit all"); - assert!(serde_json::from_value::(value).is_err()); - } - - #[test] - fn lease_guids_are_stable_and_distinct() { - let lease = Uuid::new_v4(); - assert_eq!(guid_for(lease, 0), guid_for(lease, 0)); - assert_ne!(guid_for(lease, 0), guid_for(lease, 1)); - assert_ne!(guid_for(lease, 1), guid_for(Uuid::new_v4(), 1)); - } -} diff --git a/docs/axis-isolation-contract.md b/docs/axis-isolation-contract.md index b197add..6ce0e2d 100644 --- a/docs/axis-isolation-contract.md +++ b/docs/axis-isolation-contract.md @@ -109,6 +109,17 @@ AXIS-owned layer that masks the path exactly, select another backend, or reject the policy. A backend that merely ignores deny rules is `Unsupported` for that policy. +Two Windows ProcessContainer policy fields widen access when turned on. Both +are off by default, ignored on other platforms, and reported when a sandbox +launches and by `axis policy validate`: + +- `process.windows_win32k` lets the workload make Win32k (USER32/GDI) system + calls, which tools such as PowerShell and Git for Windows need. +- `filesystem.windows_enumerate_ancestors` lets the workload list every + ancestor of its grants. The listing covers each ancestor's whole subtree: + file names, sizes and times become visible, contents do not. A launch is + refused when a denied path sits below one of these ancestors. + ## Network Semantics AXIS network policy has distinct modes. They are not interchangeable. @@ -159,6 +170,25 @@ behavior. If binary attribution, sandbox identity, or proxy reachability cannot be proven, strict proxy mode is `Unsupported` for that backend and host state. +Strict proxy mode governs outbound traffic. Inbound reachability of listeners +inside the sandbox is not part of the guarantee; each backend must document it. +Windows ProcessContainer must allow ingress for MXC's proxy mapping, so inbound +reach from private-network peers is decided by the host firewall; see +[Windows MXC 1.x Backend](windows-mxc-1.md). + +A backend that blocks bypass attempts but cannot record them plans +`audit.bypass_evidence` as `WeakerOnly`. Today only Windows ProcessContainer +does. `network.bypass_audit` decides what happens then: + +- `best_effort` (the default) launches and prints a warning that blocked + bypass attempts leave no audit record. +- `hard_requirement` refuses the launch. + +The setting never accepts anything else: a backend that cannot block bypass +attempts, a missing host dependency, or another weaker surface still refuses +the launch. Backends that record bypass attempts, including every Linux +backend, behave the same under both settings. + ### Cooperative Proxy Mode Cooperative proxying is not strict proxy isolation. A backend that only sets @@ -185,8 +215,9 @@ Required behavior: cannot be prepared safely. - `identity: isolated` is portable intent for a backend-owned isolated token or account. It must not be implemented by guessing a host username. Windows MXC - maps it to the actual least-privilege ProcessContainer token; legacy - `run_as_user` remains unsupported there. + rejects it because MXC 1.x BaseContainer has no least-privilege (LPAC) token + and the child keeps the caller's user SID; legacy `run_as_user` remains + unsupported there. - `child_processes: deny` means the workload may have no descendants. Backends enforce it as an atomic one-process tree limit; it is not translated into a guessed list of `fork`, `clone`, or process-creation API names. @@ -233,7 +264,7 @@ These rules decide which backend runs a policy, or reject it before launch: launched without it. Per-binary network policy remains unsupported on Windows ProcessContainer. A -SID-scoped WFP lease proves the sandbox identity but not the executable behind +SID-scoped WFP filter proves the sandbox identity but not the executable behind each proxied CONNECT; user-mode PID/tuple reconstruction is vulnerable to PID reuse and short-lived-connection races. AXIS will not weaken that requirement without ALE process metadata or an equivalent race-safe boundary. @@ -345,7 +376,8 @@ Required behavior: diagnostics. Runtime policy enforcement must still fail closed when evidence is required. - Direct network bypass attempts in strict proxy mode must be denied. They - should be auditable where the platform provides reliable evidence. + should be auditable where the platform provides reliable evidence; where it + does not, the launch reports it as above (`network.bypass_audit`). - Backend capability probes, dependency skips, and unsupported combinations must produce actionable messages. diff --git a/docs/backend-default-decisions.md b/docs/backend-default-decisions.md index 82e015a..114fbba 100644 --- a/docs/backend-default-decisions.md +++ b/docs/backend-default-decisions.md @@ -46,7 +46,7 @@ dependency gates, and status meanings. | --- | --- | --- | | Linux | `mxc-linux-bubblewrap` for block and allow mode | Use the MXC process backend by default while AXIS supplies seccomp, resource, credential, proxy policy, and cleanup layers around it. `runtime.provider: auto` selects `axis-native-linux` instead for strict-proxy policies (MXC v1.0.0 strict proxy is opt-in with `runtime.provider: mxc` until a capable-host CI run proves it) and for binary-restricted endpoint rules. Allow mode stays on MXC even on hosts without its private-network dependencies, where the launch is refused with what is missing rather than moved to the native backend, whose allow mode shares the host network; see the Backend Selection Rules in the [AXIS Isolation Contract](axis-isolation-contract.md). | | macOS | `axis-native-macos-seatbelt` | Retain native default while direct Seatbelt profile generation remains the proven no-extra-runtime path. | -| Windows | `mxc-windows-processcontainer` | Require packaged MXC BaseContainer with least-privilege mode while AXIS rejects unsupported policy surfaces and owns sanitized executor launch, timeout, and cleanup. AppContainer/DACL fallback remains disabled, and the legacy native host-spawn path is disabled. | +| Windows | `mxc-windows-processcontainer` | Require packaged MXC BaseContainer while AXIS rejects unsupported policy surfaces and owns sanitized executor launch, Job Object resource limits, timeout, and cleanup. MXC 1.x has no least-privilege (LPAC) mode, so `process.identity: isolated` is rejected; see [Windows MXC 1.x Backend](windows-mxc-1.md). AppContainer/DACL fallback remains disabled, and the legacy native host-spawn path is disabled. | Non-default MXC process backends are candidates. They can become defaults only after they match AXIS policy semantics and have benchmark evidence for startup, diff --git a/docs/install-and-runtime-dependencies.md b/docs/install-and-runtime-dependencies.md index d421ad6..5ebfea6 100644 --- a/docs/install-and-runtime-dependencies.md +++ b/docs/install-and-runtime-dependencies.md @@ -30,7 +30,7 @@ administrator-controlled package steps, or disposable CI/e2e scripts. | MXC process sandbox | Packaged MXC executor for the selected platform backend: `lxc-exec` on Linux and `wxc-exec.exe` on Windows. Bubblewrap, unprivileged user namespaces, and AXIS seccomp launcher support are additional Linux dependencies; Linux allow and proxy network modes also need `slirp4netns`, `unshare` and `nsenter` (util-linux), `iptables`, `ip6tables`, `iptables-restore`, `ip6tables-restore`, and `/dev/net/tun` for MXC's private sandbox network namespace. Windows ProcessContainer also requires a supported Windows build/API state. | Default user install for packaged non-privileged executors. Optional host features are discovered safely and missing enforcement fails closed. | | MXC container sandbox | LXC for Linux container launches or WSL2 for Windows container launches, plus configured rootfs/image inputs. | Host runtime setup is explicit and backend-specific. Unsupported or unavailable runtime state must reject before spawn rather than falling back silently. | | MXC VM-style sandbox | KVM on Linux, WHP on Windows, Windows Sandbox, Hyperlight runtime artifacts, microVM images, snapshots, or guest-agent assets depending on the selected backend. | VM and host-feature enablement is explicit setup. VM-style backends remain gated until AXIS can prove command, filesystem, network, lifecycle, and cleanup semantics for the requested policy. | -| AXIS proxy networking | The AXIS proxy plus platform network controls. Linux strict native proxy mode needs `ip`, `iptables`, and either native `CAP_NET_ADMIN` or the optional `axis-netns-helper`; `runtime.provider: auto` runs strict proxy on the native backend, and an explicit `mxc` provider needs native `CAP_NET_ADMIN` and is rejected before launch behind the helper; binary-restricted Linux proxy policies additionally need connect-time attribution from the native seccomp-notify path, so `runtime.provider: auto` runs them on the native backend and an explicit `mxc` provider rejects them. Windows BaseContainer strict proxy mode needs the installed `AxisWfpBroker` service and patched MXC executor. | The default quickstart does not require proxy-mode privileges. Linux helper/capability setup and Windows WFP service installation are explicit administrator choices. Missing broker state rejects proxy policies before spawn. | +| AXIS proxy networking | The AXIS proxy plus platform network controls. Linux strict native proxy mode needs `ip`, `iptables`, and either native `CAP_NET_ADMIN` or the optional `axis-netns-helper`; `runtime.provider: auto` runs strict proxy on the native backend, and an explicit `mxc` provider needs native `CAP_NET_ADMIN` and is rejected before launch behind the helper; binary-restricted Linux proxy policies additionally need connect-time attribution from the native seccomp-notify path, so `runtime.provider: auto` runs them on the native backend and an explicit `mxc` provider rejects them. Windows BaseContainer strict proxy mode needs only the packaged MXC executor, which installs per-container WFP filters through `runtimeConfig.networkProxy`. | The default quickstart does not require proxy-mode privileges. Linux helper/capability setup is an explicit administrator choice. | | Source builds | Rust toolchain and platform build tools. Xcode Command Line Tools may be needed to build or test macOS binaries from source. | Build tools are developer dependencies, not runtime prerequisites for installing release artifacts. | ## Optional Backend Dependencies diff --git a/docs/security-test-tiers.md b/docs/security-test-tiers.md index 84784e8..a7283d5 100644 --- a/docs/security-test-tiers.md +++ b/docs/security-test-tiers.md @@ -108,9 +108,9 @@ visible skip into a failure. | `AXIS_TEST_SECCOMP_NOTIFY_ATTRIBUTION=1` | 3 | Run seccomp-notify connect-attribution and Unix connect supervision proofs. | | `AXIS_TEST_RUN_AS_USER=` | 3 | Run identity/resource fallback tests for an existing non-root user. | | `AXIS_RUN_MXC_PROCESS_E2E=1` | 3 | Run Linux MXC process-runtime proofs when a safe executor and backend prerequisites are present. The Bubblewrap proofs also require `bwrap`, unprivileged user namespaces, `python3`, and, for allow-mode proofs, the MXC private-network tools (`slirp4netns`, `unshare`, `nsenter`, `iptables`/`ip6tables` and their `-restore` variants) with `/dev/net/tun`. | -| `AXIS_RUN_MXC_BASECONTAINER_E2E=1` | 3 | Require and exercise MXC BaseContainer on a feature-enabled Windows host with DACL fallback disabled. The proof covers least-privilege launch, managed-profile and environment filtering, filesystem read-only/read-write/default-deny behavior, child-tree process/aggregate-memory/single-CPU-equivalent rate limits, network allow/block behavior, timeout descendant cleanup, and host-ACL non-mutation. | +| `AXIS_RUN_MXC_BASECONTAINER_E2E=1` | 3 | Require and exercise MXC BaseContainer on a feature-enabled Windows host with DACL fallback disabled. The proof covers BaseContainer launch, managed-profile and environment filtering, filesystem read-only/read-write/default-deny behavior, child-tree process/aggregate-memory/single-CPU-equivalent rate limits, network allow/block behavior, timeout descendant cleanup, and host-ACL non-mutation. | | `AXIS_SKIP_UNAVAILABLE_MXC_BASECONTAINER_E2E=1` | CI only | Permit the Windows BaseContainer suite to report an explicit skip only when MXC returns the exact unavailable-BaseContainer and disabled-DACL-fallback result. Missing-executor fail-closed behavior is still proved first; all other launch or policy failures remain fatal. Do not set this on a runtime-qualified BaseContainer host. | -| `AXIS_RUN_WINDOWS_WFP_E2E=1` | 4 | Run the elevated Windows BaseContainer strict-proxy suite with the installed `AxisWfpBroker`. Proves allowed proxy transport, endpoint denial, raw TCP/DNS/QUIC/IPv6 bypass resistance, WFP audit correlation, concurrent lease isolation, and persistent-block crash recovery. | +| `AXIS_RUN_WINDOWS_STRICT_PROXY_E2E=1` | 3 | Run the Windows BaseContainer strict-proxy suite. Proves allowed proxy transport, endpoint denial, raw TCP/DNS/QUIC/IPv6 bypass resistance, that host loopback services (an ephemeral listener, a running axisd, and another sandbox's AXIS proxy) stay unreachable, and that one sandbox exiting does not lift another sandbox's block. | | `AXIS_REAL_MXC_PROXY_TESTS=1` | 3 | Add the `#[ignore]`d real MXC strict proxy reachability proof to the MXC process e2e wrapper. The proof sets up the sandbox network namespace with `ip netns` and `iptables`, so it needs network-namespace privileges, and a missing executor, launcher, `bwrap` user namespace, or `python3` fails it. The non-required [Linux MXC proof workflow](../.github/workflows/linux-mxc-proof.yml) runs it on a hosted Ubuntu runner. | | `AXIS_MXC_PROXY_PROOF_ONLY=1` | 3 | With `AXIS_REAL_MXC_PROXY_TESTS=1`, run only the strict proxy proof in the MXC process e2e wrapper, so a privileged caller does not run the process proofs with its capabilities. | | `AXIS_RUN_MXC_LXC_E2E=1` | 3 | Run Linux MXC LXC smoke tests when a safe `lxc-exec` or `AXIS_TEST_MXC_EXECUTOR` and configured LXC runtime/image inputs are present. | diff --git a/docs/setup-and-install.md b/docs/setup-and-install.md index 55c558b..aa9befa 100644 --- a/docs/setup-and-install.md +++ b/docs/setup-and-install.md @@ -116,43 +116,39 @@ jobs and place it beside `axis.exe`: ``` The script keeps its MXC checkout under `%LOCALAPPDATA%\axis-dev\mxc`, pins -the tested revision, applies AXIS's compatibility patch idempotently, builds -both release binaries, and configures the current PowerShell process to use -BaseContainer. Pass `-SkipAxisBuild` when only `wxc-exec.exe` needs rebuilding. -The Windows executor is pinned to an older MXC revision than the Linux one; see -[third_party/mxc/README.md](../third_party/mxc/README.md) for why. - -Strict Windows proxy policies additionally require the narrowly privileged -AXIS WFP broker. From an elevated PowerShell session, build/install it once: - -```powershell -.\scripts\install_windows_wfp_broker.ps1 -Get-Service AxisWfpBroker -``` - -The service accepts only a fixed lease operation for a suspended -`wxc-exec.exe` child. It reads the real AppContainer SID from that child, -allows TCP only to the exact per-sandbox AXIS proxy endpoint, and blocks other -IPv4/IPv6 connects. Dynamic proxy permits disappear on broker failure; -persistent fail-closed blocks are journaled under -`%ProgramData%\axis\wfp-leases` and reaped on restart after PID creation-time -validation. The install script restricts that journal to SYSTEM and -Administrators. Use `-Uninstall` only after all sandboxes have exited. +the tested upstream revision (MXC v1.0.1, unpatched), builds both release +binaries, and configures the current PowerShell process to use BaseContainer. +Pass `-SkipAxisBuild` when only `wxc-exec.exe` needs rebuilding. See +[third_party/mxc/README.md](../third_party/mxc/README.md) for the pins. + +Strict Windows proxy policies need no extra service or elevation: MXC's +`runtimeConfig.networkProxy` mapping installs per-container WFP filters that +allow TCP only to the per-sandbox AXIS proxy endpoint and block other IPv4/IPv6 +egress. Blocked bypass attempts are not recorded, so a proxy launch prints a +warning; set `network.bypass_audit: hard_requirement` to refuse such launches +instead. Hosts upgraded from v0.4.0 keep the old `AxisWfpBroker` service until +it is removed; see +[Upgrading From v0.4.0](windows-mxc-1.md#upgrading-from-v040). Windows `auto` and `mxc` policies use ProcessContainer. `axis_native` is disabled because the legacy path does not enforce the AXIS policy boundary. The supported policy slice includes filesystem read-only/read-write allowlists, non-overlapping deny rules that are redundant under BaseContainer default-deny, a managed Windows profile, child-tree process/aggregate-memory/CPU limits, -default allow/block networking, and broker-backed BaseContainer strict proxy -routing. Nested deny rules and other unmapped Windows -process-policy surfaces fail before launch. AXIS leaves MXC's upstream +default allow/block networking, and BaseContainer strict proxy routing. Nested +deny rules and other unmapped Windows process-policy surfaces fail before +launch. AXIS leaves MXC's upstream BaseContainer-first tier selection intact and always emits `fallback.allowDaclMutation=false`. An unavailable BaseContainer therefore fails closed instead of selecting an older AppContainer/DACL tier or temporarily changing host ACLs. -MXC least-privilege mode remains enabled for BaseContainer. AXIS does not select +MXC 1.x BaseContainer has no least-privilege (LPAC) mode, so the child keeps +the caller's user SID inside the container: system locations and the user's +registry hive stay readable, and `process.identity: isolated` is rejected. In +strict proxy mode MXC requires inbound connections to be allowed; whether +private-network peers can reach a sandbox listener then depends on the host +firewall. See [Windows MXC 1.x Backend](windows-mxc-1.md). AXIS does not select an older tier solely to gain a feature, including ConPTY, that the current BaseContainer API cannot provide. @@ -344,22 +340,23 @@ timeout descendant cleanup, and absence of host directory ACL mutation. Feature-key, fallback, policy, launch, isolation, resource, and cleanup errors are test failures once the gate is set. -Run the privileged strict-proxy adversarial suite from an elevated PowerShell -session after installing the broker: +Run the strict-proxy adversarial suite: ```powershell -$env:AXIS_RUN_WINDOWS_WFP_E2E = "1" +$env:AXIS_RUN_WINDOWS_STRICT_PROXY_E2E = "1" $env:AXIS_TEST_MXC_EXECUTOR = (Resolve-Path ".\target\release\wxc-exec.exe") .\e2e\windows\test_mxc_strict_proxy.ps1 ` -AxisBin .\target\release\axis.exe ``` It proves allowed HTTPS through the proxy; endpoint denial; raw TCP, DNS, -QUIC/UDP, and IPv6 bypass resistance; correlated WFP events; concurrent lease -isolation; and fail-closed broker restart recovery. +QUIC/UDP, and IPv6 bypass resistance; that host loopback services, including a +running axisd and another sandbox's AXIS proxy, stay unreachable; and that one +sandbox exiting does not lift another sandbox's block. Run it without axisd so +each sandbox hosts its own proxy. -With the same broker and BaseContainer prerequisites, run the managed-inference -boundary proof: +With the same BaseContainer prerequisites, run the managed-inference boundary +proof: ```powershell $env:AXIS_RUN_WINDOWS_INFERENCE_E2E = "1" @@ -371,8 +368,8 @@ $env:AXIS_TEST_MXC_EXECUTOR = (Resolve-Path ".\target\release\wxc-exec.exe") This uses a host mock provider to prove streaming, host-only credential injection, guest secret absence, and token-budget rejection before provider bytes are forwarded. Windows inference policies require strict proxy mode and -therefore the BaseContainer/WFP tier. `action_on_exhaust: reject` is currently -the only exact budget action; queue and fallback require the future trusted +therefore the BaseContainer strict proxy tier. `action_on_exhaust: reject` is +currently the only exact budget action; queue and fallback require the future trusted request scheduler and fail during proxy initialization. For standalone `axis run`, set `AXIS_INFERENCE_ENDPOINT=127.0.0.1:` to @@ -380,8 +377,8 @@ map the sandbox-visible `inference.local` route to a managed host provider. AXIS consumes this value in the host proxy and does not project it into the sandbox environment. -Scoped SSH uses that same BaseContainer/WFP boundary and requires the packaged -`axis-ssh-proxy.exe` beside `axis.exe`. To run its gated proof: +Scoped SSH uses that same BaseContainer strict proxy boundary and requires the +packaged `axis-ssh-proxy.exe` beside `axis.exe`. To run its gated proof: ```powershell $env:AXIS_RUN_WINDOWS_SSH_E2E = "1" diff --git a/docs/windows-mxc-1.md b/docs/windows-mxc-1.md new file mode 100644 index 0000000..f17ecfc --- /dev/null +++ b/docs/windows-mxc-1.md @@ -0,0 +1,204 @@ +# Windows MXC 1.x Backend + +AXIS runs Windows process policies through MXC BaseContainer +(`mxc-windows-processcontainer`). This document records the move of that +backend from a patched pre-1.x MXC executor to unpatched MXC 1.x, the isolation +trade-offs it accepts, and the evidence. Backend defaults are recorded in +[Backend Default Decisions](backend-default-decisions.md). + +## Problem + +Through AXIS v0.4.0, Windows `wxc-exec.exe` was built from MXC commit +`1736b48398c3fe4d1315b2311c0951cc893eb3ae` with three AXIS patches: + +- process-count, memory and CPU fields in the ProcessContainer schema; +- assignment of the BaseContainer child to an inner resource Job; +- a pre-resume hook into a privileged AXIS WFP broker service + (`axis-wfp-broker.exe`, installed by `scripts/install_windows_wfp_broker.ps1`) + that installed per-SID proxy permit and default-deny filters. + +The patches did not apply to the MXC 1.x `src/mxc-sdk` layout, so Windows was +stuck on a pre-release contract (`0.6.0-alpha`) while Linux moved to MXC +v1.0.0. Strict proxy mode also needed an elevated service install, and the +broker was AXIS-owned privileged code with its own lease journal and recovery +path. + +MXC 1.x changes the picture: + +- `runtimeConfig.networkProxy` installs per-container WFP filters that allow + egress only to one loopback proxy endpoint; +- `ui` controls Win32k, which USER32-linked tools (PowerShell, Git for Windows) + need to start; +- `processContainer.filesystem.enumeratePaths` lets the child list grant + ancestors without reading them, which path canonicalization needs; +- there is no resource-limit schema and no least-privilege (LPAC) token option + (). + +## Options + +1. **Keep the patched pre-1.x executor.** No isolation change, but the patches + would have to be rewritten for every MXC update, strict proxy keeps the + privileged broker, and Windows stays on a contract MXC no longer accepts. +2. **Port the patches to MXC 1.x.** Keeps LPAC only if MXC accepts an LPAC + patch upstream; until then it is a long-lived fork of the security-relevant + part of MXC. +3. **Use unpatched MXC 1.x and move resource limits into AXIS.** Drops the fork + and the broker; accepts the MXC 1.x limits listed under Accepted trade-offs + and reports them. + +## Decision + +Option 3. Windows `wxc-exec.exe` is built from MXC v1.0.1 +(`fda29ac63bc306b7f97f3b86b4b63d44f7f40cf2`) without patches. v1.0.1 rather +than v1.0.0 because it fixes BaseContainer loopback access to host services on +PSEC 1.0 hosts, which the proxy mapping depends on. + +- **Resource limits.** AXIS creates `wxc-exec.exe` with `CREATE_SUSPENDED`, + assigns it to an unnamed kill-on-close Job Object that carries the + process-count, memory and CPU limits, and resumes it only after the + assignment succeeds. The job has no name so another process cannot create a + same-named job first and keep it open. The job is sized `max_processes + 1` + for the executor itself. The MXC config + builder now rejects resource limits unless the caller states that AXIS + enforces them, so a future launcher that forgets the Job fails closed. +- **Strict proxy.** AXIS emits `runtimeConfig.networkProxy` with the + per-sandbox proxy URL. The WFP broker, its install script, its release assets + and the `windows.axis_wfp_broker` host dependency are removed. +- **Win32k and ancestor enumeration** are opt-in policy fields, + `process.windows_win32k` and `filesystem.windows_enumerate_ancestors`, both + off by default. They only grant access on Windows and are ignored elsewhere. + `windows_enumerate_ancestors` exposes names, sizes and times (not contents) + below every ancestor of a grant, such as `C:\`; an ancestor inside another + grant is left out so it cannot downgrade that grant. A launch with the option + on is refused when a denied path sits below one of those ancestors. Each + launch with either field on prints what it exposes, and + `axis policy validate` lists them. +- **Executor config file.** The temporary config is written below the axisd + token directory (`%LOCALAPPDATA%\axis\mxc-config`). Every sandbox launch is + refused when a grant covers that directory, so neither this sandbox nor a + concurrent one can rewrite the config before `wxc-exec` reads it. A grant + AXIS cannot canonicalize counts as covering it. +- **Bare commands.** A bare command resolves against the sandbox `PATH` + before the host `PATH`, skipping relative entries. When it resolves to a + `.cmd` or `.bat` file, which Windows runs through `cmd.exe`, arguments that + contain `& | < > ^ % ! "` or a line break are refused instead of being + reinterpreted by `cmd`. +- **Terminal launches.** An `axis run` from a terminal used to be refused + because BaseContainer cannot create a pseudoconsole. It now runs with the + terminal's own handles and no pseudoconsole; full-screen programs that need + one may not render correctly. No policy field requires a PTY, so this changes + how a launch is attached, not what a policy grants. BaseContainer denies the + sandbox writing to the terminal's input buffer. +- **Unix-only grants.** Bundled policies such as `minimal` grant Linux paths + (`/usr`). The Windows backend already skipped them under `best_effort`, but + the managed-home and axisd token checks ran first and rejected them, so the + default policy failed. Both checks now skip them too; under + `hard_requirement` the backend still refuses them. +- **Environment.** AXIS always passes an explicit environment, adding + `SYSTEMROOT` and `LOCALAPPDATA` when the caller does not set them (MXC 1.x + refuses to launch without them), so the child does not inherit the user's + persisted variables through its environment block. + +### Accepted trade-offs + +| Area | MXC 1.x behavior | AXIS handling | +| --- | --- | --- | +| Token | No LPAC. The child keeps the caller's user SID inside the container and the token keeps ALL APPLICATION PACKAGES. | `process.identity: isolated` is `Unsupported` and rejects before launch. Filesystem grants stay exact: user files outside the grants are denied, but system locations (for example `C:\Windows`) and the user's registry hive (including `HKCU\Environment`) stay readable. | +| Strict proxy ingress | `runtimeConfig.networkProxy` requires `network.ingress.default: allow`, which adds `privateNetworkClientServer`. | Egress is limited to the proxy. Whether a private-network peer can connect to a listener in the sandbox depends on the host firewall; AXIS does not enforce it. `network.strict_proxy` stays exact because the isolation contract scopes strict proxy to outbound traffic and leaves inbound reach to each backend. Marking it weaker would disable Windows proxy mode, since no policy can accept a weaker strict proxy today. | +| Bypass evidence | MXC's WFP filters block direct egress but do not report individual blocked connections. | Bypass attempts are denied but no longer produce AXIS audit records; the removed broker logged correlated WFP block events. `audit.bypass_evidence` is `WeakerOnly`. With `network.bypass_audit: best_effort` (the default) a proxy launch prints a warning that no record is kept; `hard_requirement` refuses it. Collecting Windows Filtering Platform audit events would require an administrator audit policy, which AXIS does not change. | +| Other Windows MXC contracts | MXC 1.x rejects `0.6.0-alpha`. | Only ProcessContainer has a Windows launch path. The WSLc, Isolation Session and VM-style config builders, and their benchmark harness rows, still emit `0.6.0-alpha` and need the 1.0.0 contract before they can launch. | + +## Evidence + +Windows 11 build 26100.9711, MXC v1.0.1 (the signed x64 `wxc-exec.exe` from +the MXC release, built from the pinned commit, SHA-256 +`090f5d1f7bb93104ab08dcd4e8034ef954aeefcdaf6658dde5f7dff4cfc12f3a`), and AXIS +cross-built from this change with `cargo xwin`. + +- **Gated e2e.** `test_mxc_processcontainer.ps1`, `test_mxc_strict_proxy.ps1`, + `test_mxc_inference.ps1` and `test_mxc_scoped_ssh.ps1` pass. The strict proxy + run left out the QUIC baseline and probe because the test network blocks + outbound UDP 443 for the host as well, and ran without axisd, so the axisd + port probe was skipped. The scoped SSH run used a compiled `ssh-keyscan` + stub, because endpoint protection on the test host kills `cmd.exe` children + started with an address and port as arguments. +- **Terminal and default policy.** From a new console window with no + redirection, `axis run -- cmd.exe /c "echo hi> out.txt"` with the default + policy exits 0 and writes the file; before this change it exited 125. A probe + inside the sandbox found its standard handles attached to that console, and + `WriteConsoleInputW` on them and on `CONIN$` failed with + `ERROR_ACCESS_DENIED`. +- **Launch messages.** A proxy launch prints the bypass audit warning, and + `network.bypass_audit: hard_requirement` refuses it. A `.cmd` argument + containing `&` is refused before launch. Launching a `.cmd` file directly + fails inside BaseContainer with "Access is denied" on this host, before and + after this change; `cmd.exe /c script.cmd` works. +- **Isolation probes.** + - Block and proxy modes both block direct egress, and loopback port 445 is + blocked. + - Through the proxy, the allowed host returns 200 and a denied host 403. + - Host loopback cannot connect to a listener in the sandbox in either mode. + - A connection from a different host interface (WSL NAT, `172.17.64.0/20`) + reached a host-side listener but not a sandbox listener in proxy or block + mode. That interface is not a private-profile LAN, so private-network + ingress remains untested. + - Writes to user files outside the workspace, `C:\Users`, `ProgramData` and + `C:\Users\Public` are denied; `C:\Windows` and `HKCU\Environment` are + readable. + - `max_processes` and `max_memory_mb` are enforced through the Job Object. + A process that exceeds the memory limit terminates with an access + violation rather than a clean allocation error. +- **Launch latency.** `axis --socket 0.0.0.0:9 run -- cmd.exe /c exit 0`, 20 + runs after 2 warm-up runs, against the AXIS v0.4.0 Windows package (patched + pre-1.x executor). `--socket 0.0.0.0:9` makes the axisd connect fail at once + for both builds; without it, Windows retries the refused loopback connect for + about two seconds before `axis run` falls back to standalone mode, which hides + the launch cost (2371 ms against 2498 ms median in block mode). + + | Build | Mode | Median | p90 | Failures | + | --- | --- | --- | --- | --- | + | v0.4.0 | block | 373 ms | 405 ms | 0 | + | v0.4.0 | allow | 358 ms | 388 ms | 0 | + | MXC 1.x | block | 582 ms | 637 ms | 0 | + | MXC 1.x | allow | 561 ms | 641 ms | 0 | + | MXC 1.x | proxy | 980 ms | 1026 ms | 0 | + + MXC 1.x adds about 200 ms per launch. About 70 ms of it is the executor's + own start: `wxc-exec.exe --version` takes 152 ms against 80 ms for the + pre-1.x build. v0.4.0 proxy mode needs the installed broker and was not + measured. Launches through a running axisd were not measured: on Windows, + axisd currently falls back to `/tmp/axis/sandboxes` for sandbox state when + neither `XDG_DATA_HOME` nor `HOME` is set, and `axis run` through axisd + waits for Ctrl+C. + +## Upgrading From v0.4.0 + +The v0.4.0 broker service is not removed by upgrading. If it was installed, +remove it from an elevated PowerShell session: + +```powershell +sc.exe stop AxisWfpBroker +sc.exe delete AxisWfpBroker +Remove-Item -Recurse -Force "$env:ProgramData\axis\wfp-leases" +``` + +## Follow-ups + +- Adopt an LPAC option when MXC provides one (microsoft/mxc#1496) and restore + `process.identity: isolated`. +- Prove or deny private-network ingress on a private-profile LAN. MXC 1.0.1 + requires `ingress.default: allow` with the proxy mapping even when + `allowedProxyPeer` narrows host loopback, so denying ingress needs an MXC + change. Until then AXIS could check the host firewall profile before a proxy + launch instead of assuming it blocks inbound traffic. +- Record blocked bypass attempts, for example from Windows Filtering Platform + audit events, so `audit.bypass_evidence` can become exact again. Until then, + also write the launch warning to the audit log, not only to stderr. +- Give axisd a Windows state directory: without `XDG_DATA_HOME` or `HOME` it + falls back to `/tmp/axis/sandboxes`, so daemon commands cannot create + sandboxes on Windows. +- Find where the rest of the added launch time goes (MXC 1.x container setup, + or AXIS's suspended start and resume) and measure launches through axisd once + it has a Windows state directory. +- Move the WSLc, Isolation Session and VM-style Windows config builders to the + 1.0.0 contract before they gain a launch path. diff --git a/e2e/windows/CAPABILITY_MATRIX.md b/e2e/windows/CAPABILITY_MATRIX.md index 9588cc8..132a34b 100644 --- a/e2e/windows/CAPABILITY_MATRIX.md +++ b/e2e/windows/CAPABILITY_MATRIX.md @@ -2,10 +2,10 @@ | Capability | Gate | Coverage | | --- | --- | --- | -| AXIS-through-MXC BaseContainer smoke/security | `AXIS_RUN_MXC_BASECONTAINER_E2E=1`, `AXIS_TEST_MXC_EXECUTOR=`, then `.\e2e\windows\test_mxc_processcontainer.ps1 -AxisBin .\target\release\axis.exe` | Requires MXC BaseContainer with DACL consent absent and least-privilege mode enabled. Proves missing-executor fail-closed behavior, command execution, managed-profile and secret-environment behavior, filesystem read-only/read-write/default-deny behavior, paired network allow/block behavior, process-count and child-denial mapping, aggregate memory, CPU-rate enforcement, timeout descendant cleanup, arbitrary granted-image launch, and host-directory ACL non-mutation. Hosted CI additionally sets `AXIS_SKIP_UNAVAILABLE_MXC_BASECONTAINER_E2E=1`; that accepts only MXC's exact unavailable-BaseContainer/disabled-DACL result after the missing-executor proof, while every other failure remains fatal. | -| AXIS/MXC BaseContainer strict WFP proxy | Elevated session with installed `AxisWfpBroker`, `AXIS_RUN_WINDOWS_WFP_E2E=1`, `AXIS_TEST_MXC_EXECUTOR=`, then `.\e2e\windows\test_mxc_strict_proxy.ps1 -AxisBin .\target\release\axis.exe` | Proves allowed HTTPS through the exact proxy permit; endpoint denial; raw TCP, DNS, QUIC/UDP, and IPv6 block behavior; correlated WFP block events; two simultaneous SID-scoped leases; MXC termination on broker loss; persistent fail-closed blocks; and stale-journal recovery on restart. | -| AXIS/MXC BaseContainer managed inference | Installed/running `AxisWfpBroker`, `AXIS_RUN_WINDOWS_INFERENCE_E2E=1`, `AXIS_TEST_MXC_EXECUTOR=`, then `.\e2e\windows\test_mxc_inference.ps1 -AxisBin .\target\release\axis.exe` | Runs a real BaseContainer client through the strict WFP-only proxy path to a host mock provider. Proves streaming, provider credential injection, absence of the provider secret from guest environment/output, and pre-forward token-budget rejection. | -| AXIS/MXC BaseContainer scoped SSH | Installed/running `AxisWfpBroker`, packaged `axis-ssh-proxy.exe`, `AXIS_RUN_WINDOWS_SSH_E2E=1`, `AXIS_TEST_MXC_EXECUTOR=`, then `.\e2e\windows\test_mxc_scoped_ssh.ps1 -AxisBin .\target\release\axis.exe` | Proves managed-home key/config/known-host/helper projection, Windows OpenSSH hardening, original-key default denial, a working allowed CONNECT byte stream, and proxy rejection for an unlisted destination. | -| MXC BaseContainer benchmark | `AXIS_BENCH_MXC_WINDOWS_PROCESSCONTAINER=1 pwsh -NoProfile -File e2e/windows/bench_mxc_runtime.ps1` | Requires BaseContainer with least-privilege mode, then reports JSON for cold lifecycle, warm lifecycle distribution, executor peak working set, and density. Tunables: `AXIS_MXC_WINDOWS_BENCH_RUNS`, `AXIS_MXC_WINDOWS_BENCH_DENSITY`, `AXIS_MXC_WINDOWS_BENCH_TIMEOUT_SECONDS`, and `AXIS_MXC_WINDOWS_BENCH_OUTPUT`. | -| MXC WSLC benchmark | `AXIS_BENCH_MXC_WINDOWS_WSLC=1 pwsh -NoProfile -File e2e/windows/bench_mxc_runtime.ps1` | Reports JSON for WSLC cold/warm lifecycle, executor peak working set, and density when `AXIS_MXC_WSLC_IMAGE_TAR_PATH` names repeatable input. Optional inputs: `AXIS_MXC_WSLC_IMAGE` and `AXIS_MXC_WSLC_STORAGE_PATH`. | -| MXC Windows VM-style benchmark | `AXIS_BENCH_MXC_WINDOWS_SANDBOX=1`, `AXIS_BENCH_MXC_WINDOWS_ISOLATION_SESSION=1`, `AXIS_BENCH_MXC_WINDOWS_MICROVM=1`, or `AXIS_BENCH_MXC_WINDOWS_HYPERLIGHT=1` with `pwsh -NoProfile -File e2e/windows/bench_mxc_runtime.ps1` | Reports JSON for cold start, warm start distribution, executor peak working set, and density for the selected VM-style backend. Reports metric gaps for teardown, descriptor count, and process count until richer host metrics are collected. | +| AXIS-through-MXC BaseContainer smoke/security | `AXIS_RUN_MXC_BASECONTAINER_E2E=1`, `AXIS_TEST_MXC_EXECUTOR=`, then `.\e2e\windows\test_mxc_processcontainer.ps1 -AxisBin .\target\release\axis.exe` | Requires MXC BaseContainer with DACL consent absent. Proves missing-executor fail-closed behavior, command execution, managed-profile and secret-environment behavior, filesystem read-only/read-write/default-deny behavior, paired network allow/block behavior, process-count and child-denial mapping, aggregate memory, CPU-rate enforcement, timeout descendant cleanup, arbitrary granted-image launch, and host-directory ACL non-mutation. Hosted CI additionally sets `AXIS_SKIP_UNAVAILABLE_MXC_BASECONTAINER_E2E=1`; that accepts only MXC's exact unavailable-BaseContainer/disabled-DACL result after the missing-executor proof, while every other failure remains fatal. | +| AXIS/MXC BaseContainer strict proxy | `AXIS_RUN_WINDOWS_STRICT_PROXY_E2E=1`, `AXIS_TEST_MXC_EXECUTOR=`, then `.\e2e\windows\test_mxc_strict_proxy.ps1 -AxisBin .\target\release\axis.exe` | Proves allowed HTTPS through the MXC proxy mapping; endpoint denial; raw TCP, DNS, QUIC/UDP, and IPv6 block behavior; unreachable host loopback services, including a running axisd and another sandbox's AXIS proxy; and that one sandbox exiting does not lift another sandbox's block. Inbound reachability from private-network peers is not asserted because it depends on the host firewall. | +| AXIS/MXC BaseContainer managed inference | `AXIS_RUN_WINDOWS_INFERENCE_E2E=1`, `AXIS_TEST_MXC_EXECUTOR=`, then `.\e2e\windows\test_mxc_inference.ps1 -AxisBin .\target\release\axis.exe` | Runs a real BaseContainer client through the strict proxy path to a host mock provider. Proves streaming, provider credential injection, absence of the provider secret from guest environment/output, and pre-forward token-budget rejection. | +| AXIS/MXC BaseContainer scoped SSH | Packaged `axis-ssh-proxy.exe`, `AXIS_RUN_WINDOWS_SSH_E2E=1`, `AXIS_TEST_MXC_EXECUTOR=`, then `.\e2e\windows\test_mxc_scoped_ssh.ps1 -AxisBin .\target\release\axis.exe` | Proves managed-home key/config/known-host/helper projection, Windows OpenSSH hardening, original-key default denial, a working allowed CONNECT byte stream, and proxy rejection for an unlisted destination. | +| MXC BaseContainer benchmark | `AXIS_BENCH_MXC_WINDOWS_PROCESSCONTAINER=1 pwsh -NoProfile -File e2e/windows/bench_mxc_runtime.ps1` | Requires BaseContainer and an MXC 1.x executor, then reports JSON for cold lifecycle, warm lifecycle distribution, executor peak working set, and density. Tunables: `AXIS_MXC_WINDOWS_BENCH_RUNS`, `AXIS_MXC_WINDOWS_BENCH_DENSITY`, `AXIS_MXC_WINDOWS_BENCH_TIMEOUT_SECONDS`, and `AXIS_MXC_WINDOWS_BENCH_OUTPUT`. | +| MXC WSLC benchmark | `AXIS_BENCH_MXC_WINDOWS_WSLC=1 pwsh -NoProfile -File e2e/windows/bench_mxc_runtime.ps1` | Reports JSON for WSLC cold/warm lifecycle, executor peak working set, and density when `AXIS_MXC_WSLC_IMAGE_TAR_PATH` names repeatable input. Optional inputs: `AXIS_MXC_WSLC_IMAGE` and `AXIS_MXC_WSLC_STORAGE_PATH`. The harness emits the `0.6.0-alpha` contract, which the pinned MXC 1.x executor rejects. | +| MXC Windows VM-style benchmark | `AXIS_BENCH_MXC_WINDOWS_SANDBOX=1`, `AXIS_BENCH_MXC_WINDOWS_ISOLATION_SESSION=1`, `AXIS_BENCH_MXC_WINDOWS_MICROVM=1`, or `AXIS_BENCH_MXC_WINDOWS_HYPERLIGHT=1` with `pwsh -NoProfile -File e2e/windows/bench_mxc_runtime.ps1` | Reports JSON for cold start, warm start distribution, executor peak working set, and density for the selected VM-style backend. Reports metric gaps for teardown, descriptor count, and process count until richer host metrics are collected. The harness emits the `0.6.0-alpha` contract, which the pinned MXC 1.x executor rejects. | diff --git a/e2e/windows/bench_mxc_runtime.ps1 b/e2e/windows/bench_mxc_runtime.ps1 index a85a584..5f8c30b 100644 --- a/e2e/windows/bench_mxc_runtime.ps1 +++ b/e2e/windows/bench_mxc_runtime.ps1 @@ -172,8 +172,16 @@ function Write-MxcConfig([string]$Path, [object]$Backend, [string]$Marker, [int] } if ($Backend.Containment -eq "processcontainer") { + # The pinned MXC 1.x executor accepts only the 1.0.0 contract, which has + # no platform field, directional network rules and no LPAC option. + $config.version = "1.0.0" + $config.Remove("platform") + $config.network = [ordered]@{ + egress = [ordered]@{ default = "allow" } + ingress = [ordered]@{ default = "deny"; hostLoopback = "deny" } + } $config.filesystem.readonlyPaths = @("$Path.cmd") - $config.processContainer = [ordered]@{ leastPrivilege = $true } + $config.processContainer = [ordered]@{ leastPrivilege = $false } $config.fallback = [ordered]@{ allowDaclMutation = $false } } elseif ($Backend.Containment -eq "wslc") { $config.experimental = [ordered]@{ diff --git a/e2e/windows/test_mxc_inference.ps1 b/e2e/windows/test_mxc_inference.ps1 index 2b6cca6..87c1bf2 100644 --- a/e2e/windows/test_mxc_inference.ps1 +++ b/e2e/windows/test_mxc_inference.ps1 @@ -16,10 +16,6 @@ if ($env:AXIS_RUN_WINDOWS_INFERENCE_E2E -ne "1") { exit 0 } if ($env:OS -ne "Windows_NT") { Exit-Fail "inference E2E requires Windows" } -$service = Get-Service -Name AxisWfpBroker -ErrorAction SilentlyContinue -if (-not $service -or $service.Status -ne "Running") { - Exit-Fail "AxisWfpBroker must be installed and running" -} foreach ($path in @($AxisBin, $env:AXIS_TEST_MXC_EXECUTOR)) { if (-not $path -or -not (Test-Path -LiteralPath $path -PathType Leaf)) { Exit-Fail "required executable not found: $path" diff --git a/e2e/windows/test_mxc_processcontainer.ps1 b/e2e/windows/test_mxc_processcontainer.ps1 index 207a1dd..4d3d6d6 100644 --- a/e2e/windows/test_mxc_processcontainer.ps1 +++ b/e2e/windows/test_mxc_processcontainer.ps1 @@ -113,7 +113,7 @@ if ($IsolationTier -eq "BaseContainer") { $resourcePolicyText.Replace("max_processes: 0", "max_processes: 2") ) Set-Content -LiteralPath $portableProcessPolicy -Encoding ASCII -Value ( - $resourcePolicyText.Replace("max_processes: 0", "max_processes: 32`n identity: isolated`n child_processes: deny") + $resourcePolicyText.Replace("max_processes: 0", "max_processes: 32`n child_processes: deny") ) Set-Content -LiteralPath $memoryPolicy -Encoding ASCII -Value ( $resourcePolicyText.Replace("max_processes: 0", "max_processes: 6").Replace("max_memory_mb: 0", "max_memory_mb: 88") @@ -316,6 +316,11 @@ try { if ($portableDenied.ExitCode -eq 0 -or (Get-ChildItem -LiteralPath $processMarkers -Filter "started-*.txt" -ErrorAction SilentlyContinue).Count -ne 0) { Exit-Fail "portable child_processes: deny did not map to a pre-execution one-process Job limit: exit=$($portableDenied.ExitCode) output=$($portableDenied.Output)" } + # The probe creates the marker directory before it spawns, so a launch + # refused before the probe ran cannot pass as a blocked child. + if (-not (Test-Path -LiteralPath $processMarkers -PathType Container) -or $portableDenied.Output -notmatch "spawn hold child 0") { + Exit-Fail "portable child_processes: deny run did not reach the child spawn: exit=$($portableDenied.ExitCode) output=$($portableDenied.Output)" + } $memorySingleMarkers = Join-Path $workspace "memory-single" $memorySingle = Invoke-AxisProgram -Program $resourceProbe -ProgramArgs @("spawn-allocate", "1", "48", "250", $memorySingleMarkers) -PolicyPath $memoryPolicy diff --git a/e2e/windows/test_mxc_scoped_ssh.ps1 b/e2e/windows/test_mxc_scoped_ssh.ps1 index 67032d4..109f574 100644 --- a/e2e/windows/test_mxc_scoped_ssh.ps1 +++ b/e2e/windows/test_mxc_scoped_ssh.ps1 @@ -15,8 +15,6 @@ if ($env:AXIS_RUN_WINDOWS_SSH_E2E -ne "1") { exit 0 } if ($env:OS -ne "Windows_NT") { Exit-Fail "scoped SSH E2E requires Windows" } -$service = Get-Service -Name AxisWfpBroker -ErrorAction SilentlyContinue -if (-not $service -or $service.Status -ne "Running") { Exit-Fail "AxisWfpBroker must be running" } foreach ($path in @($AxisBin, $env:AXIS_TEST_MXC_EXECUTOR, ".\target\release\axis-ssh-proxy.exe")) { if (-not $path -or -not (Test-Path -LiteralPath $path -PathType Leaf)) { Exit-Fail "required executable not found: $path" diff --git a/e2e/windows/test_mxc_strict_proxy.ps1 b/e2e/windows/test_mxc_strict_proxy.ps1 index 8d0f628..1e4f8d5 100644 --- a/e2e/windows/test_mxc_strict_proxy.ps1 +++ b/e2e/windows/test_mxc_strict_proxy.ps1 @@ -14,26 +14,15 @@ function Exit-Fail([string]$Message) { throw "FAIL: $Message" } -if ($env:AXIS_RUN_WINDOWS_WFP_E2E -ne "1") { - Write-Host "SKIP: AXIS_RUN_WINDOWS_WFP_E2E=1 not set" +if ($env:AXIS_RUN_WINDOWS_STRICT_PROXY_E2E -ne "1") { + Write-Host "SKIP: AXIS_RUN_WINDOWS_STRICT_PROXY_E2E=1 not set" exit 0 } if ($env:OS -ne "Windows_NT") { - Exit-Fail "strict WFP tests require Windows" -} - -$principal = [Security.Principal.WindowsPrincipal]::new( - [Security.Principal.WindowsIdentity]::GetCurrent() -) -if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { - Exit-Fail "the gated crash-recovery proof must run elevated" -} -$service = Get-Service -Name AxisWfpBroker -ErrorAction SilentlyContinue -if (-not $service -or $service.Status -ne "Running") { - Exit-Fail "AxisWfpBroker must be installed and running" + Exit-Fail "strict proxy tests require Windows" } if (-not $env:AXIS_TEST_MXC_EXECUTOR) { - Exit-Fail "AXIS_TEST_MXC_EXECUTOR must name the patched wxc-exec.exe" + Exit-Fail "AXIS_TEST_MXC_EXECUTOR must name the pinned MXC wxc-exec.exe" } foreach ($path in @($AxisBin, $PolicyPath, $env:AXIS_TEST_MXC_EXECUTOR)) { if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { @@ -44,12 +33,10 @@ $AxisBin = (Resolve-Path -LiteralPath $AxisBin).Path $PolicyPath = (Resolve-Path -LiteralPath $PolicyPath).Path $env:AXIS_RUN_MXC_BASECONTAINER_E2E = "1" -$root = Join-Path ([IO.Path]::GetTempPath()) ("axis-wfp-e2e-" + [guid]::NewGuid().ToString("N")) +$root = Join-Path ([IO.Path]::GetTempPath()) ("axis-proxy-e2e-" + [guid]::NewGuid().ToString("N")) $workspace = Join-Path $root "workspace" $probe = Join-Path $workspace "axis-windows-network-probe.exe" $emptyInput = Join-Path $root "empty.stdin" -$auditLog = Join-Path $env:ProgramData "axis\logs\wfp-broker.jsonl" -$leaseDir = Join-Path $env:ProgramData "axis\wfp-leases" New-Item -ItemType Directory -Path $workspace -Force | Out-Null New-Item -ItemType File -Path $emptyInput -Force | Out-Null @@ -98,8 +85,6 @@ try { } } - $auditStart = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $allowed = Invoke-Curl @( "--silent", "--show-error", "--fail", "--ssl-no-revoke", "--connect-timeout", "8", "--max-time", "20", @@ -130,7 +115,8 @@ try { } # IPv6 proof does not depend on external IPv6 routing: a listening ::1 - # endpoint is reachable on the host and must still hit the lease's V6 block. + # endpoint is reachable on the host and must still be blocked, since only + # the IPv4 proxy endpoint is permitted. $listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::IPv6Loopback, 0) $listener.Start() try { @@ -146,20 +132,80 @@ try { $listener.Stop() } - $events = Get-Content -LiteralPath $auditLog | ForEach-Object { - try { $_ | ConvertFrom-Json } catch { $null } - } | Where-Object { - $_ -and $_.timestampUnixMs -ge $auditStart -and $_.event -eq "connection_blocked" - } - if (-not ($events | Where-Object { $_.protocol -eq 6 -and $_.remoteAddress -eq "1.1.1.1" -and $_.remotePort -eq 443 })) { - Exit-Fail "no correlated WFP TCP block event was recorded" + # Proxy mode allows ingress and host loopback for MXC's proxy mapping, so + # prove the sandbox still reaches no other loopback service: an ephemeral + # listener, the axisd TCP port, and another sandbox's AXIS proxy. + # The test does not bind the axisd port itself: `axis run` connects to it + # first and would talk to a stand-in listener. + $loopbackListener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback, 0) + $loopbackListener.Start() + try { + $ports = @($loopbackListener.LocalEndpoint.Port) + $axisdClient = [Net.Sockets.TcpClient]::new() + try { + $axisdClient.Connect([Net.IPAddress]::Loopback, 18516) + $ports += 18516 + } catch { + Write-Host "NOTE: axisd is not listening on 127.0.0.1:18516; skipping the axisd port probe" + } finally { + $axisdClient.Dispose() + } + foreach ($port in $ports) { + $hostClient = [Net.Sockets.TcpClient]::new() + try { + $hostClient.Connect([Net.IPAddress]::Loopback, $port) + } catch { + Exit-Fail "host cannot reach its own loopback listener on port ${port}: $_" + } finally { + $hostClient.Dispose() + } + $result = Invoke-Probe @("tcp-hold", "127.0.0.1", "$port") + if ($result.ExitCode -eq 0 -or -not $result.Output.Contains("TCP_BLOCKED")) { + Exit-Fail "sandbox reached host loopback port ${port}: $($result.Output)" + } + } + } finally { + $loopbackListener.Stop() } - if (-not ($events | Where-Object { $_.ipVersion -eq 6 -and $_.remoteAddress -eq "::1" })) { - Exit-Fail "no correlated WFP IPv6 block event was recorded" + + $holderOut = Join-Path $root "peer-proxy-holder.out" + $holderErr = Join-Path $root "peer-proxy-holder.err" + $holder = Start-Process -FilePath $AxisBin -WindowStyle Hidden -PassThru ` + -WorkingDirectory $workspace -RedirectStandardInput $emptyInput ` + -RedirectStandardOutput $holderOut -RedirectStandardError $holderErr ` + -ArgumentList @("run", "--policy", $PolicyPath, "--", $probe, "hold", "30") + try { + $peerProxyPorts = @() + $deadline = (Get-Date).AddSeconds(15) + while ($peerProxyPorts.Count -eq 0 -and (Get-Date) -lt $deadline) { + if ($holder.HasExited) { + Exit-Fail "peer sandbox exited before its proxy was probed (exit $($holder.ExitCode))" + } + $peerProxyPorts = @( + Get-NetTCPConnection -State Listen -OwningProcess $holder.Id -LocalAddress 127.0.0.1 -ErrorAction SilentlyContinue | + Select-Object -ExpandProperty LocalPort -Unique + ) + if ($peerProxyPorts.Count -eq 0) { + Start-Sleep -Milliseconds 200 + } + } + if ($peerProxyPorts.Count -eq 0) { + Exit-Fail "peer sandbox's AXIS proxy never listened on 127.0.0.1 from its axis.exe; run this suite without axisd so each sandbox hosts its own proxy" + } + foreach ($port in $peerProxyPorts) { + $result = Invoke-Probe @("tcp-hold", "127.0.0.1", "$port") + if ($result.ExitCode -eq 0 -or -not $result.Output.Contains("TCP_BLOCKED")) { + Exit-Fail "sandbox reached another sandbox's AXIS proxy on port ${port}: $($result.Output)" + } + } + } finally { + if (-not $holder.HasExited) { + $holder.Kill() + } + $holder.WaitForExit(10000) | Out-Null } - # Two leases must coexist without filter-key collision or cross-release. - $concurrentBaseline = @(Get-ChildItem -LiteralPath $leaseDir -Filter "*.json" -ErrorAction SilentlyContinue | ForEach-Object Name) + # Per-container filters: tearing down one sandbox must not lift another's block. $firstOut = Join-Path $root "concurrent-first.out" $firstErr = Join-Path $root "concurrent-first.err" $secondOut = Join-Path $root "concurrent-second.out" @@ -171,28 +217,14 @@ try { $second = Start-Process -FilePath $AxisBin -WindowStyle Hidden -PassThru ` -WorkingDirectory $workspace -RedirectStandardInput $emptyInput ` -RedirectStandardOutput $secondOut -RedirectStandardError $secondErr ` - -ArgumentList @("run", "--policy", $PolicyPath, "--", $probe, "delay-tcp", "3", "1.1.1.1", "443") - $concurrentJournals = @() - for ($attempt = 0; $attempt -lt 100; $attempt++) { - $concurrentJournals = @(Get-ChildItem -LiteralPath $leaseDir -Filter "*.json" -ErrorAction SilentlyContinue | - Where-Object { $concurrentBaseline -notcontains $_.Name }) - if ($concurrentJournals.Count -eq 2) { break } - Start-Sleep -Milliseconds 100 - } - if ($concurrentJournals.Count -ne 2) { - $first.Kill(); $second.Kill() - Exit-Fail "two concurrent WFP lease journals did not coexist" + -ArgumentList @("run", "--policy", $PolicyPath, "--", $probe, "delay-tcp", "5", "1.1.1.1", "443") + Start-Sleep -Seconds 2 + if ($first.HasExited) { + Exit-Fail "first concurrent sandbox exited before it was stopped (exit $($first.ExitCode)), so its teardown was not tested" } $first.Kill() $first.WaitForExit(10000) | Out-Null - Start-Sleep -Milliseconds 200 - $remainingConcurrent = @(Get-ChildItem -LiteralPath $leaseDir -Filter "*.json" -ErrorAction SilentlyContinue | - Where-Object { $concurrentBaseline -notcontains $_.Name }) - if ($remainingConcurrent.Count -ne 1) { - $second.Kill() - Exit-Fail "releasing one sandbox removed or retained another sandbox's WFP lease" - } - if (-not $second.WaitForExit(15000)) { + if (-not $second.WaitForExit(30000)) { $second.Kill() Exit-Fail "second concurrent sandbox did not complete" } @@ -203,57 +235,10 @@ try { Get-Content -LiteralPath $secondErr -ErrorAction SilentlyContinue ) | Out-String if (-not $secondOutput.Contains("TCP_BLOCKED")) { - Exit-Fail "second sandbox bypassed its block after the first lease was released: $secondOutput" + Exit-Fail "second sandbox bypassed its block after the first sandbox exited: $secondOutput" } - # Broker restart: the dynamic permit disappears, persistent blocks remain, - # MXC's pipe watchdog kills the child, and restart reaps the journal/blocks. - $beforeJournals = @(Get-ChildItem -LiteralPath $leaseDir -Filter "*.json" -ErrorAction SilentlyContinue | ForEach-Object Name) - $crashOut = Join-Path $root "crash.out" - $crashErr = Join-Path $root "crash.err" - $crashProcess = Start-Process -FilePath $AxisBin -WindowStyle Hidden -PassThru ` - -WorkingDirectory $workspace -RedirectStandardInput $emptyInput ` - -RedirectStandardOutput $crashOut -RedirectStandardError $crashErr ` - -ArgumentList @("run", "--policy", $PolicyPath, "--", $probe, "hold", "120") - $newJournal = $null - for ($attempt = 0; $attempt -lt 150; $attempt++) { - $newJournal = Get-ChildItem -LiteralPath $leaseDir -Filter "*.json" -ErrorAction SilentlyContinue | - Where-Object { $beforeJournals -notcontains $_.Name } | Select-Object -First 1 - if ($newJournal) { break } - Start-Sleep -Milliseconds 100 - } - if (-not $newJournal) { - $crashProcess.Kill() - Exit-Fail "live lease journal did not appear" - } - $leaseId = [IO.Path]::GetFileNameWithoutExtension($newJournal.Name) - - Stop-Service -Name AxisWfpBroker -Force - if (-not (Test-Path -LiteralPath $newJournal.FullName)) { - Exit-Fail "broker crash removed persistent fail-closed block journal prematurely" - } - Start-Service -Name AxisWfpBroker - if (-not $crashProcess.WaitForExit(15000)) { - $crashProcess.Kill() - Exit-Fail "MXC did not terminate the child after broker pipe loss" - } - for ($attempt = 0; $attempt -lt 100 -and (Test-Path -LiteralPath $newJournal.FullName); $attempt++) { - Start-Sleep -Milliseconds 100 - } - if (Test-Path -LiteralPath $newJournal.FullName) { - Exit-Fail "broker restart did not reap the stale persistent blocks" - } - $reaped = Get-Content -LiteralPath $auditLog | ForEach-Object { - try { $_ | ConvertFrom-Json } catch { $null } - } | Where-Object { $_ -and $_.event -eq "stale_lease_reaped" -and $_.leaseId -eq $leaseId } - if (-not $reaped) { - Exit-Fail "broker restart did not audit stale lease recovery" - } - - Write-Host "PASS: AXIS Windows MXC strict WFP proxy security checks" + Write-Host "PASS: AXIS Windows MXC strict proxy security checks" } finally { - if ((Get-Service -Name AxisWfpBroker -ErrorAction SilentlyContinue).Status -ne "Running") { - Start-Service -Name AxisWfpBroker -ErrorAction SilentlyContinue - } Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue } diff --git a/scripts/install_windows_wfp_broker.ps1 b/scripts/install_windows_wfp_broker.ps1 deleted file mode 100644 index 9adf868..0000000 --- a/scripts/install_windows_wfp_broker.ps1 +++ /dev/null @@ -1,140 +0,0 @@ -# Copyright 2026 Advanced Micro Devices, Inc. -# SPDX-License-Identifier: Apache-2.0 - -[CmdletBinding()] -param( - [switch]$Uninstall, - [switch]$SkipBuild, - [string]$LogPath -) - -$ErrorActionPreference = "Stop" -Set-StrictMode -Version Latest - -if ($LogPath) { - Set-Content -LiteralPath $LogPath -Value "" -Encoding UTF8 -} - -trap { - if ($LogPath) { - $_ | Out-String | Set-Content -LiteralPath $LogPath -Encoding UTF8 - } - throw -} - -$serviceName = "AxisWfpBroker" -$repoRoot = Split-Path -Parent $PSScriptRoot -$installDir = Join-Path $env:ProgramFiles "Axis" -$installedBinary = Join-Path $installDir "axis-wfp-broker.exe" -$leaseDir = Join-Path $env:ProgramData "axis\wfp-leases" -$builtBinary = Join-Path $repoRoot "target\release\axis-wfp-broker.exe" - -$identity = [Security.Principal.WindowsIdentity]::GetCurrent() -$principal = [Security.Principal.WindowsPrincipal]::new($identity) -if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { - throw "This script must run from an elevated PowerShell session because WFP policy installation is a privileged host operation." -} - -function Invoke-Sc { - param([Parameter(Mandatory = $true)][string[]]$Arguments) - - & "$env:SystemRoot\System32\sc.exe" @Arguments - if ($LASTEXITCODE -ne 0) { - throw "sc.exe $($Arguments -join ' ') failed with exit code $LASTEXITCODE" - } -} - -function Test-ServiceExists { - & "$env:SystemRoot\System32\sc.exe" query $serviceName *> $null - return $LASTEXITCODE -eq 0 -} - -if ($Uninstall) { - $activeJournals = @(Get-ChildItem -LiteralPath $leaseDir -Filter "*.json" -ErrorAction SilentlyContinue) - if ($activeJournals.Count -ne 0) { - throw "Refusing to uninstall while WFP lease journals exist. Let active sandboxes exit, or restart the broker so it can reap a crashed lease." - } - if (Test-ServiceExists) { - & "$env:SystemRoot\System32\sc.exe" stop $serviceName *> $null - for ($attempt = 0; $attempt -lt 50; $attempt++) { - $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue - if (-not $service -or $service.Status -eq "Stopped") { - break - } - Start-Sleep -Milliseconds 100 - } - Invoke-Sc -Arguments @("delete", $serviceName) - } - if (Test-Path -LiteralPath $installedBinary) { - Remove-Item -LiteralPath $installedBinary -Force - } - Write-Host "AXIS WFP broker service removed." - exit 0 -} - -if (-not $SkipBuild) { - & cargo build --release -p axis-sandbox --bin axis-wfp-broker --manifest-path (Join-Path $repoRoot "Cargo.toml") - if ($LASTEXITCODE -ne 0) { - throw "AXIS WFP broker build failed with exit code $LASTEXITCODE" - } -} -if (-not (Test-Path -LiteralPath $builtBinary -PathType Leaf)) { - throw "Built broker not found at $builtBinary. Run without -SkipBuild first." -} - -if (Test-ServiceExists) { - & "$env:SystemRoot\System32\sc.exe" stop $serviceName *> $null - for ($attempt = 0; $attempt -lt 50; $attempt++) { - $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue - if ($service.Status -eq "Stopped") { - break - } - Start-Sleep -Milliseconds 100 - } - if ((Get-Service -Name $serviceName).Status -ne "Stopped") { - throw "Existing $serviceName service did not stop" - } -} - -New-Item -ItemType Directory -Path $installDir -Force | Out-Null -Copy-Item -LiteralPath $builtBinary -Destination $installedBinary -Force -New-Item -ItemType Directory -Path $leaseDir -Force | Out-Null -& "$env:SystemRoot\System32\icacls.exe" $leaseDir /inheritance:r /grant:r '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F' | Out-Null -if ($LASTEXITCODE -ne 0) { - throw "failed to restrict the WFP lease journal ACL" -} - -if (-not (Test-ServiceExists)) { - $quotedCommand = '"{0}" service' -f $installedBinary - New-Service ` - -Name $serviceName ` - -BinaryPathName $quotedCommand ` - -DisplayName "AXIS WFP strict-proxy broker" ` - -StartupType Automatic | Out-Null - Invoke-Sc -Arguments @("description", $serviceName, "Installs lease-scoped WFP filters for suspended AXIS MXC ProcessContainer children.") - Invoke-Sc -Arguments @("failure", $serviceName, "reset=", "86400", "actions=", "restart/1000/restart/5000/none/0") -} - -Set-Service -Name $serviceName -StartupType Automatic - -Invoke-Sc -Arguments @("start", $serviceName) -$pipePath = "\\.\pipe\axis-wfp-broker-v1" -for ($attempt = 0; $attempt -lt 100; $attempt++) { - if ([System.IO.Directory]::GetFiles("\\.\pipe\") -contains $pipePath) { - break - } - Start-Sleep -Milliseconds 100 -} -if (-not ([System.IO.Directory]::GetFiles("\\.\pipe\") -contains $pipePath)) { - throw "The $serviceName service started but its lease pipe did not become available" -} - -& $installedBinary probe -if ($LASTEXITCODE -ne 0) { - throw "The installed broker could not open the Windows Filtering Platform engine" -} - -Write-Host "AXIS WFP broker installed and running." -Write-Host "Service: $serviceName" -Write-Host "Binary: $installedBinary" -Write-Host "Pipe: $pipePath" diff --git a/scripts/setup_windows_mxc.ps1 b/scripts/setup_windows_mxc.ps1 index 4970ec3..ec8ad85 100644 --- a/scripts/setup_windows_mxc.ps1 +++ b/scripts/setup_windows_mxc.ps1 @@ -10,47 +10,17 @@ param( $ErrorActionPreference = "Stop" $mxcRepository = "https://github.com/microsoft/mxc" -# Windows stays on an older MXC revision than Linux until MXC BaseContainer can -# run least-privilege AppContainer children without DACL mutation: -# https://github.com/microsoft/mxc/issues/1496 -$mxcRef = "1736b48398c3fe4d1315b2311c0951cc893eb3ae" +# MXC v1.0.1; keep in sync with MXC_WINDOWS_REF in the workflows. +$mxcRef = "fda29ac63bc306b7f97f3b86b4b63d44f7f40cf2" $repoRoot = Split-Path -Parent $PSScriptRoot -$patchPaths = @( - (Join-Path $repoRoot "third_party\mxc\patches\0001-wxc-processcontainer-resource-limits.patch"), - (Join-Path $repoRoot "third_party\mxc\patches\0002-wxc-job-list-resource-assignment.patch"), - (Join-Path $repoRoot "third_party\mxc\patches\0003-axis-wfp-strict-proxy.patch") -) $axisReleaseDir = Join-Path $repoRoot "target\release" $installedExecutor = Join-Path $axisReleaseDir "wxc-exec.exe" -function Test-MxcPatch([string]$PatchPath, [switch]$Reverse) { - # Windows PowerShell 5.1 turns native stderr into an ErrorRecord when the - # caller uses Stop. A failed `git apply --check` is expected while deciding - # whether the patch is already present, so inspect its exit code explicitly. - $savedErrorActionPreference = $ErrorActionPreference - try { - $ErrorActionPreference = "Continue" - if ($Reverse) { - & git -C $MxcDir apply --reverse --check --whitespace=error $PatchPath 2>$null - } else { - & git -C $MxcDir apply --check --whitespace=error $PatchPath 2>$null - } - return $LASTEXITCODE -eq 0 - } finally { - $ErrorActionPreference = $savedErrorActionPreference - } -} - foreach ($command in @("git", "cargo")) { if (-not (Get-Command $command -ErrorAction SilentlyContinue)) { throw "Required command is not available on PATH: $command" } } -foreach ($patchPath in $patchPaths) { - if (-not (Test-Path -LiteralPath $patchPath -PathType Leaf)) { - throw "AXIS MXC patch not found: $patchPath" - } -} if (-not (Test-Path -LiteralPath (Join-Path $MxcDir ".git") -PathType Container)) { if (Test-Path -LiteralPath $MxcDir) { @@ -76,22 +46,6 @@ if ($LASTEXITCODE -ne 0) { throw "MXC checkout failed with exit code $LASTEXITCODE" } -# Make repeated runs safe: apply the AXIS patch only when it is not present. -if (Test-MxcPatch $patchPaths[0]) { - Write-Host "Applying AXIS MXC patches" - foreach ($patchPath in $patchPaths) { - & git -C $MxcDir apply --whitespace=error $patchPath - if ($LASTEXITCODE -ne 0) { - throw "MXC patch failed for $patchPath with exit code $LASTEXITCODE" - } - } -} else { - if (-not (Test-MxcPatch $patchPaths[-1] -Reverse)) { - throw "MXC checkout is not in a state where the AXIS patches can be applied" - } - Write-Host "AXIS MXC patches are already applied" -} - Write-Host "Building wxc-exec.exe" Push-Location (Join-Path $MxcDir "src") try { diff --git a/scripts/verify_workflow_structure.py b/scripts/verify_workflow_structure.py index 90692c3..26eca5a 100644 --- a/scripts/verify_workflow_structure.py +++ b/scripts/verify_workflow_structure.py @@ -88,7 +88,7 @@ "RUST_TOOLCHAIN": "1.95.0", "MXC_REPOSITORY": "https://github.com/microsoft/mxc", "MXC_REF": "7bf210247986cb73b1b314df60c2f1109c479c0b", - "MXC_WINDOWS_REF": "1736b48398c3fe4d1315b2311c0951cc893eb3ae", + "MXC_WINDOWS_REF": "fda29ac63bc306b7f97f3b86b4b63d44f7f40cf2", } PACKAGE_ENVIRONMENT = { "CARGO_DEB_VERSION": "3.6.4", @@ -125,7 +125,7 @@ "identity": "6a0829b6d0fca5d53cbc17051cb8e095cec10af735aa5fe7ecfc5b4087ba063a", "gate": "6c2c7b11eefc3f57f2e94c391ad7bbba235c46cc3944ad06fec7a9f245fa41ad", "gui": "385abeea4a0aac4cb93b8fc4f50c08bdf89d6949b9a217c2c000efa04bc3eaeb", - "build": "7385b7b71f09ddcbf16e51ba44e2f15d61f1c151131b094514dc47c3194a112c", + "build": "7e2d043472aa6aadd9379e00db9cec67d6c074833d5f710062ed7f5fadfc5a13", "package-linux": "33f8038e28b58b653147510eac3f2a284c73c98abef13bbc6d628690278e91c4", "sbom": "6bd541ff08680a29119a5088b8d29d18d843d701bba7d2e1cb0f83f4877460c1", "checksums": "fc4e16e505ca0b1615f92184a47701a1fee165c9c84faa89c18fd4c68c424244", @@ -136,7 +136,7 @@ "source": "396c0c9226914fc2d6d77d0abc0962b816b24fdb585f970ecd485b1d536e8443", "gate": "ccc3041871c557de8f4d4dda8f22e76b93948bd6f2aec6d7d623a4637292fc12", "gui": "d2e806ebd8d87b3d84ea52d7d7b8f171117bc344abfd76e0e77c7f46e1e2e740", - "build": "2a6323eb08aa0b48bc980abca51c9c9851788ded781b7bdc6afb2a3b22dbd076", + "build": "f487fee6ff2a9f65d90bbde5723e04d57098f602bc8e3993c147cfe235b9cabc", "sbom": "10e8e7caa4982974d3bacfc5fb6a0561459f3f6049849089724b18cbacf92680", "checksums": "a49bf91fc21806960ce8e444c4e5ea615798c8f4f518f94c1e7765113e808a63", "attest": "a3817a26b1b2d37b42d5987e5d446822f862a3f1c98988e6811188b0a721c291", @@ -925,8 +925,6 @@ def verify_common_release_build(workflow: dict[str, Any], *, nightly: bool) -> N "run": """$mxcDir = Join-Path $env:RUNNER_TEMP "mxc" git clone --filter=blob:none $env:MXC_REPOSITORY $mxcDir git -C $mxcDir checkout $env:MXC_WINDOWS_REF -Get-ChildItem (Join-Path $env:GITHUB_WORKSPACE "third_party\\mxc\\patches\\*.patch") | - Sort-Object Name | ForEach-Object { git -C $mxcDir apply --whitespace=error $_.FullName } Push-Location (Join-Path $mxcDir "src") cargo build --release -p wxc --no-default-features --locked --target ${{ matrix.target }} Pop-Location @@ -976,9 +974,7 @@ def verify_common_release_build(workflow: dict[str, Any], *, nightly: bool) -> N '"dist/axis-$env:PLATFORM.zip" "axis-$env:PLATFORM" ' "--require axis.exe --require axisd.exe " "--require wxc-exec.exe " - "--require axis-wfp-broker.exe " "--require axis-ssh-proxy.exe " - "--require install_windows_wfp_broker.ps1 " "--require REPRODUCIBILITY.json" ), }, @@ -994,12 +990,8 @@ def verify_common_release_build(workflow: dict[str, Any], *, nightly: bool) -> N "--require", "wxc-exec.exe", "--require", - "axis-wfp-broker.exe", - "--require", "axis-ssh-proxy.exe", "--require", - "install_windows_wfp_broker.ps1", - "--require", "REPRODUCIBILITY.json", ], f"{windows_name} step", @@ -1726,8 +1718,6 @@ def verify_ci_workflow(workflow: dict[str, Any]) -> None: "run": """$mxcDir = Join-Path $env:RUNNER_TEMP "mxc" git clone --filter=blob:none $env:MXC_REPOSITORY $mxcDir git -C $mxcDir checkout $env:MXC_WINDOWS_REF -Get-ChildItem (Join-Path $env:GITHUB_WORKSPACE "third_party\\mxc\\patches\\*.patch") | - Sort-Object Name | ForEach-Object { git -C $mxcDir apply --whitespace=error $_.FullName } Push-Location (Join-Path $mxcDir "src") cargo build --release -p wxc --no-default-features --locked Pop-Location diff --git a/third_party/mxc/README.md b/third_party/mxc/README.md index 33275a0..511fe53 100644 --- a/third_party/mxc/README.md +++ b/third_party/mxc/README.md @@ -1,48 +1,41 @@ -# Pinned MXC patches +# Pinned MXC -AXIS pins MXC separately per platform: +AXIS builds the MXC executors from pinned upstream commits without local +patches: - Linux `lxc-exec` is built from MXC v1.0.0 - (`7bf210247986cb73b1b314df60c2f1109c479c0b`, `MXC_REF` in the workflows) - without local patches. -- Windows `wxc-exec.exe` is built from MXC commit - `1736b48398c3fe4d1315b2311c0951cc893eb3ae` (`MXC_WINDOWS_REF`) with the - patches in `patches/` applied before compilation. - -Windows stays on the older revision because MXC 1.x BaseContainer cannot launch -least-privilege (LPAC) AppContainer children without host DACL mutation, which -AXIS forbids (), and because its -ProcessContainer proxy contract cannot route to an unpackaged loopback proxy -without also opening inbound and host-loopback access. Moving Windows to MXC -1.x requires rewriting these patches for the `src/mxc-sdk` layout as well. - -`0001-wxc-processcontainer-resource-limits.patch` adds process-count, -aggregate-memory, and CPU-rate fields to MXC's ProcessContainer schema and Job -Object implementation. Remove the patch when upstream MXC exposes equivalent -resource fields and enforcement. - -`0002-wxc-job-list-resource-assignment.patch` makes process count, -aggregate memory, and CPU-rate limits child-only. BaseContainer explicitly -breaks away from AXIS's outer lifecycle Job while suspended, then MXC assigns -it to the inner resource Job before resuming it. Silent breakaway stays -disabled, and closing either executor boundary still kills the sandbox tree. -Remove this patch when upstream MXC exposes equivalent ProcessContainer -resource fields and atomic BaseContainer Job assignment. - -`0003-axis-wfp-strict-proxy.patch` adds the narrow AXIS WFP lease contract -to MXC's BaseContainer runner. It creates the child suspended, sends its PID and -the exact proxy endpoint to the installed broker, validates the broker's -SID/filter response, and resumes only after the lease is active. It also injects -sanitized proxy environment variables. A pipe watchdog terminates the child if -the broker disappears. Remove this patch when upstream MXC provides an -equivalent pre-resume broker hook and fail-closed lease lifecycle. + (`7bf210247986cb73b1b314df60c2f1109c479c0b`, `MXC_REF` in the workflows). +- Windows `wxc-exec.exe` is built from MXC v1.0.1 + (`fda29ac63bc306b7f97f3b86b4b63d44f7f40cf2`, `MXC_WINDOWS_REF` in the + workflows and `scripts/setup_windows_mxc.ps1`). AXIS uses MXC BaseContainer only. The generated configuration leaves `fallback.allowDaclMutation=false`, so an unavailable BaseContainer fails closed instead of selecting an AppContainer/DACL tier. -The supported -`Experimental_CreateProcessInSandbox` API rejects +MXC 1.x BaseContainer has three limits that AXIS accepts and reports rather +than patches; [Windows MXC 1.x Backend](../../docs/windows-mxc-1.md) has the +evidence: + +- There is no least-privilege (LPAC) token option + (). The child keeps the + caller's user SID inside the container, so system locations and the user's + registry hive stay readable. `process.identity: isolated` is rejected. +- `runtimeConfig.networkProxy` requires `network.ingress.default: allow`, which + adds the `privateNetworkClientServer` capability. Egress is limited to the + AXIS proxy, but inbound connections from private-network peers depend on the + host firewall. +- The proxy mapping's WFP filters do not report individual blocked + connections, so direct bypass attempts are denied without an AXIS audit + record. A proxy launch warns about it, and `network.bypass_audit: + hard_requirement` refuses such launches. + +Process-count, memory and CPU limits are applied by AXIS: the executor starts +suspended inside an AXIS Job Object and is resumed only after the assignment +succeeds, so the whole executor tree is accounted for from its first +instruction. + +The `Experimental_CreateProcessInSandbox` API rejects `PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE` with `ERROR_INVALID_HANDLE` on Windows build 26300. AXIS does not downgrade to AppContainer/DACL solely to provide ConPTY. Enable the BaseContainer interactive path only after a runtime diff --git a/third_party/mxc/patches/0001-wxc-processcontainer-resource-limits.patch b/third_party/mxc/patches/0001-wxc-processcontainer-resource-limits.patch deleted file mode 100644 index 3371d5c..0000000 --- a/third_party/mxc/patches/0001-wxc-processcontainer-resource-limits.patch +++ /dev/null @@ -1,334 +0,0 @@ -diff --git a/src/backends/appcontainer/common/src/base_container_runner.rs b/src/backends/appcontainer/common/src/base_container_runner.rs ---- a/src/backends/appcontainer/common/src/base_container_runner.rs -+++ b/src/backends/appcontainer/common/src/base_container_runner.rs -@@ -25,11 +25,12 @@ use windows::Win32::System::LibraryLoader::{ - GetProcAddress, LoadLibraryExW, LOAD_LIBRARY_SEARCH_SYSTEM32, - }; - use windows::Win32::System::Threading::{ -- GetExitCodeProcess, TerminateProcess, WaitForSingleObject, PROCESS_INFORMATION, -- STARTF_USESTDHANDLES, STARTUPINFOW, -+ GetExitCodeProcess, ResumeThread, TerminateProcess, WaitForSingleObject, CREATE_SUSPENDED, -+ PROCESS_INFORMATION, STARTF_USESTDHANDLES, STARTUPINFOW, - }; - use windows_core::PCWSTR; - -+use crate::job_object::UiJobObject; - use crate::launch_diagnostics::{ - diagnose_create_process_failure, diagnose_environment_not_supported, diagnose_process_exit, - is_environment_not_supported, -@@ -420,6 +421,11 @@ impl ScriptRunner for BaseContainerRunner { - wxc_common::error::HOST_LISTS_NOT_SUPPORTED_MSG, - )); - } -+ if request.policy.resources.cpu_rate_percent > 100 { -+ return Err(ScriptResponse::error( -+ "processContainer.resources.cpuRatePercent must be between 0 and 100", -+ )); -+ } - Self::is_base_container_api_present().map_err(|e| { - let hint = if !request.experimental_enabled { - format!( -@@ -677,12 +683,6 @@ impl ScriptRunner for BaseContainerRunner { - .as_ref() - .map(|b| b.as_ptr() as *const c_void) - .unwrap_or(ptr::null()); -- let creation_flags = if env_block.is_some() { -- CREATE_UNICODE_ENVIRONMENT.0 -- } else { -- 0 -- }; -- - let _ = writeln!(logger, "launching: {}", request.script_code); - let _ = writeln!(logger, "identity: {identity}"); - -@@ -710,6 +710,47 @@ impl ScriptRunner for BaseContainerRunner { - }; - } - -+ let resources_requested = request.policy.resources.max_processes > 0 -+ || request.policy.resources.max_memory_mb > 0 -+ || request.policy.resources.cpu_rate_percent > 0; -+ let resource_job = if resources_requested { -+ let job = match UiJobObject::new().and_then(|job| { -+ job.set_resource_limits(&request.policy.resources)?; -+ Ok(job) -+ }) { -+ Ok(job) => job, -+ Err(err) => { -+ return ScriptResponse::error(&format!( -+ "failed to create ProcessContainer resource Job Object: {err}" -+ )); -+ } -+ }; -+ let _ = writeln!( -+ logger, -+ "resource job: maxProcesses={}, maxMemoryMb={}, cpuRatePercent={}", -+ request.policy.resources.max_processes, -+ request.policy.resources.max_memory_mb, -+ request.policy.resources.cpu_rate_percent -+ ); -+ Some(job) -+ } else { -+ None -+ }; -+ -+ // A child that requires Job limits is created suspended so no -+ // untrusted instruction can execute before assignment succeeds. -+ let base_creation_flags = if resource_job.is_some() { -+ CREATE_SUSPENDED.0 -+ } else { -+ 0 -+ }; -+ let creation_flags = base_creation_flags -+ | if env_block.is_some() { -+ CREATE_UNICODE_ENVIRONMENT.0 -+ } else { -+ 0 -+ }; -+ - // 4. Call Experimental_CreateProcessInSandbox. - // If the OS returns ERROR_NOT_SUPPORTED (0x32) and we passed a non-null - // environment block, this is a downlevel build that doesn't support the -@@ -776,7 +817,7 @@ impl ScriptRunner for BaseContainerRunner { - - // Retry without the environment block. - current_env_ptr = ptr::null(); -- current_creation_flags = 0; -+ current_creation_flags = base_creation_flags; - continue; - } - -@@ -834,6 +875,34 @@ impl ScriptRunner for BaseContainerRunner { - }; - } - -+ if let Some(job) = resource_job.as_ref() { -+ if let Err(err) = job.assign_process(pi.hProcess) { -+ unsafe { -+ let _ = TerminateProcess(pi.hProcess, u32::MAX); -+ let _ = WaitForSingleObject(pi.hProcess, 5000); -+ let _ = CloseHandle(pi.hProcess); -+ let _ = CloseHandle(pi.hThread); -+ } -+ return ScriptResponse::error(&format!( -+ "failed to assign suspended ProcessContainer child to resource Job Object: {err}" -+ )); -+ } -+ -+ let resume_result = unsafe { ResumeThread(pi.hThread) }; -+ if resume_result == u32::MAX { -+ let err = unsafe { GetLastError() }; -+ unsafe { -+ let _ = TerminateProcess(pi.hProcess, u32::MAX); -+ let _ = WaitForSingleObject(pi.hProcess, 5000); -+ let _ = CloseHandle(pi.hProcess); -+ let _ = CloseHandle(pi.hThread); -+ } -+ return ScriptResponse::error(&format!( -+ "failed to resume resource-limited ProcessContainer child: {err:?}" -+ )); -+ } -+ } -+ - let _ = writeln!(logger, "process created (PID: {})", pi.dwProcessId); - - let _ = writeln!(logger, "{EMOJI_SECTION} SECTION: Wait for exit"); -diff --git a/src/backends/appcontainer/common/src/job_object.rs b/src/backends/appcontainer/common/src/job_object.rs ---- a/src/backends/appcontainer/common/src/job_object.rs -+++ b/src/backends/appcontainer/common/src/job_object.rs -@@ -19,7 +19,11 @@ use std::sync::OnceLock; - use windows::Win32::Foundation::{CloseHandle, HANDLE}; - use windows::Win32::System::JobObjects::{ - AssignProcessToJobObject, CreateJobObjectW, JobObjectBasicUIRestrictions, -- SetInformationJobObject, JOBOBJECT_BASIC_UI_RESTRICTIONS, JOB_OBJECT_UILIMIT, -+ JobObjectCpuRateControlInformation, JobObjectExtendedLimitInformation, SetInformationJobObject, -+ JOBOBJECT_BASIC_UI_RESTRICTIONS, JOBOBJECT_CPU_RATE_CONTROL_INFORMATION, -+ JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_CPU_RATE_CONTROL_ENABLE, -+ JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP, JOB_OBJECT_LIMIT_ACTIVE_PROCESS, -+ JOB_OBJECT_LIMIT_JOB_MEMORY, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, JOB_OBJECT_UILIMIT, - JOB_OBJECT_UILIMIT_DESKTOP, JOB_OBJECT_UILIMIT_DISPLAYSETTINGS, JOB_OBJECT_UILIMIT_EXITWINDOWS, - JOB_OBJECT_UILIMIT_GLOBALATOMS, JOB_OBJECT_UILIMIT_HANDLES, JOB_OBJECT_UILIMIT_READCLIPBOARD, - JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS, JOB_OBJECT_UILIMIT_WRITECLIPBOARD, -@@ -28,6 +32,7 @@ use windows::Win32::System::SystemServices::JOB_OBJECT_UILIMIT_IME; - use windows_core::PCWSTR; - - use wxc_common::error::WxcError; -+use wxc_common::models::ProcessResourceLimits; - use wxc_common::ui_policy::EffectiveUiRestrictions; - - /// Helper for loading `RtlGetVersion` from `ntdll.dll` to get the true -@@ -265,6 +270,65 @@ impl UiJobObject { - .map_err(|e| WxcError::Process(format!("SetInformationJobObject(UI): {e}"))) - } - -+ /// Apply limits to this job's complete process tree. The job is configured -+ /// kill-on-close so every descendant is terminated if the executor exits. -+ pub fn set_resource_limits(&self, limits: &ProcessResourceLimits) -> Result<(), WxcError> { -+ if limits.cpu_rate_percent > 100 { -+ return Err(WxcError::Process(format!( -+ "cpuRatePercent must be between 0 and 100, got {}", -+ limits.cpu_rate_percent -+ ))); -+ } -+ -+ let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default(); -+ info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; -+ if limits.max_processes > 0 { -+ info.BasicLimitInformation.ActiveProcessLimit = limits.max_processes; -+ info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_ACTIVE_PROCESS; -+ } -+ if limits.max_memory_mb > 0 { -+ let bytes = limits -+ .max_memory_mb -+ .checked_mul(1024 * 1024) -+ .and_then(|bytes| usize::try_from(bytes).ok()) -+ .ok_or_else(|| { -+ WxcError::Process(format!( -+ "maxMemoryMb {} exceeds the host Job Object limit", -+ limits.max_memory_mb -+ )) -+ })?; -+ info.JobMemoryLimit = bytes; -+ info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_JOB_MEMORY; -+ } -+ -+ unsafe { -+ SetInformationJobObject( -+ self.handle, -+ JobObjectExtendedLimitInformation, -+ &info as *const _ as *const c_void, -+ size_of::() as u32, -+ ) -+ } -+ .map_err(|e| WxcError::Process(format!("SetInformationJobObject(resources): {e}")))?; -+ -+ if limits.cpu_rate_percent > 0 && limits.cpu_rate_percent < 100 { -+ let mut cpu = JOBOBJECT_CPU_RATE_CONTROL_INFORMATION::default(); -+ cpu.ControlFlags = -+ JOB_OBJECT_CPU_RATE_CONTROL_ENABLE | JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP; -+ cpu.Anonymous.CpuRate = limits.cpu_rate_percent * 100; -+ unsafe { -+ SetInformationJobObject( -+ self.handle, -+ JobObjectCpuRateControlInformation, -+ &cpu as *const _ as *const c_void, -+ size_of::() as u32, -+ ) -+ } -+ .map_err(|e| WxcError::Process(format!("SetInformationJobObject(CPU): {e}")))?; -+ } -+ Ok(()) -+ } -+ - /// Assigns the given process handle to this job. The process and any - /// future descendants will inherit the job's UI restrictions. - pub fn assign_process(&self, process_handle: HANDLE) -> Result<(), WxcError> { -@@ -306,6 +370,29 @@ mod tests { - drop(job); - } - -+ #[test] -+ fn resource_limits_use_aggregate_job_accounting() { -+ let job = UiJobObject::new().expect("create"); -+ job.set_resource_limits(&ProcessResourceLimits { -+ max_processes: 4, -+ max_memory_mb: 256, -+ cpu_rate_percent: 50, -+ }) -+ .expect("set resources"); -+ } -+ -+ #[test] -+ fn resource_limits_reject_invalid_cpu_rate() { -+ let job = UiJobObject::new().expect("create"); -+ let err = job -+ .set_resource_limits(&ProcessResourceLimits { -+ cpu_rate_percent: 101, -+ ..Default::default() -+ }) -+ .unwrap_err(); -+ assert!(err.to_string().contains("between 0 and 100")); -+ } -+ - #[test] - fn encoder_known_bit_positions() { - // Sanity-check that the encoder produces the documented winnt.h -diff --git a/src/core/wxc_common/src/config_parser.rs b/src/core/wxc_common/src/config_parser.rs ---- a/src/core/wxc_common/src/config_parser.rs -+++ b/src/core/wxc_common/src/config_parser.rs -@@ -45,6 +45,18 @@ struct RawProcessContainer { - learning_mode: Option, - capabilities: Option>, - ui: Option, -+ resources: Option, -+} -+ -+#[derive(Deserialize, Default)] -+#[serde(default)] -+struct RawProcessResources { -+ #[serde(rename = "maxProcesses")] -+ max_processes: Option, -+ #[serde(rename = "maxMemoryMb")] -+ max_memory_mb: Option, -+ #[serde(rename = "cpuRatePercent")] -+ cpu_rate_percent: Option, - } - - #[derive(Deserialize, Default)] -@@ -951,6 +963,12 @@ fn convert_raw_config_inner( - raw_ui.system_settings.unwrap_or_else(|| "none".to_string()); - policy.base_process_ui.ime = raw_ui.ime.unwrap_or(false); - } -+ -+ if let Some(resources) = ac.resources { -+ policy.resources.max_processes = resources.max_processes.unwrap_or(0); -+ policy.resources.max_memory_mb = resources.max_memory_mb.unwrap_or(0); -+ policy.resources.cpu_rate_percent = resources.cpu_rate_percent.unwrap_or(0); -+ } - } - - // Filesystem section -@@ -1625,7 +1643,12 @@ mod tests { - }, - "processContainer": { - "leastPrivilege": true, -- "capabilities": ["internetClient"] -+ "capabilities": ["internetClient"], -+ "resources": { -+ "maxProcesses": 12, -+ "maxMemoryMb": 768, -+ "cpuRatePercent": 35 -+ } - }, - "filesystem": { - "readwritePaths": ["C:\\rw"], -@@ -1655,6 +1678,9 @@ mod tests { - assert_eq!(req.policy.readwrite_paths, vec!["C:\\rw"]); - assert_eq!(req.policy.readonly_paths, vec!["C:\\ro"]); - assert_eq!(req.policy.denied_paths, vec!["C:\\denied"]); -+ assert_eq!(req.policy.resources.max_processes, 12); -+ assert_eq!(req.policy.resources.max_memory_mb, 768); -+ assert_eq!(req.policy.resources.cpu_rate_percent, 35); - assert_eq!(req.policy.default_network_policy, NetworkPolicy::Block); - assert_eq!( - req.policy.network_enforcement_mode, -diff --git a/src/core/wxc_common/src/models.rs b/src/core/wxc_common/src/models.rs ---- a/src/core/wxc_common/src/models.rs -+++ b/src/core/wxc_common/src/models.rs -@@ -447,6 +447,16 @@ pub struct ContainerPolicy { - pub ui: UiPolicy, - /// BaseProcessContainer-specific UI config (Windows only, from processContainer.ui). - pub base_process_ui: BaseProcessUiConfig, -+ /// Resource limits for the ProcessContainer child and all descendants. -+ pub resources: ProcessResourceLimits, -+} -+ -+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] -+#[serde(default)] -+pub struct ProcessResourceLimits { -+ pub max_processes: u32, -+ pub max_memory_mb: u64, -+ pub cpu_rate_percent: u32, - } - - /// Port mapping for host↔container port forwarding. diff --git a/third_party/mxc/patches/0002-wxc-job-list-resource-assignment.patch b/third_party/mxc/patches/0002-wxc-job-list-resource-assignment.patch deleted file mode 100644 index ed436bb..0000000 --- a/third_party/mxc/patches/0002-wxc-job-list-resource-assignment.patch +++ /dev/null @@ -1,64 +0,0 @@ -diff --git a/src/backends/appcontainer/common/src/base_container_runner.rs b/src/backends/appcontainer/common/src/base_container_runner.rs ---- a/src/backends/appcontainer/common/src/base_container_runner.rs -+++ b/src/backends/appcontainer/common/src/base_container_runner.rs -@@ -25,8 +25,9 @@ use windows::Win32::System::LibraryLoader::{ - GetProcAddress, LoadLibraryExW, LOAD_LIBRARY_SEARCH_SYSTEM32, - }; - use windows::Win32::System::Threading::{ -- GetExitCodeProcess, ResumeThread, TerminateProcess, WaitForSingleObject, CREATE_SUSPENDED, -- PROCESS_INFORMATION, STARTF_USESTDHANDLES, STARTUPINFOW, -+ GetExitCodeProcess, ResumeThread, TerminateProcess, WaitForSingleObject, -+ CREATE_BREAKAWAY_FROM_JOB, CREATE_SUSPENDED, PROCESS_INFORMATION, STARTF_USESTDHANDLES, -+ STARTUPINFOW, - }; - use windows_core::PCWSTR; - -@@ -742,7 +743,7 @@ impl ScriptRunner for BaseContainerRunner { - // A child that requires Job limits is created suspended so no - // untrusted instruction can execute before assignment succeeds. - let base_creation_flags = if resource_job.is_some() { -- CREATE_SUSPENDED.0 -+ CREATE_SUSPENDED.0 | CREATE_BREAKAWAY_FROM_JOB.0 - } else { - 0 - }; -@@ -827,7 +828,7 @@ impl ScriptRunner for BaseContainerRunner { - return ScriptResponse { - exit_code: -1, - error_message: diag.message.clone(), -- standard_err: diag.message, -+ standard_err: format!("{}\n{}", diag.message, extended_error), - extended_error, - failure_phase: FailurePhase::LaunchFailed, - ..Default::default() -diff --git a/src/backends/appcontainer/common/src/job_object.rs b/src/backends/appcontainer/common/src/job_object.rs ---- a/src/backends/appcontainer/common/src/job_object.rs -+++ b/src/backends/appcontainer/common/src/job_object.rs -@@ -29,6 +29,7 @@ use windows::Win32::System::JobObjects::{ - JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS, JOB_OBJECT_UILIMIT_WRITECLIPBOARD, - }; - use windows::Win32::System::SystemServices::JOB_OBJECT_UILIMIT_IME; -+use windows::Win32::System::Threading::{GetActiveProcessorCount, ALL_PROCESSOR_GROUPS}; - use windows_core::PCWSTR; - - use wxc_common::error::WxcError; -@@ -311,11 +312,17 @@ impl UiJobObject { - } - .map_err(|e| WxcError::Process(format!("SetInformationJobObject(resources): {e}")))?; - -- if limits.cpu_rate_percent > 0 && limits.cpu_rate_percent < 100 { -+ if limits.cpu_rate_percent > 0 { - let mut cpu = JOBOBJECT_CPU_RATE_CONTROL_INFORMATION::default(); - cpu.ControlFlags = - JOB_OBJECT_CPU_RATE_CONTROL_ENABLE | JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP; -- cpu.Anonymous.CpuRate = limits.cpu_rate_percent * 100; -+ // Job CPU rate is a fraction of all active processor capacity, -+ // while AXIS defines 100% as one Linux-cgroup CPU. Divide by the -+ // machine's logical processor count to preserve that meaning. -+ let processors = unsafe { GetActiveProcessorCount(ALL_PROCESSOR_GROUPS) }.max(1); -+ cpu.Anonymous.CpuRate = (limits.cpu_rate_percent * 100) -+ .div_ceil(processors) -+ .clamp(1, 10_000); - unsafe { - SetInformationJobObject( - self.handle, diff --git a/third_party/mxc/patches/0003-axis-wfp-strict-proxy.patch b/third_party/mxc/patches/0003-axis-wfp-strict-proxy.patch deleted file mode 100644 index 78834ee..0000000 --- a/third_party/mxc/patches/0003-axis-wfp-strict-proxy.patch +++ /dev/null @@ -1,437 +0,0 @@ -diff --git a/src/backends/appcontainer/common/src/axis_wfp_client.rs b/src/backends/appcontainer/common/src/axis_wfp_client.rs -new file mode 100644 -index 0000000..8a976cb ---- /dev/null -+++ b/src/backends/appcontainer/common/src/axis_wfp_client.rs -@@ -0,0 +1,230 @@ -+// Copyright (c) Microsoft Corporation. -+// Licensed under the MIT License. -+ -+//! Client for AXIS's privileged strict-proxy WFP broker. -+//! -+//! The returned lease owns the named-pipe connection. Dropping it is the -+//! explicit release signal; a crash closes the handle and therefore removes -+//! the broker's dynamic WFP engine session as well. -+ -+use serde::{Deserialize, Serialize}; -+use std::fs::{File, OpenOptions}; -+use std::io::{Read, Write}; -+use std::net::IpAddr; -+use std::os::windows::io::AsRawHandle; -+use std::sync::atomic::{AtomicBool, Ordering}; -+use std::sync::Arc; -+use std::thread::JoinHandle; -+use windows::Win32::Foundation::{CloseHandle, HANDLE}; -+use windows::Win32::System::Pipes::PeekNamedPipe; -+use windows::Win32::System::Threading::{ -+ OpenProcess, TerminateProcess, PROCESS_TERMINATE, -+}; -+use wxc_common::error::WxcError; -+use wxc_common::models::ExecutionRequest; -+ -+const PROTOCOL_VERSION: u32 = 1; -+const MAX_MESSAGE_BYTES: usize = 64 * 1024; -+ -+#[derive(Debug, Serialize)] -+#[serde(rename_all = "camelCase")] -+struct LeaseRequest<'a> { -+ version: u32, -+ lease_id: &'a str, -+ child_pid: u32, -+ proxy_address: IpAddr, -+ proxy_port: u16, -+} -+ -+#[derive(Debug, Deserialize)] -+#[serde(rename_all = "camelCase", deny_unknown_fields)] -+struct LeaseResponse { -+ version: u32, -+ lease_id: String, -+ accepted: bool, -+ app_container_sid: Option, -+ filter_count: u32, -+ error: Option, -+} -+ -+pub struct AxisWfpLease { -+ pipe: File, -+ completed: Arc, -+ watchdog: Option>, -+ pub app_container_sid: String, -+ pub filter_count: u32, -+} -+ -+impl Drop for AxisWfpLease { -+ fn drop(&mut self) { -+ self.completed.store(true, Ordering::Release); -+ // Any post-acceptance byte is an explicit release signal. The broker -+ // closes its side after removing the lease, which wakes the watchdog. -+ let _ = self.pipe.write_all(&[0]); -+ let _ = self.pipe.flush(); -+ if let Some(watchdog) = self.watchdog.take() { -+ let _ = watchdog.join(); -+ } -+ } -+} -+ -+pub fn install_if_requested( -+ request: &ExecutionRequest, -+ child_pid: u32, -+) -> Result, WxcError> { -+ let Some(config) = request.policy.axis_wfp.as_ref() else { -+ return Ok(None); -+ }; -+ let proxy = request -+ .policy -+ .network_proxy -+ .address -+ .as_ref() -+ .ok_or_else(|| WxcError::Firewall("axisWfp requires network.proxy".into()))?; -+ let proxy_address = proxy.host().parse::().map_err(|_| { -+ WxcError::Firewall(format!( -+ "axisWfp requires a literal proxy IP address, got {:?}", -+ proxy.host() -+ )) -+ })?; -+ if proxy.port() == 0 { -+ return Err(WxcError::Firewall( -+ "axisWfp requires a nonzero proxy port".into(), -+ )); -+ } -+ -+ let mut pipe = OpenOptions::new() -+ .read(true) -+ .write(true) -+ .open(&config.pipe_name) -+ .map_err(|e| { -+ WxcError::Firewall(format!( -+ "open AXIS WFP broker pipe {:?}: {e}", -+ config.pipe_name -+ )) -+ })?; -+ let payload = serde_json::to_vec(&LeaseRequest { -+ version: PROTOCOL_VERSION, -+ lease_id: &config.lease_id, -+ child_pid, -+ proxy_address, -+ proxy_port: proxy.port(), -+ }) -+ .map_err(|e| WxcError::Firewall(format!("serialize AXIS WFP lease: {e}")))?; -+ write_frame(&mut pipe, &payload)?; -+ let response: LeaseResponse = serde_json::from_slice(&read_frame(&mut pipe)?) -+ .map_err(|e| WxcError::Firewall(format!("decode AXIS WFP response: {e}")))?; -+ if response.version != PROTOCOL_VERSION || response.lease_id != config.lease_id { -+ return Err(WxcError::Firewall( -+ "AXIS WFP broker response did not match the requested lease".into(), -+ )); -+ } -+ if !response.accepted { -+ return Err(WxcError::Firewall(format!( -+ "AXIS WFP broker rejected strict-proxy lease: {}", -+ response.error.unwrap_or_else(|| "unspecified error".into()) -+ ))); -+ } -+ if response.filter_count < 3 { -+ return Err(WxcError::Firewall(format!( -+ "AXIS WFP broker installed only {} filters; expected an allow plus IPv4/IPv6 blocks", -+ response.filter_count -+ ))); -+ } -+ let app_container_sid = response.app_container_sid.ok_or_else(|| { -+ WxcError::Firewall("AXIS WFP broker omitted the verified AppContainer SID".into()) -+ })?; -+ let completed = Arc::new(AtomicBool::new(false)); -+ let watchdog_pipe = pipe.as_raw_handle() as usize; -+ let watchdog_completed = completed.clone(); -+ let watchdog = std::thread::spawn(move || { -+ let disconnected = loop { -+ if watchdog_completed.load(Ordering::Acquire) { -+ break false; -+ } -+ if unsafe { -+ PeekNamedPipe( -+ HANDLE(watchdog_pipe as *mut core::ffi::c_void), -+ None, -+ 0, -+ None, -+ None, -+ None, -+ ) -+ } -+ .is_err() -+ { -+ break true; -+ } -+ std::thread::sleep(std::time::Duration::from_millis(50)); -+ }; -+ if disconnected && !watchdog_completed.load(Ordering::Acquire) { -+ // Broker failure removes a dynamic permit. Kill the child so a -+ // strict policy cannot continue without its control plane. -+ if let Ok(process) = unsafe { OpenProcess(PROCESS_TERMINATE, false, child_pid) } { -+ unsafe { -+ let _ = TerminateProcess(process, u32::MAX); -+ let _ = CloseHandle(process); -+ } -+ } -+ } -+ }); -+ Ok(Some(AxisWfpLease { -+ pipe, -+ completed, -+ watchdog: Some(watchdog), -+ app_container_sid, -+ filter_count: response.filter_count, -+ })) -+} -+ -+fn read_frame(stream: &mut File) -> Result, WxcError> { -+ let mut length = [0u8; 4]; -+ stream -+ .read_exact(&mut length) -+ .map_err(|e| WxcError::Firewall(format!("read AXIS WFP response length: {e}")))?; -+ let length = u32::from_le_bytes(length) as usize; -+ if length == 0 || length > MAX_MESSAGE_BYTES { -+ return Err(WxcError::Firewall(format!( -+ "invalid AXIS WFP response length {length}" -+ ))); -+ } -+ let mut payload = vec![0; length]; -+ stream -+ .read_exact(&mut payload) -+ .map_err(|e| WxcError::Firewall(format!("read AXIS WFP response payload: {e}")))?; -+ Ok(payload) -+} -+ -+fn write_frame(stream: &mut File, payload: &[u8]) -> Result<(), WxcError> { -+ if payload.is_empty() || payload.len() > MAX_MESSAGE_BYTES { -+ return Err(WxcError::Firewall(format!( -+ "invalid AXIS WFP request length {}", -+ payload.len() -+ ))); -+ } -+ stream -+ .write_all(&(payload.len() as u32).to_le_bytes()) -+ .and_then(|_| stream.write_all(payload)) -+ .and_then(|_| stream.flush()) -+ .map_err(|e| WxcError::Firewall(format!("write AXIS WFP request: {e}"))) -+} -+ -+#[cfg(test)] -+mod tests { -+ use super::*; -+ -+ #[test] -+ fn response_rejects_unknown_fields() { -+ let json = br#"{ -+ "version":1, -+ "leaseId":"00000000-0000-0000-0000-000000000001", -+ "accepted":false, -+ "appContainerSid":null, -+ "filterCount":0, -+ "error":"no", -+ "arbitraryFilter":true -+ }"#; -+ assert!(serde_json::from_slice::(json).is_err()); -+ } -+} -diff --git a/src/backends/appcontainer/common/src/base_container_runner.rs b/src/backends/appcontainer/common/src/base_container_runner.rs -index b37e5cc..9270bd8 100644 ---- a/src/backends/appcontainer/common/src/base_container_runner.rs -+++ b/src/backends/appcontainer/common/src/base_container_runner.rs -@@ -75,6 +75,28 @@ fn encode_env_block(env_vars: &[String]) -> Vec { - block - } - -+/// Remove caller-controlled proxy variables and inject only the AXIS endpoint -+/// represented by the same strict WFP lease request. -+fn strict_proxy_environment(request: &ExecutionRequest) -> Vec { -+ const PROXY_KEYS: &[&str] = &["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY"]; -+ let mut env = request -+ .env -+ .iter() -+ .filter(|entry| { -+ entry.split_once('=').is_none_or(|(key, _)| { -+ !PROXY_KEYS.iter().any(|name| key.eq_ignore_ascii_case(name)) -+ }) -+ }) -+ .cloned() -+ .collect::>(); -+ if let Some(proxy) = request.policy.network_proxy.address.as_ref() { -+ let url = proxy.to_url(); -+ env.push(format!("HTTP_PROXY={url}")); -+ env.push(format!("HTTPS_PROXY={url}")); -+ } -+ env -+} -+ - /// Function pointer type matching `Experimental_CreateProcessInSandbox` from processmodel.dll. - type PfnCreateProcessInSandbox = unsafe extern "system" fn( - application_name: *const u16, -@@ -651,8 +673,6 @@ impl ScriptRunner for BaseContainerRunner { - } - } - -- // STARTUPINFOW -- in pipe mode, pass parent handles via STARTF_USESTDHANDLES -- // so child output streams directly to the SDK caller. - let si = STARTUPINFOW { - cb: std::mem::size_of::() as u32, - dwFlags: if pipe_mode { -@@ -665,6 +685,7 @@ impl ScriptRunner for BaseContainerRunner { - hStdError: h_stderr, - ..unsafe { std::mem::zeroed() } - }; -+ - #[allow(unused_assignments)] - let mut pi: PROCESS_INFORMATION = unsafe { std::mem::zeroed() }; - -@@ -672,12 +693,13 @@ impl ScriptRunner for BaseContainerRunner { - // If the caller specified explicit env vars, use only those. - // Otherwise, pass NULL to let the OS provide the default environment - // for the sandbox (CreateProcessInSandbox handles this internally). -- let env_block: Option> = if request.env.is_empty() { -+ let effective_env = strict_proxy_environment(&request); -+ let env_block: Option> = if effective_env.is_empty() { - // TODO: consider calling CreateEnvironmentBlock(NULL, FALSE) here - // for a cleansed default env if the OS API doesn't do it for us. - None - } else { -- Some(encode_env_block(&request.env)) -+ Some(encode_env_block(&effective_env)) - }; - - let env_ptr = env_block -@@ -738,13 +760,17 @@ impl ScriptRunner for BaseContainerRunner { - None - }; - -- // A child that requires Job limits is created suspended so no -- // untrusted instruction can execute before assignment succeeds. -- let base_creation_flags = if resource_job.is_some() { -- CREATE_SUSPENDED.0 | CREATE_BREAKAWAY_FROM_JOB.0 -- } else { -- 0 -- }; -+ // A child that requires Job or WFP limits is created suspended so no -+ // untrusted instruction can execute before every requested boundary is -+ // installed. Explicit Job breakaway is needed only for the inner Job. -+ let strict_wfp_requested = request.policy.axis_wfp.is_some(); -+ let mut base_creation_flags = 0; -+ if resource_job.is_some() || strict_wfp_requested { -+ base_creation_flags |= CREATE_SUSPENDED.0; -+ } -+ if resource_job.is_some() { -+ base_creation_flags |= CREATE_BREAKAWAY_FROM_JOB.0; -+ } - let creation_flags = base_creation_flags - | if env_block.is_some() { - CREATE_UNICODE_ENVIRONMENT.0 -@@ -888,7 +914,36 @@ impl ScriptRunner for BaseContainerRunner { - "failed to assign suspended ProcessContainer child to resource Job Object: {err}" - )); - } -+ } -+ -+ let _axis_wfp_lease = match crate::axis_wfp_client::install_if_requested( -+ &request, -+ pi.dwProcessId, -+ ) { -+ Ok(lease) => { -+ if let Some(lease) = lease.as_ref() { -+ let _ = writeln!( -+ logger, -+ "AXIS WFP strict-proxy lease installed for {} with {} filters", -+ lease.app_container_sid, lease.filter_count -+ ); -+ } -+ lease -+ } -+ Err(err) => { -+ unsafe { -+ let _ = TerminateProcess(pi.hProcess, u32::MAX); -+ let _ = WaitForSingleObject(pi.hProcess, 5000); -+ let _ = CloseHandle(pi.hProcess); -+ let _ = CloseHandle(pi.hThread); -+ } -+ return ScriptResponse::error(&format!( -+ "failed to install suspended ProcessContainer WFP lease: {err}" -+ )); -+ } -+ }; - -+ if resource_job.is_some() || strict_wfp_requested { - let resume_result = unsafe { ResumeThread(pi.hThread) }; - if resume_result == u32::MAX { - let err = unsafe { GetLastError() }; -@@ -899,7 +954,7 @@ impl ScriptRunner for BaseContainerRunner { - let _ = CloseHandle(pi.hThread); - } - return ScriptResponse::error(&format!( -- "failed to resume resource-limited ProcessContainer child: {err:?}" -+ "failed to resume policy-constrained ProcessContainer child: {err:?}" - )); - } - } -diff --git a/src/backends/appcontainer/common/src/lib.rs b/src/backends/appcontainer/common/src/lib.rs -index 361eb67..88ca25a 100644 ---- a/src/backends/appcontainer/common/src/lib.rs -+++ b/src/backends/appcontainer/common/src/lib.rs -@@ -14,6 +14,8 @@ - #[cfg(target_os = "windows")] - pub mod appcontainer_runner; - #[cfg(target_os = "windows")] -+pub mod axis_wfp_client; -+#[cfg(target_os = "windows")] - pub mod base_container_runner; - #[cfg(target_os = "windows")] - pub mod dispatcher; -diff --git a/src/core/wxc_common/src/config_parser.rs b/src/core/wxc_common/src/config_parser.rs -index a17a49f..4053a34 100644 ---- a/src/core/wxc_common/src/config_parser.rs -+++ b/src/core/wxc_common/src/config_parser.rs -@@ -10,7 +10,7 @@ use crate::encoding::base64_decode; - use crate::error::WxcError; - use crate::logger::Logger; - use crate::models::{ -- ClipboardPolicy, ContainerPolicy, ContainmentBackend, ExecutionRequest, ExperimentalConfig, -+ AxisWfpConfig, ClipboardPolicy, ContainerPolicy, ContainmentBackend, ExecutionRequest, ExperimentalConfig, - IsolationSessionConfig, IsolationSessionUser, LifecycleConfig, LxcConfig, - NetworkEnforcementMode, NetworkPolicy, PortMapping, ProxyAddress, ProxyConfig, SeatbeltConfig, - TestFeatureConfig, UiPolicy, WindowsSandboxConfig, WslcConfig, -@@ -46,6 +46,8 @@ struct RawProcessContainer { - capabilities: Option>, - ui: Option, - resources: Option, -+ #[serde(rename = "axisWfp")] -+ axis_wfp: Option, - } - - #[derive(Deserialize, Default)] -@@ -969,6 +971,7 @@ fn convert_raw_config_inner( - policy.resources.max_memory_mb = resources.max_memory_mb.unwrap_or(0); - policy.resources.cpu_rate_percent = resources.cpu_rate_percent.unwrap_or(0); - } -+ policy.axis_wfp = ac.axis_wfp; - } - - // Filesystem section -diff --git a/src/core/wxc_common/src/models.rs b/src/core/wxc_common/src/models.rs -index 36eac37..ee2bc44 100644 ---- a/src/core/wxc_common/src/models.rs -+++ b/src/core/wxc_common/src/models.rs -@@ -449,6 +449,16 @@ pub struct ContainerPolicy { - pub base_process_ui: BaseProcessUiConfig, - /// Resource limits for the ProcessContainer child and all descendants. - pub resources: ProcessResourceLimits, -+ /// AXIS-owned strict-proxy WFP lease installed while the child is suspended. -+ pub axis_wfp: Option, -+} -+ -+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -+pub struct AxisWfpConfig { -+ #[serde(rename = "pipeName")] -+ pub pipe_name: String, -+ #[serde(rename = "leaseId")] -+ pub lease_id: String, - } - - #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]