From 4c9e6cfbf2789bf27d37856067c6a212b9f93cc0 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Fri, 6 Nov 2026 23:59:47 +0000 Subject: [PATCH] fix(network): drop caller Host headers and refuse encoded slashes in path rules A script could send `-H 'Host: other'` to an approved IP so injected credentials reached another virtual host, and `/v1/..%2Fadmin` matched a `/v1/` rule on servers that decode before routing. HttpClient now drops caller Host/framing/proxy headers for every caller (TM-NET-031) and path-scoped patterns refuse %2F/%5C (TM-NET-032). --- crates/bashkit/docs/threat-model.md | 2 + crates/bashkit/src/builtins/cpython/http.rs | 19 ++------ crates/bashkit/src/network/allowlist.rs | 36 ++++++++++++++ crates/bashkit/src/network/client.rs | 47 +++++++++++++++++++ crates/bashkit/src/network/mod.rs | 29 ++++++++++++ .../integration/credential_injection_tests.rs | 47 +++++++++++++++++++ knowledge/log.md | 1 + knowledge/security/credential-injection.md | 2 + knowledge/security/threat-model.md | 2 + 9 files changed, 169 insertions(+), 16 deletions(-) diff --git a/crates/bashkit/docs/threat-model.md b/crates/bashkit/docs/threat-model.md index 53d90f85f..7a481eec2 100644 --- a/crates/bashkit/docs/threat-model.md +++ b/crates/bashkit/docs/threat-model.md @@ -414,6 +414,8 @@ Network access is disabled by default. When enabled, strict controls apply. | Repeated curl data bypasses body cap (TM-NET-028) | Many data/file parts plus encoding expansion exceed 10 MB in aggregate | Checked aggregate appends; file metadata checked against remaining capacity before reads | MITIGATED | | Private IP behind NAT64/6to4 or reserved range (TM-NET-029) | AAAA `64:ff9b::a9fe:a9fe` / `2002:7f00:1::`, or A in `0.0.0.0/8`, `198.18.0.0/15`, multicast | `is_private_ip` checks the embedded IPv4 of NAT64/6to4 and blocks all non-global special-purpose ranges | MITIGATED | | Embedded CLI egress bypass (TM-NET-030) | `fetchkit fetch`/`markkit extract URL` follow a redirect off the allowlist or read host proxy env | Both builtins send every hop through the sandbox HTTP client (allowlist re-checked per hop); no own TLS stack; `--allow-env-proxy` refused | MITIGATED | +| Host header steers credentials (TM-NET-031) | `curl -H 'Host: other'` to an approved IP | Caller Host/framing/proxy headers are dropped before credential injection | MITIGATED | +| Encoded slash escapes path rule (TM-NET-032) | `/v1/..%2Fadmin` against a `/v1/` rule | Path-scoped rules refuse `%2F`/`%5C` | MITIGATED | **Credential Injection (TM-NET-024–027):** diff --git a/crates/bashkit/src/builtins/cpython/http.rs b/crates/bashkit/src/builtins/cpython/http.rs index d007529c3..68940bc3a 100644 --- a/crates/bashkit/src/builtins/cpython/http.rs +++ b/crates/bashkit/src/builtins/cpython/http.rs @@ -48,19 +48,7 @@ const MAX_REQUEST_BODY: usize = 16 * 1024 * 1024; /// Longest error text handed back to the guest (TM-INF-022). const MAX_ERROR_LEN: usize = 512; -/// Headers the host (or reqwest) sets itself; guest values are dropped. -const HOST_OWNED_HEADERS: &[&str] = &[ - "host", - "content-length", - "transfer-encoding", - "connection", - "keep-alive", - "upgrade", - "te", - "trailer", - "proxy-connection", - "proxy-authorization", -]; +use crate::network::is_host_owned_header; /// Per-call HTTP state of one guest instance. pub(crate) struct HttpState { @@ -167,8 +155,7 @@ pub(crate) fn decode_request(buf: &[u8]) -> Result { if value.bytes().any(|b| b == b'\r' || b == b'\n' || b == 0) { return Err("invalid header value".to_string()); } - let lower = name.to_ascii_lowercase(); - if HOST_OWNED_HEADERS.contains(&lower.as_str()) { + if is_host_owned_header(name) { continue; } headers.push((name.to_string(), value.trim().to_string())); @@ -201,7 +188,7 @@ pub(crate) fn check_request_invariants(buf: &[u8]) { for (name, value) in &req.headers { assert!(is_token(name), "header name {name:?}"); // debug-ok: fuzz assertion assert!(!value.bytes().any(|b| b == b'\r' || b == b'\n' || b == 0)); - assert!(!HOST_OWNED_HEADERS.contains(&name.to_ascii_lowercase().as_str())); + assert!(!is_host_owned_header(name)); } assert!(req.body.len() <= MAX_REQUEST_BODY); } diff --git a/crates/bashkit/src/network/allowlist.rs b/crates/bashkit/src/network/allowlist.rs index 9535a7c62..8bcf6644f 100644 --- a/crates/bashkit/src/network/allowlist.rs +++ b/crates/bashkit/src/network/allowlist.rs @@ -102,6 +102,15 @@ fn is_private_ipv4(v4: &std::net::Ipv4Addr) -> bool { /// Redact credentials from a URL for safe inclusion in error messages. /// Replaces `user:pass@` in the authority with `***@`. +/// Whether `path` holds a percent-encoded `/` (`%2F`) or `\\` (`%5C`). +fn has_encoded_separator(path: &str) -> bool { + path.as_bytes().windows(3).any(|w| { + w[0] == b'%' + && (w[1] == b'2' && w[2].eq_ignore_ascii_case(&b'f') + || w[1] == b'5' && w[2].eq_ignore_ascii_case(&b'c')) + }) +} + fn redact_url(url: &str) -> String { match Url::parse(url) { Ok(mut parsed) => { @@ -337,6 +346,15 @@ impl NetworkAllowlist { return false; } + // THREAT[TM-NET-032]: an encoded `/` or `\` lets the URL climb out of + // the allowed prefix on servers that decode before routing + // (`/assets/..%2Fadmin` -> `/admin`). `url` already resolves literal + // and `%2e` dot segments, so only these encodings remain. Refused + // only for path-scoped patterns; a host-wide pattern allows any path. + if has_encoded_separator(url_path) { + return false; + } + // If pattern path doesn't end with /, ensure we're at a path boundary // Use byte indexing consistently since url_path.len() and pattern_path.len() // are both byte counts, and starts_with already confirmed the prefix matches. @@ -551,6 +569,24 @@ mod tests { } } + #[test] + fn test_path_prefix_refuses_encoded_separators() { + let allowlist = NetworkAllowlist::new().allow("https://cdn.example.com/assets/"); + for url in [ + "https://cdn.example.com/assets/..%2Fadmin", + "https://cdn.example.com/assets/..%2fadmin", + "https://cdn.example.com/assets/..%5Cadmin", + "https://cdn.example.com/assets/%2e%2e/admin", + "https://cdn.example.com/assets/../admin", + ] { + assert!(!allowlist.is_allowed(url), "{url}"); + } + assert!(allowlist.is_allowed("https://cdn.example.com/assets/a%20b.png")); + // Host-wide patterns keep allowing any path. + let host_wide = NetworkAllowlist::new().allow("https://cdn.example.com"); + assert!(host_wide.is_allowed("https://cdn.example.com/a%2Fb")); + } + #[test] fn test_path_boundary_check_byte_safe() { // Ensure path boundary check uses byte-safe indexing diff --git a/crates/bashkit/src/network/client.rs b/crates/bashkit/src/network/client.rs index 3a65724c9..cba2b37cd 100644 --- a/crates/bashkit/src/network/client.rs +++ b/crates/bashkit/src/network/client.rs @@ -589,6 +589,17 @@ impl HttpClient { // Check allowlist + private IP policy BEFORE making any network request. self.enforce_url_security(url).await?; + // THREAT[TM-NET-031]: drop caller-set Host/framing/proxy headers + // before hooks run, so injected credentials only ever travel to the + // allowlisted host the URL names. Hooks (host-trusted) may still add + // headers. + let caller_headers: Vec<(String, String)> = headers + .iter() + .filter(|(name, _)| !super::is_host_owned_header(name)) + .cloned() + .collect(); + let headers: &[(String, String)] = &caller_headers; + // Fire before_http hooks — may modify URL/headers or cancel the request let (url, headers) = if !self.before_http.is_empty() { let event = crate::hooks::HttpRequestEvent { @@ -1268,6 +1279,42 @@ mod tests { assert_eq!(seen[0].method, Method::Get); } + // THREAT[TM-NET-031]: caller Host/framing/proxy headers never reach the + // transport, so injected credentials go only to the URL's host. + #[tokio::test] + async fn test_caller_host_owned_headers_are_dropped() { + let transport = Arc::new(CapturingTransport::default()); + let mut client = HttpClient::new(NetworkAllowlist::allow_all()); + client.set_transport(transport.clone()); + + let headers: Vec<(String, String)> = [ + ("Host", "internal.example.com"), + (" host", "x"), + ("Proxy-Authorization", "Basic eA=="), + ("Transfer-Encoding", "chunked"), + ("Content-Length", "0"), + ("X-Keep", "1"), + ] + .iter() + .map(|(n, v)| (n.to_string(), v.to_string())) + .collect(); + client + .request_with_timeouts( + Method::Get, + "http://93.184.216.34/", + None, + &headers, + None, + None, + ) + .await + .unwrap(); + + let seen = transport.seen.lock().unwrap(); + let names: Vec<&str> = seen[0].headers.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(names, ["X-Keep"]); + } + #[tokio::test] async fn test_transport_receives_timeouts_and_response_cap() { let transport = Arc::new(CapturingTransport::default()); diff --git a/crates/bashkit/src/network/mod.rs b/crates/bashkit/src/network/mod.rs index cb19b418c..5032864a0 100644 --- a/crates/bashkit/src/network/mod.rs +++ b/crates/bashkit/src/network/mod.rs @@ -100,3 +100,32 @@ pub use client::{HttpClient, HttpLimits, Method, Response}; #[cfg(feature = "http_client")] pub use transport::{HttpTransport, HttpTransportError, HttpTransportRequest}; + +/// Headers the host (or reqwest) owns; caller-supplied values are dropped +/// before hooks, credential injection and transport dispatch. +/// +/// THREAT[TM-NET-031]: a script-chosen `Host` sent to an allowlisted IP +/// reaches whichever virtual host it names, carrying credentials injected +/// for the allowlisted name. Framing and proxy headers would let a script +/// smuggle requests or authenticate to an egress proxy. +#[cfg(any(feature = "http_client", feature = "cpython"))] +pub(crate) const HOST_OWNED_HEADERS: &[&str] = &[ + "host", + "content-length", + "transfer-encoding", + "connection", + "keep-alive", + "upgrade", + "te", + "trailer", + "proxy-connection", + "proxy-authorization", +]; + +/// Whether `name` (any case) is in [`HOST_OWNED_HEADERS`]. +#[cfg(any(feature = "http_client", feature = "cpython"))] +pub(crate) fn is_host_owned_header(name: &str) -> bool { + HOST_OWNED_HEADERS + .iter() + .any(|owned| owned.eq_ignore_ascii_case(name.trim())) +} diff --git a/crates/bashkit/tests/integration/credential_injection_tests.rs b/crates/bashkit/tests/integration/credential_injection_tests.rs index 088903e38..921388fa7 100644 --- a/crates/bashkit/tests/integration/credential_injection_tests.rs +++ b/crates/bashkit/tests/integration/credential_injection_tests.rs @@ -302,6 +302,53 @@ mod scoping { assert!(auth_v2.is_none(), "/v2/ should NOT have Authorization"); } + /// THREAT[TM-NET-031]/[TM-NET-032]: a script cannot steer injected + /// credentials to another virtual host with `-H Host:`, nor out of a + /// path-scoped rule with an encoded slash. + #[tokio::test] + async fn script_cannot_redirect_credentials() { + let captured = std::sync::Arc::new(std::sync::Mutex::new(Vec::<( + String, + Vec<(String, String)>, + )>::new())); + let captured_clone = captured.clone(); + + let mut bash = Bash::builder() + .network(NetworkAllowlist::allow_all()) + .credential( + "https://api.example.com/v1/", + Credential::bearer("v1_token"), + ) + .before_http(Box::new(move |req: HttpRequestEvent| { + captured_clone + .lock() + .unwrap() + .push((req.url.clone(), req.headers.clone())); + HookAction::Cancel("captured".into()) + })) + .build(); + + bash.exec("curl -s -H 'Host: admin.example.com' https://api.example.com/v1/users") + .await + .unwrap(); + bash.exec("curl -s 'https://api.example.com/v1/..%2Fadmin'") + .await + .unwrap(); + + let requests = captured.lock().unwrap(); + assert_eq!(requests.len(), 2); + let host = requests[0] + .1 + .iter() + .find(|(name, _)| name.eq_ignore_ascii_case("host")); + assert!(host.is_none(), "Host header must be dropped"); + let auth = requests[1] + .1 + .iter() + .find(|(name, _)| name.eq_ignore_ascii_case("authorization")); + assert!(auth.is_none(), "encoded slash must not match /v1/"); + } + /// Multiple credentials for different hosts. #[tokio::test] async fn multiple_hosts() { diff --git a/knowledge/log.md b/knowledge/log.md index 757a1b428..0504ce971 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -2,6 +2,7 @@ ## 2026-11-06 +* **Credentials stay on the approved host**: a security audit found a script could send `-H 'Host: other.example'` to an approved IP, so injected credentials reached another virtual host, and that `/v1/..%2Fadmin` matched a `/v1/` rule on servers that decode before routing. `HttpClient` now drops caller Host/framing/proxy headers for every caller (the list moved from the CPython bridge to `network`), and path-scoped rules refuse `%2F`/`%5C`. See [Credential Injection](security/credential-injection.md), TM-NET-031, TM-NET-032. * **Python wall-clock limit**: Monty 1.x pauses its clock while the VM waits on the host, so `PythonLimits::max_duration` bounded VM time only. A `while True: p.write_text('x')` loop under a 500 ms limit ran 6 s, never yielding its worker thread, so caller-side timeouts could not cancel it and co-tenants on that thread stalled. The host-call loop now enforces the wall-clock deadline (exit 124) and yields at every host call. Found by the multi-tenant stress suite. See [Python Builtin](runtimes/python-builtin.md), TM-PY-036. * **Monty fork drift markers completed**: the drift check landed (#2861) from a branch cut before the shared-graph fix (#2857), so `main` went red on 12 unmarked regions the moment both were in. Eleven were real #2857 edits (seven `repr_check_time(..)?` call sites, the `ResourceError` import, a doc sentence, the `tick` initializer) and are now marked. The twelfth was a checker blind spot: its fixed three-line window read the tail of a multi-line fork note and missed the marker on the note's first line, which is how the forks are written (`repr_check_time`'s note is eleven lines). The window now covers the whole comment/attribute block attached to the changed item, stopping at the first line of code so one item's note cannot mark the next item's drift. See [Dependencies](operations/dependencies.md#monty-forks). * **Monty fork drift check**: `scripts/check_monty_fork.py` compares both forks with the SHA-256-pinned upstream 1.4.0 crates and fails on unmarked edits (it found one unmarked import, now marked); runs in CI lint and `just check`. Re-sync checklist for upstream security fixes added. See [Dependencies](operations/dependencies.md#monty-forks). diff --git a/knowledge/security/credential-injection.md b/knowledge/security/credential-injection.md index 2379dd3eb..9be64ab06 100644 --- a/knowledge/security/credential-injection.md +++ b/knowledge/security/credential-injection.md @@ -118,6 +118,8 @@ Properties: |--------|-----------| | Script reads env var to get real secret | Injection mode: no env var. Placeholder mode: env var contains random placeholder, not real secret | | Script exfiltrates placeholder to unapproved host | Allowlist blocks unapproved hosts. Placeholder only replaced for matching patterns | +| Script sets `Host:` to reach another virtual host on the approved IP with injected credentials | `HttpClient` drops caller `Host`, framing and proxy headers before hooks run (TM-NET-031) | +| Script escapes a path-scoped rule with `%2F`/`%5C` (`/v1/..%2Fadmin`) | Path-scoped patterns refuse encoded separators (TM-NET-032) | | Script sets competing Authorization header | Overwrite semantics: injected header replaces script's header | | Credential appears in error messages | Injected values redacted in all error paths (extend TM-INF-015) | | Credential appears in traces | Trace output shows `[CREDENTIAL]` instead of real values | diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index f4f34aa54..82d594b75 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -886,6 +886,8 @@ matches literal host strings exactly, never resolved IPs; no DNS lookup. | TM-NET-028 | Repeated curl data parts bypass the request-body cap | Many individually valid `-d`/`--data-*` values, file reads, encoding expansion, and inserted `&` separators combine into an oversized allocation/request | One ordered aggregate uses checked appends; every separator and encoded byte counts toward the 10 MB cap; file metadata is compared with remaining capacity before VFS reads. Exact-boundary and one-byte-over tests cover the invariant. | **MITIGATED** | | TM-NET-029 | Private IP behind a v4-embedding or reserved v6/v4 form | Allowlisted host returns AAAA `64:ff9b::a9fe:a9fe` (NAT64), `2002:7f00:1::` (6to4), or A in `0.0.0.0/8`, `198.18.0.0/15`, multicast, `240.0.0.0/4` | `is_private_ip` classifies NAT64/6to4 by the embedded v4 address and blocks all non-global special-purpose ranges (Teredo, local-use NAT64, site-local, multicast) at pre-resolve and connect time | **MITIGATED** | | TM-NET-030 | Embedded CLI egress bypass | `fetchkit fetch`/`markkit extract URL` open their own sockets, follow redirects off the allowlist, or read host proxy env | Both builtins route every hop (redirects, discovery probes, API subrequests) through the sandbox `HttpClient`; no upstream TLS stack is linked; `--allow-env-proxy` refused ([Markkit and Fetchkit Builtins](../runtimes/markkit-fetchkit-builtins.md)) | **MITIGATED** | +| TM-NET-031 | Script-chosen Host carries injected credentials to another vhost | `curl -H 'Host: other.example' https://approved.example/` reaches the vhost named by Host on the approved IP, with credentials injected for the approved name | `HttpClient::request_with_timeouts` drops caller `Host`, `Content-Length`, `Transfer-Encoding`, connection and proxy headers (`network::HOST_OWNED_HEADERS`, shared with the CPython HTTP bridge) before hooks, credential injection and transport dispatch. Regressions: `test_caller_host_owned_headers_are_dropped`, `script_cannot_redirect_credentials` | **MITIGATED** | +| TM-NET-032 | Encoded slash escapes a path-scoped allow/credential rule | `https://api.example/v1/..%2Fadmin` matches prefix `/v1/`; servers that decode before routing serve `/admin` (with `/v1/` credentials) | Path-scoped patterns refuse URL paths holding `%2F` or `%5C`; `url` already resolves literal and `%2e` dot segments and `\`. Host-wide patterns are unchanged. Regression: `test_path_prefix_refuses_encoded_separators` | **MITIGATED** | **Current Risk**: LOW - Multiple mitigations in place