diff --git a/docs/backends/wslc/wsl-container-getting-started.md b/docs/backends/wslc/wsl-container-getting-started.md index e559ea833..1275e49ba 100644 --- a/docs/backends/wslc/wsl-container-getting-started.md +++ b/docs/backends/wslc/wsl-container-getting-started.md @@ -523,8 +523,8 @@ no separate `--setup-wslc` step is required. | Type | Exact policy | WSLC behavior | |---|---|---| -| Bridged | Egress, ingress, and host-loopback defaults all `allow`, without egress rules | The container gets an address on WSLC's NAT network in the session VM. It can reach the internet, the local network, and [port mappings](#port-mappings) forward Windows ports into it. Windows host loopback isn't accessible. Nothing is filtered. | -| Isolated | All three defaults omitted or `deny`, without egress allow rules or port mappings | No networking. The container only has its own loopback interface. It can't reach anything outside itself, and nothing can reach it. | +| Bridged | Egress and ingress defaults `allow`, without egress rules. Container lifecycle operations also require the host-loopback default `allow`. | The container gets an address on WSLC's NAT network in the session VM. It can reach the internet, the local network, and [port mappings](#port-mappings) forward Windows ports into it. In create-and-run execution with `hostLoopback: "allow"`, it reaches Windows `127.0.0.1` at `host.wslc.internal`; otherwise it can't. Nothing else is filtered. | +| Isolated | All three defaults omitted or `deny`, without egress allow rules, port mappings, or `runtimeConfig.networkProxy` | No networking. The container only has its own loopback interface. It can't reach anything outside itself, and nothing can reach it. | | Built-in proxy | Any other combination, create-and-run execution | Egress filtered by the [built-in proxy](#built-in-proxy) | | Built-in proxy | Any other combination, container lifecycle operations | Rejected | @@ -554,7 +554,8 @@ as follows: - It joins only the internal network. - `NET_RAW` is dropped, so the workload can't send raw frames to the proxy container. - `HTTP_PROXY`/`HTTPS_PROXY` (and the lower-case forms) point at - `http://10.231.1.254:3128`, `NO_PROXY` is empty + `http://10.231.1.254:3128`, or at the [custom proxy](#custom-proxy); + `NO_PROXY` is empty, or `host.wslc.internal` with [host loopback](#host-loopback) - `/etc/resolv.conf` is a read-only mount of a host temporary file naming `10.231.1.254`. - Node is told to use the proxy: `NODE_USE_ENV_PROXY` is `1` (can be overwritten with `env`) @@ -583,8 +584,7 @@ as follows: - Rejected with the proxy: `allow` entries for any protocol except `tcp` (including entries without `ports`, which cover every protocol; use `"ports": [{ "protocol": "tcp" }]` for every TCP port), IPv6 - CIDRs, targets inside `10.231.0.0/16`, `hostLoopback: "allow"`, and - `runtimeConfig.networkProxy`. `deny` entries + CIDRs, and targets inside `10.231.0.0/16`. `deny` entries for `udp` or `icmp` have no effect, because only TCP leaves through the proxy, and log a warning. @@ -600,6 +600,56 @@ as follows: - Denied requests and refused lookups appear in the run log as `[WSLC][gateway]` lines. +#### Host loopback + +With `network.ingress.hostLoopback: "allow"`, the workload reaches TCP +services on Windows `127.0.0.1` at `host.wslc.internal`, on any port. + +- `host.wslc.internal` resolves to `10.231.1.3`, which the proxy container + relays to Windows. Requests through the proxy reach it too. Egress rules + don't apply to it. + +- Only Windows `127.0.0.1` is reachable, not other `127.0.0.0/8` addresses or `::1`. + +- The proxy container is granted `NET_ADMIN` to add the relay address. If the + `AllowWSLContainerPrivileged` policy forbids it, the run is rejected. + +- With `hostLoopback: "deny"`, the proxy refuses lookups and requests for + `host.wslc.internal`. + +- Not available with container lifecycle operations. For bridged networking, + see [Network configuration](#network-configuration). + +#### Custom proxy + +With `runtimeConfig.networkProxy`, `network.egress.default: "deny"`, and no +egress rules, the built-in proxy relays the workload to your proxy and +nothing else. Your proxy decides where traffic goes. + +- The workload reaches your proxy at `10.231.1.254`, on your proxy's port. + +- A hostname URL is passed to the workload unchanged. MXC resolves the + hostname on Windows when the run starts, and the built-in proxy answers + lookups for it with `10.231.1.254`. This is how to use an `https://` proxy: + its certificate still matches the name. + +- An IP address is replaced with `10.231.1.254` in the workload's proxy + variables. For example, `http://192.0.2.10:8080` becomes + `http://10.231.1.254:8080/`. Credentials are kept. + +- A proxy on Windows loopback must use `http://127.0.0.1` or + `http://localhost`. The built-in proxy relays to it through + `host.wslc.internal`; the workload still can't reach `host.wslc.internal` + unless [host loopback](#host-loopback) is allowed. + +- DNS lookups are forwarded. [Port mappings](#port-mappings) work as usual. + +- Rejected: egress rules, `network.egress.default: "allow"` without bridged + networking, `https://` with an IP address or `localhost`, IPv6 addresses, + addresses inside `10.231.0.0/16`, port 53, hostnames with no IPv4 address on + Windows or that resolve to loopback, and other loopback addresses + (`127.0.0.2`, `0.0.0.0`). + #### Cleanup - After the workload exits, times out, or is killed, MXC deletes both @@ -628,54 +678,42 @@ as follows: ### External network proxy (cooperative, unprivileged) -WSLC supports a **cooperative HTTP/HTTPS proxy**: setting `runtimeConfig.networkProxy` -routes a container's egress through a proxy you provide. WSLC cannot apply an -`iptables` drop-floor — the container has no `CAP_NET_ADMIN` and MXC has no -VM-level enforcement hook — so -enforcement is *cooperative*, applied by handing the workload proxy environment -variables that well-behaved clients honor. - -**How it works** - -1. When `runtimeConfig.networkProxy` is set, MXC translates it into the - `HTTP_PROXY`, `HTTPS_PROXY`, `http_proxy`, and `https_proxy` environment - variables inside the container (via `WslcSetProcessSettingsEnvVariables`). - Any caller-supplied values for these keys — including `NO_PROXY` / - `no_proxy` — are **stripped** from the *initial* process environment first. - Because WSLC merges the process environment onto the image's baked-in - `ENV`, MXC also sets `NO_PROXY` / `no_proxy` to the **empty string**, - so an image-baked exemption (e.g. `ENV NO_PROXY=*`) cannot silently disable - the proxy. This sanitizes the process's *starting* environment only; see the - cooperative-model caveat below. -2. Cooperative tools (curl, wget, Python `requests`, Node `https`, etc.) honor - the env vars and their traffic flows through the proxy. - -**The runtime field contains a URL string.** A WSLC container runs in its own -network namespace (a separate WSL system VM). Its own `127.0.0.1` loopback is -valid for a proxy running inside that container, as in the test fixture below; -a proxy on the host's or WSL distro's loopback is **not reachable**. An external -proxy must have an address routable from the container: +With [bridged](#network-configuration) networking, `runtimeConfig.networkProxy` +is cooperative: MXC gives the workload proxy settings, and clients that honor +them use your proxy. With any other policy, it goes through the built-in proxy +instead; see [Custom proxy](#custom-proxy). + +- MXC sets `HTTP_PROXY`, `HTTPS_PROXY`, `http_proxy` and `https_proxy` to the + URL, and `NO_PROXY`/`no_proxy` to empty so an image's `ENV NO_PROXY` can't + bypass it. Caller-supplied values for these keys are dropped. + +- Nothing is enforced. Clients that ignore the variables (raw sockets, some + static binaries) connect directly, and the workload can change its own + environment. To enforce the proxy, deny egress so the built-in proxy relays + to it. + +- The URL must be reachable from the container. `127.0.0.1` is the + container's own loopback; reach Windows loopback at `host.wslc.internal` + with [`hostLoopback: "allow"`](#network-configuration). + +- Container lifecycle operations set the proxy on `exec`, not at provision. + +This create-and-run example uses a proxy on Windows `127.0.0.1:8888`: ```json { - "version": "0.9.0-alpha", + "version": "1.0.0", "containment": "wslc", - "process": { "commandLine": "curl -fsSL https://example.com && echo OK" }, + "process": { "commandLine": "wget -qO- http://example.com && echo OK" }, "network": { "egress": { "default": "allow" }, "ingress": { "default": "allow", "hostLoopback": "allow" } }, - "runtimeConfig": { "networkProxy": "http://proxy.example:8080" }, + "runtimeConfig": { "networkProxy": "http://host.wslc.internal:8888" }, "wslc": { "image": "alpine:latest" } } ``` -The removed `network.proxy` object and its `localhost`/`builtinTestServer` -forms are rejected by schema `0.9.0-alpha`. Create-and-run proxy use requires the unrestricted -bridged posture shown above; a proxy cannot make isolated networking reach an -external listener. Execution in an existing container (`exec`) instead supplies only `runtimeConfig` and -inherits its provisioned network posture. - ### Filtering for container lifecycle operations Container lifecycle operations do not use the built-in proxy yet. A @@ -701,19 +739,6 @@ requires explicit host-to-container forwards through `wslc.portMappings` (create-and-run execution) or `wslc.provision.portMappings` (container lifecycle operations); `ingress.default: "allow"` alone does not create them. -**Caveats** - -- **Cooperative model, not enforcement.** Only clients that honor the proxy - env vars are routed through the proxy. Tools that bypass them (raw sockets, - custom HTTP clients, statically-linked binaries that ignore the env) are - **not** contained. WSLC cannot provide a hard network floor — the container - has no `CAP_NET_ADMIN` and MXC has no VM-level enforcement hook. For strict - network isolation in v0.9, use the deny/deny/deny posture instead. -- **Consumer-provided proxy.** MXC does not start a proxy for WSLC; you supply - a reachable URL via `runtimeConfig.networkProxy`. Host filtering is the - proxy's responsibility; directional rules cannot be combined to create a - firewall WSLC does not have. - ### Filesystem mounts Paths in `filesystem.readwritePaths` and `filesystem.readonlyPaths` are mounted diff --git a/sdk/dotnet/Microsoft.Mxc.Sdk.Tests/V1/MxcContainerWslcE2ETests.cs b/sdk/dotnet/Microsoft.Mxc.Sdk.Tests/V1/MxcContainerWslcE2ETests.cs index c1d0eeafe..25b964eff 100644 --- a/sdk/dotnet/Microsoft.Mxc.Sdk.Tests/V1/MxcContainerWslcE2ETests.cs +++ b/sdk/dotnet/Microsoft.Mxc.Sdk.Tests/V1/MxcContainerWslcE2ETests.cs @@ -602,7 +602,6 @@ public async Task Spawn_BuiltInProxyIsRemovedAfterKill() public static TheoryData UnenforceableEgressCases() => new() { { "external proxy", "runtimeConfig.networkProxy cannot be combined with egress filtering" }, - { "host loopback", "hostLoopback 'allow' cannot be combined with egress filtering" }, { "UDP allow", "network.egress.allow supports only protocol 'tcp' (got 'udp')" }, { "IPv6", "network.egress CIDR 2606:4700::/32 is IPv6" }, { "reserved subnet", "which the built-in proxy reserves for its own networks" }, @@ -619,9 +618,6 @@ public async Task BuiltInProxyRejectsEgressItCannotEnforceBeforeStartingAContain case "external proxy": network.RuntimeConfig = new NetworkRuntimeConfig { NetworkProxy = "http://127.0.0.1:8888" }; break; - case "host loopback": - network.Ingress!.HostLoopback = NetworkAction.Allow; - break; case "UDP allow": network.Egress!.Allow = [Rule("1.1.1.1/32", NetworkProtocol.Udp, 53)]; break; diff --git a/sdk/node/tests/integration/wslc-e2e.test.ts b/sdk/node/tests/integration/wslc-e2e.test.ts index 1ad97bc24..be973cf50 100644 --- a/sdk/node/tests/integration/wslc-e2e.test.ts +++ b/sdk/node/tests/integration/wslc-e2e.test.ts @@ -620,12 +620,9 @@ describe('WSLC SDK E2E — built-in proxy', { }); it('should reject egress rules the built-in proxy cannot enforce before starting a container', { timeout: 120_000 }, async () => { - const rules = ALLOW_CLOUDFLARE_443.egress!; const cases: Array<[string, NetworkPolicy, Record, string]> = [ ['external proxy', { ...ALLOW_CLOUDFLARE_443, runtimeConfig: { networkProxy: 'http://127.0.0.1:8888' } }, {}, 'runtimeConfig.networkProxy cannot be combined with egress filtering'], - ['host loopback', { egress: rules, ingress: { default: 'deny', hostLoopback: 'allow' } }, {}, - "hostLoopback 'allow' cannot be combined with egress filtering"], ['UDP allow', { egress: { default: 'deny', allow: [{ to: [{ cidr: '1.1.1.1/32' }], ports: [{ protocol: 'udp', port: 53 }] }] }, ingress: DENY_INGRESS }, {}, "network.egress.allow supports only protocol 'tcp' (got 'udp')"], ['IPv6', { egress: { default: 'deny', allow: [{ to: [{ cidr: '2606:4700::/32' }], ports: [{ protocol: 'tcp', port: 443 }] }] }, ingress: DENY_INGRESS }, {}, diff --git a/src/mxc-sdk/src/backends/wslc/common/egress_gateway.rs b/src/mxc-sdk/src/backends/wslc/common/egress_gateway.rs index 57715fa00..b856043d6 100644 --- a/src/mxc-sdk/src/backends/wslc/common/egress_gateway.rs +++ b/src/mxc-sdk/src/backends/wslc/common/egress_gateway.rs @@ -17,7 +17,7 @@ use std::ffi::{CStr, CString, OsStr}; use std::fmt::Write as _; -use std::net::Ipv4Addr; +use std::net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs}; use std::path::{Path, PathBuf}; use std::ptr; use std::sync::atomic::{AtomicBool, Ordering}; @@ -35,7 +35,7 @@ use crate::mxc_common::string_util::CoTaskMemPWSTR; use crate::wslc_common::container_steps::{self, cstr_bytes, sdk_error, ProcessSettings}; use crate::wslc_common::error::WslcError; use crate::wslc_common::image; -use crate::wslc_common::policy::ProxiedEgress; +use crate::wslc_common::policy::{self, CustomProxy, CustomProxyHost, ProxiedEgress}; use crate::wslc_common::policy_mapping::VolumeMount; use crate::wslc_common::process_env::EnvScope; use crate::wslc_common::wslc_bindings::*; @@ -115,6 +115,8 @@ const GATEWAY_EGRESS_ADDRESS: Ipv4Addr = Ipv4Addr::new(10, 231, 0, 2); const GATEWAY_WORKLOAD_ADDRESS: Ipv4Addr = Ipv4Addr::new(10, 231, 1, 254); /// Pinned so the gateway knows where to relay port mappings. const WORKLOAD_ADDRESS: Ipv4Addr = Ipv4Addr::new(10, 231, 1, 2); +/// The address the workload reaches Windows loopback through. +const HOST_LOOPBACK_RELAY_ADDRESS: Ipv4Addr = Ipv4Addr::new(10, 231, 1, 3); const PROXY_PORT: u16 = 3128; const NODE_USE_ENV_PROXY: &str = "NODE_USE_ENV_PROXY"; @@ -140,6 +142,8 @@ pub(crate) struct Gateway { resolv_conf: tempfile::TempPath, records: StoreRecords, names: ProxyNames, + proxy_url: String, + host_loopback: bool, torn_down: AtomicBool, } @@ -159,21 +163,39 @@ impl Gateway { port_mappings: &[PortMapping], logger: &mut Logger, ) -> Result { + let custom_proxy = egress + .custom_proxy + .as_ref() + .map(|proxy| relayed_custom_proxy(proxy, |host, port| (host, port).to_socket_addrs())) + .transpose() + .map_err(|e| WslcError::Rejected(e).into_response())?; + let proxy_url = workload_proxy_url(egress.custom_proxy.as_ref()).map_err(host_error)?; + let policy = render_policy(egress, custom_proxy, port_mappings); + let records = StoreRecords::open(store_path).map_err(host_error)?; let names = ProxyNames::for_session(session_name); refuse_unrecorded(sdk, session, &records, &names)?; records.write(&names, &names.all()).map_err(host_error)?; - match Self::start_inner(sdk, session, &names, egress, port_mappings, logger) { - Ok((container, process, resolv_conf)) => Ok(Self { - sdk, - session, - _container: container, - process, - resolv_conf, - records, - names, - torn_down: AtomicBool::new(false), - }), + match Self::start_inner(sdk, session, &names, &policy, port_mappings, logger) { + Ok((container, process, resolv_conf)) => { + let _ = writeln!( + logger, + "[WSLC] Built-in proxy ready at {}", + proxy_env::redact_proxy_url(&proxy_url) + ); + Ok(Self { + sdk, + session, + _container: container, + process, + resolv_conf, + records, + names, + proxy_url, + host_loopback: egress.host_loopback, + torn_down: AtomicBool::new(false), + }) + } Err(mut e) => { if let Err(cleanup) = remove_recorded(sdk, session, &records, &names) { e.error_message = @@ -188,7 +210,7 @@ impl Gateway { sdk: &'static WslcSdk, session: WslcSession, names: &ProxyNames, - egress: &ProxiedEgress, + policy: &gateway::Policy, port_mappings: &[PortMapping], logger: &mut Logger, ) -> Result<(WslcContainerGuard, ProcessSettings, tempfile::TempPath), ScriptResponse> { @@ -220,6 +242,22 @@ impl Gateway { if hr != S_OK { return Err(sdk_error("WslcSetContainerSettingsNetworks failed", hr, "")); } + // Only the host loopback relay changes the gateway's own network. + let net_admin = [c"NET_ADMIN".as_ptr()]; + if policy.host_loopback.is_some() { + let hr = sdk.WslcSetContainerSettingsCapabilityAdditions( + &mut settings, + net_admin.as_ptr(), + net_admin.len() as u32, + ); + if hr != S_OK { + return Err(sdk_error( + "WslcSetContainerSettingsCapabilityAdditions failed", + hr, + "", + )); + } + } // Published ports reach only a container with a non-internal network, // so the gateway takes the workload's mappings and relays them. let mappings = container_steps::sdk_port_mappings(port_mappings); @@ -238,7 +276,7 @@ impl Gateway { } } - let policy = serde_json::to_string(&render_policy(egress, port_mappings)).map_err(|e| { + let policy = serde_json::to_string(policy).map_err(|e| { WslcError::Host(format!("could not render the built-in proxy policy: {e}")) .into_response() })?; @@ -259,6 +297,14 @@ impl Gateway { let mut container: WslcContainer = ptr::null_mut(); let mut err_msg = CoTaskMemPWSTR::null(); let hr = sdk.WslcCreateContainer(session, &settings, &mut container, err_msg.as_mut_ptr()); + if hr == WSLC_E_CAPABILITY_ADDITIONS_DISABLED { + return Err(WslcError::Unavailable( + "WSLc: network.ingress.hostLoopback 'allow' needs the built-in proxy to add \ + NET_ADMIN, which the AllowWSLContainerPrivileged policy forbids on this host" + .to_string(), + ) + .into_response()); + } if hr != S_OK { return Err(sdk_error( "Could not create the built-in proxy's container", @@ -296,7 +342,6 @@ impl Gateway { )) .into_response() })?; - let _ = writeln!(logger, "[WSLC] Built-in proxy ready at {}", proxy_url()); Ok((container, process, resolv_conf)) } @@ -346,22 +391,31 @@ impl Gateway { Err(e) => Err(format!("could not remove the built-in proxy: {e}")), } } -} -impl Drop for Gateway { - fn drop(&mut self) { - let _ = self.teardown(&mut Logger::new(Mode::Buffer)); + /// The workload's environment: the caller's, pointed at the proxy. + pub(crate) fn workload_env(&self, caller_env: &[String], scope: EnvScope) -> Vec { + workload_env(caller_env, scope, &self.proxy_url, self.host_loopback) } } -/// The proxy URL the workload is pointed at. -pub(crate) fn proxy_url() -> String { - format!("http://{GATEWAY_WORKLOAD_ADDRESS}:{PROXY_PORT}") -} - -/// The workload's environment: the caller's, pointed at the proxy. -pub(crate) fn workload_env(caller_env: &[String], scope: EnvScope) -> Vec { - let mut env = proxy_env::apply_cooperative_proxy_env(caller_env, &proxy_url()); +fn workload_env( + caller_env: &[String], + scope: EnvScope, + proxy_url: &str, + host_loopback: bool, +) -> Vec { + let mut env = proxy_env::apply_cooperative_proxy_env(caller_env, proxy_url); + // Windows loopback is reached directly; a custom proxy couldn't reach it. + if host_loopback { + for entry in env.iter_mut() { + if let Some(key) = proxy_env::PROXY_NEUTRALIZE_KEYS + .iter() + .find(|key| entry.strip_suffix('=') == Some(**key)) + { + *entry = format!("{key}={}", gateway::HOST_LOOPBACK_NAME); + } + } + } // Node.js ignores HTTP(S)_PROXY unless this is set. It joins the default // environment, so a replacing request doesn't get it. if scope == EnvScope::Merge @@ -374,7 +428,73 @@ pub(crate) fn workload_env(caller_env: &[String], scope: EnvScope) -> Vec gateway::Policy { +impl Drop for Gateway { + fn drop(&mut self) { + let _ = self.teardown(&mut Logger::new(Mode::Buffer)); + } +} + +/// The proxy URL the workload is pointed at. A custom proxy's IP or loopback +/// host is unreachable from the workload, so it becomes the gateway's address. +fn workload_proxy_url(custom: Option<&CustomProxy>) -> Result { + let Some(custom) = custom else { + return Ok(format!("http://{GATEWAY_WORKLOAD_ADDRESS}:{PROXY_PORT}")); + }; + if let CustomProxyHost::Name(_) = custom.host { + return Ok(custom.url.clone()); + } + let mut url = url::Url::parse(&custom.url) + .map_err(|_| "runtimeConfig.networkProxy is not a valid URL".to_string())?; + url.set_host(Some(&GATEWAY_WORKLOAD_ADDRESS.to_string())) + .map_err(|e| { + format!("could not point runtimeConfig.networkProxy at the built-in proxy: {e}") + })?; + Ok(url.into()) +} + +/// The custom proxy as the gateway relays it. A hostname is resolved here, +/// on Windows, so the gateway never resolves it. +fn relayed_custom_proxy( + custom: &CustomProxy, + lookup: impl FnOnce(&str, u16) -> std::io::Result>, +) -> Result { + let (name, address) = match &custom.host { + CustomProxyHost::Name(name) => { + let ip = lookup(name, custom.port) + .into_iter() + .flatten() + .find_map(|a| match a.ip() { + IpAddr::V4(ip) => Some(ip), + IpAddr::V6(_) => None, + }) + .ok_or_else(|| { + format!("WSLc: runtimeConfig.networkProxy host '{name}' has no IPv4 address on Windows") + })?; + let address = policy::relayed_proxy_address(ip).map_err(|e| e.message)?; + if address.is_none() { + return Err(format!( + "WSLc: runtimeConfig.networkProxy host '{name}' resolves to Windows loopback; \ + use http://127.0.0.1:{} instead", + custom.port + )); + } + (Some(name.clone()), address) + } + CustomProxyHost::Address(address) => (None, *address), + }; + Ok(gateway::CustomProxy { + name, + address, + port: custom.port, + }) +} + +fn render_policy( + egress: &ProxiedEgress, + custom_proxy: Option, + port_mappings: &[PortMapping], +) -> gateway::Policy { + let host_loopback = egress.host_loopback; let egress = egress.egress.clone(); let mut relayed: Vec = Vec::new(); for mapping in port_mappings { @@ -392,11 +512,17 @@ fn render_policy(egress: &ProxiedEgress, port_mappings: &[PortMapping]) -> gatew gateway::Policy { workload_address: GATEWAY_WORKLOAD_ADDRESS, egress_address: GATEWAY_EGRESS_ADDRESS, - proxy_port: PROXY_PORT, - forward_dns: egress.default == gateway::Action::Allow || !egress.allow.is_empty(), + // The workload keeps the custom proxy's port. + proxy_port: custom_proxy.as_ref().map_or(PROXY_PORT, |proxy| proxy.port), + forward_dns: egress.default == gateway::Action::Allow + || !egress.allow.is_empty() + || custom_proxy.is_some(), egress, - host_loopback: None, - custom_proxy: None, + host_loopback: host_loopback.then_some(gateway::HostLoopback { + relay_address: HOST_LOOPBACK_RELAY_ADDRESS, + prefix_length: SUBNET_PREFIX_LENGTH, + }), + custom_proxy, port_mappings: relayed, } } @@ -952,6 +1078,8 @@ mod tests { allow, deny: Vec::new(), }, + host_loopback: false, + custom_proxy: None, warnings: Vec::new(), }; let rule = gateway::Rule { @@ -962,12 +1090,107 @@ mod tests { ports: None, }; - let policy = render_policy(&egress(gateway::Action::Deny, vec![rule]), &[]); + let policy = render_policy(&egress(gateway::Action::Deny, vec![rule]), None, &[]); assert!(policy.forward_dns); assert_eq!(policy.workload_address, GATEWAY_WORKLOAD_ADDRESS); - assert_eq!(proxy_url(), "http://10.231.1.254:3128"); - assert!(render_policy(&egress(gateway::Action::Allow, Vec::new()), &[]).forward_dns); - assert!(!render_policy(&egress(gateway::Action::Deny, Vec::new()), &[]).forward_dns); + assert_eq!(policy.proxy_port, PROXY_PORT); + assert_eq!( + workload_proxy_url(None).unwrap(), + "http://10.231.1.254:3128" + ); + assert!(render_policy(&egress(gateway::Action::Allow, Vec::new()), None, &[]).forward_dns); + assert!(!render_policy(&egress(gateway::Action::Deny, Vec::new()), None, &[]).forward_dns); + } + + fn custom(url: &str, host: CustomProxyHost, port: u16) -> CustomProxy { + CustomProxy { + url: url.to_string(), + host, + port, + } + } + + fn resolves_to( + addrs: &[&str], + ) -> impl FnOnce(&str, u16) -> std::io::Result> { + let addrs: Vec = addrs.iter().map(|a| a.parse().unwrap()).collect(); + move |_, _| Ok(addrs.into_iter()) + } + + #[test] + fn a_custom_proxy_is_relayed_on_its_own_port_with_dns_forwarded() { + let egress = ProxiedEgress { + egress: gateway::Egress { + default: gateway::Action::Deny, + allow: Vec::new(), + deny: Vec::new(), + }, + host_loopback: false, + custom_proxy: None, + warnings: Vec::new(), + }; + let relayed = gateway::CustomProxy { + name: None, + address: Some(Ipv4Addr::new(1, 1, 1, 1)), + port: 8080, + }; + let policy = render_policy(&egress, Some(relayed.clone()), &[]); + assert_eq!(policy.proxy_port, 8080); + assert!(policy.forward_dns); + assert_eq!(policy.custom_proxy, Some(relayed)); + } + + #[test] + fn a_custom_proxy_hostname_is_resolved_to_its_first_ipv4_address() { + let proxy = custom( + "http://proxy.example:8080", + CustomProxyHost::Name("proxy.example".to_string()), + 8080, + ); + let relayed = + relayed_custom_proxy(&proxy, resolves_to(&["[2001:db8::1]:8080", "1.2.3.4:8080"])) + .unwrap(); + assert_eq!(relayed.name.as_deref(), Some("proxy.example")); + assert_eq!(relayed.address, Some(Ipv4Addr::new(1, 2, 3, 4))); + assert_eq!(relayed.port, 8080); + + for addrs in [ + ["[2001:db8::1]:8080"], + ["127.0.0.1:8080"], + ["10.231.1.9:8080"], + ] { + assert!(relayed_custom_proxy(&proxy, resolves_to(&addrs)).is_err()); + } + let failed = relayed_custom_proxy(&proxy, |_, _| Err(std::io::ErrorKind::NotFound.into())); + assert!(failed.unwrap_err().contains("has no IPv4 address")); + } + + #[test] + fn the_workload_reaches_a_custom_proxy_ip_through_the_gateway() { + let ip = |url: &str, port| { + custom( + url, + CustomProxyHost::Address(Some(Ipv4Addr::new(1, 1, 1, 1))), + port, + ) + }; + assert_eq!( + workload_proxy_url(Some(&ip("http://user:pw@1.1.1.1:8080", 8080))).unwrap(), + "http://user:pw@10.231.1.254:8080/" + ); + assert_eq!( + workload_proxy_url(Some(&ip("socks5://1.1.1.1:1080", 1080))).unwrap(), + "socks5://10.231.1.254:1080" + ); + let named = custom( + "https://proxy.example:443", + CustomProxyHost::Name("proxy.example".to_string()), + 443, + ); + assert_eq!( + workload_proxy_url(Some(&named)).unwrap(), + "https://proxy.example:443" + ); } #[test] @@ -983,10 +1206,13 @@ mod tests { allow: Vec::new(), deny: Vec::new(), }, + host_loopback: false, + custom_proxy: None, warnings: Vec::new(), }; let policy = render_policy( &egress, + None, &[ mapping(18080, 8080), mapping(18081, 8080), @@ -1006,15 +1232,26 @@ mod tests { #[test] fn workload_env_adds_node_proxy_to_the_default_environment() { - let env = workload_env(&["HTTPS_PROXY=http://other:1".to_string()], EnvScope::Merge); + let url = "http://10.231.1.254:3128"; + let env = workload_env( + &["HTTPS_PROXY=http://other:1".to_string()], + EnvScope::Merge, + url, + false, + ); assert!(env.contains(&"HTTPS_PROXY=http://10.231.1.254:3128".to_string())); assert!(env.contains(&"NODE_USE_ENV_PROXY=1".to_string())); - let env = workload_env(&[], EnvScope::Replace); + let env = workload_env(&[], EnvScope::Replace, url, false); assert!(env.contains(&"HTTPS_PROXY=http://10.231.1.254:3128".to_string())); assert!(!env.iter().any(|e| e.starts_with("NODE_USE_ENV_PROXY="))); - let env = workload_env(&["NODE_USE_ENV_PROXY=0".to_string()], EnvScope::Merge); + let env = workload_env( + &["NODE_USE_ENV_PROXY=0".to_string()], + EnvScope::Merge, + url, + false, + ); assert_eq!( env.iter() .filter(|e| e.starts_with("NODE_USE_ENV_PROXY=")) @@ -1023,6 +1260,46 @@ mod tests { ); } + #[test] + fn host_loopback_is_relayed_at_its_own_address_and_bypasses_the_proxy() { + let egress = |host_loopback| ProxiedEgress { + egress: gateway::Egress { + default: gateway::Action::Deny, + allow: Vec::new(), + deny: Vec::new(), + }, + host_loopback, + custom_proxy: None, + warnings: Vec::new(), + }; + assert_eq!( + render_policy(&egress(true), None, &[]).host_loopback, + Some(gateway::HostLoopback { + relay_address: Ipv4Addr::new(10, 231, 1, 3), + prefix_length: 24, + }) + ); + assert_eq!(render_policy(&egress(false), None, &[]).host_loopback, None); + + let caller = ["NO_PROXY=*".to_string()]; + let no_proxy = |host_loopback| { + workload_env( + &caller, + EnvScope::Merge, + "http://10.231.1.254:3128", + host_loopback, + ) + .into_iter() + .filter(|e| e.to_ascii_uppercase().starts_with("NO_PROXY=")) + .collect::>() + }; + assert_eq!( + no_proxy(true), + ["NO_PROXY=host.wslc.internal", "no_proxy=host.wslc.internal"] + ); + assert_eq!(no_proxy(false), ["NO_PROXY=", "no_proxy="]); + } + #[test] fn cleanup_tries_every_owned_resource_after_a_failure() { let names = ProxyNames::for_session("session"); diff --git a/src/mxc-sdk/src/backends/wslc/common/policy.rs b/src/mxc-sdk/src/backends/wslc/common/policy.rs index 61cfe6e92..640668ac0 100644 --- a/src/mxc-sdk/src/backends/wslc/common/policy.rs +++ b/src/mxc-sdk/src/backends/wslc/common/policy.rs @@ -22,15 +22,16 @@ //! mounted `rw`/`ro` parent is rejected, because WSLc has no overlay primitive //! to mask a subtree of a mounted volume. //! -//! Create-and-run also accepts egress rules, mixed postures and port mappings -//! without bridged networking, which [`create_and_run_network_mode`] routes -//! through the built-in proxy. +//! Create-and-run also accepts egress rules, mixed postures (including +//! `hostLoopback: allow`), port mappings without bridged networking and a +//! `networkProxy` with egress denied, which [`create_and_run_network_mode`] +//! routes through the built-in proxy. //! //! Checks run filesystem → ui → network, so a request that trips several gets a //! stable message rather than one that depends on field order (asserted by //! tests). [`reject_ui_policy`] applies to both one-shot and state-aware validation. -use std::net::IpAddr; +use std::net::{IpAddr, Ipv4Addr}; use crate::mxc_common::models::{ ExecutionRequest, NetworkAction, NetworkCidr, NetworkEgressPolicy, NetworkPeer, NetworkPort, @@ -65,6 +66,19 @@ const ERR_PROXY_URL_FORM: &str = const ERR_PROXY_WITHOUT_ROUTE: &str = "WSLc runtimeConfig.networkProxy requires bridged networking; a proxy cannot create a route \ in an isolated container"; +const ERR_PROXY_WITH_RULES: &str = + "WSLc: runtimeConfig.networkProxy cannot be combined with egress filtering rules \ + (network.egress allow/deny); the proxy decides where traffic goes. Remove the rules or the \ + proxy"; +const ERR_PROXY_WITH_EGRESS_ALLOW: &str = + "WSLc: runtimeConfig.networkProxy with network.egress.default 'allow' requires bridged \ + networking. Set network.ingress.default to 'allow', or set network.egress.default to 'deny' \ + so traffic leaves only through the proxy"; +const ERR_PROXY_NOT_URL: &str = + "WSLc: runtimeConfig.networkProxy requires a URL-backed proxy address"; +const ERR_PROXY_LOOPBACK: &str = + "WSLc: a runtimeConfig.networkProxy on Windows loopback must use 127.0.0.1 or localhost; \ + the built-in proxy relays only to Windows 127.0.0.1"; const ERR_UI_POLICY: &str = "WSLc: the ui section is not supported. The backend has no mechanism to enforce UI \ restrictions on a container, so no ui posture is truthful here. Omitting the ui section is \ @@ -98,20 +112,64 @@ pub(crate) fn create_and_run_network_policy_support() -> NetworkPolicySupport { pub(crate) enum NetworkMode { /// No network at all. None, - /// The session's NAT network, unfiltered. - Bridged, + /// The session's NAT network, unfiltered. It reaches Windows loopback only + /// with `host_loopback`, which enables it for the session. + Bridged { host_loopback: bool }, /// An internal network whose only way out is the built-in proxy. Proxied(ProxiedEgress), } +impl NetworkMode { + /// Whether the session must reach Windows loopback. The setting is + /// session-wide, which is safe only because each create-and-run gets its + /// own session. + pub(crate) fn session_host_loopback(&self) -> bool { + match self { + NetworkMode::Bridged { host_loopback } => *host_loopback, + NetworkMode::Proxied(proxied) => { + proxied.host_loopback + || matches!( + proxied.custom_proxy, + Some(CustomProxy { + host: CustomProxyHost::Address(None), + .. + }) + ) + } + NetworkMode::None => false, + } + } +} + /// Egress filtering for [`NetworkMode::Proxied`]. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct ProxiedEgress { pub(crate) egress: gateway::Egress, + /// Relay `host.wslc.internal` to Windows loopback. + pub(crate) host_loopback: bool, + /// Where the built-in proxy relays instead of filtering itself. + pub(crate) custom_proxy: Option, /// Deny entries the proxy has nothing to apply to. pub(crate) warnings: Vec, } +/// A `runtimeConfig.networkProxy` behind the built-in proxy. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct CustomProxy { + /// The configured URL. + pub(crate) url: String, + pub(crate) host: CustomProxyHost, + pub(crate) port: u16, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum CustomProxyHost { + /// Resolved on Windows when the built-in proxy starts. + Name(String), + /// `None` is Windows 127.0.0.1. + Address(Option), +} + /// Choose how a create-and-run container is networked, rejecting what the /// chosen mode cannot enforce. Port mappings are their own grant, so an /// otherwise isolated container with them is proxied rather than unnetworked. @@ -130,37 +188,37 @@ pub(crate) fn create_and_run_network_mode( && ingress.default == NetworkAction::Deny && ingress.host_loopback == NetworkAction::Deny { - if proxy { - return Err(MxcError::policy_validation(ERR_PROXY_WITHOUT_ROUTE)); - } - if !has_port_mappings { + if !proxy && !has_port_mappings { return Ok(NetworkMode::None); } } else if egress.default == NetworkAction::Allow && egress.allow.is_empty() && egress.deny.is_empty() && ingress.default == NetworkAction::Allow - && ingress.host_loopback == NetworkAction::Allow { - return Ok(NetworkMode::Bridged); + return Ok(NetworkMode::Bridged { + host_loopback: ingress.host_loopback == NetworkAction::Allow, + }); } - if ingress.host_loopback == NetworkAction::Allow { - return Err(MxcError::policy_validation( - "WSLc: network.ingress.hostLoopback 'allow' cannot be combined with egress filtering \ - by the built-in proxy. Set it to 'deny', or use bridged networking", - )); - } - if proxy { - return Err(MxcError::policy_validation( - "WSLc: runtimeConfig.networkProxy cannot be combined with egress filtering by the \ - built-in proxy. Remove the proxy, or use bridged networking", - )); - } + let host_loopback = ingress.host_loopback == NetworkAction::Allow; + let custom_proxy = if proxy { + if !egress.allow.is_empty() || !egress.deny.is_empty() { + return Err(MxcError::policy_validation(ERR_PROXY_WITH_RULES)); + } + if egress.default == NetworkAction::Allow { + return Err(MxcError::policy_validation(ERR_PROXY_WITH_EGRESS_ALLOW)); + } + Some(custom_proxy(request)?) + } else { + None + }; let mut proxied = proxied_egress(&egress)?; if ingress.default == NetworkAction::Allow { let warning = if egress.default == NetworkAction::Deny && egress.allow.is_empty() + && custom_proxy.is_none() + && !host_loopback && !has_port_mappings { "the workload has no network access: network.ingress.default 'allow' has no effect \ @@ -171,9 +229,76 @@ pub(crate) fn create_and_run_network_mode( }; proxied.warnings.push(warning.to_string()); } + proxied.host_loopback = host_loopback; + proxied.custom_proxy = custom_proxy; Ok(NetworkMode::Proxied(proxied)) } +fn custom_proxy(request: &ExecutionRequest) -> Result { + let invalid = |reason: &str| { + MxcError::policy_validation(format!("WSLc: runtimeConfig.networkProxy {reason}")) + }; + let url = + exec_proxy_url(request).ok_or_else(|| MxcError::policy_validation(ERR_PROXY_NOT_URL))?; + let parsed = url::Url::parse(url).map_err(|_| invalid("is not a valid URL"))?; + let port = parsed + .port_or_known_default() + .filter(|&port| port != 0) + .ok_or_else(|| invalid("must name a port"))?; + if port == 53 { + return Err(invalid( + "can't use port 53, where the built-in proxy serves DNS", + )); + } + let host = match parsed.host() { + Some(url::Host::Ipv4(ip)) => CustomProxyHost::Address(relayed_proxy_address(ip)?), + Some(url::Host::Domain(name)) => match name.parse::() { + Ok(ip) => CustomProxyHost::Address(relayed_proxy_address(ip)?), + Err(_) if name.eq_ignore_ascii_case("localhost") => { + CustomProxyHost::Address(relayed_proxy_address(Ipv4Addr::LOCALHOST)?) + } + Err(_) => CustomProxyHost::Name(name.to_string()), + }, + Some(url::Host::Ipv6(_)) => { + return Err(invalid( + "must use a hostname or an IPv4 address; the built-in proxy carries IPv4 only", + )) + } + None => return Err(invalid("must name a host")), + }; + if matches!(host, CustomProxyHost::Address(_)) && parsed.scheme() == "https" { + return Err(invalid( + "with an IP address or loopback host must use http://. The workload reaches it at \ + the built-in proxy's address, which the proxy's certificate can't name; use the \ + proxy's hostname for https://", + )); + } + Ok(CustomProxy { + url: url.to_string(), + host, + port, + }) +} + +/// The address the built-in proxy relays a custom proxy at; `None` is +/// Windows 127.0.0.1, the only loopback address WSL relays to. +pub(crate) fn relayed_proxy_address(ip: Ipv4Addr) -> Result, MxcError> { + if ip == Ipv4Addr::LOCALHOST { + return Ok(None); + } + if ip.is_loopback() || ip.is_unspecified() { + return Err(MxcError::policy_validation(ERR_PROXY_LOOPBACK)); + } + if gateway::GATEWAY_SUBNETS.contains(ip) { + return Err(MxcError::policy_validation(format!( + "WSLc: runtimeConfig.networkProxy address {ip} is inside {}, which the built-in \ + proxy reserves for its own networks", + gateway::GATEWAY_SUBNETS + ))); + } + Ok(Some(ip)) +} + /// Lower egress rules to the proxy's TCP-only rules. fn proxied_egress(egress: &NetworkEgressPolicy) -> Result { let mut allow = Vec::with_capacity(egress.allow.len()); @@ -248,6 +373,8 @@ fn proxied_egress(egress: &NetworkEgressPolicy) -> Result Result { + let mut request = one_shot(network); + request.policy.network_proxy = ProxyConfig { + address: Some(ProxyAddress::from_url(url, String::new(), 0)), + }; + create_and_run_network_mode(&request, port_mappings) + } + + #[test] + fn a_custom_proxy_is_relayed_through_the_built_in_proxy() { + for (url, host, port) in [ + ( + "http://proxy.example:8080", + CustomProxyHost::Name("proxy.example".to_string()), + 8080, + ), + ( + "https://Proxy.Example:8443", + CustomProxyHost::Name("proxy.example".to_string()), + 8443, + ), + ( + "http://192.0.2.10:3128", + CustomProxyHost::Address(Some(Ipv4Addr::new(192, 0, 2, 10))), + 3128, + ), + ( + "socks5://192.0.2.10:1080", + CustomProxyHost::Address(Some(Ipv4Addr::new(192, 0, 2, 10))), + 1080, + ), + ( + "http://127.0.0.1:8888", + CustomProxyHost::Address(None), + 8888, + ), + ( + "http://localhost:8888", + CustomProxyHost::Address(None), + 8888, + ), + ] { + for (network, mappings) in [ + ("{}", false), + ("{}", true), + (r#"{"ingress":{"default":"allow"}}"#, false), + ] { + let NetworkMode::Proxied(p) = proxy_mode(network, url, mappings).unwrap() else { + panic!("{url} with {network} was not proxied"); + }; + assert_eq!(p.egress.default, gateway::Action::Deny); + assert!(!p.warnings.iter().any(|w| w.contains("no network access"))); + assert!(!p.host_loopback); + assert_eq!( + NetworkMode::Proxied(p.clone()).session_host_loopback(), + host == CustomProxyHost::Address(None) + ); + assert_eq!( + p.custom_proxy, + Some(CustomProxy { + url: url.to_string(), + host: host.clone(), + port, + }) + ); + } + } + } + #[test] fn the_proxy_rejects_what_it_cannot_enforce() { - let rule = r#"{"egress":{"allow":[{"to":[{"cidr":"192.0.2.0/24"}]}]}}"#; - let mut with_proxy = one_shot(rule); - with_proxy.policy.network_proxy = url_proxy(); - assert_policy_validation( - create_and_run_network_mode(&with_proxy, false).unwrap_err(), - "runtimeConfig.networkProxy cannot be combined", - ); - let mut isolated_with_proxy = one_shot("{}"); - isolated_with_proxy.policy.network_proxy = url_proxy(); + for (network, url, needle) in [ + ( + r#"{"egress":{"allow":[{"to":[{"cidr":"192.0.2.0/24"}],"ports":[{"protocol":"tcp"}]}]}}"#, + "http://proxy.example:8080", + "cannot be combined with egress filtering rules", + ), + ( + r#"{"egress":{"default":"allow"}}"#, + "http://proxy.example:8080", + "requires bridged networking", + ), + ("{}", "https://192.0.2.10:443", "must use http://"), + ("{}", "https://localhost:8443", "must use http://"), + ("{}", "http://[2001:db8::1]:8080", "IPv4 only"), + ("{}", "http://proxy.example:53", "port 53"), + ("{}", "http://127.0.0.2:8888", "127.0.0.1 or localhost"), + ("{}", "http://0.0.0.0:8888", "127.0.0.1 or localhost"), + ( + "{}", + "http://10.231.1.254:3128", + "reserves for its own networks", + ), + ] { + assert_policy_validation(proxy_mode(network, url, false).unwrap_err(), needle); + } + let mut non_url = one_shot("{}"); + non_url.policy.network_proxy = non_url_proxy(); assert_policy_validation( - create_and_run_network_mode(&isolated_with_proxy, true).unwrap_err(), - "requires bridged networking", + create_and_run_network_mode(&non_url, false).unwrap_err(), + "URL-backed", ); for (network, needle) in [ - ( - r#"{"egress":{"default":"allow"},"ingress":{"hostLoopback":"allow"}}"#, - "hostLoopback 'allow' cannot be combined", - ), ( r#"{"egress":{"allow":[{"ports":[{"protocol":"udp","port":53}]}]}}"#, "only protocol 'tcp' (got 'udp')", diff --git a/src/mxc-sdk/src/backends/wslc/common/wsl_container_runner.rs b/src/mxc-sdk/src/backends/wslc/common/wsl_container_runner.rs index 33debfa59..2d01ecfc7 100644 --- a/src/mxc-sdk/src/backends/wslc/common/wsl_container_runner.rs +++ b/src/mxc-sdk/src/backends/wslc/common/wsl_container_runner.rs @@ -42,6 +42,7 @@ use crate::wslc_common::process_env; use crate::wslc_common::sdk_init; use crate::wslc_common::stream_buffer::{stream_pair, StreamReader, StreamWriter}; use crate::wslc_common::wslc_bindings::*; +use crate::wslc_gateway_policy as gateway; fn sdk_wait_error(operation: &str, hr: HRESULT, sdk_msg: &str) -> WslcStepError { WslcError::sdk(format!("{operation} failed"), hr, sdk_msg) @@ -631,6 +632,7 @@ impl WSLContainerRunner { sdk: &'static WslcSdk, request: &ExecutionRequest, session_name_str: &str, + host_loopback: bool, logger: &mut Logger, ) -> Result { // Backstop for a direct `execute` that skipped `validate_runner`. @@ -693,15 +695,45 @@ impl WSLContainerRunner { } } + // The SDK reads the name when the session is created. + let host_loopback_name = + CString::new(gateway::HOST_LOOPBACK_NAME).expect("the host loopback name has no NUL"); + if host_loopback { + let hr = + sdk.WslcSetSessionSettingsHostLoopback(&mut settings, host_loopback_name.as_ptr()); + if hr != S_OK { + return Err(sdk_error( + "WslcSetSessionSettingsHostLoopback failed", + hr, + "", + )); + } + } + // Create session while string data is still alive let mut session: WslcSession = ptr::null_mut(); let mut err_msg = CoTaskMemPWSTR::null(); let hr = sdk.WslcCreateSession(&mut settings, &mut session, err_msg.as_mut_ptr()); + if hr == WSLC_E_RUNTIME_UPDATE_NEEDED && host_loopback { + return Err(WslcError::Unavailable( + "WSLc: network.ingress.hostLoopback 'allow' and a runtimeConfig.networkProxy on \ + Windows loopback need WSL 3.0.5 or later. Run `wsl --update`" + .to_string(), + ) + .into_response()); + } if hr != S_OK { let msg = err_msg.to_string_lossy(); return Err(sdk_error("WslcCreateSession failed", hr, &msg)); } let _ = writeln!(logger, "[WSLC] Session created: {session_name_str}"); + if host_loopback { + let _ = writeln!( + logger, + "[WSLC] Session reaches Windows loopback as {}", + gateway::HOST_LOOPBACK_NAME + ); + } Ok(WslcSessionGuard::from_raw( session, @@ -997,7 +1029,13 @@ impl WSLContainerRunner { // -- Session (configure + create in one step to keep string data alive) -- let session_name = resolve_session_name(&request.container_id); - let session_guard = self.create_session(sdk, request, &session_name, logger)?; + let session_guard = self.create_session( + sdk, + request, + &session_name, + network_mode.session_host_loopback(), + logger, + )?; // -- Image resolution -- // An isolated sandbox gets no registry fetch on its behalf; the pull @@ -1048,7 +1086,7 @@ impl WSLContainerRunner { logger, )?) } - policy::NetworkMode::None | policy::NetworkMode::Bridged => None, + policy::NetworkMode::None | policy::NetworkMode::Bridged { .. } => None, }; // -- Process settings -- @@ -1098,8 +1136,8 @@ impl WSLContainerRunner { // belongs to the proxy. Inject HTTP(S)_PROXY after scrubbing caller // proxy variables. // See crate::mxc_common::proxy_env. - let effective_env: Vec = if gateway.is_some() { - egress_gateway::workload_env(request.env_entries(), process_env::EnvScope::of(request)) + let effective_env: Vec = if let Some(gateway) = &gateway { + gateway.workload_env(request.env_entries(), process_env::EnvScope::of(request)) } else if request.policy.network_proxy.is_enabled() { // A directly constructed request must retain its proxy URL so the // guest receives a routable endpoint instead of an empty setting. diff --git a/src/mxc-sdk/src/backends/wslc/common/wslc_bindings.rs b/src/mxc-sdk/src/backends/wslc/common/wslc_bindings.rs index 52c9d4481..fd9673ff3 100644 --- a/src/mxc-sdk/src/backends/wslc/common/wslc_bindings.rs +++ b/src/mxc-sdk/src/backends/wslc/common/wslc_bindings.rs @@ -50,6 +50,12 @@ pub const WSLC_E_NETWORK_NOT_FOUND: HRESULT = wslc_error(9); /// Administrative policy on this host forbids reaching the registry. pub const WSLC_E_REGISTRY_BLOCKED_BY_POLICY: HRESULT = wslc_error(13); +/// Administrative policy on this host forbids adding container capabilities. +pub const WSLC_E_CAPABILITY_ADDITIONS_DISABLED: HRESULT = wslc_error(20); + +/// The WSL runtime is older than a requested SDK feature. +pub const WSLC_E_RUNTIME_UPDATE_NEEDED: HRESULT = wslc_error(21); + // --------------------------------------------------------------------------- // Raw function-pointer types used by the RAII guards. // @@ -201,6 +207,8 @@ impl WslcSdk { WslcListSessionNetworks, WslcSetContainerSettingsNetworks, WslcSetContainerSettingsCapabilityDrops, + WslcSetContainerSettingsCapabilityAdditions, + WslcSetSessionSettingsHostLoopback, WslcSetContainerSettingsName, WslcOpenContainer, WslcGetContainerID, diff --git a/tests/configs/wslc_network_bridged.json b/tests/configs/wslc_network_bridged.json index da66096d3..63b3f3f48 100644 --- a/tests/configs/wslc_network_bridged.json +++ b/tests/configs/wslc_network_bridged.json @@ -4,7 +4,7 @@ "containerId": "wslc-network-bridged", "containment": "wslc", "process": { - "commandLine": "python3 -c \"import socket\ns = socket.socket(); s.settimeout(8)\ntry:\n s.connect(('1.1.1.1', 443)); print('NET_EGRESS_REACHED')\nexcept OSError as e:\n print('NET_EGRESS_BLOCKED', e.errno)\nprint('NET_PROBE_DONE')\"" + "commandLine": "python3 -c \"import socket\ns = socket.socket(); s.settimeout(8)\ntry:\n s.connect(('1.1.1.1', 443)); print('NET_EGRESS_REACHED')\nexcept OSError as e:\n print('NET_EGRESS_BLOCKED', e.errno)\ntry:\n c = socket.create_connection(('host.wslc.internal', 18890), timeout=8)\n c.sendall(b'GET / HTTP/1.0\\r\\n\\r\\n')\n print('NET_HOST_LOOPBACK=' + c.recv(64).split(b' ')[1].decode())\nexcept (OSError, IndexError) as e:\n print('NET_HOST_LOOPBACK=ERROR', e)\nprint('NET_PROBE_DONE')\"" }, "network": { "egress": { "default": "allow" }, diff --git a/tests/configs/wslc_network_bridged_host_loopback_denied.json b/tests/configs/wslc_network_bridged_host_loopback_denied.json new file mode 100644 index 000000000..69f27defe --- /dev/null +++ b/tests/configs/wslc_network_bridged_host_loopback_denied.json @@ -0,0 +1,16 @@ +{ + "$schema": "../../schemas/stable/mxc-config.schema.1.0.0.json", + "version": "1.0.0", + "containerId": "wslc-network-bridged-host-loopback-denied", + "containment": "wslc", + "process": { + "commandLine": "python3 -c \"import socket\ns = socket.socket(); s.settimeout(8)\ntry:\n s.connect(('1.1.1.1', 443)); print('NET_EGRESS_REACHED')\nexcept OSError as e:\n print('NET_EGRESS_BLOCKED', e.errno)\ntry:\n c = socket.create_connection(('host.wslc.internal', 18890), timeout=8)\n c.sendall(b'GET / HTTP/1.0\\r\\n\\r\\n')\n print('NET_HOST_LOOPBACK=' + c.recv(64).split(b' ')[1].decode())\nexcept (OSError, IndexError) as e:\n print('NET_HOST_LOOPBACK=ERROR', e)\nprint('NET_PROBE_DONE')\"" + }, + "network": { + "egress": { "default": "allow" }, + "ingress": { "default": "allow" } + }, + "wslc": { + "image": "python:3.12-alpine" + } +} diff --git a/tests/configs/wslc_network_egress_custom_proxy_https_name.json b/tests/configs/wslc_network_egress_custom_proxy_https_name.json new file mode 100644 index 000000000..b4f6edd32 --- /dev/null +++ b/tests/configs/wslc_network_egress_custom_proxy_https_name.json @@ -0,0 +1,12 @@ +{ + "$schema": "../../schemas/stable/mxc-config.schema.1.0.0.json", + "version": "1.0.0", + "containerId": "wslc-network-egress-custom-proxy-https-name", + "containment": "wslc", + "process": { + "commandLine": "python3 - <<'EOF'\nimport os, socket, ssl\nprint('PROXY_ENV=' + os.environ.get('HTTPS_PROXY', 'unset'))\ntry:\n print('RESOLVED=' + socket.gethostbyname('one.one.one.one'))\nexcept OSError as e:\n print('RESOLVED=ERROR', e)\ndef tls(name):\n try:\n with socket.create_connection(('one.one.one.one', 8443), timeout=10) as s:\n with ssl.create_default_context().wrap_socket(s, server_hostname=name):\n return 'VERIFIED'\n except OSError as e:\n return 'ERROR ' + str(e)\nprint('TLS_PROXY=' + tls('one.one.one.one'))\nprint('TLS_OTHER_NAME=' + tls('dns.google'))\ntry:\n socket.create_connection(('1.1.1.1', 443), timeout=5).close()\n print('DIRECT=REACHED')\nexcept OSError:\n print('DIRECT=BLOCKED')\nEOF" + }, + "network": { "ingress": { "default": "allow" } }, + "runtimeConfig": { "networkProxy": "https://one.one.one.one:8443" }, + "wslc": { "image": "python:3.12-alpine" } +} diff --git a/tests/configs/wslc_network_egress_custom_proxy_ip.json b/tests/configs/wslc_network_egress_custom_proxy_ip.json new file mode 100644 index 000000000..4cafd184d --- /dev/null +++ b/tests/configs/wslc_network_egress_custom_proxy_ip.json @@ -0,0 +1,11 @@ +{ + "$schema": "../../schemas/stable/mxc-config.schema.1.0.0.json", + "version": "1.0.0", + "containerId": "wslc-network-egress-custom-proxy-ip", + "containment": "wslc", + "process": { + "commandLine": "python3 - <<'EOF'\nimport os, socket, urllib.parse\nprint('PROXY_ENV=' + os.environ.get('HTTP_PROXY', 'unset') + ' ' + os.environ.get('HTTPS_PROXY', 'unset'))\nprint('NO_PROXY=' + os.environ.get('NO_PROXY', 'unset'))\ndef status(host, port):\n try:\n with socket.create_connection((host, port), timeout=10) as s:\n s.sendall(b'GET http://one.one.one.one/cdn-cgi/trace HTTP/1.1\\r\\nHost: one.one.one.one\\r\\nConnection: close\\r\\n\\r\\n')\n return s.recv(64).split(b' ')[1].decode()\n except (OSError, IndexError) as e:\n return 'ERROR ' + str(e)\nproxy = urllib.parse.urlsplit(os.environ['HTTP_PROXY'])\nprint('VIA_PROXY=' + status(proxy.hostname, proxy.port))\nprint('BUILT_IN=' + status('10.231.1.254', 3128))\nprint('DIRECT=' + status('1.1.1.1', 80))\ntry:\n print('RESOLVED=' + socket.gethostbyname('example.com'))\nexcept OSError as e:\n print('RESOLVED=ERROR', e)\nEOF" + }, + "runtimeConfig": { "networkProxy": "http://1.1.1.1:8080" }, + "wslc": { "image": "python:3.12-alpine" } +} diff --git a/tests/configs/wslc_network_egress_custom_proxy_loopback.json b/tests/configs/wslc_network_egress_custom_proxy_loopback.json new file mode 100644 index 000000000..29da81330 --- /dev/null +++ b/tests/configs/wslc_network_egress_custom_proxy_loopback.json @@ -0,0 +1,11 @@ +{ + "$schema": "../../schemas/stable/mxc-config.schema.1.0.0.json", + "version": "1.0.0", + "containerId": "wslc-network-egress-custom-proxy-loopback", + "containment": "wslc", + "process": { + "commandLine": "hp=${HTTP_PROXY#http://}\nhp=${hp%/}\necho PROXY_ENV=$HTTP_PROXY\necho VIA_PROXY=$(printf 'GET http://example.com/ HTTP/1.0\\r\\n\\r\\n' | nc -w 10 \"${hp%:*}\" \"${hp##*:}\" | head -n1 | cut -d' ' -f2)\nnslookup host.wslc.internal >/dev/null 2>&1 && echo HOST_DNS=RESOLVED || echo HOST_DNS=REFUSED\nnc -z -w 3 1.1.1.1 443 && echo DIRECT=REACHED || echo DIRECT=BLOCKED" + }, + "runtimeConfig": { "networkProxy": "http://127.0.0.1:18890" }, + "wslc": { "image": "alpine:latest" } +} diff --git a/tests/configs/wslc_network_egress_host_loopback.json b/tests/configs/wslc_network_egress_host_loopback.json new file mode 100644 index 000000000..add81dff0 --- /dev/null +++ b/tests/configs/wslc_network_egress_host_loopback.json @@ -0,0 +1,17 @@ +{ + "$schema": "../../schemas/stable/mxc-config.schema.1.0.0.json", + "version": "1.0.0", + "containerId": "wslc-network-egress-host-loopback", + "containment": "wslc", + "process": { + "commandLine": "hp=${HTTPS_PROXY#http://}\np() { printf 'CONNECT %s HTTP/1.1\\r\\n\\r\\n' \"$1\" | nc -w 10 \"${hp%:*}\" \"${hp##*:}\" | head -n1 | cut -d' ' -f2; }\necho NO_PROXY=$NO_PROXY\necho HOST_DNS=$(nslookup host.wslc.internal 2>/dev/null | awk '/^Address/ { a = $NF } END { print a }')\necho HOST_DIRECT=$(printf 'GET / HTTP/1.0\\r\\n\\r\\n' | nc -w 10 host.wslc.internal 18890 | head -n1 | cut -d' ' -f2)\necho HOST_VIA_PROXY=$(p host.wslc.internal:18890)\necho LOOPBACK=$(p 127.0.0.1:18890)\necho ALLOWED=$(p 1.1.1.1:443)\necho DENIED=$(p 8.8.8.8:443)\nnc -z -w 3 1.1.1.1 443 && echo DIRECT=REACHED || echo DIRECT=BLOCKED" + }, + "network": { + "egress": { + "default": "deny", + "allow": [{ "to": [{ "cidr": "1.1.1.1/32" }], "ports": [{ "port": 443, "protocol": "tcp" }] }] + }, + "ingress": { "default": "deny", "hostLoopback": "allow" } + }, + "wslc": { "image": "alpine:latest" } +} diff --git a/tests/configs/wslc_network_egress_network_proxy_egress_allow_rejected.json b/tests/configs/wslc_network_egress_network_proxy_egress_allow_rejected.json new file mode 100644 index 000000000..846ee6d2b --- /dev/null +++ b/tests/configs/wslc_network_egress_network_proxy_egress_allow_rejected.json @@ -0,0 +1,10 @@ +{ + "$schema": "../../schemas/stable/mxc-config.schema.1.0.0.json", + "version": "1.0.0", + "containerId": "wslc-network-egress-network-proxy-egress-allow-rejected", + "containment": "wslc", + "process": { "commandLine": "echo WSLC_EGRESS_RULES_SHOULD_NOT_RUN" }, + "network": { "egress": { "default": "allow" } }, + "runtimeConfig": { "networkProxy": "http://1.1.1.1:8080" }, + "wslc": { "image": "alpine:latest" } +} diff --git a/tests/configs/wslc_network_egress_network_proxy_https_ip_rejected.json b/tests/configs/wslc_network_egress_network_proxy_https_ip_rejected.json new file mode 100644 index 000000000..e434289fa --- /dev/null +++ b/tests/configs/wslc_network_egress_network_proxy_https_ip_rejected.json @@ -0,0 +1,9 @@ +{ + "$schema": "../../schemas/stable/mxc-config.schema.1.0.0.json", + "version": "1.0.0", + "containerId": "wslc-network-egress-network-proxy-https-ip-rejected", + "containment": "wslc", + "process": { "commandLine": "echo WSLC_EGRESS_RULES_SHOULD_NOT_RUN" }, + "runtimeConfig": { "networkProxy": "https://1.1.1.1:8443" }, + "wslc": { "image": "alpine:latest" } +} diff --git a/tests/configs/wslc_network_egress_network_proxy_loopback_rejected.json b/tests/configs/wslc_network_egress_network_proxy_loopback_rejected.json new file mode 100644 index 000000000..348269b30 --- /dev/null +++ b/tests/configs/wslc_network_egress_network_proxy_loopback_rejected.json @@ -0,0 +1,9 @@ +{ + "$schema": "../../schemas/stable/mxc-config.schema.1.0.0.json", + "version": "1.0.0", + "containerId": "wslc-network-egress-network-proxy-loopback-rejected", + "containment": "wslc", + "process": { "commandLine": "echo WSLC_EGRESS_RULES_SHOULD_NOT_RUN" }, + "runtimeConfig": { "networkProxy": "http://127.0.0.2:8888" }, + "wslc": { "image": "alpine:latest" } +} diff --git a/tests/configs/wslc_network_egress_network_proxy_unresolvable_rejected.json b/tests/configs/wslc_network_egress_network_proxy_unresolvable_rejected.json new file mode 100644 index 000000000..d77e9234e --- /dev/null +++ b/tests/configs/wslc_network_egress_network_proxy_unresolvable_rejected.json @@ -0,0 +1,9 @@ +{ + "$schema": "../../schemas/stable/mxc-config.schema.1.0.0.json", + "version": "1.0.0", + "containerId": "wslc-network-egress-network-proxy-unresolvable-rejected", + "containment": "wslc", + "process": { "commandLine": "echo WSLC_EGRESS_RULES_SHOULD_NOT_RUN" }, + "runtimeConfig": { "networkProxy": "http://mxc-proxy.invalid:8080" }, + "wslc": { "image": "alpine:latest" } +} diff --git a/tests/configs/wslc_network_egress_port_mapping_host_loopback.json b/tests/configs/wslc_network_egress_port_mapping_host_loopback.json new file mode 100644 index 000000000..48ab6cb90 --- /dev/null +++ b/tests/configs/wslc_network_egress_port_mapping_host_loopback.json @@ -0,0 +1,17 @@ +{ + "$schema": "../../schemas/stable/mxc-config.schema.1.0.0.json", + "version": "1.0.0", + "containerId": "wslc-network-egress-port-mapping-host-loopback", + "containment": "wslc", + "process": { + "commandLine": "serve() { echo \"MAPPED_$1\" | timeout 120 nc -l -p \"$1\" > /tmp/r; echo \"RECEIVED_$2=$(cat /tmp/r)\"; }\necho HOST_DIRECT=$(printf 'GET / HTTP/1.0\\r\\n\\r\\n' | nc -w 10 host.wslc.internal 18890 | head -n1 | cut -d' ' -f2)\nnc -z -w 3 1.1.1.1 443 && echo DIRECT=REACHED || echo DIRECT=BLOCKED\nserve 8091 1" + }, + "network": { + "egress": { "default": "deny" }, + "ingress": { "default": "deny", "hostLoopback": "allow" } + }, + "wslc": { + "image": "alpine:latest", + "portMappings": [{ "windowsPort": 18091, "containerPort": 8091, "protocol": "tcp" }] + } +} diff --git a/tests/configs/wslc_network_egress_port_mapping_host_loopback_rejected.json b/tests/configs/wslc_network_egress_port_mapping_host_loopback_rejected.json deleted file mode 100644 index c0839ee2d..000000000 --- a/tests/configs/wslc_network_egress_port_mapping_host_loopback_rejected.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "$schema": "../../schemas/stable/mxc-config.schema.1.0.0.json", - "version": "1.0.0", - "containerId": "wslc-network-egress-port-mapping-host-loopback-rejected", - "containment": "wslc", - "process": { - "commandLine": "echo WSLC_EGRESS_RULES_SHOULD_NOT_RUN" - }, - "network": { - "egress": { "default": "deny" }, - "ingress": { "default": "deny", "hostLoopback": "allow" } - }, - "wslc": { - "image": "alpine:latest", - "portMappings": [{ "windowsPort": 18088, "containerPort": 80, "protocol": "tcp" }] - } -} diff --git a/tests/configs/wslc_network_egress_port_mapping_network_proxy.json b/tests/configs/wslc_network_egress_port_mapping_network_proxy.json new file mode 100644 index 000000000..50571423c --- /dev/null +++ b/tests/configs/wslc_network_egress_port_mapping_network_proxy.json @@ -0,0 +1,14 @@ +{ + "$schema": "../../schemas/stable/mxc-config.schema.1.0.0.json", + "version": "1.0.0", + "containerId": "wslc-network-egress-port-mapping-network-proxy", + "containment": "wslc", + "process": { + "commandLine": "serve() { echo \"MAPPED_$1\" | timeout 120 nc -l -p \"$1\" > /tmp/r; echo \"RECEIVED_$2=$(cat /tmp/r)\"; }\necho PROXY_ENV=$HTTP_PROXY\necho RESOLVED=$(nslookup one.one.one.one 2>/dev/null | awk '/^Address/ {a=$NF} END {print a}')\necho VIA_PROXY=$(printf 'GET http://one.one.one.one/cdn-cgi/trace HTTP/1.1\\r\\nHost: one.one.one.one\\r\\nConnection: close\\r\\n\\r\\n' | nc -w 10 one.one.one.one 8080 | head -n1 | cut -d' ' -f2)\nnc -z -w 3 1.1.1.1 80 && echo DIRECT=REACHED || echo DIRECT=BLOCKED\nserve 8089 1" + }, + "runtimeConfig": { "networkProxy": "http://one.one.one.one:8080" }, + "wslc": { + "image": "alpine:latest", + "portMappings": [{ "windowsPort": 18089, "containerPort": 8089, "protocol": "tcp" }] + } +} diff --git a/tests/configs/wslc_network_egress_port_mapping_network_proxy_rejected.json b/tests/configs/wslc_network_egress_port_mapping_network_proxy_rejected.json deleted file mode 100644 index 1b8b40f47..000000000 --- a/tests/configs/wslc_network_egress_port_mapping_network_proxy_rejected.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "$schema": "../../schemas/stable/mxc-config.schema.1.0.0.json", - "version": "1.0.0", - "containerId": "wslc-network-egress-port-mapping-network-proxy-rejected", - "containment": "wslc", - "process": { - "commandLine": "echo WSLC_EGRESS_RULES_SHOULD_NOT_RUN" - }, - "runtimeConfig": { "networkProxy": "http://127.0.0.1:8888" }, - "wslc": { - "image": "alpine:latest", - "portMappings": [{ "windowsPort": 18089, "containerPort": 80, "protocol": "tcp" }] - } -} diff --git a/tests/configs/wslc_network_egress_rules_host_loopback_rejected.json b/tests/configs/wslc_network_egress_rules_host_loopback_rejected.json deleted file mode 100644 index b3e73f505..000000000 --- a/tests/configs/wslc_network_egress_rules_host_loopback_rejected.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "$schema": "../../schemas/stable/mxc-config.schema.1.0.0.json", - "version": "1.0.0", - "containerId": "wslc-network-egress-rules-host-loopback-rejected", - "containment": "wslc", - "process": { - "commandLine": "echo WSLC_EGRESS_RULES_SHOULD_NOT_RUN" - }, - "network": { - "egress": { - "default": "allow", - "deny": [{ "to": [{ "cidr": "10.0.0.0/8" }] }] - }, - "ingress": { "default": "allow", "hostLoopback": "allow" } - }, - "wslc": { - "image": "alpine:latest" - } -} diff --git a/tests/scripts/run_wslc_all_tests.ps1 b/tests/scripts/run_wslc_all_tests.ps1 index 5ec668e44..3da0405ce 100644 --- a/tests/scripts/run_wslc_all_tests.ps1 +++ b/tests/scripts/run_wslc_all_tests.ps1 @@ -655,6 +655,81 @@ Invoke-WslcMappedRun "wslc_network_egress_port_mapping_ingress_allow.json" ([ord Invoke-WslcMappedRun "wslc_port_mapping_bridged_reached.json" ([ordered]@{ 18086 = 8086 }) ` -OutputNotContains "Built-in proxy ready" +# A custom proxy is the only destination, relayed by the built-in proxy. Probes +# send an absolute-form HTTP request through it to Cloudflare's port 8080, which +# answers it like a proxy would. A hostname keeps its URL and resolves to the +# built-in proxy; an IP is rewritten to the built-in proxy's address. +$null = $results.Add((Run-WslcTest "wslc_network_egress_custom_proxy_ip.json" -ForceDebug -OutputNotContains $NotClean ` + -OutputContains "Built-in proxy ready at http://10.231.1.254:8080/", "custom proxy: 10.231.1.254:8080 relays to 1.1.1.1:8080", $Clean ` + -Probes ([ordered]@{ + PROXY_ENV = "http://10\.231\.1\.254:8080/ http://10\.231\.1\.254:8080/"; NO_PROXY = ""; VIA_PROXY = "[1-5]\d\d" + BUILT_IN = "ERROR .*"; DIRECT = "ERROR .*"; RESOLVED = "\d+\.\d+\.\d+\.\d+" + }))) +# TLS to the proxy verifies against its hostname through the relay. +$null = $results.Add((Run-WslcTest "wslc_network_egress_custom_proxy_https_name.json" -ForceDebug -OutputNotContains $NotClean ` + -OutputContains "Built-in proxy ready at https://one.one.one.one:8443", "accepts connections only through port mappings", $Clean ` + -Probes ([ordered]@{ + PROXY_ENV = "https://one\.one\.one\.one:8443"; RESOLVED = "10\.231\.1\.254"; TLS_PROXY = "VERIFIED" + TLS_OTHER_NAME = "ERROR .*"; DIRECT = "BLOCKED" + }))) +Invoke-WslcMappedRun "wslc_network_egress_port_mapping_network_proxy.json" ([ordered]@{ 18089 = 8089 }) ` + -OutputContains "Built-in proxy ready at http://one.one.one.one:8080" ` + -Probes ([ordered]@{ + PROXY_ENV = "http://one\.one\.one\.one:8080"; RESOLVED = "10\.231\.1\.254"; VIA_PROXY = "[1-5]\d\d"; DIRECT = "BLOCKED" + }) + +# A Windows 127.0.0.1 server answering every connection with an HTTP 200. +$HostLoopbackPort = 18890 +$hostLoopbackServer = Start-Job -ArgumentList $HostLoopbackPort -ScriptBlock { + param($Port) + $listener = [Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback, $Port) + $listener.Start() + $reply = [Text.Encoding]::ASCII.GetBytes("HTTP/1.1 200 OK`r`nContent-Length: 0`r`nConnection: close`r`n`r`n") + $buffer = [byte[]]::new(4096) + while ($true) { + $client = $listener.AcceptTcpClient() + try { + $stream = $client.GetStream() + $stream.ReadTimeout = 2000 + try { $null = $stream.Read($buffer, 0, $buffer.Length) } catch {} + $stream.Write($reply, 0, $reply.Length) + $client.Client.Shutdown([Net.Sockets.SocketShutdown]::Send) + } catch { + } finally { + $client.Dispose() + } + } +} +$deadline = (Get-Date).AddSeconds(30) +while (-not (Test-WslcTcpConnect "127.0.0.1" $HostLoopbackPort) -and (Get-Date) -lt $deadline) { Start-Sleep 1 } +try { + # host.wslc.internal reaches the server directly and through the proxy; + # the workload's own loopback stays denied. + $null = $results.Add((Run-WslcTest "wslc_network_egress_host_loopback.json" -ForceDebug -OutputNotContains $NotClean ` + -OutputContains "Session reaches Windows loopback as host.wslc.internal", $Clean ` + -Probes ([ordered]@{ + NO_PROXY = "host\.wslc\.internal"; HOST_DNS = "10\.231\.1\.3"; HOST_DIRECT = "200"; HOST_VIA_PROXY = "200" + LOOPBACK = "403"; ALLOWED = "200"; DENIED = "403"; DIRECT = "BLOCKED" + }))) + Invoke-WslcMappedRun "wslc_network_egress_port_mapping_host_loopback.json" ([ordered]@{ 18091 = 8091 }) ` + -Probes ([ordered]@{ HOST_DIRECT = "200"; DIRECT = "BLOCKED" }) + # A custom proxy on Windows 127.0.0.1 doesn't expose host.wslc.internal. + $null = $results.Add((Run-WslcTest "wslc_network_egress_custom_proxy_loopback.json" -ForceDebug -OutputNotContains $NotClean ` + -OutputContains "Built-in proxy ready at http://10.231.1.254:18890/", $Clean ` + -Probes ([ordered]@{ + PROXY_ENV = "http://10\.231\.1\.254:18890/"; VIA_PROXY = "200"; HOST_DNS = "REFUSED"; DIRECT = "BLOCKED" + }))) + # Bridged containers reach it without the built-in proxy. + $null = $results.Add((Run-WslcTest "wslc_network_bridged.json" -As "wslc_network_bridged.json (host loopback)" ` + -OutputContains "NET_EGRESS_REACHED", "NET_HOST_LOOPBACK=200")) + $null = $results.Add((Run-WslcTest "wslc_network_bridged_host_loopback_denied.json" -ForceDebug ` + -OutputContains "NET_EGRESS_REACHED", "NET_HOST_LOOPBACK=ERROR" ` + -OutputNotContains "Built-in proxy ready", "reaches Windows loopback")) +} finally { + Stop-Job $hostLoopbackServer + Remove-Job $hostLoopbackServer +} + # Rejected before any container is created. $egressRejections = [ordered]@{ "allow_udp" = "network.egress.allow supports only protocol 'tcp' (got 'udp')" @@ -665,11 +740,12 @@ $egressRejections = [ordered]@{ "deny_ipv6" = "network.egress CIDR 2001:db8::/32 is IPv6" "reserved_subnet" = "which the built-in proxy reserves for its own networks" "network_proxy" = "runtimeConfig.networkProxy cannot be combined with egress filtering" - "rules_host_loopback" = "hostLoopback 'allow' cannot be combined with egress filtering" + "network_proxy_egress_allow" = "runtimeConfig.networkProxy with network.egress.default 'allow' requires bridged networking" + "network_proxy_https_ip" = "with an IP address or loopback host must use http://" + "network_proxy_loopback" = "runtimeConfig.networkProxy on Windows loopback must use 127.0.0.1 or localhost" + "network_proxy_unresolvable" = "runtimeConfig.networkProxy host 'mxc-proxy.invalid' has no IPv4 address on Windows" "port_mapping_udp" = "unknown variant ``udp``" "port_mapping_duplicate" = "duplicate windowsPort 18087 for protocol 'tcp'" - "port_mapping_host_loopback" = "hostLoopback 'allow' cannot be combined with egress filtering" - "port_mapping_network_proxy" = "runtimeConfig.networkProxy requires bridged networking" } foreach ($name in $egressRejections.Keys) { $null = $results.Add((Run-WslcTest "wslc_network_egress_$($name)_rejected.json" -ExpectedExit 1 `