From a0fb8f132b3da4d530fe43416779b1bba47b445e Mon Sep 17 00:00:00 2001 From: craig Date: Fri, 2 Oct 2026 14:06:20 -0700 Subject: [PATCH 1/7] feat(supervisor): trust supplemental upstream CAs per endpoint Signed-off-by: craig --- Cargo.lock | 3 + architecture/security-policy.md | 7 + crates/openshell-policy/Cargo.toml | 5 + crates/openshell-policy/src/ambiguity.rs | 17 ++ crates/openshell-policy/src/lib.rs | 126 +++++++++ crates/openshell-policy/src/merge.rs | 122 +++++++- crates/openshell-providers/src/profiles.rs | 1 + crates/openshell-server/src/grpc/policy.rs | 1 + .../data/sandbox-policy.rego | 11 +- .../src/l7/tls.rs | 261 ++++++++++++++++++ .../openshell-supervisor-network/src/opa.rs | 32 +++ .../src/policy_local.rs | 1 + .../openshell-supervisor-network/src/proxy.rs | 18 +- .../openshell-supervisor-network/src/run.rs | 5 +- docs/reference/policy-schema.mdx | 1 + proto/sandbox.proto | 5 +- .../v1/internal/converter/coverage_test.go | 1 + .../v1/internal/converter/network_policy.go | 2 + .../internal/converter/network_policy_test.go | 4 + sdk/go/openshell/v1/types/network_policy.go | 12 +- sdk/go/proto/sandboxv1/sandbox.pb.go | 22 +- 21 files changed, 638 insertions(+), 19 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 59b92b4185..fdd150c96a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4358,6 +4358,9 @@ dependencies = [ "noyalib", "openshell-core", "prost-types", + "rcgen", + "rustls", + "rustls-pemfile", "serde", "serde_json", ] diff --git a/architecture/security-policy.md b/architecture/security-policy.md index 62f5837e70..9f8794901b 100644 --- a/architecture/security-policy.md +++ b/architecture/security-policy.md @@ -142,6 +142,13 @@ flag defaults to `false` and is security-flagged in policy approval flows. Incremental merges only ever add the flag to a matching endpoint; clearing it requires removing the endpoint or replacing the policy. +TLS endpoints may specify `upstream_ca_pem` in their policy. The supervisor +adds that PEM certificate bundle only to the selected endpoint's upstream +rustls verifier, alongside its normal roots. CONNECT still terminates client +TLS and uses the parsed HTTP relay, so credential rewrite, middleware, and +redaction retain their normal boundary. Policy validation rejects this field +on `tls: skip` and `protocol: tcp` endpoints, which do not use the verifier. + The network supervisor independently enforces the same boundary. Credentialed WebSocket upgrades use the parsed relay, binary frames fail closed, and text placeholders require rewrite. REST bodies can continue streaming when body diff --git a/crates/openshell-policy/Cargo.toml b/crates/openshell-policy/Cargo.toml index cb32584186..6589c4462f 100644 --- a/crates/openshell-policy/Cargo.toml +++ b/crates/openshell-policy/Cargo.toml @@ -18,6 +18,11 @@ serde_json = { workspace = true } serde_yml = { workspace = true } miette = { workspace = true } prost-types = { workspace = true } +rustls = { workspace = true } +rustls-pemfile = { workspace = true } [lints] workspace = true + +[dev-dependencies] +rcgen = { workspace = true } diff --git a/crates/openshell-policy/src/ambiguity.rs b/crates/openshell-policy/src/ambiguity.rs index 2c0b1b1944..0a3fa5c522 100644 --- a/crates/openshell-policy/src/ambiguity.rs +++ b/crates/openshell-policy/src/ambiguity.rs @@ -181,6 +181,9 @@ fn connection_conflicts(left: &NetworkEndpoint, right: &NetworkEndpoint) -> Vec< &normalized_strings(&left.allowed_ips), &normalized_strings(&right.allowed_ips), ); + if left.upstream_ca_pem != right.upstream_ca_pem { + conflicts.push("upstream_ca_pem differs".to_string()); + } conflicts } @@ -1066,4 +1069,18 @@ mod tests { .any(|conflict| conflict.contains("transparent_tcp_eligible")) ); } + + #[test] + fn different_upstream_ca_pem_is_ambiguous_without_disclosing_certificates() { + let mut left = endpoint("api.example.com", 443); + left.upstream_ca_pem = "private-left-pem".to_string(); + let mut right = endpoint("api.example.com", 443); + right.upstream_ca_pem = "private-right-pem".to_string(); + let ambiguities = find_endpoint_ambiguities(&policy_with(left, right)); + assert_eq!(ambiguities.len(), 1); + let diagnostic = ambiguities[0].to_string(); + assert!(diagnostic.contains("upstream_ca_pem differs")); + assert!(!diagnostic.contains("private-left-pem")); + assert!(!diagnostic.contains("private-right-pem")); + } } diff --git a/crates/openshell-policy/src/lib.rs b/crates/openshell-policy/src/lib.rs index b2c15e4595..5e93d6155b 100644 --- a/crates/openshell-policy/src/lib.rs +++ b/crates/openshell-policy/src/lib.rs @@ -129,6 +129,8 @@ struct NetworkEndpointDef { protocol: String, #[serde(default, skip_serializing_if = "String::is_empty")] tls: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + upstream_ca_pem: Option, #[serde(default, skip_serializing_if = "String::is_empty")] enforcement: String, #[serde(default, skip_serializing_if = "String::is_empty")] @@ -845,6 +847,7 @@ fn to_proto(raw: PolicyFile) -> Result { ports: normalized_ports, protocol: protocol.clone(), tls: e.tls, + upstream_ca_pem: e.upstream_ca_pem.unwrap_or_default(), enforcement: e.enforcement, access: e.access, rules: allow_rules @@ -1013,6 +1016,8 @@ fn from_proto(policy: &SandboxPolicy) -> PolicyFile { ports, protocol, tls: e.tls.clone(), + upstream_ca_pem: (!e.upstream_ca_pem.is_empty()) + .then(|| e.upstream_ca_pem.clone()), enforcement: e.enforcement.clone(), access: e.access.clone(), rules, @@ -1164,6 +1169,17 @@ pub fn parse_sandbox_policy(yaml: &str) -> Result { let raw: PolicyFile = serde_yml::from_str(yaml) .into_diagnostic() .wrap_err("failed to parse sandbox policy YAML")?; + for rule in raw.network_policies.values() { + for endpoint in &rule.endpoints { + if endpoint + .upstream_ca_pem + .as_deref() + .is_some_and(str::is_empty) + { + return Err(miette::miette!("upstream_ca_pem cannot be empty")); + } + } + } validate_mcp_version_schema(&raw)?; to_proto(raw) } @@ -1817,7 +1833,22 @@ fn validate_sandbox_policy_with_mcp_presence( .unwrap_or(false), }; let mut l7_errors = validate_l7_endpoint_semantics(&fields); + if !ep.upstream_ca_pem.is_empty() { + if ep.tls.eq_ignore_ascii_case("skip") { + l7_errors.push("upstream_ca_pem cannot be used with tls: skip".to_string()); + } + let usable = validate_upstream_ca_pem(&ep.upstream_ca_pem); + if !usable { + l7_errors.push( + "upstream_ca_pem must contain at least one usable PEM certificate" + .to_string(), + ); + } + } let mut explicit_tcp_fields = Vec::new(); + if !ep.upstream_ca_pem.is_empty() { + explicit_tcp_fields.push("upstream_ca_pem"); + } if !ep.enforcement.is_empty() { explicit_tcp_fields.push("enforcement"); } @@ -1922,6 +1953,101 @@ fn validate_sandbox_policy_with_mcp_presence( } } +/// Accept only usable certificate PEM blocks; private keys and unrelated PEM +/// material must never be carried in an endpoint policy. +fn validate_upstream_ca_pem(pem: &str) -> bool { + let mut reader = std::io::BufReader::new(pem.as_bytes()); + let mut certs = Vec::new(); + loop { + match rustls_pemfile::read_one(&mut reader) { + Ok(Some(rustls_pemfile::Item::X509Certificate(cert))) => certs.push(cert), + Ok(None) => break, + _ => return false, + } + } + if certs.is_empty() { + return false; + } + let mut store = rustls::RootCertStore::empty(); + let expected = certs.len(); + let (added, ignored) = store.add_parsable_certificates(certs); + added == expected && ignored == 0 +} + +#[cfg(test)] +mod upstream_ca_tests { + use super::*; + + #[test] + fn supplemental_ca_round_trips_and_rejects_unsafe_combinations() { + let cert = rcgen::generate_simple_self_signed(vec!["api.example.test".into()]).unwrap(); + let pem = cert.cert.pem(); + let indented_pem = pem + .lines() + .map(|line| format!(" {line}")) + .collect::>() + .join("\n"); + let yaml = format!( + "version: 1\nnetwork_policies:\n api:\n endpoints:\n - host: api.example.test\n port: 443\n upstream_ca_pem: |\n{indented_pem}\n" + ); + let policy = parse_sandbox_policy(&yaml).unwrap(); + assert_eq!( + policy.network_policies["api"].endpoints[0] + .upstream_ca_pem + .trim(), + pem.trim() + ); + assert_eq!( + parse_sandbox_policy(&serialize_sandbox_policy(&policy).unwrap()).unwrap(), + policy + ); + let mut skip = policy.clone(); + skip.network_policies.get_mut("api").unwrap().endpoints[0].tls = "skip".into(); + assert!(validate_sandbox_policy(&skip).unwrap_err().iter().any(|v| { + v.to_string() + .contains("upstream_ca_pem cannot be used with tls: skip") + })); + let mut tcp = policy; + tcp.network_policies.get_mut("api").unwrap().endpoints[0].protocol = "tcp".into(); + assert!( + validate_sandbox_policy(&tcp) + .unwrap_err() + .iter() + .any(|v| v.to_string().contains("upstream_ca_pem")) + ); + } + + #[test] + fn supplemental_ca_rejects_empty_invalid_and_private_key_material() { + assert!(!validate_upstream_ca_pem("")); + assert!(!validate_upstream_ca_pem("not a certificate")); + assert!(!validate_upstream_ca_pem( + "-----BEGIN PRIVATE KEY-----\nAA==\n-----END PRIVATE KEY-----" + )); + let yaml = "version: 1\nnetwork_policies:\n api:\n endpoints:\n - host: api.example.test\n port: 443\n upstream_ca_pem: ''\n"; + assert!( + parse_sandbox_policy(yaml) + .unwrap_err() + .to_string() + .contains("upstream_ca_pem cannot be empty") + ); + let mut policy = parse_sandbox_policy("version: 1\nnetwork_policies:\n api:\n endpoints:\n - host: api.example.test\n port: 443\n").unwrap(); + for invalid in [ + "not a certificate", + "-----BEGIN PRIVATE KEY-----\nAA==\n-----END PRIVATE KEY-----", + ] { + policy.network_policies.get_mut("api").unwrap().endpoints[0].upstream_ca_pem = + invalid.into(); + assert!( + validate_sandbox_policy(&policy) + .unwrap_err() + .iter() + .any(|v| v.to_string().contains("upstream_ca_pem must contain")) + ); + } + } +} + fn host_wildcard_shape_invalid(host: &str) -> bool { if host == "*" || host == "**" { return true; diff --git a/crates/openshell-policy/src/merge.rs b/crates/openshell-policy/src/merge.rs index e6d72d4899..c59507f53a 100644 --- a/crates/openshell-policy/src/merge.rs +++ b/crates/openshell-policy/src/merge.rs @@ -302,6 +302,12 @@ pub enum PolicyMergeError { /// Rendered effective contract the operation asked for. incoming: String, }, + /// An overlapping endpoint already trusts a different supplemental CA. + UpstreamCaConflict { + operation_index: usize, + host: String, + port: u32, + }, /// Newly added binary scope would inherit an existing endpoint /// authorization that the incoming rule did not declare. NewBinaryWouldInheritAuthorization { @@ -419,6 +425,14 @@ impl std::fmt::Display for PolicyMergeError { f, "merge operation {operation_index} cannot combine MCP contracts at {host}:{port}: existing {existing}, incoming {incoming}" ), + Self::UpstreamCaConflict { + operation_index, + host, + port, + } => write!( + f, + "merge operation {operation_index} cannot change upstream_ca_pem for {host}:{port}; replace the endpoint policy" + ), Self::NewBinaryWouldInheritAuthorization { operation_index, rule_name, @@ -675,6 +689,9 @@ fn endpoint_attributes_cover(loaded: &NetworkEndpoint, proposed: &NetworkEndpoin if !proposed.tls.is_empty() && effective_tls(&loaded.tls) != effective_tls(&proposed.tls) { return false; } + if !proposed.upstream_ca_pem.is_empty() && loaded.upstream_ca_pem != proposed.upstream_ca_pem { + return false; + } if !proposed.enforcement.is_empty() && effective_enforcement(&loaded.enforcement) != effective_enforcement(&proposed.enforcement) @@ -1293,6 +1310,7 @@ fn is_authorization_inheritance_conflict(error: &PolicyMergeError) -> bool { // inspection contract per host and port rather than per rule, so two // contracts stay ambiguous however they are split. PolicyMergeError::McpContractConflict { .. } + | PolicyMergeError::UpstreamCaConflict { .. } | PolicyMergeError::ConflictingInspectionContracts { .. } => false, // Reports an unsupported or missing state in the policy the fold @@ -1461,6 +1479,19 @@ fn merge_endpoint( }, warnings, ); + if existing.upstream_ca_pem.is_empty() { + existing + .upstream_ca_pem + .clone_from(&incoming.upstream_ca_pem); + } else if !incoming.upstream_ca_pem.is_empty() + && existing.upstream_ca_pem != incoming.upstream_ca_pem + { + return Err(PolicyMergeError::UpstreamCaConflict { + operation_index, + host, + port, + }); + } if !incoming.rules.is_empty() { expand_existing_access(existing, &host, port, warnings)?; @@ -1728,6 +1759,9 @@ fn adopt_unset_retained_fields( if adopted.tls.is_empty() { adopted.tls.clone_from(&merged.tls); } + if adopted.upstream_ca_pem.is_empty() { + adopted.upstream_ca_pem.clone_from(&merged.upstream_ca_pem); + } if adopted.enforcement.is_empty() { adopted.enforcement.clone_from(&merged.enforcement); } @@ -2216,8 +2250,8 @@ mod tests { use super::{ ANY_BINARY_SCOPE, DEFAULT_JSON_RPC_MAX_BODY_BYTES, PolicyMergeError, PolicyMergeOp, - PolicyMergeWarning, canonical_ports, canonicalize_advisor_add_rule, generated_rule_name, - merge_policy, policy_covers_rule, + PolicyMergeWarning, adopt_unset_retained_fields, canonical_ports, + canonicalize_advisor_add_rule, generated_rule_name, merge_policy, policy_covers_rule, }; use crate::{restrictive_default_policy, validate_sandbox_policy}; use openshell_core::{ @@ -3699,6 +3733,90 @@ mod tests { assert_eq!(rule.binaries.len(), 2); } + #[test] + fn add_rule_preserves_requested_upstream_ca_and_coverage() { + let pem = rcgen::generate_simple_self_signed(vec!["api.example.com".into()]) + .unwrap() + .cert + .pem(); + let existing = rule_with_authorizations( + "api", + vec![endpoint("api.example.com", 443)], + &["/usr/bin/client"], + ); + let mut incoming_endpoint = endpoint("api.example.com", 443); + incoming_endpoint.upstream_ca_pem = pem.clone(); + let incoming = + rule_with_authorizations("api", vec![incoming_endpoint], &["/usr/bin/client"]); + let merged = merge_policy( + policy_with_rule("api", existing), + &[PolicyMergeOp::AddRule { + rule_name: "api".into(), + rule: incoming.clone(), + }], + ) + .unwrap() + .policy; + assert_eq!( + merged.network_policies["api"].endpoints[0].upstream_ca_pem, + pem + ); + assert!(policy_covers_rule(&merged, &incoming)); + let mut without_ca = merged; + without_ca + .network_policies + .get_mut("api") + .unwrap() + .endpoints[0] + .upstream_ca_pem + .clear(); + assert!(!policy_covers_rule(&without_ca, &incoming)); + } + + #[test] + fn add_rule_rejects_conflicting_upstream_ca_without_exposing_pem() { + let first = rcgen::generate_simple_self_signed(vec!["api.example.com".into()]) + .unwrap() + .cert + .pem(); + let second = rcgen::generate_simple_self_signed(vec!["api.example.com".into()]) + .unwrap() + .cert + .pem(); + let mut existing_endpoint = endpoint("api.example.com", 443); + existing_endpoint.upstream_ca_pem = first.clone(); + let mut incoming_endpoint = endpoint("api.example.com", 443); + incoming_endpoint.upstream_ca_pem = second.clone(); + let existing = + rule_with_authorizations("api", vec![existing_endpoint], &["/usr/bin/client"]); + let incoming = + rule_with_authorizations("api", vec![incoming_endpoint], &["/usr/bin/client"]); + let error = merge_policy( + policy_with_rule("api", existing), + &[PolicyMergeOp::AddRule { + rule_name: "api".into(), + rule: incoming, + }], + ) + .unwrap_err(); + assert!(matches!(error, PolicyMergeError::UpstreamCaConflict { .. })); + let message = error.to_string(); + assert!(message.contains("upstream_ca_pem")); + assert!(!message.contains(&first)); + assert!(!message.contains(&second)); + } + + #[test] + fn inheritance_adopts_unset_upstream_ca() { + let declared = endpoint("api.example.com", 443); + let mut merged = declared.clone(); + merged.upstream_ca_pem = "retained-ca".into(); + assert_eq!( + adopt_unset_retained_fields(&declared, &merged).upstream_ca_pem, + "retained-ca" + ); + } + #[test] fn add_rule_user_binary_clears_advisor_marker_for_same_path() { let mut policy = restrictive_default_policy(); diff --git a/crates/openshell-providers/src/profiles.rs b/crates/openshell-providers/src/profiles.rs index 9cdf2257ad..c51015f0ad 100644 --- a/crates/openshell-providers/src/profiles.rs +++ b/crates/openshell-providers/src/profiles.rs @@ -1431,6 +1431,7 @@ fn endpoint_to_proto(endpoint: &EndpointProfile) -> NetworkEndpoint { port: endpoint.port, protocol: endpoint.protocol.clone(), tls: endpoint.tls.clone(), + upstream_ca_pem: String::new(), enforcement: endpoint.enforcement.clone(), access: endpoint.access.clone(), rules: endpoint diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 054a3c34c6..b1fb3b2d2f 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -6355,6 +6355,7 @@ fn map_policy_merge_error(error: openshell_policy::PolicyMergeError) -> Status { } openshell_policy::PolicyMergeError::InvalidInputPolicy { .. } | openshell_policy::PolicyMergeError::McpContractConflict { .. } + | openshell_policy::PolicyMergeError::UpstreamCaConflict { .. } | openshell_policy::PolicyMergeError::NewBinaryWouldInheritAuthorization { .. } | openshell_policy::PolicyMergeError::ExistingBinariesWouldInheritAuthorization { .. diff --git a/crates/openshell-supervisor-network/data/sandbox-policy.rego b/crates/openshell-supervisor-network/data/sandbox-policy.rego index e3fa6d36b4..f3abcf2ffa 100644 --- a/crates/openshell-supervisor-network/data/sandbox-policy.rego +++ b/crates/openshell-supervisor-network/data/sandbox-policy.rego @@ -876,10 +876,11 @@ command_matches(actual, expected) if { upper(actual) == upper(expected) } -# --- Matched endpoint config (for L7 and allowed_ips extraction) --- +# --- Matched endpoint config (for L7, allowed_ips, and upstream_ca_pem extraction) --- # Returns the raw endpoint object for the matched policy + host:port. # Used by Rust to extract L7 config (protocol, tls, enforcement, -# allow_encoded_slash) and/or allowed_ips for SSRF allowlist validation. +# allow_encoded_slash), allowed_ips for SSRF validation, and upstream_ca_pem +# for endpoint-scoped upstream TLS verification. # Per-policy helper: returns matching endpoint configs for a single policy. _policy_endpoint_configs(policy) := [ep | @@ -1023,7 +1024,7 @@ endpoint_path_matches_request(ep, request) if { } # An endpoint has extended config if it specifies an L7 protocol, allowed_ips, -# or an explicit tls mode (e.g. tls: skip). Explicit protocol "tcp" is the +# upstream_ca_pem, or an explicit tls mode (e.g. tls: skip). Explicit protocol "tcp" is the # authored spelling of plain L4 behavior and does not select an L7 config. endpoint_has_extended_config(ep) if { protocol := object.get(ep, "protocol", "") @@ -1038,3 +1039,7 @@ endpoint_has_extended_config(ep) if { endpoint_has_extended_config(ep) if { ep.tls } + +endpoint_has_extended_config(ep) if { + ep.upstream_ca_pem +} diff --git a/crates/openshell-supervisor-network/src/l7/tls.rs b/crates/openshell-supervisor-network/src/l7/tls.rs index 943117620b..b4f6b5accd 100644 --- a/crates/openshell-supervisor-network/src/l7/tls.rs +++ b/crates/openshell-supervisor-network/src/l7/tls.rs @@ -139,6 +139,8 @@ impl CertCache { pub struct ProxyTlsState { cert_cache: CertCache, upstream_config: Arc, + upstream_roots: Option, + endpoint_configs: Mutex>>, } impl ProxyTlsState { @@ -147,9 +149,17 @@ impl ProxyTlsState { Self { cert_cache, upstream_config, + upstream_roots: None, + endpoint_configs: Mutex::new(HashMap::new()), } } + /// Attach the same system roots used by the default upstream config. + pub fn with_upstream_roots(mut self, system_ca_bundle: &str) -> Result { + self.upstream_roots = Some(build_upstream_root_store(system_ca_bundle)?); + Ok(self) + } + /// Get or generate a leaf cert for the hostname and return a TLS acceptor. fn acceptor_for(&self, hostname: &str) -> Result { let leaf = self.cert_cache.get_or_generate(hostname)?; @@ -165,6 +175,257 @@ impl ProxyTlsState { pub fn upstream_config(&self) -> &Arc { &self.upstream_config } + + /// Return an endpoint-only upstream verifier with system roots plus its CA. + /// The PEM content is the cache key, so changed policy content cannot reuse + /// an old verifier; the bounded cache avoids retaining removed policies. + pub fn endpoint_upstream_config(&self, pem: &str) -> Result> { + if pem.is_empty() { + return Ok(Arc::clone(&self.upstream_config)); + } + let mut cache = self + .endpoint_configs + .lock() + .map_err(|_| miette!("endpoint TLS config cache lock poisoned"))?; + if let Some(config) = cache.get(pem) { + return Ok(Arc::clone(config)); + } + let mut roots = self + .upstream_roots + .clone() + .ok_or_else(|| miette!("system upstream roots unavailable"))?; + let (added, ignored) = load_pem_certs_into_store(&mut roots, pem); + if added == 0 || ignored > 0 { + return Err(miette!( + "endpoint upstream CA contains no usable certificates or malformed certificates" + )); + } + let mut config = ClientConfig::builder() + .with_root_certificates(roots) + .with_no_client_auth(); + config.alpn_protocols = vec![b"http/1.1".to_vec()]; + let config = Arc::new(config); + if cache.len() >= MAX_CACHED_CERTS { + cache.clear(); + } + cache.insert(pem.to_string(), Arc::clone(&config)); + Ok(config) + } +} + +#[cfg(test)] +mod endpoint_ca_tests { + use super::*; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + fn client_config_with_test_ca(pem: &str) -> Arc { + let mut roots = rustls::RootCertStore::empty(); + assert_eq!(load_pem_certs_into_store(&mut roots, pem), (1, 0)); + let mut config = ClientConfig::builder() + .with_root_certificates(roots) + .with_no_client_auth(); + config.alpn_protocols = vec![b"http/1.1".to_vec()]; + Arc::new(config) + } + + #[tokio::test] + async fn endpoint_ca_trust_is_scoped_to_its_upstream_config() { + let upstream_ca = SandboxCa::generate().unwrap(); + #[cfg(feature = "bundled-ca-roots")] + let system_ca = SandboxCa::generate().unwrap(); + #[cfg(feature = "bundled-ca-roots")] + let system_pem = system_ca.cert_pem().to_string(); + #[cfg(not(feature = "bundled-ca-roots"))] + let system_pem = String::new(); + let server = Arc::new(ProxyTlsState::new( + CertCache::new(upstream_ca), + build_upstream_client_config("").unwrap(), + )); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let pem = server.cert_cache.ca.cert_pem().to_string(); + tokio::spawn(async move { + for _ in 0..2 { + let (stream, _) = listener.accept().await.unwrap(); + let server = Arc::clone(&server); + tokio::spawn(async move { + let _ = tls_terminate_client(stream, &server, "private.example.test").await; + }); + } + }); + let client = ProxyTlsState::new( + CertCache::new(SandboxCa::generate().unwrap()), + build_upstream_client_config(&system_pem).unwrap(), + ) + .with_upstream_roots(&system_pem) + .unwrap(); + let scoped = client.endpoint_upstream_config(&pem).unwrap(); + let stream = TcpStream::connect(address).await.unwrap(); + tls_connect_upstream(stream, "private.example.test", &scoped) + .await + .expect("endpoint CA should verify upstream"); + let stream = TcpStream::connect(address).await.unwrap(); + assert!( + tls_connect_upstream(stream, "private.example.test", client.upstream_config()) + .await + .is_err(), + "default upstream config must not trust endpoint CA" + ); + assert!(Arc::ptr_eq( + &scoped, + &client.endpoint_upstream_config(&pem).unwrap() + )); + assert!(!client.upstream_roots.as_ref().unwrap().roots.is_empty()); + + #[cfg(feature = "bundled-ca-roots")] + { + let system_server = Arc::new(ProxyTlsState::new( + CertCache::new(system_ca), + build_upstream_client_config("").unwrap(), + )); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + tokio::spawn(async move { + for _ in 0..2 { + let (stream, _) = listener.accept().await.unwrap(); + let _ = + tls_terminate_client(stream, &system_server, "system.example.test").await; + } + }); + let stream = TcpStream::connect(address).await.unwrap(); + tls_connect_upstream(stream, "system.example.test", client.upstream_config()) + .await + .expect("default config must retain system roots"); + let stream = TcpStream::connect(address).await.unwrap(); + tls_connect_upstream(stream, "system.example.test", &scoped) + .await + .expect("endpoint config must retain system roots"); + } + } + + #[tokio::test] + async fn endpoint_ca_keeps_tls_termination_and_credential_relay() { + use crate::l7::relay::{L7EvalContext, relay_passthrough_with_credentials}; + use crate::opa::OpaEngine; + use openshell_core::secrets::SecretResolver; + + let proxy_ca = SandboxCa::generate().unwrap(); + let proxy_pem = proxy_ca.cert_pem().to_string(); + let upstream_ca = SandboxCa::generate().unwrap(); + let upstream_pem = upstream_ca.cert_pem().to_string(); + let upstream_state = ProxyTlsState::new( + CertCache::new(upstream_ca), + build_upstream_client_config("").unwrap(), + ); + let upstream_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let upstream_addr = upstream_listener.local_addr().unwrap(); + let (captured_tx, captured_rx) = tokio::sync::oneshot::channel(); + tokio::spawn(async move { + let (socket, _) = upstream_listener.accept().await.unwrap(); + let mut tls = tls_terminate_client(socket, &upstream_state, "api.example.test") + .await + .unwrap(); + let mut request = Vec::new(); + while !request.windows(4).any(|bytes| bytes == b"\r\n\r\n") { + let mut buf = [0u8; 512]; + let n = tokio::time::timeout(std::time::Duration::from_secs(3), tls.read(&mut buf)) + .await + .unwrap() + .unwrap(); + assert!( + n > 0 && request.len() + n <= 2048, + "HTTP request headers incomplete or too large" + ); + request.extend_from_slice(&buf[..n]); + } + captured_tx + .send(String::from_utf8_lossy(&request).to_string()) + .unwrap(); + tls.write_all( + b"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ) + .await + .unwrap(); + tls.shutdown().await.unwrap(); + }); + + let (child_env, resolver) = SecretResolver::from_provider_env( + std::iter::once(("API_TOKEN".to_string(), "real-secret".to_string())).collect(), + ); + let placeholder = child_env.get("API_TOKEN").unwrap().clone(); + let proxy_state = ProxyTlsState::new( + CertCache::new(proxy_ca), + build_upstream_client_config("").unwrap(), + ) + .with_upstream_roots("") + .unwrap(); + let proxy_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let proxy_addr = proxy_listener.local_addr().unwrap(); + let proxy_task = tokio::spawn(async move { + let (client, _) = proxy_listener.accept().await.unwrap(); + let mut client_tls = tls_terminate_client(client, &proxy_state, "api.example.test") + .await + .unwrap(); + let upstream = TcpStream::connect(upstream_addr).await.unwrap(); + let config = proxy_state.endpoint_upstream_config(&upstream_pem).unwrap(); + let mut upstream_tls = tls_connect_upstream(upstream, "api.example.test", &config) + .await + .unwrap(); + let engine = OpaEngine::from_strings( + include_str!("../../data/sandbox-policy.rego"), + "network_policies: {}\n", + ) + .unwrap(); + let guard = engine + .generation_guard(engine.current_generation()) + .unwrap(); + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 443, + request_default_port: Some(443), + secret_resolver: resolver.map(Arc::new), + ..Default::default() + }; + relay_passthrough_with_credentials( + &mut client_tls, + &mut upstream_tls, + &ctx, + &guard, + None, + ) + .await + .unwrap(); + }); + let client_config = client_config_with_test_ca(&proxy_pem); + let socket = TcpStream::connect(proxy_addr).await.unwrap(); + let mut client_tls = tls_connect_upstream(socket, "api.example.test", &client_config) + .await + .unwrap(); + client_tls.write_all(format!("GET / HTTP/1.1\r\nHost: api.example.test\r\nAuthorization: Bearer {placeholder}\r\nConnection: close\r\n\r\n").as_bytes()).await.unwrap(); + let request = tokio::time::timeout(std::time::Duration::from_secs(3), captured_rx) + .await + .unwrap() + .unwrap(); + assert!( + request.contains("Authorization: Bearer real-secret"), + "upstream received: {request:?}" + ); + assert!(!request.contains(&placeholder)); + let mut response = [0u8; 256]; + let n = tokio::time::timeout( + std::time::Duration::from_secs(3), + client_tls.read(&mut response), + ) + .await + .unwrap() + .unwrap(); + assert!(String::from_utf8_lossy(&response[..n]).starts_with("HTTP/1.1 204")); + drop(client_tls); + tokio::time::timeout(std::time::Duration::from_secs(3), proxy_task) + .await + .unwrap() + .unwrap(); + } } /// Accept TLS from a sandbox client, presenting a dynamic cert for the hostname. diff --git a/crates/openshell-supervisor-network/src/opa.rs b/crates/openshell-supervisor-network/src/opa.rs index 98632686e9..88b4a5e4ec 100644 --- a/crates/openshell-supervisor-network/src/opa.rs +++ b/crates/openshell-supervisor-network/src/opa.rs @@ -1955,6 +1955,9 @@ fn proto_to_opa_data_json(proto: &ProtoSandboxPolicy, entrypoint_pid: u32) -> St if !e.tls.is_empty() { ep["tls"] = e.tls.clone().into(); } + if !e.upstream_ca_pem.is_empty() { + ep["upstream_ca_pem"] = e.upstream_ca_pem.clone().into(); + } if !e.enforcement.is_empty() { ep["enforcement"] = e.enforcement.clone().into(); } @@ -4960,6 +4963,35 @@ network_policies: assert_eq!(l7.enforcement, crate::l7::EnforcementMode::Enforce); } + #[test] + fn endpoint_ca_survives_proto_to_opa_selection_without_l7_protocol() { + let mut policy = test_proto(); + let ca_pem = crate::l7::tls::SandboxCa::generate() + .unwrap() + .cert_pem() + .to_string(); + let endpoint = &mut policy + .network_policies + .get_mut("claude_code") + .unwrap() + .endpoints[0]; + endpoint.upstream_ca_pem = ca_pem.clone(); + let engine = OpaEngine::from_proto(&policy).unwrap(); + let input = NetworkInput { + host: "api.anthropic.com".into(), + port: 443, + binary_path: PathBuf::from("/usr/local/bin/claude"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + let config = engine.query_endpoint_config(&input).unwrap().unwrap(); + assert_eq!( + get_str(&config, "upstream_ca_pem").as_deref(), + Some(ca_pem.as_str()) + ); + } + #[test] fn explicit_tcp_authorizes_as_l4_without_endpoint_config() { let engine = l7_engine(); diff --git a/crates/openshell-supervisor-network/src/policy_local.rs b/crates/openshell-supervisor-network/src/policy_local.rs index 520a22adba..2a6b04ec60 100644 --- a/crates/openshell-supervisor-network/src/policy_local.rs +++ b/crates/openshell-supervisor-network/src/policy_local.rs @@ -1199,6 +1199,7 @@ fn network_endpoint_from_json( port, protocol: endpoint.protocol, tls: endpoint.tls, + upstream_ca_pem: String::new(), enforcement: endpoint.enforcement, access: endpoint.access, rules, diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index 7df34f9149..49e42f6553 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -2219,8 +2219,24 @@ async fn handle_tcp_connection( let tls_result = async { let mut tls_client = crate::l7::tls::tls_terminate_client(client, tls, &host_lc).await?; + let endpoint_ca = decision + .endpoint + .policy_configs + .first() + .and_then(|config| match config { + regorus::Value::Object(fields) => { + fields.get(®orus::Value::String("upstream_ca_pem".into())) + } + _ => None, + }) + .and_then(|value| match value { + regorus::Value::String(value) => Some(value.as_ref()), + _ => None, + }) + .unwrap_or(""); + let upstream_config = tls.endpoint_upstream_config(endpoint_ca)?; let mut tls_upstream = - crate::l7::tls::tls_connect_upstream(upstream, &host_lc, tls.upstream_config()) + crate::l7::tls::tls_connect_upstream(upstream, &host_lc, &upstream_config) .await?; let Some(relay_context) = relay::prepare_http_relay(l7_route, &opa_engine, &decision, &ctx) diff --git a/crates/openshell-supervisor-network/src/run.rs b/crates/openshell-supervisor-network/src/run.rs index f6a38025c4..bb34aea6d2 100644 --- a/crates/openshell-supervisor-network/src/run.rs +++ b/crates/openshell-supervisor-network/src/run.rs @@ -350,7 +350,10 @@ pub async fn run_networking( let upstream_config = build_upstream_client_config(&system_ca_bundle)?; let cert_cache = CertCache::new(ca); - let state = Arc::new(ProxyTlsState::new(cert_cache, upstream_config)); + let state = Arc::new( + ProxyTlsState::new(cert_cache, upstream_config) + .with_upstream_roots(&system_ca_bundle)?, + ); ocsf_emit!( ConfigStateChangeBuilder::new(ocsf_ctx()) .severity(SeverityId::Informational) diff --git a/docs/reference/policy-schema.mdx b/docs/reference/policy-schema.mdx index 29eafa60de..679c44f85b 100644 --- a/docs/reference/policy-schema.mdx +++ b/docs/reference/policy-schema.mdx @@ -165,6 +165,7 @@ Each endpoint defines a reachable destination and optional inspection rules. | `path` | string | No | Optional HTTP path glob used to select between L7 endpoints that share the same host and port. Empty means all paths. Use this when REST and GraphQL live under the same host, such as `/repos/**` and `/graphql`. | | `protocol` | string | No | Set to `tcp` with a valid DNS hostname to allow native TCP clients through policy DNS and transparent capture without payload inspection. Omit the field for L4 passthrough through an explicit proxy, including legacy hostless `allowed_ips` endpoints. Set to `rest` for HTTP method/path inspection, `websocket` for RFC 6455 upgrade and client text-message inspection, `graphql` for GraphQL-over-HTTP operation inspection, `mcp` for MCP Streamable HTTP request inspection, or `json-rpc` for generic JSON-RPC-over-HTTP method inspection. WebSocket endpoints can also use GraphQL operation rules for GraphQL-over-WebSocket traffic. Provider-credentialed endpoints require an inspected protocol unless `allow_uninspected_credentials` is explicitly set. | | `tls` | string | No | TLS handling mode. The proxy auto-detects TLS by peeking the first bytes of each connection and terminates it for inspected HTTPS traffic, so this field is optional in most cases. Set to `skip` to disable auto-detection for edge cases such as client-certificate mTLS or non-standard protocols. Provider-credentialed endpoints reject `tls: skip` unless `allow_uninspected_credentials` is explicitly set. The values `terminate` and `passthrough` are deprecated and log a warning; they are still accepted for backward compatibility but have no effect on behavior. | +| `upstream_ca_pem` | string | No | PEM-encoded CA certificate bundle trusted only for the supervisor's TLS connection to this endpoint. Use a YAML block scalar containing one or more `-----BEGIN CERTIFICATE-----` blocks. The supervisor adds these certificates to its normal system roots for this endpoint only; it still terminates client TLS, inspects requests, and rewrites credentials. Cannot be combined with `tls: skip` or `protocol: tcp`. Do not include private keys. | | `enforcement` | string | No | `enforce` actively blocks disallowed requests. `audit` logs violations but allows traffic through. | | `access` | string | No | Access preset. One of `read-only`, `read-write`, or `full`. Mutually exclusive with `rules`. Not valid on `protocol: mcp` or `protocol: json-rpc`; MCP uses explicit rules unless `mcp.allow_all_known_mcp_methods: true` enables the endpoint method profile, and JSON-RPC always uses explicit rules. | | `rules` | list of allow rule objects | No | Fine-grained protocol-specific allow rules. Mutually exclusive with `access`. | diff --git a/proto/sandbox.proto b/proto/sandbox.proto index c2b61d0b3a..aeba688fc9 100644 --- a/proto/sandbox.proto +++ b/proto/sandbox.proto @@ -112,7 +112,7 @@ message NetworkEndpoint { // Endpoint protocol. "tcp" and "" select L4-only handling; "rest", // "websocket", "graphql", "sql", "json-rpc", and "mcp" select L7 inspection. string protocol = 3; - // TLS handling: "terminate" or "passthrough" (default). + // TLS handling: "auto" (default) or "skip" (raw tunnel). string tls = 4; // Enforcement mode: "enforce" or "audit" (default). string enforcement = 5; @@ -194,6 +194,9 @@ message NetworkEndpoint { // Internal gateway-derived marker indicating that this endpoint belongs to // an attached credentialed provider. User-authored values are ignored. bool provider_credentialed = 26; + // Additional PEM-encoded CA certificates trusted only when the supervisor + // re-encrypts TLS to this endpoint. Does not disable TLS inspection. + string upstream_ca_pem = 27; } // MCP options are grouped so MCP-specific policy can grow without adding more diff --git a/sdk/go/openshell/v1/internal/converter/coverage_test.go b/sdk/go/openshell/v1/internal/converter/coverage_test.go index 16929f672c..32b34eade3 100644 --- a/sdk/go/openshell/v1/internal/converter/coverage_test.go +++ b/sdk/go/openshell/v1/internal/converter/coverage_test.go @@ -180,6 +180,7 @@ func TestConverterCoversAllProtoFields_NetworkEndpoint(t *testing.T) { "ports": true, "protocol": true, "tls": true, + "upstream_ca_pem": true, "enforcement": true, "access": true, "rules": true, diff --git a/sdk/go/openshell/v1/internal/converter/network_policy.go b/sdk/go/openshell/v1/internal/converter/network_policy.go index 2451f6f426..f45d975772 100644 --- a/sdk/go/openshell/v1/internal/converter/network_policy.go +++ b/sdk/go/openshell/v1/internal/converter/network_policy.go @@ -68,6 +68,7 @@ func policyNetworkEndpointFromProto(ep *sbv1.NetworkEndpoint) types.PolicyNetwor Port: ep.GetPort(), Protocol: ep.GetProtocol(), TLS: ep.GetTls(), + UpstreamCAPEM: ep.GetUpstreamCaPem(), Enforcement: ep.GetEnforcement(), Access: ep.GetAccess(), AllowEncodedSlash: ep.GetAllowEncodedSlash(), @@ -130,6 +131,7 @@ func policyNetworkEndpointToProto(ep *types.PolicyNetworkEndpoint) *sbv1.Network Port: ep.Port, Protocol: ep.Protocol, Tls: ep.TLS, + UpstreamCaPem: ep.UpstreamCAPEM, Enforcement: ep.Enforcement, Access: ep.Access, AllowEncodedSlash: ep.AllowEncodedSlash, diff --git a/sdk/go/openshell/v1/internal/converter/network_policy_test.go b/sdk/go/openshell/v1/internal/converter/network_policy_test.go index 5f83a82645..0b93b9b89b 100644 --- a/sdk/go/openshell/v1/internal/converter/network_policy_test.go +++ b/sdk/go/openshell/v1/internal/converter/network_policy_test.go @@ -23,6 +23,7 @@ func TestNetworkPolicyRuleFromProto(t *testing.T) { Port: 443, Protocol: "rest", Tls: "strict", + UpstreamCaPem: "test-ca-pem", Enforcement: "enforce", Access: "allow", Ports: []uint32{80, 443}, @@ -102,6 +103,7 @@ func TestNetworkPolicyRuleFromProto(t *testing.T) { assert.Equal(t, uint32(443), ep.Port) assert.Equal(t, "rest", ep.Protocol) assert.Equal(t, "strict", ep.TLS) + assert.Equal(t, "test-ca-pem", ep.UpstreamCAPEM) assert.Equal(t, "enforce", ep.Enforcement) assert.Equal(t, "allow", ep.Access) assert.Equal(t, []uint32{80, 443}, ep.Ports) @@ -182,6 +184,7 @@ func TestNetworkPolicyRuleRoundTrip(t *testing.T) { Port: 8080, Protocol: "graphql", TLS: "permissive", + UpstreamCAPEM: "roundtrip-ca-pem", Enforcement: "audit", Access: "allow", Ports: []uint32{8080, 8443}, @@ -257,6 +260,7 @@ func TestNetworkPolicyRuleRoundTrip(t *testing.T) { assert.Equal(t, original.Endpoints[0].Port, roundTrip.Endpoints[0].Port) assert.Equal(t, original.Endpoints[0].Protocol, roundTrip.Endpoints[0].Protocol) assert.Equal(t, original.Endpoints[0].TLS, roundTrip.Endpoints[0].TLS) + assert.Equal(t, original.Endpoints[0].UpstreamCAPEM, roundTrip.Endpoints[0].UpstreamCAPEM) assert.Equal(t, original.Endpoints[0].Enforcement, roundTrip.Endpoints[0].Enforcement) assert.Equal(t, original.Endpoints[0].Access, roundTrip.Endpoints[0].Access) assert.Equal(t, original.Endpoints[0].Ports, roundTrip.Endpoints[0].Ports) diff --git a/sdk/go/openshell/v1/types/network_policy.go b/sdk/go/openshell/v1/types/network_policy.go index 69e44e1242..f0731b23e7 100644 --- a/sdk/go/openshell/v1/types/network_policy.go +++ b/sdk/go/openshell/v1/types/network_policy.go @@ -17,11 +17,13 @@ type NetworkPolicyRule struct { // as used in sandbox network policy rules. This is distinct from [NetworkEndpoint] // which is the simplified profile-level endpoint (Host, Port, Protocol only). type PolicyNetworkEndpoint struct { - Host string - Port uint32 - Ports []uint32 - Protocol string - TLS string + Host string + Port uint32 + Ports []uint32 + Protocol string + TLS string + // UpstreamCAPEM adds trust anchors only for this endpoint's upstream TLS connection. + UpstreamCAPEM string Enforcement string Access string Rules []L7Rule diff --git a/sdk/go/proto/sandboxv1/sandbox.pb.go b/sdk/go/proto/sandboxv1/sandbox.pb.go index 989589002b..7d62b58f7b 100644 --- a/sdk/go/proto/sandboxv1/sandbox.pb.go +++ b/sdk/go/proto/sandboxv1/sandbox.pb.go @@ -655,7 +655,7 @@ type NetworkEndpoint struct { // Endpoint protocol. "tcp" and "" select L4-only handling; "rest", // "websocket", "graphql", "sql", "json-rpc", and "mcp" select L7 inspection. Protocol string `protobuf:"bytes,3,opt,name=protocol,proto3" json:"protocol,omitempty"` - // TLS handling: "terminate" or "passthrough" (default). + // TLS handling: "auto" (default) or "skip" (raw tunnel). Tls string `protobuf:"bytes,4,opt,name=tls,proto3" json:"tls,omitempty"` // Enforcement mode: "enforce" or "audit" (default). Enforcement string `protobuf:"bytes,5,opt,name=enforcement,proto3" json:"enforcement,omitempty"` @@ -738,8 +738,11 @@ type NetworkEndpoint struct { // Internal gateway-derived marker indicating that this endpoint belongs to // an attached credentialed provider. User-authored values are ignored. ProviderCredentialed bool `protobuf:"varint,26,opt,name=provider_credentialed,json=providerCredentialed,proto3" json:"provider_credentialed,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Additional PEM-encoded CA certificates trusted only when the supervisor + // re-encrypts TLS to this endpoint. Does not disable TLS inspection. + UpstreamCaPem string `protobuf:"bytes,27,opt,name=upstream_ca_pem,json=upstreamCaPem,proto3" json:"upstream_ca_pem,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *NetworkEndpoint) Reset() { @@ -954,6 +957,13 @@ func (x *NetworkEndpoint) GetProviderCredentialed() bool { return false } +func (x *NetworkEndpoint) GetUpstreamCaPem() string { + if x != nil { + return x.UpstreamCaPem + } + return "" +} + // MCP options are grouped so MCP-specific policy can grow without adding more // top-level NetworkEndpoint fields. OpenShell owns the supported revision // profiles instead of treating dependency enums as the policy contract. @@ -2113,8 +2123,7 @@ const file_sandbox_proto_rawDesc = "" + "\ainclude\x18\x01 \x03(\tR\ainclude\x12\x18\n" + "\aexclude\x18\x02 \x03(\tR\aexclude\"6\n" + "\x18NetworkCredentialBinding\x12\x1a\n" + - "\bprovider\x18\x01 \x01(\tR\bprovider\"\xdc\n" + - "\n" + + "\bprovider\x18\x01 \x01(\tR\bprovider\"\x84\v\n" + "\x0fNetworkEndpoint\x12\x12\n" + "\x04host\x18\x01 \x01(\tR\x04host\x12\x12\n" + "\x04port\x18\x02 \x01(\rR\x04port\x12\x1a\n" + @@ -2144,7 +2153,8 @@ const file_sandbox_proto_rawDesc = "" + "\x03mcp\x18\x17 \x01(\v2 .openshell.sandbox.v1.McpOptionsR\x03mcp\x12]\n" + "\x12credential_binding\x18\x18 \x01(\v2..openshell.sandbox.v1.NetworkCredentialBindingR\x11credentialBinding\x12B\n" + "\x1dallow_uninspected_credentials\x18\x19 \x01(\bR\x1ballowUninspectedCredentials\x123\n" + - "\x15provider_credentialed\x18\x1a \x01(\bR\x14providerCredentialed\x1ar\n" + + "\x15provider_credentialed\x18\x1a \x01(\bR\x14providerCredentialed\x12&\n" + + "\x0fupstream_ca_pem\x18\x1b \x01(\tR\rupstreamCaPem\x1ar\n" + "\x1cGraphqlPersistedQueriesEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12<\n" + "\x05value\x18\x02 \x01(\v2&.openshell.sandbox.v1.GraphqlOperationR\x05value:\x028\x01\"\xd2\x01\n" + From 2db194bf237bd6967e11151c57ddddd810615a81 Mon Sep 17 00:00:00 2001 From: craig Date: Fri, 2 Oct 2026 17:56:39 -0700 Subject: [PATCH 2/7] feat(supervisor): route policy-approved egress through appliance tunnel Signed-off-by: craig --- Cargo.lock | 316 ++++- ...-supervisor-terminated-appliance-tunnel.md | 19 + architecture/sandbox.md | 14 + crates/openshell-core/src/gateway_channels.rs | 3 + .../src/provider_credentials.rs | 117 +- crates/openshell-core/src/secrets.rs | 16 + crates/openshell-policy/Cargo.toml | 2 + crates/openshell-policy/src/l7_validate.rs | 3 +- crates/openshell-policy/src/lib.rs | 236 +++- crates/openshell-policy/src/merge.rs | 26 + crates/openshell-providers/src/profiles.rs | 1 + crates/openshell-sandbox/src/lib.rs | 28 +- crates/openshell-server/src/grpc/policy.rs | 1 + .../openshell-supervisor-network/Cargo.toml | 1 + .../data/sandbox-policy.rego | 11 + .../src/l7/rest.rs | 2 +- .../openshell-supervisor-network/src/lib.rs | 1 + .../openshell-supervisor-network/src/opa.rs | 109 ++ .../src/policy_local.rs | 48 +- .../openshell-supervisor-network/src/proxy.rs | 419 +++++- .../src/proxy/destination.rs | 44 +- .../openshell-supervisor-network/src/run.rs | 23 + .../src/tunnel.rs | 496 +++++++ .../src/upstream_proxy.rs | 14 + docs/reference/policy-schema.mdx | 49 +- proto/sandbox.proto | 17 + vendor/tokio-wireguard/.cargo_vcs_info.json | 6 + vendor/tokio-wireguard/Cargo.lock | 1141 +++++++++++++++++ vendor/tokio-wireguard/Cargo.toml | 102 ++ vendor/tokio-wireguard/Cargo.toml.orig | 48 + vendor/tokio-wireguard/LICENSE-Apache-2.0 | 202 +++ vendor/tokio-wireguard/LICENSE-MIT | 19 + vendor/tokio-wireguard/README.md | 6 + vendor/tokio-wireguard/examples/tcp.rs | 72 ++ vendor/tokio-wireguard/examples/udp.rs | 73 ++ vendor/tokio-wireguard/src/config.rs | 271 ++++ vendor/tokio-wireguard/src/interface.rs | 528 ++++++++ .../src/interface/allocations.rs | 158 +++ .../tokio-wireguard/src/interface/device.rs | 131 ++ .../tokio-wireguard/src/interface/random.rs | 85 ++ .../tokio-wireguard/src/interface/sockets.rs | 149 +++ .../tokio-wireguard/src/interface/tunnel.rs | 278 ++++ vendor/tokio-wireguard/src/io.rs | 274 ++++ vendor/tokio-wireguard/src/lib.rs | 79 ++ vendor/tokio-wireguard/src/tcp.rs | 763 +++++++++++ vendor/tokio-wireguard/src/udp.rs | 267 ++++ vendor/tokio-wireguard/src/x25519.rs | 10 + 47 files changed, 6576 insertions(+), 102 deletions(-) create mode 100644 architecture/adr/0001-supervisor-terminated-appliance-tunnel.md create mode 100644 crates/openshell-supervisor-network/src/tunnel.rs create mode 100644 vendor/tokio-wireguard/.cargo_vcs_info.json create mode 100644 vendor/tokio-wireguard/Cargo.lock create mode 100644 vendor/tokio-wireguard/Cargo.toml create mode 100644 vendor/tokio-wireguard/Cargo.toml.orig create mode 100644 vendor/tokio-wireguard/LICENSE-Apache-2.0 create mode 100644 vendor/tokio-wireguard/LICENSE-MIT create mode 100644 vendor/tokio-wireguard/README.md create mode 100644 vendor/tokio-wireguard/examples/tcp.rs create mode 100644 vendor/tokio-wireguard/examples/udp.rs create mode 100644 vendor/tokio-wireguard/src/config.rs create mode 100644 vendor/tokio-wireguard/src/interface.rs create mode 100644 vendor/tokio-wireguard/src/interface/allocations.rs create mode 100644 vendor/tokio-wireguard/src/interface/device.rs create mode 100644 vendor/tokio-wireguard/src/interface/random.rs create mode 100644 vendor/tokio-wireguard/src/interface/sockets.rs create mode 100644 vendor/tokio-wireguard/src/interface/tunnel.rs create mode 100644 vendor/tokio-wireguard/src/io.rs create mode 100644 vendor/tokio-wireguard/src/lib.rs create mode 100644 vendor/tokio-wireguard/src/tcp.rs create mode 100644 vendor/tokio-wireguard/src/udp.rs create mode 100644 vendor/tokio-wireguard/src/x25519.rs diff --git a/Cargo.lock b/Cargo.lock index fdd150c96a..55b953ae5f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common 0.1.7", + "generic-array 0.14.7", +] + [[package]] name = "aead" version = "0.6.1" @@ -24,7 +34,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99" dependencies = [ "crypto-common 0.2.2", - "inout", + "inout 0.2.2", ] [[package]] @@ -33,7 +43,7 @@ version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8eb277bec05f56a0e0591f155a484cbd0f4f07ff2905051a48c72f004f7ed58" dependencies = [ - "cipher", + "cipher 0.5.2", "cpubits", "cpufeatures 0.3.0", "zeroize", @@ -45,9 +55,9 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdf011db2e21ce0d575593d749db5554b47fed37aff429e4dc50bc91ac93a028" dependencies = [ - "aead", + "aead 0.6.1", "aes", - "cipher", + "cipher 0.5.2", "ctr", "ghash", "subtle", @@ -174,7 +184,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7af50940b73bf4e16c15c448a2b121c63f2d68e3e54b6a8731673cb4aa0cdff5" dependencies = [ "base64ct", - "blake2", + "blake2 0.11.0-rc.6", "cpufeatures 0.3.0", "password-hash", ] @@ -779,6 +789,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest 0.10.7", +] + [[package]] name = "blake2" version = "0.11.0-rc.6" @@ -823,7 +842,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "62ce3946557b35e71d1bbe07ec385073ce9eda05043f95de134eb578fcf1a298" dependencies = [ "byteorder", - "cipher", + "cipher 0.5.2", ] [[package]] @@ -870,6 +889,31 @@ dependencies = [ "serde_repr", ] +[[package]] +name = "boringtun" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15dd6a8a89cbe8997f37ca0cf035e6ea4d64cd2ecea4aed83ffb9f99f7126939" +dependencies = [ + "aead 0.5.2", + "base64", + "blake2 0.10.6", + "chacha20poly1305", + "hex", + "hmac 0.12.1", + "ip_network", + "ip_network_table", + "libc", + "nix 0.31.3", + "parking_lot", + "portable-atomic", + "rand_core 0.6.4", + "ring", + "tracing", + "untrusted 0.9.0", + "x25519-dalek", +] + [[package]] name = "bstr" version = "1.12.1" @@ -940,7 +984,7 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" dependencies = [ - "cipher", + "cipher 0.5.2", ] [[package]] @@ -973,6 +1017,17 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher 0.4.4", + "cpufeatures 0.2.17", +] + [[package]] name = "chacha20" version = "0.10.1" @@ -980,12 +1035,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" dependencies = [ "cfg-if", - "cipher", + "cipher 0.5.2", "cpufeatures 0.3.0", "rand_core 0.10.1", "zeroize", ] +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead 0.5.2", + "chacha20 0.9.1", + "cipher 0.4.4", + "poly1305 0.8.0", + "zeroize", +] + [[package]] name = "chrono" version = "0.4.44" @@ -1000,6 +1068,17 @@ dependencies = [ "windows-link", ] +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout 0.1.4", + "zeroize", +] + [[package]] name = "cipher" version = "0.5.2" @@ -1008,7 +1087,7 @@ checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" dependencies = [ "block-buffer 0.12.0", "crypto-common 0.2.2", - "inout", + "inout 0.2.2", "zeroize", ] @@ -1349,6 +1428,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array 0.14.7", + "rand_core 0.6.4", "typenum", ] @@ -1379,7 +1459,7 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21" dependencies = [ - "cipher", + "cipher 0.5.2", ] [[package]] @@ -1495,6 +1575,46 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b" +[[package]] +name = "defmt" +version = "0.3.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0963443817029b2024136fc4dd07a5107eb8f977eaf18fcd1fdeb11306b64ad" +dependencies = [ + "defmt 1.1.1", +] + +[[package]] +name = "defmt" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "defmt-parser" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +dependencies = [ + "thiserror 2.0.18", +] + [[package]] name = "delegate" version = "0.13.5" @@ -1588,7 +1708,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "916a94e407b54f9034d71dd748234cd1e516ced6284009906ae246f177eafe5a" dependencies = [ - "cipher", + "cipher 0.5.2", ] [[package]] @@ -2289,6 +2409,15 @@ dependencies = [ "tracing", ] +[[package]] +name = "hash32" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606" +dependencies = [ + "byteorder", +] + [[package]] name = "hashbrown" version = "0.14.5" @@ -2356,6 +2485,16 @@ dependencies = [ "http 1.4.0", ] +[[package]] +name = "heapless" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad" +dependencies = [ + "hash32", + "stable_deref_trait", +] + [[package]] name = "heck" version = "0.5.0" @@ -2646,7 +2785,7 @@ dependencies = [ "libc", "percent-encoding", "pin-project-lite", - "socket2", + "socket2 0.6.3", "tokio", "tower-service", "tracing", @@ -2870,6 +3009,15 @@ dependencies = [ "libc", ] +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array 0.14.7", +] + [[package]] name = "inout" version = "0.2.2" @@ -2892,6 +3040,28 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "ip_network" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa2f047c0a98b2f299aa5d6d7088443570faae494e9ae1305e48be000c9e0eb1" + +[[package]] +name = "ip_network_table" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4099b7cfc5c5e2fe8c5edf3f6f7adf7a714c9cc697534f63a5a5da30397cb2c0" +dependencies = [ + "ip_network", + "ip_network_table-deps-treebitmap", +] + +[[package]] +name = "ip_network_table-deps-treebitmap" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e537132deb99c0eb4b752f0346b6a836200eaaa3516dd7e5514b63930a09e5d" + [[package]] name = "ipnet" version = "2.12.0" @@ -3425,6 +3595,12 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" +[[package]] +name = "managed" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ca88d725a0a943b096803bd34e73a4437208b6077654cc4ecb2947a5f91618d" + [[package]] name = "matchers" version = "0.2.0" @@ -3896,6 +4072,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + [[package]] name = "openshell-bootstrap" version = "0.0.0" @@ -4353,7 +4535,9 @@ dependencies = [ name = "openshell-policy" version = "0.0.0" dependencies = [ + "base64", "hickory-proto", + "ipnet", "miette", "noyalib", "openshell-core", @@ -4535,7 +4719,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.10.9", - "socket2", + "socket2 0.6.3", "spiffe", "sqlx", "sqlx-core", @@ -4644,6 +4828,7 @@ dependencies = [ "tokio-rustls", "tokio-stream", "tokio-tungstenite 0.26.2", + "tokio-wireguard", "tonic", "tower-mcp-types", "tracing", @@ -4675,7 +4860,7 @@ dependencies = [ "seccompiler", "serde_json", "sha2 0.10.9", - "socket2", + "socket2 0.6.3", "tempfile", "tokio", "tokio-stream", @@ -5188,6 +5373,17 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash 0.5.1", +] + [[package]] name = "poly1305" version = "0.9.1" @@ -5195,7 +5391,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c" dependencies = [ "cpufeatures 0.3.0", - "universal-hash", + "universal-hash 0.6.1", "zeroize", ] @@ -5207,7 +5403,7 @@ checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd" dependencies = [ "cpubits", "cpufeatures 0.3.0", - "universal-hash", + "universal-hash 0.6.1", ] [[package]] @@ -5495,7 +5691,7 @@ dependencies = [ "quinn-udp", "rustc-hash 2.1.2", "rustls", - "socket2", + "socket2 0.6.3", "thiserror 2.0.18", "tokio", "tracing", @@ -5534,7 +5730,7 @@ dependencies = [ "cfg_aliases", "libc", "once_cell", - "socket2", + "socket2 0.6.3", "tracing", "windows-sys 0.60.2", ] @@ -5587,7 +5783,7 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" dependencies = [ - "chacha20", + "chacha20 0.10.1", "getrandom 0.4.2", "rand_core 0.10.1", ] @@ -5946,7 +6142,7 @@ dependencies = [ "byteorder", "bytes", "cbc", - "cipher", + "cipher 0.5.2", "crypto-bigint 0.7.5", "ctr", "curve25519-dalek 5.0.0", @@ -5965,7 +6161,7 @@ dependencies = [ "ghash", "hex-literal", "hmac 0.13.0", - "inout", + "inout 0.2.2", "internal-russh-num-bigint", "keccak", "log", @@ -6001,7 +6197,7 @@ dependencies = [ "thiserror 2.0.18", "tokio", "typenum", - "universal-hash", + "universal-hash 0.6.1", "zeroize", ] @@ -6195,7 +6391,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f874456e72520ff1375a06c588eaf074b0f01f9e9e1aada45bd9b7954a6e42c" dependencies = [ "cfg-if", - "cipher", + "cipher 0.5.2", ] [[package]] @@ -6662,6 +6858,30 @@ dependencies = [ "serde", ] +[[package]] +name = "smoltcp" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a1a996951e50b5971a2c8c0fa05a381480d70a933064245c4a223ddc87ccc97" +dependencies = [ + "bitflags 1.3.2", + "byteorder", + "cfg-if", + "defmt 0.3.100", + "heapless", + "managed", +] + +[[package]] +name = "socket2" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + [[package]] name = "socket2" version = "0.6.3" @@ -6915,14 +7135,14 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d801accda99469cde6d73da741422610fdf6508a72d9a69d1b55cb241c720597" dependencies = [ - "aead", + "aead 0.6.1", "aes", "aes-gcm", - "chacha20", - "cipher", + "chacha20 0.10.1", + "cipher 0.5.2", "ctutils", "des", - "poly1305", + "poly1305 0.9.1", "ssh-encoding", "zeroize", ] @@ -7324,7 +7544,7 @@ dependencies = [ "parking_lot", "pin-project-lite", "signal-hook-registry", - "socket2", + "socket2 0.6.3", "tokio-macros", "windows-sys 0.61.2", ] @@ -7403,6 +7623,22 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-wireguard" +version = "0.1.3" +dependencies = [ + "atomic-waker", + "boringtun", + "bytes", + "ipnet", + "parking_lot", + "pin-project-lite", + "rand 0.8.6", + "smoltcp", + "socket2 0.5.10", + "tokio", +] + [[package]] name = "toml" version = "0.8.23" @@ -7464,7 +7700,7 @@ dependencies = [ "percent-encoding", "pin-project", "rustls-native-certs", - "socket2", + "socket2 0.6.3", "sync_wrapper", "tokio", "tokio-rustls", @@ -7820,6 +8056,16 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common 0.1.7", + "subtle", +] + [[package]] name = "universal-hash" version = "0.6.1" @@ -8690,6 +8936,18 @@ version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" +[[package]] +name = "x25519-dalek" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" +dependencies = [ + "curve25519-dalek 4.1.3", + "rand_core 0.6.4", + "serde", + "zeroize", +] + [[package]] name = "x509-parser" version = "0.16.0" diff --git a/architecture/adr/0001-supervisor-terminated-appliance-tunnel.md b/architecture/adr/0001-supervisor-terminated-appliance-tunnel.md new file mode 100644 index 0000000000..4d674d6652 --- /dev/null +++ b/architecture/adr/0001-supervisor-terminated-appliance-tunnel.md @@ -0,0 +1,19 @@ +# 1. Supervisor-terminated customer appliance tunnel + +Date: 2026-10-02 + +Status: Proposed + +## Context + +Customer private services require a route from a sandbox to a customer appliance. A tunnel inside the workload would let decrypted packets leave the supervisor's policy point. A shared cluster exit would also couple customer routes and keys across sandboxes. The supervisor already authorizes explicit proxy destinations, inspects supported application traffic, and rewrites endpoint-bound credentials. + +## Decision + +Each sandbox supervisor owns its own userspace WireGuard interface and TCP stack. Its policy names the appliance's exact UDP endpoint and an inner destination endpoint that references the tunnel. The appliance endpoint is a supervisor-only transport exception; workload TCP cannot use it. The inner host and port remain ordinary policy objects. Destination validation and applicable L7 and credential handling stay in the existing proxy path, with the tunnel replacing only the final upstream TCP transport. A failed tunnel has no direct or corporate-proxy fallback. + +The policy carries a reference to a sandbox-scoped provider credential containing the private key. The supervisor suppresses that environment key before workload startup and resolves it only in its own credential state. Key bytes do not enter policy persistence, policy introspection, or the workload environment. The first implementation accepts one named tunnel, one IPv4 literal destination and port, and one route bound to the initial policy generation. A later policy generation refuses tunnel dials until sandbox restart. + +## Consequences + +The supervisor remains the enforcement point for inner destinations. Tunnel keys and decrypted packets stay outside the workload. The appliance must expose a reachable WireGuard UDP listener and trust the supervisor peer key and tunnel source address. CONNECT establishes the upstream TCP stream after endpoint and address authorization, before its existing TLS and L7 request inspection; stricter pre-dial application authorization would require a separate CONNECT flow change. Tunnel DNS, hot reload and key rotation, multiple routes, IPv6, and alternate TCP carriers remain future work. diff --git a/architecture/sandbox.md b/architecture/sandbox.md index ba5b3c59b0..e5080cd38a 100644 --- a/architecture/sandbox.md +++ b/architecture/sandbox.md @@ -228,6 +228,20 @@ handled by the inference interception path: External inference endpoints that do not use `inference.local` are treated like ordinary network traffic and must be allowed by policy. +For an explicitly configured customer appliance, the supervisor owns one +userspace WireGuard interface. The workload receives neither its key nor a +tunnel network interface. A private IPv4 destination remains an ordinary +network endpoint: the explicit proxy authorizes its host and port, checks its +exact `allowed_ips` entry, then selects the named tunnel at the upstream dial +boundary. HTTP forward requests still pass L7 rules and credential rewriting +before the dial. CONNECT keeps its existing sequence: endpoint authorization +and address validation precede the TCP dial; TLS interception and request +inspection follow establishment. A `wireguard-udp` endpoint authorizes only +the supervisor's exact appliance socket and cannot authorize workload TCP. +The first implementation binds one tunnel and one inner endpoint to the +initial policy generation. A later policy generation requires a sandbox +restart for tunnel traffic; dials fail closed rather than using a stale route. + In proxy-required networks, the supervisor chains upstream TLS tunnels through a corporate forward proxy with HTTP CONNECT instead of connecting directly, once policy and SSRF checks pass. Only TLS (CONNECT) egress is chained: diff --git a/crates/openshell-core/src/gateway_channels.rs b/crates/openshell-core/src/gateway_channels.rs index 8025d369dc..7023e47594 100644 --- a/crates/openshell-core/src/gateway_channels.rs +++ b/crates/openshell-core/src/gateway_channels.rs @@ -1,3 +1,6 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + //! Gateway connections whose supervisor session is currently established. //! //! A supervisor multi-connects to a subset of the gateway fleet and holds one diff --git a/crates/openshell-core/src/provider_credentials.rs b/crates/openshell-core/src/provider_credentials.rs index 2b1537a21b..796b6e12cd 100644 --- a/crates/openshell-core/src/provider_credentials.rs +++ b/crates/openshell-core/src/provider_credentials.rs @@ -14,6 +14,13 @@ use std::fmt; use std::sync::{Arc, RwLock}; const MAX_RETAINED_CREDENTIAL_GENERATIONS: usize = 8; +const SUPERVISOR_TUNNEL_ENV_PREFIX: &str = "OPENSHELL_WG_"; + +/// Reserved supervisor tunnel material remains in the resolver but never in +/// any workload-facing environment snapshot, including sidecar refreshes. +fn strip_supervisor_tunnel_keys(child_env: &mut HashMap) { + child_env.retain(|key, _| !key.starts_with(SUPERVISOR_TUNNEL_ENV_PREFIX)); +} #[derive(Debug, Clone, Default)] pub struct ProviderCredentialSnapshot { @@ -80,12 +87,13 @@ impl ProviderCredentialState { credential_expires_at_ms: HashMap, dynamic_credentials: HashMap, ) -> Self { - let (child_env, generation_resolver, current_resolver) = + let (mut child_env, generation_resolver, current_resolver) = SecretResolver::from_provider_env_for_current_revision( env, credential_expires_at_ms, revision, ); + strip_supervisor_tunnel_keys(&mut child_env); let snapshot = Arc::new(ProviderCredentialSnapshot { revision, child_env, @@ -124,13 +132,14 @@ impl ProviderCredentialState { &non_secret_environment_keys, )?; let stable_handles = static_credential_stable_handles(&static_credential_bindings); - let (child_env, generation_resolver, current_resolver) = + let (mut child_env, generation_resolver, current_resolver) = SecretResolver::from_provider_env_for_current_revision_with_stable_handles( env, credential_expires_at_ms, revision, &stable_handles, ); + strip_supervisor_tunnel_keys(&mut child_env); let snapshot = Arc::new(ProviderCredentialSnapshot { revision, child_env, @@ -170,7 +179,8 @@ impl ProviderCredentialState { /// workload-facing env map over a local control channel. The process leaf /// must inject that map into child processes without re-placeholderizing it /// or holding the gateway-side resolver material. - pub fn from_child_env_snapshot(revision: u64, child_env: HashMap) -> Self { + pub fn from_child_env_snapshot(revision: u64, mut child_env: HashMap) -> Self { + strip_supervisor_tunnel_keys(&mut child_env); let snapshot = Arc::new(ProviderCredentialSnapshot { revision, child_env, @@ -208,6 +218,7 @@ impl ProviderCredentialState { .write() .expect("provider credential state poisoned"); + strip_supervisor_tunnel_keys(&mut child_env); for key in &inner.suppressed_keys { child_env.remove(key); } @@ -240,7 +251,26 @@ impl ProviderCredentialState { .read() .expect("provider credential state poisoned") .combined_resolver - .clone() + .as_ref() + .map(|resolver| Arc::new(resolver.without_env_key_prefix(SUPERVISOR_TUNNEL_ENV_PREFIX))) + } + + /// Resolve a reserved tunnel key for supervisor transport setup only. + /// Workload-facing resolver views never contain this value. + pub fn supervisor_tunnel_private_key(&self, key: &str) -> Option { + if !key.starts_with(SUPERVISOR_TUNNEL_ENV_PREFIX) + || key.len() == SUPERVISOR_TUNNEL_ENV_PREFIX.len() + { + return None; + } + self.inner + .read() + .expect("provider credential state poisoned") + .current_resolver + .as_ref()? + .resolve_current_env_key_checked(key, "supervisor tunnel") + .ok()? + .map(str::to_owned) } /// Resolve provider placeholders only for credentials bound to this @@ -295,6 +325,7 @@ impl ProviderCredentialState { .map(|(key, _)| key.clone()) .collect(); let resolver = inner.combined_resolver.as_ref().map(|resolver| { + let workload_resolver = resolver.without_env_key_prefix(SUPERVISOR_TUNNEL_ENV_PREFIX); let revision_fallback_allowed_revisions = inner .static_credential_identity_epochs .iter() @@ -307,7 +338,7 @@ impl ProviderCredentialState { }) .map(|(key, epoch)| (key.clone(), epoch.revisions.clone())) .collect(); - Arc::new(resolver.scoped_to_env_keys( + Arc::new(workload_resolver.scoped_to_env_keys( &inner.known_static_credential_keys, &allowed, revision_fallback_allowed_revisions, @@ -474,6 +505,7 @@ impl ProviderCredentialState { .write() .expect("provider credential state poisoned"); + strip_supervisor_tunnel_keys(&mut child_env); for key in &inner.suppressed_keys { child_env.remove(key); } @@ -537,6 +569,7 @@ impl ProviderCredentialState { .write() .expect("provider credential state poisoned"); + strip_supervisor_tunnel_keys(&mut child_env); for key in &inner.suppressed_keys { child_env.remove(key); } @@ -2084,6 +2117,80 @@ mod tests { ); } + #[test] + fn supervisor_tunnel_key_never_enters_workload_or_sidecar_environment() { + let key = "OPENSHELL_WG_PRIVATE_KEY"; + let env = HashMap::from([ + (key.to_string(), "supervisor-secret".to_string()), + ("API_TOKEN".to_string(), "ordinary-secret".to_string()), + ]); + let state = ProviderCredentialState::from_environment( + 1, + env.clone(), + HashMap::new(), + HashMap::new(), + ); + assert!(!state.snapshot().child_env.contains_key(key)); + assert!(!state.child_env_with_gcp_resolved().contains_key(key)); + assert!(state.snapshot().child_env.contains_key("API_TOKEN")); + assert_eq!( + state.supervisor_tunnel_private_key(key).as_deref(), + Some("supervisor-secret") + ); + for token in [ + "openshell:resolve:env:OPENSHELL_WG_PRIVATE_KEY", + "openshell:resolve:env:v1_OPENSHELL_WG_PRIVATE_KEY", + "xOPENSHELL-RESOLVE-ENV-OPENSHELL_WG_PRIVATE_KEY", + ] { + assert!( + state + .resolver() + .unwrap() + .resolve_placeholder(token) + .is_none() + ); + assert!( + state + .resolver_for_endpoint("api.example.test", 80, "/") + .unwrap() + .resolve_placeholder(token) + .is_none() + ); + } + state.install_environment(2, env.clone(), HashMap::new(), HashMap::new()); + assert!(!state.snapshot().child_env.contains_key(key)); + assert_eq!( + state.supervisor_tunnel_private_key(key).as_deref(), + Some("supervisor-secret") + ); + for token in [ + "openshell:resolve:env:OPENSHELL_WG_PRIVATE_KEY", + "openshell:resolve:env:v1_OPENSHELL_WG_PRIVATE_KEY", + "openshell:resolve:env:v2_OPENSHELL_WG_PRIVATE_KEY", + ] { + assert!( + state + .resolver() + .unwrap() + .resolve_placeholder(token) + .is_none() + ); + assert!( + state + .resolver_for_endpoint("api.example.test", 80, "/") + .unwrap() + .resolve_placeholder(token) + .is_none() + ); + } + + let sidecar = ProviderCredentialState::from_child_env_snapshot(1, env.clone()); + assert!(!sidecar.snapshot().child_env.contains_key(key)); + sidecar.install_child_env_snapshot(2, env); + assert!(!sidecar.snapshot().child_env.contains_key(key)); + assert!(sidecar.snapshot().child_env.contains_key("API_TOKEN")); + } + #[test] fn child_env_snapshot_install_updates_env_without_resolver_material() { let state = ProviderCredentialState::from_child_env_snapshot( diff --git a/crates/openshell-core/src/secrets.rs b/crates/openshell-core/src/secrets.rs index 0ec130bd8e..d3091b3e7d 100644 --- a/crates/openshell-core/src/secrets.rs +++ b/crates/openshell-core/src/secrets.rs @@ -376,6 +376,22 @@ impl SecretResolver { } } + /// Remove supervisor-only environment keys from a workload resolver view. + /// This filters canonical, revisioned, stable, and provider-shaped aliases; + /// revision fallback cannot restore a removed canonical key. + pub(crate) fn without_env_key_prefix(&self, prefix: &str) -> Self { + let mut view = self.clone(); + view.by_placeholder.retain(|placeholder, _| { + placeholder_env_key(placeholder).is_none_or(|key| !key.starts_with(prefix)) + }); + view.denied_env_keys.retain(|key| !key.starts_with(prefix)); + view.identity_bound_env_keys + .retain(|key| !key.starts_with(prefix)); + view.revision_fallback_allowed_revisions + .retain(|key, _| !key.starts_with(prefix)); + view + } + /// Return a cheap endpoint-scoped resolver view. /// /// Secret strings are shared through cloned resolver entries. Credential diff --git a/crates/openshell-policy/Cargo.toml b/crates/openshell-policy/Cargo.toml index 6589c4462f..0e3b23fe99 100644 --- a/crates/openshell-policy/Cargo.toml +++ b/crates/openshell-policy/Cargo.toml @@ -11,6 +11,8 @@ license.workspace = true repository.workspace = true [dependencies] +base64 = { workspace = true } +ipnet = "2" hickory-proto = { workspace = true } openshell-core = { path = "../openshell-core", default-features = false } serde = { workspace = true } diff --git a/crates/openshell-policy/src/l7_validate.rs b/crates/openshell-policy/src/l7_validate.rs index fe07df123f..1c0d272c95 100644 --- a/crates/openshell-policy/src/l7_validate.rs +++ b/crates/openshell-policy/src/l7_validate.rs @@ -150,7 +150,8 @@ pub fn validate_l7_endpoint_semantics(ep: &L7EndpointFields<'_>) -> Vec let is_jsonrpc = matches!(l7_protocol, Some(L7Protocol::JsonRpc)); // 1. Unknown protocol - if !protocol.is_empty() && l7_protocol.is_none() && !explicit_tcp { + if !protocol.is_empty() && l7_protocol.is_none() && !explicit_tcp && protocol != "wireguard-udp" + { errors.push(format!( "unknown protocol '{protocol}' (expected tcp, rest, websocket, graphql, sql, json-rpc, or mcp)" )); diff --git a/crates/openshell-policy/src/lib.rs b/crates/openshell-policy/src/lib.rs index 5e93d6155b..d4b12c64dc 100644 --- a/crates/openshell-policy/src/lib.rs +++ b/crates/openshell-policy/src/lib.rs @@ -14,6 +14,7 @@ mod l7_validate; mod merge; mod middleware; +use base64::Engine as _; use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::fmt; use std::net::IpAddr; @@ -28,8 +29,8 @@ use miette::{IntoDiagnostic, Result, WrapErr}; use openshell_core::mcp::{DEFAULT_MCP_PROTOCOL_VERSION, McpProtocolVersion}; use openshell_core::proto::{ FilesystemPolicy, GraphqlOperation, L7Allow, L7DenyRule, L7QueryMatcher, L7Rule, - LandlockPolicy, McpOptions, NetworkBinary, NetworkEndpoint, NetworkPolicyRule, ProcessPolicy, - SandboxPolicy, + LandlockPolicy, McpOptions, NetworkBinary, NetworkEndpoint, NetworkPolicyRule, NetworkTunnel, + ProcessPolicy, SandboxPolicy, }; use serde::{Deserialize, Deserializer, Serialize}; @@ -67,6 +68,38 @@ struct PolicyFile { network_policies: BTreeMap, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] network_middlewares: BTreeMap, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + tunnels: BTreeMap, +} + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct NetworkTunnelDef { + endpoint_host: String, + endpoint_udp_port: u16, + peer_public_key: String, + private_key_env_key: String, + local_address: String, + allowed_inner_cidrs: Vec, + #[serde(default)] + mtu: u32, + #[serde(default)] + keepalive_seconds: u32, +} + +impl fmt::Debug for NetworkTunnelDef { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("NetworkTunnelDef") + .field("endpoint_host", &self.endpoint_host) + .field("endpoint_udp_port", &self.endpoint_udp_port) + .field("peer_public_key", &"[redacted]") + .field("private_key_env_key", &self.private_key_env_key) + .field("local_address", &self.local_address) + .field("allowed_inner_cidrs", &self.allowed_inner_cidrs) + .field("mtu", &self.mtu) + .field("keepalive_seconds", &self.keepalive_seconds) + .finish() + } } #[derive(Debug, Serialize, Deserialize)] @@ -132,6 +165,8 @@ struct NetworkEndpointDef { #[serde(default, skip_serializing_if = "Option::is_none")] upstream_ca_pem: Option, #[serde(default, skip_serializing_if = "String::is_empty")] + tunnel_id: String, + #[serde(default, skip_serializing_if = "String::is_empty")] enforcement: String, #[serde(default, skip_serializing_if = "String::is_empty")] access: String, @@ -810,6 +845,28 @@ fn yaml_mcp_method( } fn to_proto(raw: PolicyFile) -> Result { + let tunnels = raw + .tunnels + .into_iter() + .map(|(name, tunnel)| { + let peer_public_key = base64::engine::general_purpose::STANDARD + .decode(&tunnel.peer_public_key) + .map_err(|_| miette::miette!("invalid WireGuard public key encoding"))?; + Ok(( + name, + NetworkTunnel { + endpoint_host: tunnel.endpoint_host, + endpoint_udp_port: u32::from(tunnel.endpoint_udp_port), + peer_public_key, + private_key_env_key: tunnel.private_key_env_key, + local_address: tunnel.local_address, + allowed_inner_cidrs: tunnel.allowed_inner_cidrs, + mtu: tunnel.mtu, + keepalive_seconds: tunnel.keepalive_seconds, + }, + )) + }) + .collect::>>()?; let network_middlewares = middleware::into_proto(raw.network_middlewares) .into_diagnostic() .wrap_err("failed to convert network middleware config")?; @@ -848,6 +905,7 @@ fn to_proto(raw: PolicyFile) -> Result { protocol: protocol.clone(), tls: e.tls, upstream_ca_pem: e.upstream_ca_pem.unwrap_or_default(), + tunnel_id: e.tunnel_id, enforcement: e.enforcement, access: e.access, rules: allow_rules @@ -929,6 +987,7 @@ fn to_proto(raw: PolicyFile) -> Result { }), network_policies, network_middlewares, + tunnels, }) } @@ -1018,6 +1077,7 @@ fn from_proto(policy: &SandboxPolicy) -> PolicyFile { tls: e.tls.clone(), upstream_ca_pem: (!e.upstream_ca_pem.is_empty()) .then(|| e.upstream_ca_pem.clone()), + tunnel_id: e.tunnel_id.clone(), enforcement: e.enforcement.clone(), access: e.access.clone(), rules, @@ -1070,6 +1130,26 @@ fn from_proto(policy: &SandboxPolicy) -> PolicyFile { .collect(); let network_middlewares = middleware::from_proto(&policy.network_middlewares); + let tunnels = policy + .tunnels + .iter() + .map(|(name, tunnel)| { + ( + name.clone(), + NetworkTunnelDef { + endpoint_host: tunnel.endpoint_host.clone(), + endpoint_udp_port: u16::try_from(tunnel.endpoint_udp_port).unwrap_or(u16::MAX), + peer_public_key: base64::engine::general_purpose::STANDARD + .encode(&tunnel.peer_public_key), + private_key_env_key: tunnel.private_key_env_key.clone(), + local_address: tunnel.local_address.clone(), + allowed_inner_cidrs: tunnel.allowed_inner_cidrs.clone(), + mtu: tunnel.mtu, + keepalive_seconds: tunnel.keepalive_seconds, + }, + ) + }) + .collect(); PolicyFile { version: policy.version, @@ -1078,6 +1158,7 @@ fn from_proto(policy: &SandboxPolicy) -> PolicyFile { process, network_policies, network_middlewares, + tunnels, } } @@ -1287,6 +1368,7 @@ pub fn restrictive_default_policy() -> SandboxPolicy { process: None, network_policies: HashMap::new(), network_middlewares: HashMap::default(), + tunnels: HashMap::default(), } } @@ -1354,6 +1436,8 @@ pub enum PolicyViolation { }, /// A network endpoint uses a wildcard shape that does not match runtime semantics. InvalidHostWildcard { policy_name: String, host: String }, + /// Supervisor tunnel configuration is incomplete or ambiguous. + InvalidTunnelConfig { reason: String }, /// `credential_signing` is set but `signing_service` is missing. MissingSigningService { policy_name: String, host: String }, /// `credential_signing` has an unrecognized value. @@ -1499,6 +1583,9 @@ impl fmt::Display for PolicyViolation { is only allowed as the entire first label" ) } + Self::InvalidTunnelConfig { reason } => { + write!(f, "invalid tunnel configuration: {reason}") + } Self::MissingSigningService { policy_name, host } => { write!( f, @@ -1734,6 +1821,14 @@ fn validate_sandbox_policy_with_mcp_presence( violations.push(PolicyViolation::MissingEndpointHost { policy_name: name.clone(), }); + } else if explicit_tcp && !ep.tunnel_id.is_empty() { + if ep.host.parse::().is_err() { + violations.push(PolicyViolation::InvalidTcpEndpointHost { + policy_name: name.clone(), + host: ep.host.clone(), + reason: "tunneled TCP endpoint must be an exact IPv4 literal".to_string(), + }); + } } else if explicit_tcp { if ep.host.parse::().is_ok() { violations.push(PolicyViolation::TcpEndpointIpLiteral { @@ -1945,6 +2040,7 @@ fn validate_sandbox_policy_with_mcp_presence( } violations.extend(middleware::validate(policy)); + validate_tunnel_policy(policy, &mut violations); if violations.is_empty() { Ok(()) @@ -1953,6 +2049,102 @@ fn validate_sandbox_policy_with_mcp_presence( } } +/// Validate the single `WireGuard` route before policy persistence or delivery. +fn validate_tunnel_policy(policy: &SandboxPolicy, violations: &mut Vec) { + let single_port = |endpoint: &NetworkEndpoint| match endpoint.ports.as_slice() { + [] if endpoint.port != 0 => Some(endpoint.port), + [port] if endpoint.port == 0 || endpoint.port == *port => Some(*port), + _ => None, + }; + let mut fail = |reason: &str| { + violations.push(PolicyViolation::InvalidTunnelConfig { + reason: reason.to_string(), + }); + }; + let endpoints: Vec<_> = policy + .network_policies + .values() + .flat_map(|rule| &rule.endpoints) + .collect(); + let inner: Vec<_> = endpoints + .iter() + .filter(|endpoint| !endpoint.tunnel_id.is_empty()) + .collect(); + let outer: Vec<_> = endpoints + .iter() + .filter(|endpoint| endpoint.protocol == "wireguard-udp") + .collect(); + if policy.tunnels.is_empty() { + if !inner.is_empty() || !outer.is_empty() { + fail("tunnel endpoints require a named tunnel"); + } + return; + } + if policy.tunnels.len() != 1 || inner.len() != 1 || outer.len() != 1 { + fail("phase 1 requires one tunnel, one inner endpoint, and one appliance UDP endpoint"); + return; + } + let (id, tunnel) = policy.tunnels.iter().next().expect("one tunnel"); + let inner = *inner[0]; + let outer = *outer[0]; + let Ok(inner_ip) = inner.host.parse::() else { + fail("inner endpoint must be an exact IPv4 literal"); + return; + }; + let Ok(route) = tunnel + .allowed_inner_cidrs + .first() + .map_or("", String::as_str) + .parse::() + else { + fail("inner route must be a valid IPv4 CIDR"); + return; + }; + if id.is_empty() + || inner.tunnel_id != *id + || tunnel.allowed_inner_cidrs.len() != 1 + || route.prefix_len() == 0 + || !route.contains(&inner_ip) + || inner.allowed_ips != [inner_ip.to_string()] + || single_port(inner).is_none() + { + fail("inner endpoint must have one exact allowed IP and port within its named route"); + } + if tunnel.endpoint_host.parse::().is_err() + || tunnel.endpoint_udp_port == 0 + || tunnel.endpoint_udp_port > u16::MAX.into() + || outer.host != tunnel.endpoint_host + || outer.host.contains('*') + || single_port(outer) != Some(tunnel.endpoint_udp_port) + || !outer.tunnel_id.is_empty() + { + fail("appliance must have one exact IPv4 UDP endpoint policy"); + } + if tunnel.peer_public_key.len() != 32 + || !tunnel.private_key_env_key.starts_with("OPENSHELL_WG_") + || tunnel.private_key_env_key.len() == "OPENSHELL_WG_".len() + || !tunnel + .private_key_env_key + .bytes() + .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_') + || tunnel.local_address.parse::().is_err() + || (tunnel.mtu != 0 && !(1200..=1420).contains(&tunnel.mtu)) + || (tunnel.keepalive_seconds != 0 && !(5..=120).contains(&tunnel.keepalive_seconds)) + { + fail("WireGuard peer parameters are invalid"); + } + if endpoints + .iter() + .filter(|endpoint| { + endpoint.host == inner.host && single_port(endpoint) == single_port(inner) + }) + .count() + != 1 + { + fail("inner destination host and port must not have competing endpoint rules"); + } +} + /// Accept only usable certificate PEM blocks; private keys and unrelated PEM /// material must never be carried in an endpoint policy. fn validate_upstream_ca_pem(pem: &str) -> bool { @@ -3853,6 +4045,7 @@ network_policies: landlock: None, network_policies: HashMap::new(), network_middlewares: HashMap::default(), + tunnels: HashMap::new(), }; assert!(validate_sandbox_policy(&policy).is_ok()); } @@ -4311,6 +4504,7 @@ network_policies: landlock: None, network_policies: HashMap::new(), network_middlewares: HashMap::default(), + tunnels: HashMap::new(), }; assert!(validate_sandbox_policy(&policy).is_ok()); } @@ -4327,6 +4521,7 @@ network_policies: landlock: None, network_policies: HashMap::new(), network_middlewares: HashMap::default(), + tunnels: HashMap::new(), }; assert!(validate_sandbox_policy(&policy).is_ok()); } @@ -4399,6 +4594,7 @@ network_policies: landlock: None, network_policies: HashMap::new(), network_middlewares: HashMap::default(), + tunnels: HashMap::new(), }; assert!(validate_sandbox_policy(&policy).is_ok()); } @@ -4455,6 +4651,42 @@ network_policies: assert_eq!(ep.port, 443); } + #[test] + fn tunnel_policy_accepts_scalar_ports_for_inner_and_outer_endpoints() { + let policy = parse_sandbox_policy( + r" +version: 1 +tunnels: + customer: + endpoint_host: 198.51.100.20 + endpoint_udp_port: 51820 + peer_public_key: AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA= + private_key_env_key: OPENSHELL_WG_PRIVATE_KEY + local_address: 10.80.0.1/32 + allowed_inner_cidrs: [10.80.0.2/32] +network_policies: + transport: + endpoints: + - { host: 198.51.100.20, port: 51820, protocol: wireguard-udp } + service: + endpoints: + - { host: 10.80.0.2, port: 8080, allowed_ips: [10.80.0.2], tunnel_id: customer } + binaries: + - { path: /usr/bin/example-app } +", + ) + .expect("scalar-port tunnel policy"); + assert_eq!( + policy.network_policies["transport"].endpoints[0].ports, + [51820] + ); + assert_eq!( + policy.network_policies["service"].endpoints[0].ports, + [8080] + ); + validate_sandbox_policy(&policy).expect("valid tunnel policy"); + } + #[test] fn round_trip_preserves_endpoint_path() { let yaml = r#" diff --git a/crates/openshell-policy/src/merge.rs b/crates/openshell-policy/src/merge.rs index c59507f53a..a5a1212b40 100644 --- a/crates/openshell-policy/src/merge.rs +++ b/crates/openshell-policy/src/merge.rs @@ -308,6 +308,12 @@ pub enum PolicyMergeError { host: String, port: u32, }, + /// Overlapping endpoints cannot silently change their tunnel route. + TunnelRouteConflict { + operation_index: usize, + host: String, + port: u32, + }, /// Newly added binary scope would inherit an existing endpoint /// authorization that the incoming rule did not declare. NewBinaryWouldInheritAuthorization { @@ -433,6 +439,14 @@ impl std::fmt::Display for PolicyMergeError { f, "merge operation {operation_index} cannot change upstream_ca_pem for {host}:{port}; replace the endpoint policy" ), + Self::TunnelRouteConflict { + operation_index, + host, + port, + } => write!( + f, + "merge operation {operation_index} cannot change tunnel route for {host}:{port}" + ), Self::NewBinaryWouldInheritAuthorization { operation_index, rule_name, @@ -675,6 +689,9 @@ fn endpoint_attributes_cover(loaded: &NetworkEndpoint, proposed: &NetworkEndpoin if !loaded.host.eq_ignore_ascii_case(&proposed.host) || loaded.path != proposed.path { return false; } + if loaded.tunnel_id != proposed.tunnel_id { + return false; + } // Fields `merge_endpoint` retains rather than widens. An unset proposal // value is unspecified, not a request for the default: the merge leaves the @@ -1311,6 +1328,7 @@ fn is_authorization_inheritance_conflict(error: &PolicyMergeError) -> bool { // contracts stay ambiguous however they are split. PolicyMergeError::McpContractConflict { .. } | PolicyMergeError::UpstreamCaConflict { .. } + | PolicyMergeError::TunnelRouteConflict { .. } | PolicyMergeError::ConflictingInspectionContracts { .. } => false, // Reports an unsupported or missing state in the policy the fold @@ -1428,6 +1446,14 @@ fn merge_endpoint( .or_else(|| incoming_ports.first().copied()) .unwrap_or(0); + if existing.tunnel_id != incoming.tunnel_id { + return Err(PolicyMergeError::TunnelRouteConflict { + operation_index, + host, + port, + }); + } + let promotes_l4_to_mcp = promotes_l4_endpoint_to_mcp(existing, incoming); ensure_mcp_contract_compatible(existing, incoming, operation_index, &host, port)?; diff --git a/crates/openshell-providers/src/profiles.rs b/crates/openshell-providers/src/profiles.rs index c51015f0ad..145176a369 100644 --- a/crates/openshell-providers/src/profiles.rs +++ b/crates/openshell-providers/src/profiles.rs @@ -1432,6 +1432,7 @@ fn endpoint_to_proto(endpoint: &EndpointProfile) -> NetworkEndpoint { protocol: endpoint.protocol.clone(), tls: endpoint.tls.clone(), upstream_ca_pem: String::new(), + tunnel_id: String::new(), enforcement: endpoint.enforcement.clone(), access: endpoint.access.clone(), rules: endpoint diff --git a/crates/openshell-sandbox/src/lib.rs b/crates/openshell-sandbox/src/lib.rs index 3421d6cde2..4989b1847d 100644 --- a/crates/openshell-sandbox/src/lib.rs +++ b/crates/openshell-sandbox/src/lib.rs @@ -256,7 +256,8 @@ pub async fn run_sandbox( bootstrap.provider_env_revision, bootstrap.provider_child_env.clone(), ); - (provider_credentials, bootstrap.provider_child_env.clone()) + let provider_env = provider_credentials.snapshot().child_env.clone(); + (provider_credentials, provider_env) } else { // Fetch provider environment variables from the server. // This is done after loading the policy so the sandbox can still start @@ -4704,6 +4705,31 @@ fn format_setting_value(es: &openshell_core::proto::EffectiveSetting) -> String mod tests { use super::*; + #[test] + fn tunnel_key_is_absent_from_main_and_sidecar_bootstrap_environments() { + let env = std::collections::HashMap::from([ + ("OPENSHELL_WG_PRIVATE_KEY".to_string(), "secret".to_string()), + ("ORDINARY_CONFIG".to_string(), "visible".to_string()), + ]); + let network_credentials = ProviderCredentialState::from_environment( + 1, + env.clone(), + std::collections::HashMap::new(), + std::collections::HashMap::new(), + ); + let provider_env = network_credentials.child_env_with_gcp_resolved(); + let main_env = provider_env.clone(); + let sidecar_bootstrap_env = provider_env.clone(); + assert!(!main_env.contains_key("OPENSHELL_WG_PRIVATE_KEY")); + assert!(!sidecar_bootstrap_env.contains_key("OPENSHELL_WG_PRIVATE_KEY")); + assert!(main_env.contains_key("ORDINARY_CONFIG")); + + let process_credentials = ProviderCredentialState::from_child_env_snapshot(1, env); + let process_provider_env = process_credentials.snapshot().child_env.clone(); + assert!(!process_provider_env.contains_key("OPENSHELL_WG_PRIVATE_KEY")); + assert!(process_provider_env.contains_key("ORDINARY_CONFIG")); + } + #[test] fn transparent_tcp_capability_requires_exact_driver_marker() { let required = openshell_core::sandbox_env::POLICY_DNS_TRANSPARENT_TCP_CAPABILITY; diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index b1fb3b2d2f..81dd5aed4f 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -6356,6 +6356,7 @@ fn map_policy_merge_error(error: openshell_policy::PolicyMergeError) -> Status { openshell_policy::PolicyMergeError::InvalidInputPolicy { .. } | openshell_policy::PolicyMergeError::McpContractConflict { .. } | openshell_policy::PolicyMergeError::UpstreamCaConflict { .. } + | openshell_policy::PolicyMergeError::TunnelRouteConflict { .. } | openshell_policy::PolicyMergeError::NewBinaryWouldInheritAuthorization { .. } | openshell_policy::PolicyMergeError::ExistingBinariesWouldInheritAuthorization { .. diff --git a/crates/openshell-supervisor-network/Cargo.toml b/crates/openshell-supervisor-network/Cargo.toml index 34d9c32a47..e6f3c3fb97 100644 --- a/crates/openshell-supervisor-network/Cargo.toml +++ b/crates/openshell-supervisor-network/Cargo.toml @@ -45,6 +45,7 @@ sha2 = { workspace = true } spiffe = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true } +tokio-wireguard = { path = "../../vendor/tokio-wireguard" } tokio-rustls = { workspace = true } tower-mcp-types = { workspace = true } tracing = { workspace = true } diff --git a/crates/openshell-supervisor-network/data/sandbox-policy.rego b/crates/openshell-supervisor-network/data/sandbox-policy.rego index f3abcf2ffa..cdacfae4c3 100644 --- a/crates/openshell-supervisor-network/data/sandbox-policy.rego +++ b/crates/openshell-supervisor-network/data/sandbox-policy.rego @@ -108,6 +108,7 @@ endpoint_policy_for_request if { endpoint_allowed(policy, network) if { some endpoint endpoint := policy.endpoints[_] + lower(object.get(endpoint, "protocol", "")) != "wireguard-udp" not contains(endpoint.host, "*") lower(endpoint.host) == lower(network.host) endpoint.ports[_] == network.port @@ -119,6 +120,7 @@ endpoint_allowed(policy, network) if { endpoint_allowed(policy, network) if { some endpoint endpoint := policy.endpoints[_] + lower(object.get(endpoint, "protocol", "")) != "wireguard-udp" contains(endpoint.host, "*") glob.match(lower(endpoint.host), ["."], lower(network.host)) endpoint.ports[_] == network.port @@ -130,6 +132,7 @@ endpoint_allowed(policy, network) if { endpoint_allowed(policy, network) if { some endpoint endpoint := policy.endpoints[_] + lower(object.get(endpoint, "protocol", "")) != "wireguard-udp" object.get(endpoint, "host", "") == "" count(object.get(endpoint, "allowed_ips", [])) > 0 endpoint.ports[_] == network.port @@ -974,6 +977,7 @@ network_middlewares := object.get(data, "network_middlewares", {}) _policy_has_exact_declared_endpoint(policy) if { some ep ep := policy.endpoints[_] + lower(object.get(ep, "protocol", "")) != "wireguard-udp" not object.get(ep, "advisor_proposed", false) not contains(ep.host, "*") lower(ep.host) == lower(input.network.host) @@ -989,6 +993,7 @@ exact_declared_endpoint_host if { # Hosted endpoint: exact host match + port in ports list. endpoint_matches_request(ep, network) if { + lower(object.get(ep, "protocol", "")) != "wireguard-udp" not contains(ep.host, "*") lower(ep.host) == lower(network.host) ep.ports[_] == network.port @@ -996,6 +1001,7 @@ endpoint_matches_request(ep, network) if { # Hosted endpoint: glob host match + port in ports list. endpoint_matches_request(ep, network) if { + lower(object.get(ep, "protocol", "")) != "wireguard-udp" contains(ep.host, "*") glob.match(lower(ep.host), ["."], lower(network.host)) ep.ports[_] == network.port @@ -1003,6 +1009,7 @@ endpoint_matches_request(ep, network) if { # Hostless endpoint with allowed_ips: match on port only. endpoint_matches_request(ep, network) if { + lower(object.get(ep, "protocol", "")) != "wireguard-udp" object.get(ep, "host", "") == "" count(object.get(ep, "allowed_ips", [])) > 0 ep.ports[_] == network.port @@ -1040,6 +1047,10 @@ endpoint_has_extended_config(ep) if { ep.tls } +endpoint_has_extended_config(ep) if { + ep.tunnel_id +} + endpoint_has_extended_config(ep) if { ep.upstream_ca_pem } diff --git a/crates/openshell-supervisor-network/src/l7/rest.rs b/crates/openshell-supervisor-network/src/l7/rest.rs index 93315a671a..9611b1cd4d 100644 --- a/crates/openshell-supervisor-network/src/l7/rest.rs +++ b/crates/openshell-supervisor-network/src/l7/rest.rs @@ -2165,7 +2165,7 @@ fn append_header(headers: &[u8], name: &str, value: &str) -> Vec { let split = headers .windows(4) .position(|w| w == b"\r\n\r\n") - .map_or(headers.len(), |pos| pos); + .unwrap_or(headers.len()); let mut out = Vec::with_capacity(headers.len() + name.len() + value.len() + 4); out.extend_from_slice(&headers[..split]); out.extend_from_slice(b"\r\n"); diff --git a/crates/openshell-supervisor-network/src/lib.rs b/crates/openshell-supervisor-network/src/lib.rs index 4fec48b300..fad30767d7 100644 --- a/crates/openshell-supervisor-network/src/lib.rs +++ b/crates/openshell-supervisor-network/src/lib.rs @@ -19,6 +19,7 @@ pub mod proxy; pub mod run; pub mod sigv4; mod token_grant; +mod tunnel; pub mod upstream_proxy; #[cfg(test)] diff --git a/crates/openshell-supervisor-network/src/opa.rs b/crates/openshell-supervisor-network/src/opa.rs index 88b4a5e4ec..267d665ce9 100644 --- a/crates/openshell-supervisor-network/src/opa.rs +++ b/crates/openshell-supervisor-network/src/opa.rs @@ -1958,6 +1958,9 @@ fn proto_to_opa_data_json(proto: &ProtoSandboxPolicy, entrypoint_pid: u32) -> St if !e.upstream_ca_pem.is_empty() { ep["upstream_ca_pem"] = e.upstream_ca_pem.clone().into(); } + if !e.tunnel_id.is_empty() { + ep["tunnel_id"] = e.tunnel_id.clone().into(); + } if !e.enforcement.is_empty() { ep["enforcement"] = e.enforcement.clone().into(); } @@ -2252,6 +2255,7 @@ fn proto_to_opa_data_json(proto: &ProtoSandboxPolicy, entrypoint_pid: u32) -> St )] mod tests { use super::*; + use std::collections::HashMap; use openshell_core::mcp::DEFAULT_MCP_PROTOCOL_VERSION; use openshell_core::proto::{ @@ -2321,6 +2325,7 @@ mod tests { run_as_group: "sandbox".to_string(), }), network_policies, + tunnels: HashMap::default(), network_middlewares: std::collections::HashMap::default(), } } @@ -3418,6 +3423,7 @@ process: run_as_group: "sandbox".to_string(), }), network_policies, + tunnels: HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto_with_pid_and_binary_identity_required(&proto, 0, false) @@ -3957,6 +3963,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + tunnels: HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; @@ -4029,6 +4036,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + tunnels: HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; @@ -4106,6 +4114,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + tunnels: HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; @@ -5233,6 +5242,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + tunnels: HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; @@ -5291,6 +5301,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + tunnels: HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; @@ -5350,6 +5361,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + tunnels: HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; @@ -5411,6 +5423,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + tunnels: HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; @@ -5471,6 +5484,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + tunnels: HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; @@ -6389,6 +6403,97 @@ process: } } + #[test] + fn tunneled_inner_endpoint_uses_normal_policy_and_outer_udp_is_not_workload_egress() { + use openshell_core::proto::NetworkTunnel; + let mut proto = test_proto(); + proto.tunnels.insert( + "customer".into(), + NetworkTunnel { + endpoint_host: "198.51.100.20".into(), + endpoint_udp_port: 51820, + peer_public_key: vec![7; 32], + private_key_env_key: "OPENSHELL_WG_PRIVATE_KEY".into(), + local_address: "10.80.0.1/32".into(), + allowed_inner_cidrs: vec!["10.80.0.2/32".into()], + ..Default::default() + }, + ); + proto.network_policies.insert( + "appliance".into(), + NetworkPolicyRule { + endpoints: vec![NetworkEndpoint { + host: "198.51.100.20".into(), + port: 51820, + ports: vec![51820], + protocol: "wireguard-udp".into(), + ..Default::default() + }], + ..Default::default() + }, + ); + proto.network_policies.insert( + "orders".into(), + NetworkPolicyRule { + endpoints: vec![NetworkEndpoint { + host: "10.80.0.2".into(), + port: 8080, + ports: vec![8080], + allowed_ips: vec!["10.80.0.2".into()], + tunnel_id: "customer".into(), + ..Default::default() + }], + binaries: vec![NetworkBinary { + path: "/usr/local/bin/claude".into(), + ..Default::default() + }], + ..Default::default() + }, + ); + let engine = OpaEngine::from_proto(&proto).expect("tunnel policy"); + let input = |host: &str, port: u16, binary: &str| NetworkInput { + host: host.into(), + port, + binary_path: binary.into(), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + assert!(matches!( + engine + .evaluate_network_action(&input("10.80.0.2", 8080, "/usr/local/bin/claude")) + .unwrap(), + NetworkAction::Allow { .. } + )); + assert!(matches!( + engine + .evaluate_network_action(&input("10.80.0.2", 8080, "/usr/bin/python3")) + .unwrap(), + NetworkAction::Deny { .. } + )); + assert!(matches!( + engine + .evaluate_network_action(&input("10.80.0.2", 8081, "/usr/local/bin/claude")) + .unwrap(), + NetworkAction::Deny { .. } + )); + assert!(matches!( + engine + .evaluate_network_action(&input("198.51.100.20", 51820, "/usr/local/bin/claude")) + .unwrap(), + NetworkAction::Deny { .. } + )); + let endpoint_only = + OpaEngine::from_proto_with_pid_and_binary_identity_required(&proto, 0, false) + .expect("endpoint-only tunnel policy"); + assert!(matches!( + endpoint_only + .evaluate_network_action(&input("198.51.100.20", 51820, "/usr/local/bin/claude")) + .unwrap(), + NetworkAction::Deny { .. } + )); + } + #[test] fn network_action_with_dev_policy() { let engine = test_engine(); @@ -6862,6 +6967,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + tunnels: HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto(&proto).expect("engine from proto"); @@ -6917,6 +7023,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + tunnels: HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto(&proto).expect("engine from proto"); @@ -6988,6 +7095,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + tunnels: HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto(&proto).expect("Failed to create engine from proto"); @@ -7219,6 +7327,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, + tunnels: HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto(&proto).unwrap(); diff --git a/crates/openshell-supervisor-network/src/policy_local.rs b/crates/openshell-supervisor-network/src/policy_local.rs index 2a6b04ec60..ae555dcdbc 100644 --- a/crates/openshell-supervisor-network/src/policy_local.rs +++ b/crates/openshell-supervisor-network/src/policy_local.rs @@ -120,7 +120,10 @@ impl PolicyLocalContext { workspace_rx: tokio::sync::watch::Receiver, ) -> Self { Self { - current_policy: Arc::new(RwLock::new(current_policy.map(Arc::new))), + current_policy: Arc::new(RwLock::new(current_policy.map(|mut policy| { + redact_tunnels(&mut policy); + Arc::new(policy) + }))), agent_proposals, gateway_endpoint, sandbox_name, @@ -129,10 +132,11 @@ impl PolicyLocalContext { } } - pub async fn set_current_policy(&self, policy: ProtoSandboxPolicy) { + pub async fn set_current_policy(&self, mut policy: ProtoSandboxPolicy) { // Every successful reload receives a distinct Arc, including an // identical policy installed again. Waiters use pointer identity to // decide whether the installed snapshot needs another coverage scan. + redact_tunnels(&mut policy); *self.current_policy.write().await = Some(Arc::new(policy)); } @@ -151,6 +155,16 @@ impl PolicyLocalContext { } } +/// Keep supervisor tunnel configuration out of workload policy introspection. +fn redact_tunnels(policy: &mut ProtoSandboxPolicy) { + policy.tunnels.clear(); + for rule in policy.network_policies.values_mut() { + for endpoint in &mut rule.endpoints { + endpoint.tunnel_id.clear(); + } + } +} + pub async fn handle_forward_request( ctx: &PolicyLocalContext, method: &str, @@ -1200,6 +1214,7 @@ fn network_endpoint_from_json( protocol: endpoint.protocol, tls: endpoint.tls, upstream_ca_pem: String::new(), + tunnel_id: String::new(), enforcement: endpoint.enforcement, access: endpoint.access, rules, @@ -1419,6 +1434,35 @@ mod tests { use super::*; use openshell_core::proposals::AgentProposals; + #[test] + fn tunnel_configuration_is_hidden_from_policy_introspection() { + let mut policy = ProtoSandboxPolicy::default(); + policy.tunnels.insert( + "customer".into(), + openshell_core::proto::NetworkTunnel { + private_key_env_key: "WG_PRIVATE_KEY".into(), + ..Default::default() + }, + ); + policy.network_policies.insert( + "inner".into(), + NetworkPolicyRule { + endpoints: vec![NetworkEndpoint { + tunnel_id: "customer".into(), + ..Default::default() + }], + ..Default::default() + }, + ); + redact_tunnels(&mut policy); + assert!(policy.tunnels.is_empty()); + assert!( + policy.network_policies["inner"].endpoints[0] + .tunnel_id + .is_empty() + ); + } + fn test_workspace_rx() -> tokio::sync::watch::Receiver { tokio::sync::watch::channel(String::new()).1 } diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index 49e42f6553..16ea6c2e0b 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -13,6 +13,7 @@ use crate::opa::{NetworkAction, OpaEngine, PolicyGenerationGuard}; #[cfg(target_os = "linux")] use crate::policy_dns::{MappingLookupError, PolicyEndpointId, ResolvedEndpointStore}; use crate::policy_local::{POLICY_LOCAL_HOST, PolicyLocalContext}; +use crate::tunnel::TunnelManager; use crate::upstream_proxy::{self, UpstreamProxyConfig}; use miette::{IntoDiagnostic, Result}; use openshell_core::activity::{ActivitySender, try_record_activity}; @@ -53,6 +54,9 @@ use self::egress::{ }; const MAX_HEADER_BYTES: usize = 8192; +tokio::task_local! { + pub(crate) static TUNNEL_MANAGER: Option>; +} const TUNNEL_PROTOCOL_PEEK_BYTES: usize = crate::l7::rest::HTTP2_PRIOR_KNOWLEDGE_PREFACE.len(); #[cfg(not(test))] const TUNNEL_PROTOCOL_PEEK_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(100); @@ -256,6 +260,7 @@ impl ProxyHandle { engine_ready: tokio::sync::watch::Receiver, upstream_proxy_args: &upstream_proxy::UpstreamProxyArgs, sandbox_id: Option<&str>, + tunnel_manager: Option>, ) -> Result { // Use override bind_addr, fall back to policy http_addr, then default // to loopback:3128. The default allows the proxy to function when no @@ -397,26 +402,31 @@ impl ProxyHandle { }); let dtx = denial_tx.clone(); let atx = activity_tx.clone(); + let tunnel = tunnel_manager.clone(); tokio::spawn(async move { #[allow(clippy::large_futures)] - if let Err(err) = handle_tcp_connection( - stream, - opa, - cache, - spid, - tls, - inf, - policy_local, - proposals, - gw, - up_proxy, - credentials, - resolver, - dynamic_credentials, - dtx, - atx, - ) - .await + if let Err(err) = TUNNEL_MANAGER + .scope( + tunnel, + handle_tcp_connection( + stream, + opa, + cache, + spid, + tls, + inf, + policy_local, + proposals, + gw, + up_proxy, + credentials, + resolver, + dynamic_credentials, + dtx, + atx, + ), + ) + .await { let event = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Fail) @@ -509,6 +519,7 @@ impl TransparentTcpHandle { upstream_proxy_args: &upstream_proxy::UpstreamProxyArgs, sandbox_id: Option<&str>, engine_ready: tokio::sync::watch::Receiver, + tunnel: Option>, ) -> Result { let upstream_proxy = Arc::new( UpstreamProxyConfig::from_args(upstream_proxy_args, sandbox_id) @@ -524,6 +535,7 @@ impl TransparentTcpHandle { let denial_tx = denial_tx.clone(); let activity_tx = activity_tx.clone(); let upstream_proxy = upstream_proxy.clone(); + let tunnel = tunnel.clone(); let mut engine_ready = engine_ready.clone(); joins.push(tokio::spawn(async move { if tokio::time::timeout( @@ -550,6 +562,7 @@ impl TransparentTcpHandle { let denial_tx = denial_tx.clone(); let activity_tx = activity_tx.clone(); let upstream_proxy = upstream_proxy.clone(); + let tunnel = tunnel.clone(); tokio::spawn(async move { if let Err(error) = handle_transparent_tcp_connection( stream, @@ -561,6 +574,7 @@ impl TransparentTcpHandle { denial_tx, activity_tx, upstream_proxy, + tunnel, ) .await { @@ -602,6 +616,7 @@ async fn handle_transparent_tcp_connection( denial_tx: Option>, activity_tx: Option, upstream_proxy: Arc>, + tunnel: Option>, ) -> Result<()> { let workload_addr = client.peer_addr().into_diagnostic()?; let original = original_destination(&client).into_diagnostic()?; @@ -728,6 +743,15 @@ async fn handle_transparent_tcp_connection( crate::l7::middleware::emit_middleware_uninspectable(&ctx, "transparent tcp", false); } let approved_real_ip_candidates = connector.addrs().to_vec(); + if transparent_tunnel_route_refused( + query_tunnel_id(&decision).as_deref(), + &approved_real_ip_candidates, + tunnel.as_deref(), + ) { + emit_transparent_policy_denial(&decision, workload_addr, &host, port); + emit_activity(&activity_tx, true, "transparent_tcp_tunnel_unsupported"); + return Ok(()); + } generation_guard.ensure_current()?; let mut upstream = dial_transparent_upstream(&upstream_proxy, &host, port, &approved_real_ip_candidates) @@ -2095,8 +2119,9 @@ async fn handle_tcp_connection( return Ok(()); } + let tunnel_id = query_tunnel_id(&decision); let upstream_result = tokio::select! { - result = dial_upstream(&upstream_proxy, &host_lc, &raw_host_lc, port, connector.addrs()) => Some(result), + result = dial_upstream(&upstream_proxy, &host_lc, &raw_host_lc, port, connector.addrs(), tunnel_id.as_deref(), decision.policy_generation) => Some(result), () = connect_generation_guard.wait_until_stale() => None, }; let Some(upstream_result) = upstream_result else { @@ -4025,13 +4050,49 @@ fn validate_declared_endpoint_resolved_addrs( /// Both paths return a [`upstream_proxy::PrefixedStream`]: for proxied /// dials it replays any tunneled bytes that arrived in the same read as the /// CONNECT response; for direct dials it is a plain passthrough. -async fn dial_upstream( +pub(crate) async fn dial_upstream( upstream_proxy: &Option, host_lc: &str, raw_host_lc: &str, port: u16, addrs: &[SocketAddr], + tunnel_id: Option<&str>, + policy_generation: u64, ) -> std::io::Result { + if let Some(id) = tunnel_id { + let manager = TUNNEL_MANAGER + .try_with(Clone::clone) + .ok() + .flatten() + .ok_or_else(|| { + std::io::Error::new(std::io::ErrorKind::PermissionDenied, "tunnel unavailable") + })?; + let [address] = addrs else { + return Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "tunnel requires one validated address", + )); + }; + return manager + .dial(id, *address, policy_generation) + .await + .map(upstream_proxy::PrefixedStream::from_tunnel); + } + if TUNNEL_MANAGER + .try_with(|manager| { + manager.as_ref().is_some_and(|tunnel| { + addrs + .iter() + .any(|address| tunnel.owns_destination(*address)) + }) + }) + .unwrap_or(false) + { + return Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "tunneled destination lacks route selection", + )); + } if let Some(cfg) = upstream_proxy.as_ref() { return match cfg.decision(host_lc, port, addrs) { upstream_proxy::ProxyDecision::Proxy(endpoint) => { @@ -4240,6 +4301,31 @@ fn query_allowed_ips(decision: &EgressDecision) -> Vec { .unwrap_or_default() } +/// Return the tunnel selected by the authorized inner endpoint snapshot. +fn query_tunnel_id(decision: &EgressDecision) -> Option { + decision.endpoint.policy_configs.first().and_then(|config| { + let regorus::Value::Object(fields) = config else { + return None; + }; + match fields.get(®orus::Value::String("tunnel_id".into())) { + Some(regorus::Value::String(id)) if !id.is_empty() => Some(id.to_string()), + _ => None, + } + }) +} + +/// Transparent TCP has no phase-1 tunnel transport. Refuse a selected route +/// and any stale policy decision that would dial its inner address directly. +#[cfg(any(target_os = "linux", test))] +pub(crate) fn transparent_tunnel_route_refused( + tunnel_id: Option<&str>, + approved: &[SocketAddr], + tunnel: Option<&TunnelManager>, +) -> bool { + tunnel_id.is_some_and(|id| !id.is_empty()) + || tunnel.is_some_and(|manager| approved.iter().any(|addr| manager.owns_destination(*addr))) +} + fn endpoint_config_string_array(config: ®orus::Value, key: &str) -> Vec { let regorus::Value::Object(fields) = config else { return Vec::new(); @@ -4533,7 +4619,7 @@ fn canonicalize_forward_host_header(raw: &[u8], authority: &str) -> Result 0, "forward request ended before headers"); + request.extend_from_slice(&buf[..n]); + if request.windows(4).any(|bytes| bytes == b"\r\n\r\n") { + break; + } + } + stream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") + .await + .unwrap(); + request + }); + let (allow_result, request, response) = tokio::time::timeout( + Duration::from_secs(20), + Box::pin(async { tokio::join!(handler, appliance_request, client) }), + ) + .await + .expect("forward tunnel request timed out"); + allow_result.expect("forward handler"); + let request = String::from_utf8(request).unwrap(); + assert!(request.contains("Authorization: Bearer appliance-secret")); + assert!(!request.contains("openshell:resolve:env:")); + assert!(String::from_utf8_lossy(&response.unwrap()).contains("200 OK")); + + let denied_listener = tokio_wireguard::TcpListener::bind("10.80.0.2:8081", &appliance) + .await + .unwrap(); + let denied_proxy = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let denied_proxy_port = denied_proxy.local_addr().unwrap().port(); + let denied_client = tokio::spawn(async move { + let mut socket = TcpStream::connect(("127.0.0.1", denied_proxy_port)) + .await + .unwrap(); + socket + .write_all(b"GET http://10.80.0.2:8081/p HTTP/1.1\r\nHost: 10.80.0.2:8081\r\n\r\n") + .await + .unwrap(); + let mut response = Vec::new(); + socket.read_to_end(&mut response).await.unwrap(); + response + }); + let (denied_server, _) = denied_proxy.accept().await.unwrap(); + let denied_handler = Box::pin(TUNNEL_MANAGER.scope( + Some(manager), + handle_tcp_connection( + denied_server, + engine, + Arc::new(BinaryIdentityCache::new()), + Arc::new(AtomicU32::new(std::process::id())), + None, + None, + None, + AgentProposals::default(), + Arc::new(None), + Arc::new(None), + Some(credentials.clone()), + credentials.resolver(), + None, + None, + None, + ), + )); + let (denied_result, denied_response) = tokio::time::timeout( + Duration::from_secs(10), + Box::pin(async { tokio::join!(denied_handler, denied_client) }), + ) + .await + .expect("denied forward request timed out"); + denied_result.expect("denied forward handler"); + assert!(String::from_utf8_lossy(&denied_response.unwrap()).starts_with("HTTP/1.1 403")); + assert!( + tokio::time::timeout(Duration::from_millis(100), denied_listener.accept()) + .await + .is_err(), + "policy-denied destination must never reach the appliance" + ); + appliance.close(); + } + /// End-to-end regression for the gator finding on PR #2162: with no TLS /// termination state, a terminating `CONNECT` must have its 503 written as /// the FIRST bytes on the socket — never after a `200 Connection diff --git a/crates/openshell-supervisor-network/src/proxy/destination.rs b/crates/openshell-supervisor-network/src/proxy/destination.rs index 1ce514133a..e2e2b37297 100644 --- a/crates/openshell-supervisor-network/src/proxy/destination.rs +++ b/crates/openshell-supervisor-network/src/proxy/destination.rs @@ -15,9 +15,8 @@ use super::{ resolve_and_reject_internal, }; use ipnet::IpNet; -use openshell_core::net::{connect_tcp_nodelay_best_effort, is_always_blocked_ip, is_internal_ip}; +use openshell_core::net::{is_always_blocked_ip, is_internal_ip}; use std::net::{IpAddr, SocketAddr}; -use tokio::net::TcpStream; /// Address-validation mode selected from the current endpoint configuration. #[derive(Debug, Clone, PartialEq, Eq)] @@ -242,11 +241,8 @@ pub(crate) fn filter_resolved_addresses( /// Validated, but not yet opened, upstream destination. /// -/// The explicit proxy adapter controls when `connect` is called so CONNECT and -/// forward HTTP retain their current upstream-dial timing during the refactor. +/// The explicit proxy adapter controls the upstream dial after validation. pub(crate) struct UpstreamConnector { - host: String, - port: u16, addrs: Vec, } @@ -255,25 +251,8 @@ impl UpstreamConnector { &self.addrs } - /// Opens the connection with `TCP_NODELAY` set: this is the upstream dial - /// boundary for latency-sensitive proxied request/response traffic, where - /// Nagle would stall sub-MSS writes on delayed ACKs. - pub(crate) async fn connect(&self) -> std::io::Result { - tracing::debug!( - host = %self.host, - port = self.port, - address_count = self.addrs.len(), - "Opening validated upstream connection" - ); - connect_tcp_nodelay_best_effort(self.addrs.as_slice()).await - } - - pub(crate) fn new(host: &str, port: u16, addrs: Vec) -> Self { - Self { - host: host.to_string(), - port, - addrs, - } + pub(crate) const fn new(addrs: Vec) -> Self { + Self { addrs } } } @@ -332,7 +311,7 @@ pub(crate) async fn validate_destination( .collect(), }; - Ok(UpstreamConnector::new(host, port, addrs)) + Ok(UpstreamConnector::new(addrs)) } #[cfg(test)] @@ -349,19 +328,6 @@ mod tests { } } - /// Regression test: the shared upstream dial boundary sets `TCP_NODELAY`. - #[tokio::test] - async fn upstream_connector_sets_tcp_nodelay() { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("bind listener"); - let addr = listener.local_addr().expect("local addr"); - - let connector = UpstreamConnector::new("127.0.0.1", addr.port(), vec![addr]); - let stream = connector.connect().await.expect("connect"); - assert!(stream.nodelay().expect("query TCP_NODELAY")); - } - #[tokio::test] async fn default_mode_classifies_loopback_as_internal_address() { let plan = DestinationValidationPlan { diff --git a/crates/openshell-supervisor-network/src/run.rs b/crates/openshell-supervisor-network/src/run.rs index bb34aea6d2..170552cfe7 100644 --- a/crates/openshell-supervisor-network/src/run.rs +++ b/crates/openshell-supervisor-network/src/run.rs @@ -37,6 +37,7 @@ use crate::l7::tls::{ use crate::opa::OpaEngine; use crate::policy_local::PolicyLocalContext; use crate::proxy::ProxyHandle; +use crate::tunnel::TunnelManager; #[cfg(target_os = "linux")] pub struct TransparentRuntimeSetup { @@ -149,6 +150,7 @@ fn advance_allocation_epoch(path: &std::path::Path, sandbox_id: Option<&str>) -> /// `run_sandbox`'s frame. pub struct Networking { pub proxy: Option, + _tunnel: Option>, pub ca_file_paths: Option<(std::path::PathBuf, std::path::PathBuf)>, /// Policy-local route context: shared with the orchestrator's policy poll @@ -198,6 +200,11 @@ pub async fn run_networking( upstream_proxy_args: &crate::upstream_proxy::UpstreamProxyArgs, #[cfg(target_os = "linux")] transparent_runtime: Option, ) -> Result { + let tunnel = retained_proto + .map(|proto| TunnelManager::new(proto, provider_credentials)) + .transpose()? + .flatten() + .map(Arc::new); // Build the policy-local route context. The orchestrator's policy poll // loop also holds an `Arc` clone (via `Networking::policy_local_ctx`) so // it can publish updated policy snapshots after a successful reload. @@ -231,6 +238,7 @@ pub async fn run_networking( let resolve_engine = engine.clone(); let resolve_proto = proto.clone(); let resolve_pid = entrypoint_pid.clone(); + let resolve_tunnel = tunnel.clone(); tokio::spawn(async move { // Phase 1: wait for run_process to publish the entrypoint PID. // 20 attempts * 250ms = 5s window. @@ -251,6 +259,9 @@ pub async fn run_networking( "Entrypoint PID never published; binary symlink resolution skipped. \ Policy binary paths will be matched literally." ); + if let Some(tunnel) = &resolve_tunnel { + tunnel.accept_initial_generation(resolve_engine.current_generation()); + } let _ = engine_ready_tx.send(true); return; } @@ -282,6 +293,9 @@ pub async fn run_networking( ); } } + if let Some(tunnel) = &resolve_tunnel { + tunnel.accept_initial_generation(resolve_engine.current_generation()); + } let _ = engine_ready_tx.send(true); return; } @@ -298,10 +312,16 @@ pub async fn run_networking( If binaries are symlinks, use canonical paths in your policy \ (run 'readlink -f ' inside the sandbox)" ); + if let Some(tunnel) = &resolve_tunnel { + tunnel.accept_initial_generation(resolve_engine.current_generation()); + } let _ = engine_ready_tx.send(true); }); } else { // No process supervisor — PID will never arrive, skip symlink resolution. + if let Some(tunnel) = &tunnel { + tunnel.accept_initial_generation(engine.current_generation()); + } let _ = engine_ready_tx.send(true); } } else { @@ -451,6 +471,7 @@ pub async fn run_networking( engine_ready_rx, upstream_proxy_args, sandbox_id, + tunnel.clone(), ) .await?; Some(proxy_handle) @@ -487,6 +508,7 @@ pub async fn run_networking( upstream_proxy_args, sandbox_id, transparent_engine_ready_rx, + tunnel.clone(), )?; (Some(dns), Some(transparent)) } else { @@ -495,6 +517,7 @@ pub async fn run_networking( Ok(Networking { proxy: proxy_handle, + _tunnel: tunnel, ca_file_paths, policy_local_ctx, #[cfg(target_os = "linux")] diff --git a/crates/openshell-supervisor-network/src/tunnel.rs b/crates/openshell-supervisor-network/src/tunnel.rs new file mode 100644 index 0000000000..8bb5aaa887 --- /dev/null +++ b/crates/openshell-supervisor-network/src/tunnel.rs @@ -0,0 +1,496 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Supervisor-owned `WireGuard` transport for one policy-authorized IPv4 endpoint. + +use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; +use std::sync::OnceLock; +use std::time::Duration; + +use base64::Engine as _; +use ipnet::IpNet; +use miette::Result; +use openshell_core::proto::{NetworkEndpoint, SandboxPolicy}; +use openshell_core::provider_credentials::ProviderCredentialState; +use tokio_wireguard::config::{Config, Interface as InterfaceConfig, Peer}; +use tokio_wireguard::interface::Interface; +use tokio_wireguard::x25519::{PublicKey, StaticSecret}; + +/// A single revision-scoped tunnel route. Its drop closes the userspace interface. +pub struct TunnelManager { + id: String, + destination: SocketAddrV4, + accepted_generation: OnceLock, + interface: tokio::sync::OnceCell, + private_key: [u8; 32], + peer_public_key: [u8; 32], + endpoint: SocketAddrV4, + local_address: tokio_wireguard::config::Address, + route: IpNet, + mtu: usize, + keepalive: u16, +} + +impl TunnelManager { + pub(crate) fn owns_destination(&self, address: SocketAddr) -> bool { + address == SocketAddr::V4(self.destination) + } + /// Validate the one-tunnel policy and start its supervisor-only UDP socket. + pub(crate) fn new( + policy: &SandboxPolicy, + credentials: &ProviderCredentialState, + ) -> Result> { + let single_port = |endpoint: &NetworkEndpoint| match endpoint.ports.as_slice() { + [] if endpoint.port != 0 => Some(endpoint.port), + [port] if endpoint.port == 0 || endpoint.port == *port => Some(*port), + _ => None, + }; + if policy.tunnels.is_empty() { + if policy.network_policies.values().any(|rule| { + rule.endpoints + .iter() + .any(|endpoint| !endpoint.tunnel_id.is_empty()) + }) { + return Err(miette::miette!( + "tunneled endpoint has no tunnel configuration" + )); + } + return Ok(None); + } + if policy.tunnels.len() != 1 { + return Err(miette::miette!("phase 1 supports exactly one tunnel")); + } + let (id, tunnel) = policy.tunnels.iter().next().expect("one tunnel"); + if id.is_empty() { + return Err(miette::miette!("tunnel name is empty")); + } + let endpoint_ip: Ipv4Addr = tunnel + .endpoint_host + .parse() + .map_err(|_| miette::miette!("phase 1 requires an IPv4 appliance address"))?; + let endpoint_port = u16::try_from(tunnel.endpoint_udp_port) + .ok() + .filter(|port| *port != 0) + .ok_or_else(|| miette::miette!("invalid appliance UDP port"))?; + let outer_allowed = policy + .network_policies + .values() + .flat_map(|rule| &rule.endpoints) + .filter(|endpoint| { + endpoint.protocol == "wireguard-udp" + && endpoint.host == tunnel.endpoint_host + && single_port(endpoint) == Some(u32::from(endpoint_port)) + }) + .count() + == 1; + if !outer_allowed { + return Err(miette::miette!( + "appliance UDP endpoint is not exactly authorized" + )); + } + let inner: Vec<_> = policy + .network_policies + .values() + .flat_map(|rule| &rule.endpoints) + .filter(|endpoint| !endpoint.tunnel_id.is_empty()) + .collect(); + if inner.len() != 1 || inner[0].tunnel_id != *id { + return Err(miette::miette!( + "phase 1 requires one inner endpoint bound to the tunnel" + )); + } + let endpoint = inner[0]; + let inner_ip: Ipv4Addr = endpoint + .host + .parse() + .map_err(|_| miette::miette!("phase 1 requires an IPv4 literal inner endpoint"))?; + let inner_port = u16::try_from(single_port(endpoint).unwrap_or(0)) + .ok() + .filter(|port| *port != 0) + .ok_or_else(|| miette::miette!("invalid inner endpoint port"))?; + if endpoint.allowed_ips != [inner_ip.to_string()] { + return Err(miette::miette!( + "inner endpoint must have one port and exact allowed IP" + )); + } + if tunnel.allowed_inner_cidrs.len() != 1 { + return Err(miette::miette!("phase 1 requires one inner CIDR")); + } + let route: IpNet = tunnel.allowed_inner_cidrs[0] + .parse() + .map_err(|_| miette::miette!("invalid inner tunnel CIDR"))?; + if !matches!(route, IpNet::V4(_)) + || route.prefix_len() == 0 + || !route.contains(&std::net::IpAddr::V4(inner_ip)) + { + return Err(miette::miette!("inner endpoint is outside tunnel route")); + } + let key_name = &tunnel.private_key_env_key; + if !key_name.starts_with("OPENSHELL_WG_") + || key_name.len() == "OPENSHELL_WG_".len() + || !key_name + .bytes() + .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_') + { + return Err(miette::miette!("invalid tunnel private key reference")); + } + credentials.remove_env_key(key_name); + let private_key = credentials + .supervisor_tunnel_private_key(key_name) + .ok_or_else(|| miette::miette!("tunnel key unavailable"))?; + let decode = |value: &[u8]| -> Result<[u8; 32]> { + value + .try_into() + .map_err(|_| miette::miette!("invalid WireGuard key length")) + }; + let private = decode( + &base64::engine::general_purpose::STANDARD + .decode(private_key) + .map_err(|_| miette::miette!("invalid WireGuard private key encoding"))?, + )?; + let public = decode(&tunnel.peer_public_key)?; + let local_address = tunnel + .local_address + .parse() + .map_err(|_| miette::miette!("invalid local tunnel address"))?; + let mtu = if tunnel.mtu == 0 { 1280 } else { tunnel.mtu }; + if !(1200..=1420).contains(&mtu) { + return Err(miette::miette!("tunnel MTU out of bounds")); + } + let keepalive = if tunnel.keepalive_seconds == 0 { + 25 + } else { + tunnel.keepalive_seconds + }; + if !(5..=120).contains(&keepalive) { + return Err(miette::miette!("tunnel keepalive out of bounds")); + } + Ok(Some(Self { + id: id.clone(), + destination: SocketAddrV4::new(inner_ip, inner_port), + accepted_generation: OnceLock::new(), + interface: tokio::sync::OnceCell::new(), + private_key: private, + peer_public_key: public, + endpoint: SocketAddrV4::new(endpoint_ip, endpoint_port), + local_address, + route, + mtu: mtu as usize, + keepalive: u16::try_from(keepalive).expect("validated keepalive bounds"), + })) + } + + /// Accept only the generation resulting from initial binary reconciliation. + pub(crate) fn accept_initial_generation(&self, generation: u64) { + let _ = self.accepted_generation.set(generation); + } + + /// Connect only the destination pinned by the validated endpoint decision. + pub(crate) async fn dial( + &self, + id: &str, + destination: SocketAddr, + policy_generation: u64, + ) -> std::io::Result { + if id != self.id + || destination != SocketAddr::V4(self.destination) + || self.accepted_generation.get() != Some(&policy_generation) + { + return Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "tunnel route unavailable", + )); + } + let interface = self + .interface + .get_or_try_init(|| async { + Interface::new(Config { + interface: InterfaceConfig { + private_key: StaticSecret::from(self.private_key), + address: self.local_address, + listen_port: None, + mtu: Some(self.mtu), + }, + peers: vec![Peer { + endpoint: Some(SocketAddr::V4(self.endpoint)), + allowed_ips: vec![self.route], + public_key: PublicKey::from(self.peer_public_key), + persistent_keepalive: Some(self.keepalive), + }], + }) + }) + .await?; + if interface.is_closed() { + return Err(std::io::Error::new( + std::io::ErrorKind::NotConnected, + "tunnel closed", + )); + } + tokio::time::timeout( + Duration::from_secs(10), + tokio_wireguard::TcpStream::connect(destination, interface), + ) + .await + .map_err(|_| std::io::Error::new(std::io::ErrorKind::TimedOut, "tunnel dial timed out"))? + } +} + +impl Drop for TunnelManager { + fn drop(&mut self) { + if let Some(interface) = self.interface.get() { + interface.close(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use openshell_core::proto::{NetworkEndpoint, NetworkPolicyRule, NetworkTunnel}; + use std::collections::HashMap; + use std::sync::Arc; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn userspace_tunnel_connects_injects_and_fails_closed() { + let (server_private, server_public) = tokio_wireguard::x25519::keypair(); + let (client_private, client_public) = tokio_wireguard::x25519::keypair(); + let udp = std::net::UdpSocket::bind("127.0.0.1:0").unwrap(); + let udp_port = udp.local_addr().unwrap().port(); + drop(udp); + let server = Interface::new(Config { + interface: InterfaceConfig { + private_key: server_private, + address: "10.80.0.2/32".parse().unwrap(), + listen_port: Some(udp_port), + mtu: Some(1280), + }, + peers: vec![Peer { + endpoint: None, + allowed_ips: vec!["10.80.0.1/32".parse().unwrap()], + public_key: client_public, + persistent_keepalive: None, + }], + }) + .unwrap(); + let listener = tokio_wireguard::TcpListener::bind("10.80.0.2:8080", &server) + .await + .unwrap(); + let mut policy = SandboxPolicy::default(); + policy.tunnels.insert( + "customer".into(), + NetworkTunnel { + endpoint_host: "127.0.0.1".into(), + endpoint_udp_port: u32::from(udp_port), + peer_public_key: server_public.as_bytes().to_vec(), + private_key_env_key: "OPENSHELL_WG_PRIVATE_KEY".into(), + local_address: "10.80.0.1/32".into(), + allowed_inner_cidrs: vec!["10.80.0.2/32".into()], + ..Default::default() + }, + ); + policy.network_policies.insert( + "outer".into(), + NetworkPolicyRule { + endpoints: vec![NetworkEndpoint { + host: "127.0.0.1".into(), + port: u32::from(udp_port), + ports: vec![u32::from(udp_port)], + protocol: "wireguard-udp".into(), + ..Default::default() + }], + ..Default::default() + }, + ); + policy.network_policies.insert( + "inner".into(), + NetworkPolicyRule { + endpoints: vec![NetworkEndpoint { + host: "10.80.0.2".into(), + port: 8080, + ports: vec![8080], + allowed_ips: vec!["10.80.0.2".into()], + tunnel_id: "customer".into(), + ..Default::default() + }], + ..Default::default() + }, + ); + let credentials = ProviderCredentialState::from_environment( + 1, + HashMap::from([( + "OPENSHELL_WG_PRIVATE_KEY".into(), + base64::engine::general_purpose::STANDARD.encode(client_private.to_bytes()), + )]), + HashMap::new(), + HashMap::new(), + ); + let unrelated = ProviderCredentialState::from_environment( + 1, + HashMap::from([("API_TOKEN".into(), "must-stay-visible".into())]), + HashMap::new(), + HashMap::new(), + ); + policy + .tunnels + .get_mut("customer") + .unwrap() + .private_key_env_key = "API_TOKEN".into(); + assert!(TunnelManager::new(&policy, &unrelated).is_err()); + assert!(unrelated.snapshot().child_env.contains_key("API_TOKEN")); + policy + .tunnels + .get_mut("customer") + .unwrap() + .private_key_env_key = "OPENSHELL_WG_PRIVATE_KEY".into(); + let manager = TunnelManager::new(&policy, &credentials).unwrap().unwrap(); + assert!(crate::proxy::transparent_tunnel_route_refused( + Some("customer"), + &["10.80.0.2:8080".parse().unwrap()], + Some(&manager), + )); + assert!(crate::proxy::transparent_tunnel_route_refused( + None, + &["10.80.0.2:8080".parse().unwrap()], + Some(&manager), + )); + assert!(!crate::proxy::transparent_tunnel_route_refused( + None, + &["10.80.0.3:8080".parse().unwrap()], + Some(&manager), + )); + assert!( + !credentials + .snapshot() + .child_env + .contains_key("OPENSHELL_WG_PRIVATE_KEY") + ); + credentials.install_environment( + 2, + HashMap::from([( + "OPENSHELL_WG_PRIVATE_KEY".into(), + base64::engine::general_purpose::STANDARD.encode(client_private.to_bytes()), + )]), + HashMap::new(), + HashMap::new(), + ); + assert!( + !credentials + .snapshot() + .child_env + .contains_key("OPENSHELL_WG_PRIVATE_KEY") + ); + assert!( + manager + .dial("customer", "10.80.0.2:8080".parse().unwrap(), 1) + .await + .is_err() + ); + manager.accept_initial_generation(42); + assert!( + manager + .dial("wrong", "10.80.0.2:8080".parse().unwrap(), 42) + .await + .is_err() + ); + assert!( + manager + .dial("customer", "10.80.0.2:8080".parse().unwrap(), 43) + .await + .is_err() + ); + assert!( + manager + .dial("customer", "10.80.0.3:8080".parse().unwrap(), 42) + .await + .is_err() + ); + let (client, accepted) = tokio::join!( + tokio::time::timeout( + Duration::from_secs(15), + manager.dial("customer", "10.80.0.2:8080".parse().unwrap(), 42), + ), + tokio::time::timeout(Duration::from_secs(15), listener.accept()), + ); + let mut client = client.expect("WireGuard TCP connect timed out").unwrap(); + let (mut appliance, _) = accepted.expect("appliance accept timed out").unwrap(); + client.write_all(b"ping").await.unwrap(); + let mut message = [0; 4]; + appliance.read_exact(&mut message).await.unwrap(); + assert_eq!(&message, b"ping"); + let (_, resolver) = openshell_core::secrets::SecretResolver::from_provider_env( + HashMap::from([("API_TOKEN".into(), "appliance-secret".into())]), + ); + let raw = b"GET http://10.80.0.2:8080/p HTTP/1.1\r\nHost: 10.80.0.2:8080\r\nAuthorization: Bearer openshell:resolve:env:API_TOKEN\r\n\r\n"; + let rewritten = crate::proxy::rewrite_forward_request( + raw, + raw.len(), + "/p", + "10.80.0.2:8080", + resolver.as_ref(), + false, + ) + .unwrap(); + client.write_all(&rewritten).await.unwrap(); + let mut observed = vec![0; rewritten.len()]; + appliance.read_exact(&mut observed).await.unwrap(); + assert!( + String::from_utf8_lossy(&observed).contains("Authorization: Bearer appliance-secret") + ); + assert!(!String::from_utf8_lossy(&observed).contains("openshell:resolve:env:")); + drop(client); + drop(appliance); + drop(listener); + server.close(); + tokio::time::timeout(Duration::from_secs(5), server.closed()) + .await + .expect("server close timed out"); + // A selected tunnel route must never reach a direct listener, even + // when that listener could accept an ordinary TCP connection. + let direct_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let direct = direct_listener.local_addr().unwrap(); + let manager = Arc::new(manager); + let dial = crate::proxy::TUNNEL_MANAGER.scope(Some(Arc::clone(&manager)), async { + crate::proxy::dial_upstream( + &None, + "127.0.0.1", + "127.0.0.1", + direct.port(), + &[direct], + Some("customer"), + 42, + ) + .await + }); + assert!( + dial.await.is_err(), + "unrouted selected tunnel dial must fail" + ); + assert!( + tokio::time::timeout(Duration::from_millis(100), direct_listener.accept()) + .await + .is_err(), + "direct listener must observe no fallback connection" + ); + + let down_dial = crate::proxy::TUNNEL_MANAGER.scope(Some(manager), async { + crate::proxy::dial_upstream( + &None, + "10.80.0.2", + "10.80.0.2", + 8080, + &["10.80.0.2:8080".parse().unwrap()], + Some("customer"), + 42, + ) + .await + }); + assert!( + tokio::time::timeout(Duration::from_secs(15), down_dial) + .await + .expect("down appliance dial must time out") + .is_err(), + "down appliance must refuse the selected tunnel dial" + ); + } +} diff --git a/crates/openshell-supervisor-network/src/upstream_proxy.rs b/crates/openshell-supervisor-network/src/upstream_proxy.rs index 78a4c41682..f03700f1d7 100644 --- a/crates/openshell-supervisor-network/src/upstream_proxy.rs +++ b/crates/openshell-supervisor-network/src/upstream_proxy.rs @@ -868,6 +868,7 @@ fn basic_auth_header(credential: &str) -> Result { enum UpstreamStream { Plain(TcpStream), Tls(Box>), + Tunnel(tokio_wireguard::TcpStream), } impl AsyncRead for UpstreamStream { @@ -879,6 +880,7 @@ impl AsyncRead for UpstreamStream { match self.get_mut() { Self::Plain(s) => Pin::new(s).poll_read(cx, buf), Self::Tls(s) => Pin::new(s.as_mut()).poll_read(cx, buf), + Self::Tunnel(s) => Pin::new(s).poll_read(cx, buf), } } } @@ -892,6 +894,7 @@ impl AsyncWrite for UpstreamStream { match self.get_mut() { Self::Plain(s) => Pin::new(s).poll_write(cx, buf), Self::Tls(s) => Pin::new(s.as_mut()).poll_write(cx, buf), + Self::Tunnel(s) => Pin::new(s).poll_write(cx, buf), } } @@ -903,6 +906,7 @@ impl AsyncWrite for UpstreamStream { match self.get_mut() { Self::Plain(s) => Pin::new(s).poll_write_vectored(cx, bufs), Self::Tls(s) => Pin::new(s.as_mut()).poll_write_vectored(cx, bufs), + Self::Tunnel(s) => Pin::new(s).poll_write_vectored(cx, bufs), } } @@ -910,6 +914,7 @@ impl AsyncWrite for UpstreamStream { match self { Self::Plain(s) => s.is_write_vectored(), Self::Tls(s) => s.is_write_vectored(), + Self::Tunnel(s) => s.is_write_vectored(), } } @@ -917,6 +922,7 @@ impl AsyncWrite for UpstreamStream { match self.get_mut() { Self::Plain(s) => Pin::new(s).poll_flush(cx), Self::Tls(s) => Pin::new(s.as_mut()).poll_flush(cx), + Self::Tunnel(s) => Pin::new(s).poll_flush(cx), } } @@ -924,6 +930,7 @@ impl AsyncWrite for UpstreamStream { match self.get_mut() { Self::Plain(s) => Pin::new(s).poll_shutdown(cx), Self::Tls(s) => Pin::new(s.as_mut()).poll_shutdown(cx), + Self::Tunnel(s) => Pin::new(s).poll_shutdown(cx), } } } @@ -964,6 +971,12 @@ impl PrefixedStream { Self::new(inner, Vec::new()) } + /// Wrap a supervisor-owned userspace `WireGuard` TCP stream. + #[must_use] + pub fn from_tunnel(inner: tokio_wireguard::TcpStream) -> Self { + Self::over(UpstreamStream::Tunnel(inner), Vec::new()) + } + /// Wrap an already-established upstream connection (plain or TLS-wrapped /// proxy), replaying `prefix` before further reads. fn over(inner: UpstreamStream, prefix: Vec) -> Self { @@ -986,6 +999,7 @@ impl PrefixedStream { match &self.inner { UpstreamStream::Plain(s) => s.peer_addr(), UpstreamStream::Tls(s) => s.get_ref().0.peer_addr(), + UpstreamStream::Tunnel(s) => s.peer_addr(), } } diff --git a/docs/reference/policy-schema.mdx b/docs/reference/policy-schema.mdx index 679c44f85b..bdc0237806 100644 --- a/docs/reference/policy-schema.mdx +++ b/docs/reference/policy-schema.mdx @@ -21,6 +21,7 @@ landlock: { ... } process: { ... } network_policies: { ... } network_middlewares: { ... } +tunnels: { ... } ``` | Field | Type | Required | Category | Description | @@ -31,6 +32,7 @@ network_middlewares: { ... } | `process` | object | No | Static | Sets the user and group the agent process runs as. | | `network_policies` | map | No | Dynamic | Declares which binaries can reach which network endpoints. | | `network_middlewares` | map | No | Dynamic | Attaches ordered middleware by destination host; each implementation's manifest selects its supported HTTP and WebSocket operations. | +| `tunnels` | map | No | Static | Names one supervisor-owned customer-appliance WireGuard connection. Phase 1 requires sandbox restart after policy changes. | Static fields are set at sandbox creation time. Changing them requires destroying and recreating the sandbox. Dynamic fields can be updated on a running sandbox with `openshell policy update` for incremental merges or `openshell policy set` for full replacement, and take effect without restarting. @@ -144,6 +146,50 @@ process: A map of named network policy entries. Each entry declares a set of endpoints and a set of binaries. Only the listed binaries are permitted to connect to the listed endpoints. The map key is a logical identifier. The `name` field inside the entry is the display name used in logs. +### Customer appliance tunnel + +Phase 1 supports one named tunnel and one private IPv4 literal destination. The tunnel is a supervisor transport; the workload receives no tunnel interface or key. The appliance needs a reachable WireGuard UDP listener and a peer entry for the supervisor's public key and local tunnel address. The application must provision the private key as a sandbox-scoped provider credential before the sandbox starts, then set `private_key_env_key` to its environment key. The key name must start with `OPENSHELL_WG_` and continue with uppercase letters, digits, or underscores. The supervisor removes that key from the workload environment. + +| `tunnels.` field | Type | Description | +|---|---|---| +| `endpoint_host` | IPv4 literal | Exact public appliance address. | +| `endpoint_udp_port` | integer | Exact WireGuard UDP port, 1 through 65535. | +| `peer_public_key` | base64 string | Raw 32-byte WireGuard public key of the appliance. | +| `private_key_env_key` | string | Supervisor-only provider credential environment key containing the base64-encoded raw 32-byte private key. No private key bytes appear in policy. | +| `local_address` | IPv4 CIDR | Supervisor address inside the tunnel. | +| `allowed_inner_cidrs` | one-item list | IPv4 route containing the inner endpoint; default routes are refused. | +| `mtu` | integer | Optional, defaults to 1280; range 1200–1420. | +| `keepalive_seconds` | integer | Optional, defaults to 25; range 5–120. | + +Add an exact `protocol: wireguard-udp` endpoint for `endpoint_host` and `endpoint_udp_port`. This endpoint only permits the supervisor's UDP socket; it never grants workload TCP access. Add a separate inner endpoint with an IPv4 `host`, one `port`, `allowed_ips` containing exactly that IPv4 address, and `tunnel_id` equal to the tunnel name. The inner endpoint's protocol, TLS mode, L7 rules, credential binding, and `upstream_ca_pem` still govern traffic. A tunnel failure refuses the connection without a direct fallback. WireGuard authenticates the appliance public key and does not use a CA. + +```yaml +tunnels: + customer: + endpoint_host: 198.51.100.20 + endpoint_udp_port: 51820 + peer_public_key: AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA= + private_key_env_key: OPENSHELL_WG_PRIVATE_KEY + local_address: 10.80.0.1/32 + allowed_inner_cidrs: [10.80.0.2/32] +network_policies: + appliance_transport: + endpoints: + - host: 198.51.100.20 + port: 51820 + protocol: wireguard-udp + appliance_service: + endpoints: + - host: 10.80.0.2 + port: 8080 + allowed_ips: [10.80.0.2] + tunnel_id: customer + binaries: + - path: /usr/bin/example-app +``` + +The example uses scalar `port`; policy parsing and the OPA adapter normalize it to a one-element `ports` list. The `wireguard-udp` entry is supervisor-only even if a binary is listed under its policy rule. + ### Network Policy Entry Each entry in the `network_policies` map has the following fields: @@ -163,9 +209,10 @@ Each endpoint defines a reachable destination and optional inspection rules. | `host` | string | Conditional | Hostname or IP address. Required for `protocol: tcp`; transparent TCP requires a valid DNS hostname and rejects literal IPs. A non-TCP proxy endpoint may omit `host` only when `allowed_ips` supplies the destination constraint. Supports a `*` wildcard inside the first DNS label only: `*.example.com`, `**.example.com`, and intra-label patterns like `*-aiplatform.googleapis.com` are accepted; bare `*`/`**`, TLD wildcards (`*.com`), and wildcards outside the first label are rejected at load time. Prefer exact hosts for `protocol: tcp`: a wildcard authorizes DNS queries for all matching names and can provide a DNS-label exfiltration channel. | | `port` | integer | Yes | TCP port number. | | `path` | string | No | Optional HTTP path glob used to select between L7 endpoints that share the same host and port. Empty means all paths. Use this when REST and GraphQL live under the same host, such as `/repos/**` and `/graphql`. | -| `protocol` | string | No | Set to `tcp` with a valid DNS hostname to allow native TCP clients through policy DNS and transparent capture without payload inspection. Omit the field for L4 passthrough through an explicit proxy, including legacy hostless `allowed_ips` endpoints. Set to `rest` for HTTP method/path inspection, `websocket` for RFC 6455 upgrade and client text-message inspection, `graphql` for GraphQL-over-HTTP operation inspection, `mcp` for MCP Streamable HTTP request inspection, or `json-rpc` for generic JSON-RPC-over-HTTP method inspection. WebSocket endpoints can also use GraphQL operation rules for GraphQL-over-WebSocket traffic. Provider-credentialed endpoints require an inspected protocol unless `allow_uninspected_credentials` is explicitly set. | +| `protocol` | string | No | Set to `tcp` with a valid DNS hostname to allow native TCP clients through policy DNS and transparent capture without payload inspection. Omit the field for L4 passthrough through an explicit proxy, including legacy hostless `allowed_ips` endpoints. Set to `rest` for HTTP method/path inspection, `websocket` for RFC 6455 upgrade and client text-message inspection, `graphql` for GraphQL-over-HTTP operation inspection, `mcp` for MCP Streamable HTTP request inspection, or `json-rpc` for generic JSON-RPC-over-HTTP method inspection. `wireguard-udp` is reserved for the exact supervisor-owned appliance socket and never authorizes workload traffic. WebSocket endpoints can also use GraphQL operation rules for GraphQL-over-WebSocket traffic. Provider-credentialed endpoints require an inspected protocol unless `allow_uninspected_credentials` is explicitly set. | | `tls` | string | No | TLS handling mode. The proxy auto-detects TLS by peeking the first bytes of each connection and terminates it for inspected HTTPS traffic, so this field is optional in most cases. Set to `skip` to disable auto-detection for edge cases such as client-certificate mTLS or non-standard protocols. Provider-credentialed endpoints reject `tls: skip` unless `allow_uninspected_credentials` is explicitly set. The values `terminate` and `passthrough` are deprecated and log a warning; they are still accepted for backward compatibility but have no effect on behavior. | | `upstream_ca_pem` | string | No | PEM-encoded CA certificate bundle trusted only for the supervisor's TLS connection to this endpoint. Use a YAML block scalar containing one or more `-----BEGIN CERTIFICATE-----` blocks. The supervisor adds these certificates to its normal system roots for this endpoint only; it still terminates client TLS, inspects requests, and rewrites credentials. Cannot be combined with `tls: skip` or `protocol: tcp`. Do not include private keys. | +| `tunnel_id` | string | No | Name of the supervisor tunnel used for this inner IPv4 destination after endpoint authorization. Phase 1 allows one inner endpoint and one port. | | `enforcement` | string | No | `enforce` actively blocks disallowed requests. `audit` logs violations but allows traffic through. | | `access` | string | No | Access preset. One of `read-only`, `read-write`, or `full`. Mutually exclusive with `rules`. Not valid on `protocol: mcp` or `protocol: json-rpc`; MCP uses explicit rules unless `mcp.allow_all_known_mcp_methods: true` enables the endpoint method profile, and JSON-RPC always uses explicit rules. | | `rules` | list of allow rule objects | No | Fine-grained protocol-specific allow rules. Mutually exclusive with `access`. | diff --git a/proto/sandbox.proto b/proto/sandbox.proto index aeba688fc9..fbc8618fb7 100644 --- a/proto/sandbox.proto +++ b/proto/sandbox.proto @@ -31,6 +31,21 @@ message SandboxPolicy { // policy-local names. At most 10 configs are accepted, and at most 10 stages // can be selected per request. map network_middlewares = 6; + // Supervisor-owned WireGuard peers. Key bytes never enter the workload. + map tunnels = 7; +} + +// One supervisor-originated WireGuard transport to a customer appliance. +message NetworkTunnel { + string endpoint_host = 1; + uint32 endpoint_udp_port = 2; + bytes peer_public_key = 3; + // Supervisor-only provider credential key. The material is never stored in policy. + string private_key_env_key = 4; + string local_address = 5; + repeated string allowed_inner_cidrs = 6; + uint32 mtu = 7; + uint32 keepalive_seconds = 8; } // Filesystem access policy. @@ -197,6 +212,8 @@ message NetworkEndpoint { // Additional PEM-encoded CA certificates trusted only when the supervisor // re-encrypts TLS to this endpoint. Does not disable TLS inspection. string upstream_ca_pem = 27; + // Named supervisor WireGuard transport for this inner destination. + string tunnel_id = 28; } // MCP options are grouped so MCP-specific policy can grow without adding more diff --git a/vendor/tokio-wireguard/.cargo_vcs_info.json b/vendor/tokio-wireguard/.cargo_vcs_info.json new file mode 100644 index 0000000000..6c64cdfbd1 --- /dev/null +++ b/vendor/tokio-wireguard/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "4e71d82c4dac3989cd2a4b814144e3ae3dda6613" + }, + "path_in_vcs": "crates/tokio-wireguard" +} \ No newline at end of file diff --git a/vendor/tokio-wireguard/Cargo.lock b/vendor/tokio-wireguard/Cargo.lock new file mode 100644 index 0000000000..15648ed5e4 --- /dev/null +++ b/vendor/tokio-wireguard/Cargo.lock @@ -0,0 +1,1141 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "addr2line" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e4503c46a5c0c7844e948c9a4d6acd9f50cccb4de1c48eb9e291ea17470c678" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" + +[[package]] +name = "backtrace" +version = "0.3.72" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17c6a35df3749d2e8bb1b7b21a976d82b15548788d2735b9d82f329268f71a11" +dependencies = [ + "addr2line", + "cc", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", +] + +[[package]] +name = "base64" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" + +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "boringtun" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "751787b019c674b9ac353f4eaa285e6711c21badb421cd8c199bf2c83b727f29" +dependencies = [ + "aead", + "base64", + "blake2", + "chacha20poly1305", + "hex", + "hmac", + "ip_network", + "ip_network_table", + "libc", + "nix", + "parking_lot", + "rand_core", + "ring", + "tracing", + "untrusted 0.9.0", + "x25519-dalek", +] + +[[package]] +name = "bumpalo" +version = "3.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9" + +[[package]] +name = "cc" +version = "1.0.98" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41c270e7540d725e65ac7f1b212ac8ce349719624d7bcff99f8e2e488e8cf03f" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20", + "cipher", + "poly1305", + "zeroize", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", + "zeroize", +] + +[[package]] +name = "cpufeatures" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53fe5e26ff1b7aef8bca9c6080520cfb8d9333c7568e1829cef191a9723e5504" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "rand_core", + "typenum", +] + +[[package]] +name = "curve25519-dalek" +version = "4.0.0-rc.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "436ace70fc06e06f7f689d2624dc4e2f0ea666efb5aa704215f7249ae6e047a7" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "fiat-crypto", + "platforms", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.66", +] + +[[package]] +name = "defmt" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a99dd22262668b887121d4672af5a64b238f026099f1a2a1b322066c9ecfe9e0" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9f309eff1f79b3ebdf252954d90ae440599c26c2c553fe87a2d17195f2dcb" +dependencies = [ + "defmt-parser", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.66", +] + +[[package]] +name = "defmt-parser" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff4a5fefe330e8d7f31b16a318f9ce81000d8e35e69b93eae154d16d2278f70f" +dependencies = [ + "thiserror", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e825f6987101665dea6ec934c09ec6d721de7bc1bf92248e1d5810c8cd636b77" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "gimli" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40ecd4077b5ae9fd2e9e169b102c6c330d0605168eb0e8bf79952b256dbefffd" + +[[package]] +name = "hash32" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606" +dependencies = [ + "byteorder", +] + +[[package]] +name = "heapless" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad" +dependencies = [ + "hash32", + "stable_deref_trait", +] + +[[package]] +name = "hermit-abi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "inout" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0c10553d664a4d0bcff9f4215d0aac67a639cc68ef660840afe309b807bc9f5" +dependencies = [ + "generic-array", +] + +[[package]] +name = "ip_network" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa2f047c0a98b2f299aa5d6d7088443570faae494e9ae1305e48be000c9e0eb1" + +[[package]] +name = "ip_network_table" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4099b7cfc5c5e2fe8c5edf3f6f7adf7a714c9cc697534f63a5a5da30397cb2c0" +dependencies = [ + "ip_network", + "ip_network_table-deps-treebitmap", +] + +[[package]] +name = "ip_network_table-deps-treebitmap" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e537132deb99c0eb4b752f0346b6a836200eaaa3516dd7e5514b63930a09e5d" + +[[package]] +name = "ipnet" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f518f335dce6725a761382244631d86cf0ccb2863413590b31338feb467f9c3" + +[[package]] +name = "js-sys" +version = "0.3.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.155" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" + +[[package]] +name = "lock_api" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" + +[[package]] +name = "managed" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ca88d725a0a943b096803bd34e73a4437208b6077654cc4ecb2947a5f91618d" + +[[package]] +name = "memchr" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d" + +[[package]] +name = "miniz_oxide" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87dfd01fe195c66b572b37921ad8803d010623c0aca821bea2302239d155cdae" +dependencies = [ + "adler", +] + +[[package]] +name = "mio" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.48.0", +] + +[[package]] +name = "nix" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f346ff70e7dbfd675fe90590b92d59ef2de15a8779ae305ebcbfd3f0caf59be4" +dependencies = [ + "autocfg", + "bitflags 1.3.2", + "cfg-if", + "libc", +] + +[[package]] +name = "num_cpus" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "object" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8ec7ab813848ba4522158d5517a6093db1ded27575b070f4177b8d12b41db5e" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "parking_lot" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-targets 0.52.5", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02" + +[[package]] +name = "platforms" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db23d408679286588f4d4644f965003d056e3dd5abcaaa938116871d7ce2fee7" + +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name = "proc-macro2" +version = "1.0.85" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22244ce15aa966053a896d1accb3a6e68469b97c7f33f284b99f0d576879fc23" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "redox_syscall" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "469052894dcb553421e483e4209ee581a45100d31b4018de03e5a7ad86374a7e" +dependencies = [ + "bitflags 2.5.0", +] + +[[package]] +name = "ring" +version = "0.16.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" +dependencies = [ + "cc", + "libc", + "once_cell", + "spin", + "untrusted 0.7.1", + "web-sys", + "winapi", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" + +[[package]] +name = "rustc_version" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" +dependencies = [ + "semver", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" + +[[package]] +name = "serde" +version = "1.0.203" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7253ab4de971e72fb7be983802300c30b5a7f0c2e56fab8abfc6a214307c0094" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.203" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "500cbc0ebeb6f46627f50f3f5811ccf6bf00643be300b4c3eabc0ef55dc5b5ba" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.66", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" +dependencies = [ + "libc", +] + +[[package]] +name = "smallvec" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" + +[[package]] +name = "smoltcp" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a1a996951e50b5971a2c8c0fa05a381480d70a933064245c4a223ddc87ccc97" +dependencies = [ + "bitflags 1.3.2", + "byteorder", + "cfg-if", + "defmt", + "heapless", + "managed", +] + +[[package]] +name = "socket2" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "spin" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" + +[[package]] +name = "stable_deref_trait" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" + +[[package]] +name = "subtle" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.66" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c42f3f41a2de00b01c0aaad383c5a45241efc8b2d1eda5661812fda5f3cdcff5" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "1.0.61" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c546c80d6be4bc6a00c0f01730c08df82eaa7a7a61f11d656526506112cc1709" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.61" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c3384250002a6d5af4d114f2845d37b57521033f30d5c3f46c4d70e1197533" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.66", +] + +[[package]] +name = "tokio" +version = "1.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba4f4a02a7a80d6f274636f0aa95c7e383b912d41fe721a31f29e29698585a4a" +dependencies = [ + "backtrace", + "bytes", + "libc", + "mio", + "num_cpus", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.48.0", +] + +[[package]] +name = "tokio-macros" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f5ae998a069d4b5aba8ee9dad856af7d520c3699e6159b185c2acd48155d39a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.66", +] + +[[package]] +name = "tokio-wireguard" +version = "0.1.3" +dependencies = [ + "atomic-waker", + "boringtun", + "bytes", + "ipnet", + "parking_lot", + "pin-project-lite", + "rand", + "smoltcp", + "socket2", + "tokio", +] + +[[package]] +name = "tracing" +version = "0.1.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.66", +] + +[[package]] +name = "tracing-core" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" +dependencies = [ + "once_cell", +] + +[[package]] +name = "typenum" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" + +[[package]] +name = "unicode-ident" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "version_check" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "wasm-bindgen" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" +dependencies = [ + "cfg-if", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" +dependencies = [ + "bumpalo", + "log", + "once_cell", + "proc-macro2", + "quote", + "syn 2.0.66", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.66", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" + +[[package]] +name = "web-sys" +version = "0.3.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77afa9a11836342370f4817622a2f0f418b134426d91a82dfb48f532d2ec13ef" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.5", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb" +dependencies = [ + "windows_aarch64_gnullvm 0.52.5", + "windows_aarch64_msvc 0.52.5", + "windows_i686_gnu 0.52.5", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.5", + "windows_x86_64_gnu 0.52.5", + "windows_x86_64_gnullvm 0.52.5", + "windows_x86_64_msvc 0.52.5", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0" + +[[package]] +name = "x25519-dalek" +version = "2.0.0-rc.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec7fae07da688e17059d5886712c933bb0520f15eff2e09cfa18e30968f4e63a" +dependencies = [ + "curve25519-dalek", + "rand_core", + "serde", + "zeroize", +] + +[[package]] +name = "zeroize" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.66", +] diff --git a/vendor/tokio-wireguard/Cargo.toml b/vendor/tokio-wireguard/Cargo.toml new file mode 100644 index 0000000000..998d876eaa --- /dev/null +++ b/vendor/tokio-wireguard/Cargo.toml @@ -0,0 +1,102 @@ +# SPDX-License-Identifier: MIT OR Apache-2.0 +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +rust-version = "1.75" +name = "tokio-wireguard" +version = "0.1.3" +authors = ["Raphaël Thériault "] +description = "In-process WireGuard for Tokio" +readme = "README.md" +keywords = [ + "wireguard", + "tokio", + "wg", +] +categories = [ + "network-programming", + "asynchronous", + "cryptography", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/raftario/river" + +[package.metadata.docs.rs] +rustc-args = ["--cfg=curve25519_dalek_backend=\"serial\""] + +[dependencies.atomic-waker] +version = "1.0" +default-features = false + +[dependencies.boringtun] +version = "0.7.1" +default-features = false + +[dependencies.bytes] +version = "1.0" +default-features = false + +[dependencies.ipnet] +version = "2.2" +features = ["std"] +default-features = false + +[dependencies.parking_lot] +version = "0.12.1" +features = [ + "arc_lock", + "send_guard", +] +default-features = false + +[dependencies.pin-project-lite] +version = "0.2.12" +default-features = false + +[dependencies.rand] +version = "0.8.4" +features = ["getrandom"] +default-features = false + +[dependencies.smoltcp] +version = "0.11.0" +features = [ + "std", + "medium-ip", + "proto-ipv4", + "proto-ipv6", + "socket-tcp", + "socket-udp", + "async", +] +default-features = false + +[dependencies.socket2] +version = "0.5.3" +default-features = false + +[dependencies.tokio] +version = "1.30" +features = [ + "rt", + "net", + "time", + "sync", + "io-util", + "parking_lot", +] +default-features = false + +[dev-dependencies.tokio] +version = "1" +features = ["full"] diff --git a/vendor/tokio-wireguard/Cargo.toml.orig b/vendor/tokio-wireguard/Cargo.toml.orig new file mode 100644 index 0000000000..344e834b17 --- /dev/null +++ b/vendor/tokio-wireguard/Cargo.toml.orig @@ -0,0 +1,48 @@ +# SPDX-License-Identifier: MIT OR Apache-2.0 +[package] +name = "tokio-wireguard" +description = "In-process WireGuard for Tokio" +categories = ["network-programming", "asynchronous", "cryptography"] +keywords = ["wireguard", "tokio", "wg"] +repository = "https://github.com/raftario/river" +version = "0.1.3" +rust-version = "1.75" +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +tokio = { version = "1.30", default-features = false, features = [ + "rt", + "net", + "time", + "sync", + "io-util", + "parking_lot", +] } +boringtun = { version = "0.6.0", default-features = false } +smoltcp = { version = "0.11.0", default-features = false, features = [ + "std", + "medium-ip", + "proto-ipv4", + "proto-ipv6", + "socket-tcp", + "socket-udp", + "async", +] } +bytes = { version = "1.0", default-features = false } +socket2 = { version = "0.5.3", default-features = false } +ipnet = { version = "2.2", default-features = false, features = ["std"] } +parking_lot = { version = "0.12.1", default-features = false, features = [ + "arc_lock", + "send_guard", +] } +rand = { version = "0.8.4", default-features = false, features = ["getrandom"] } +atomic-waker = { version = "1.0", default-features = false } +pin-project-lite = { version = "0.2.12", default-features = false } + +[dev-dependencies] +tokio = { version = "1", features = ["full"] } + +[package.metadata.docs.rs] +rustc-args = ['--cfg=curve25519_dalek_backend="serial"'] diff --git a/vendor/tokio-wireguard/LICENSE-Apache-2.0 b/vendor/tokio-wireguard/LICENSE-Apache-2.0 new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/vendor/tokio-wireguard/LICENSE-Apache-2.0 @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/tokio-wireguard/LICENSE-MIT b/vendor/tokio-wireguard/LICENSE-MIT new file mode 100644 index 0000000000..5eb2161c6c --- /dev/null +++ b/vendor/tokio-wireguard/LICENSE-MIT @@ -0,0 +1,19 @@ +Copyright (c) 2024 Raphaël Thériault + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/tokio-wireguard/README.md b/vendor/tokio-wireguard/README.md new file mode 100644 index 0000000000..cc454b9243 --- /dev/null +++ b/vendor/tokio-wireguard/README.md @@ -0,0 +1,6 @@ +# tokio-wireguard + +In-process WireGuard for Tokio + +[![crates.io](https://img.shields.io/crates/v/tokio-wireguard.svg)](https://crates.io/crates/tokio-wireguard) +[![Documentation](https://docs.rs/tokio-wireguard/badge.svg)](https://docs.rs/tokio-wireguard) diff --git a/vendor/tokio-wireguard/examples/tcp.rs b/vendor/tokio-wireguard/examples/tcp.rs new file mode 100644 index 0000000000..fa26ddc1ef --- /dev/null +++ b/vendor/tokio-wireguard/examples/tcp.rs @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; +use tokio_wireguard::{config::*, x25519, TcpListener, TcpStream}; + +#[tokio::main] +async fn main() { + let (server_secret, server_public) = x25519::keypair(); + let (client_secret, client_public) = x25519::keypair(); + + let server_config = Config { + interface: Interface { + address: "100.64.0.1/32".parse().unwrap(), + private_key: server_secret, + listen_port: Some(51820), + mtu: None, + }, + peers: vec![Peer { + allowed_ips: vec!["100.64.0.2/32".parse().unwrap()], + public_key: client_public, + endpoint: None, + persistent_keepalive: None, + }], + }; + let client_config = Config { + interface: Interface { + address: "100.64.0.2/32".parse().unwrap(), + private_key: client_secret, + listen_port: None, + mtu: None, + }, + peers: vec![Peer { + endpoint: "127.0.0.1:51820".parse().ok(), + allowed_ips: vec!["100.64.0.1/32".parse().unwrap()], + public_key: server_public, + persistent_keepalive: None, + }], + }; + + tokio::spawn(async move { + let server = TcpListener::bind("0.0.0.0:8080", server_config) + .await + .unwrap(); + + println!( + "Listening on {} (.exit to quit)", + server.local_addr().unwrap() + ); + + while let Ok((stream, addr)) = server.accept().await { + tokio::spawn(async move { + let mut stream = BufReader::new(stream).lines(); + while let Some(line) = stream.next_line().await.unwrap() { + println!("[{addr}] {line}"); + } + }); + } + }); + + let mut client = TcpStream::connect("100.64.0.1:8080", client_config) + .await + .unwrap(); + + let mut stdin = BufReader::new(tokio::io::stdin()).lines(); + while let Some(mut message) = stdin.next_line().await.unwrap() { + if message == ".exit" { + break; + } + + message.push('\n'); + client.write_all(message.as_bytes()).await.unwrap(); + } +} diff --git a/vendor/tokio-wireguard/examples/udp.rs b/vendor/tokio-wireguard/examples/udp.rs new file mode 100644 index 0000000000..9410b86fae --- /dev/null +++ b/vendor/tokio-wireguard/examples/udp.rs @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +use tokio::io::{AsyncBufReadExt, BufReader}; +use tokio_wireguard::{config::*, x25519, UdpSocket}; + +#[tokio::main] +async fn main() { + let (server_secret, server_public) = x25519::keypair(); + let (client_secret, client_public) = x25519::keypair(); + + let server_config = Config { + interface: Interface { + address: "100.64.0.1/32".parse().unwrap(), + private_key: server_secret, + listen_port: Some(51820), + mtu: None, + }, + peers: vec![Peer { + allowed_ips: vec!["100.64.0.2/32".parse().unwrap()], + public_key: client_public, + endpoint: None, + persistent_keepalive: None, + }], + }; + let client_config = Config { + interface: Interface { + address: "100.64.0.2/32".parse().unwrap(), + private_key: client_secret, + listen_port: None, + mtu: None, + }, + peers: vec![Peer { + endpoint: "127.0.0.1:51820".parse().ok(), + allowed_ips: vec!["100.64.0.1/32".parse().unwrap()], + public_key: server_public, + persistent_keepalive: None, + }], + }; + + tokio::spawn(async move { + let server = UdpSocket::bind("0.0.0.0:8080", server_config) + .await + .unwrap(); + + println!( + "Listening on {} (.exit to quit)", + server.local_addr().unwrap() + ); + + let mut buf = Vec::new(); + loop { + let (len, addr) = server.recv_from(&mut buf).await.unwrap(); + + let message = std::str::from_utf8(&buf[..len]).unwrap(); + println!("[{addr}] {message}"); + + buf.clear(); + } + }); + + let client = UdpSocket::bind("0.0.0.0:0", client_config).await.unwrap(); + + let mut stdin = BufReader::new(tokio::io::stdin()).lines(); + while let Some(message) = stdin.next_line().await.unwrap() { + if message == ".exit" { + break; + } + + client + .send_to(message.as_bytes(), "100.64.0.1:8080") + .await + .unwrap(); + } +} diff --git a/vendor/tokio-wireguard/src/config.rs b/vendor/tokio-wireguard/src/config.rs new file mode 100644 index 0000000000..dfb33cc4cb --- /dev/null +++ b/vendor/tokio-wireguard/src/config.rs @@ -0,0 +1,271 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +use std::{ + array, fmt, + net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}, + str::FromStr, +}; + +use boringtun::x25519::{PublicKey, StaticSecret}; +use ipnet::{IpNet, Ipv4Net, Ipv6Net}; + +/// WireGuard configuration +pub struct Config { + /// Local interface configuration + pub interface: Interface, + /// Remote peer configurations + /// + /// Peers can also be added and removed dynamically at runtime using + /// [`Interface::add_peer`](crate::Interface::add_peer) and [`Interface::remove_peer`](crate::Interface::remove_peer). + pub peers: Vec, +} + +/// Local interface configuration +pub struct Interface { + /// Local WireGuard address + /// + /// This is the address of the local peer on the WireGuard network, + /// as opposed to the address on which WireGuard traffic is tunneled. + /// + /// This should be a unicast IPv4 or IPv6 address, or both. The network mask + /// specifies which IP addresses the interface can forward traffic to in addition + /// to its own address. + pub address: Address, + /// Port on which tunneled WireGuard traffic is listened for. + /// + /// If not specified, a random port is chosen. + pub listen_port: Option, + /// Private key of the local peer + pub private_key: StaticSecret, + /// MTU + /// + /// Should be left unspecified. + pub mtu: Option, +} + +/// Remote peer configuration +#[derive(Debug, Clone)] +pub struct Peer { + /// Endpoint of the remote peer + /// + /// If not specified, the endpoint will be automatically populated when + /// tunneled traffic from the peer is received. + pub endpoint: Option, + /// IP addresses for which the peer is allowed to send and receive traffic + /// + /// Some peers are capable of forwarding traffic, in which case this can be set to + /// any number of IP addresses. + pub allowed_ips: Vec, + /// Public key of the remote peer + pub public_key: PublicKey, + /// Keepalive interval at which the peer is pinged + /// + /// This is useful when the local interface is behind a NAT to + /// keep the connection alive. + pub persistent_keepalive: Option, +} + +/// An IPv4 or IPv6 address, or both, and their associated network mask +#[derive(Debug, Clone, Copy)] +pub enum Address { + Dual(Ipv4Net, Ipv6Net), + V4(Ipv4Net), + V6(Ipv6Net), +} + +#[derive(Debug)] +pub enum AddressFromStrErr { + Invalid(::Err), + Multicast(IpNet), + DuplicateV4, + DuplicateV6, + Empty, +} + +impl Address { + /// Returns an iterator over the full IP networks of the address + pub fn networks(&self) -> impl Iterator { + match self { + Self::Dual(v4, v6) => { + AddressIterator::Dual([IpNet::V4(*v4), IpNet::V6(*v6)].into_iter()) + } + Self::V4(net) => AddressIterator::Single([IpNet::V4(*net)].into_iter()), + Self::V6(net) => AddressIterator::Single([IpNet::V6(*net)].into_iter()), + } + } + + /// Returns an iterator over the specific IP addresses of the address + /// + /// The iterator will only yield one or two addresses, as opposed to every address + /// included in its networks. + pub fn addresses(&self) -> impl Iterator { + self.networks().map(|net| net.addr()) + } + + /// Returns the IPv4 address if there is one + pub fn v4(&self) -> Option { + match self { + Self::V4(net) | Self::Dual(net, _) => Some(net.addr()), + _ => None, + } + } + /// Returns the IPv6 address if there is one + pub fn v6(&self) -> Option { + match self { + Self::V6(net) | Self::Dual(_, net) => Some(net.addr()), + _ => None, + } + } + + /// Whether the address is a dual stack address + pub fn is_dual(&self) -> bool { + matches!(self, Self::Dual(..)) + } + /// Whether the address has an IPv4 address + pub fn is_v4(&self) -> bool { + matches!(self, Self::V4(..) | Self::Dual(..)) + } + /// Whether the address has an IPv6 address + pub fn is_v6(&self) -> bool { + matches!(self, Self::V6(..) | Self::Dual(..)) + } + + /// Whether the address has the same family as the given address + pub fn is_compatible(&self, other: SocketAddr) -> bool { + match (self, other) { + (Self::Dual(..) | Self::V4(..), SocketAddr::V4(..)) => true, + (Self::Dual(..) | Self::V6(..), SocketAddr::V6(..)) => true, + _ => false, + } + } +} + +impl FromStr for Address { + type Err = AddressFromStrErr; + + fn from_str(s: &str) -> Result { + let mut v4 = None; + let mut v6 = None; + + let nets = s.split(',').map(|s| ::from_str(s.trim())); + for net in nets { + match net { + Ok(net) if net.addr().is_multicast() => { + return Err(AddressFromStrErr::Multicast(net)) + } + Ok(IpNet::V4(net)) => { + if v4.replace(net).is_some() { + return Err(AddressFromStrErr::DuplicateV4); + } + } + Ok(IpNet::V6(net)) => { + if v6.replace(net).is_some() { + return Err(AddressFromStrErr::DuplicateV6); + } + } + Err(err) => return Err(AddressFromStrErr::Invalid(err)), + } + } + + match (v4, v6) { + (Some(v4), Some(v6)) => Ok(Address::Dual(v4, v6)), + (Some(v4), None) => Ok(Address::V4(v4)), + (None, Some(v6)) => Ok(Address::V6(v6)), + (None, None) => Err(AddressFromStrErr::Empty), + } + } +} + +impl fmt::Display for Address { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Dual(v4, v6) => { + fmt::Display::fmt(v4, f)?; + f.write_str(",")?; + fmt::Display::fmt(v6, f)?; + Ok(()) + } + Self::V4(v4) => fmt::Display::fmt(v4, f), + Self::V6(v6) => fmt::Display::fmt(v6, f), + } + } +} + +impl From for Address { + fn from(net: IpNet) -> Self { + match net { + IpNet::V4(net) => Self::V4(net), + IpNet::V6(net) => Self::V6(net), + } + } +} +impl From for Address { + fn from(net: Ipv4Net) -> Self { + Self::V4(net) + } +} +impl From for Address { + fn from(net: Ipv6Net) -> Self { + Self::V6(net) + } +} +impl From for Address { + fn from(addr: IpAddr) -> Self { + Self::from(IpNet::from(addr)) + } +} +impl From for Address { + fn from(addr: Ipv4Addr) -> Self { + Self::from(Ipv4Net::from(addr)) + } +} +impl From for Address { + fn from(addr: Ipv6Addr) -> Self { + Self::from(Ipv6Net::from(addr)) + } +} + +impl fmt::Display for AddressFromStrErr { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Invalid(err) => err.fmt(f), + Self::Multicast(..) => f.write_str("multicast address"), + Self::DuplicateV4 => f.write_str("duplicate IPv4 address"), + Self::DuplicateV6 => f.write_str("duplicate IPv6 address"), + Self::Empty => f.write_str("empty address"), + } + } +} + +impl std::error::Error for AddressFromStrErr {} + +enum AddressIterator { + Dual(array::IntoIter), + Single(array::IntoIter), +} + +impl Iterator for AddressIterator { + type Item = T; + + fn next(&mut self) -> Option { + match self { + Self::Dual(iter) => iter.next(), + Self::Single(iter) => iter.next(), + } + } +} +impl ExactSizeIterator for AddressIterator { + fn len(&self) -> usize { + match self { + Self::Dual(iter) => iter.len(), + Self::Single(iter) => iter.len(), + } + } +} +impl DoubleEndedIterator for AddressIterator { + fn next_back(&mut self) -> Option { + match self { + Self::Dual(iter) => iter.next_back(), + Self::Single(iter) => iter.next_back(), + } + } +} diff --git a/vendor/tokio-wireguard/src/interface.rs b/vendor/tokio-wireguard/src/interface.rs new file mode 100644 index 0000000000..e1c8071250 --- /dev/null +++ b/vendor/tokio-wireguard/src/interface.rs @@ -0,0 +1,528 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +use std::{ + any::type_name, + fmt, + future::{poll_fn, Future}, + io, + net::{IpAddr, SocketAddr}, + ops::Deref, + pin::Pin, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, + task::{Context, Poll}, + time::Duration, +}; + +use allocations::Proto; +use boringtun::x25519::PublicKey; +use pin_project_lite::pin_project; +use rand::{rngs::OsRng, Rng, SeedableRng}; +use random::AtomicXorShift32; +use smoltcp::{ + socket::{tcp, udp}, + wire::HardwareAddress, +}; +use tokio::{ + runtime::Handle, + sync::{futures::Notified, mpsc, oneshot, Notify}, + time, +}; + +mod allocations; +mod device; +mod random; +mod sockets; +mod tunnel; + +pub(crate) use allocations::Allocation; + +/// A handle to a WireGuard interface +/// +/// Cloning returns a new handle to the same interface. +#[derive(Clone)] +pub struct Interface { + tx: mpsc::UnboundedSender, + shared: Arc, + allocations: allocations::Allocations, + _drop: Arc, +} + +/// Advanced options for configuring an [`Interface`] +#[derive(Debug, Clone)] +#[non_exhaustive] +pub struct Options { + /// Handle to the Tokio runtime on which the interface will be run + pub runtime: Handle, + /// Default poll interval for the interface when idle + pub poll_interval: Duration, + /// Inteval at which to update the internal WireGuard timers + pub timer_interval: Duration, + /// TCP options + pub tcp: TcpOptions, + /// UDP options + pub udp: UdpOptions, +} + +/// Advanced TCP options for configuring an [`Interface`] +#[derive(Debug, Clone)] +#[non_exhaustive] +pub struct TcpOptions { + /// Timeout for connecting to a remote peer + pub connect_timeout: Duration, + /// Size of the TCP receive buffer + pub recv_buffer_size: usize, + /// Size of the TCP send buffer + pub send_buffer_size: usize, + /// Maximum number of pending connections on the listener + pub backlog: usize, +} + +/// Advanced UDP options for configuring an [`Interface`] +#[derive(Debug, Clone, Copy)] +#[non_exhaustive] +pub struct UdpOptions { + /// Size of the UDP receive buffer + pub recv_buffer_size: usize, + /// Size of the UDP send buffer + pub send_buffer_size: usize, +} + +/// A trait for types that can be converted into an [`Interface`] +pub trait ToInterface { + fn to_interface(self) -> impl Future>; +} + +struct Shared { + is_closed: AtomicBool, + notify_closed: Notify, + options: Options, + rng: AtomicXorShift32, +} + +#[derive(Debug)] +enum Message { + Tcp(crate::Shared>), + Udp(crate::Shared>), + TcpConnect { + socket: crate::Shared>, + allocation: Allocation, + target: SocketAddr, + result: oneshot::Sender>, + }, + AddPeer { + config: crate::config::Peer, + result: oneshot::Sender>, + }, + RemovePeer { + key: PublicKey, + result: oneshot::Sender, + }, + Close, +} + +pin_project! { + /// Future that resolves once its associated interface is in the closed state + pub struct Closed<'a> { + #[pin] + notified: Notified<'a>, + shared: Arc, + } +} + +impl Interface { + /// Create a new interface + pub fn new(config: crate::config::Config) -> Result { + Self::new_with(config, Options::default()) + } + + /// Local address of the interface within the WireGuard network + pub fn address(&self) -> Address { + self.allocations.address + } + + /// Advanced options for the interface + pub fn options(&self) -> &Options { + &self.shared.options + } + + /// Request that the interface be closed + /// + /// All sockets created by the interface will be closed, and any attempt to send or receive data + /// using them will result in an error. Once all remaining queued packets have been sent, + /// the interface will enter the closed state. + pub fn close(&self) { + self.tx.send(Message::Close).ok(); + } + + /// Returns a future that resolves once the interface is in the closed state + /// + /// See [`close`](Self::close) for more information. + pub fn closed(&self) -> Closed<'_> { + Closed { + notified: self.shared.notify_closed.notified(), + shared: self.shared.clone(), + } + } + + /// Whether the interface is in the closed state + /// + /// See [`close`](Self::close) for more information. + pub fn is_closed(&self) -> bool { + self.shared.is_closed.load(Ordering::Acquire) + } + + /// Create a new interface with advanced options + pub fn new_with(config: crate::config::Config, options: Options) -> Result { + #[derive(Clone, Copy)] + enum Close { + No, + Requested, + Ready, + } + let runtime = options.runtime.clone(); + let scope = runtime.enter(); + + let crate::config::Config { + interface: config, + peers: peer_configs, + } = config; + let (tx, mut rx) = mpsc::unbounded_channel(); + let (mut interface, mut device) = Self::smol(&config); + + let mut sockets = sockets::Sockets::new(); + let mut tunnel = tunnel::Tunnel::new(&config, peer_configs)?; + + let poll = time::sleep_until(time::Instant::now()); + let mut timers = time::interval(options.timer_interval); + timers.set_missed_tick_behavior(time::MissedTickBehavior::Delay); + + let mut close = Close::No; + let shared = Arc::new(Shared { + is_closed: AtomicBool::new(false), + notify_closed: Notify::new(), + options, + rng: AtomicXorShift32::from_entropy(), + }); + + let i = Self { + tx: tx.clone(), + shared: shared.clone(), + allocations: allocations::Allocations::new(&config), + _drop: Arc::new(CloseOnDrop { tx }), + }; + let shared = NotifyOnDrop(shared); + + tokio::spawn(async move { + tokio::pin!(poll); + loop { + #[derive(Debug)] + enum Select { + Poll, + Message(Message), + Recv, + Send, + Timers, + Close, + } + + let selected = poll_fn(|cx| { + let recv = tunnel.socket().poll_recv_ready(cx); + let send = tunnel.socket().poll_send_ready(cx); + let can_send = device.can_send(); + + if let Poll::Ready(()) = poll.as_mut().poll(cx) { + Poll::Ready(Select::Poll) + } else if let (Poll::Ready(Some(message)), Close::No) = + (rx.poll_recv(cx), close) + { + Poll::Ready(Select::Message(message)) + } else if let (Poll::Ready(..), Poll::Ready(..)) = (recv, &send) { + Poll::Ready(Select::Recv) + } else if let (true, Poll::Ready(..)) = (can_send, send) { + Poll::Ready(Select::Send) + } else if let Poll::Ready(..) = timers.poll_tick(cx) { + Poll::Ready(Select::Timers) + } else if let (false, Close::Ready) = (can_send, close) { + Poll::Ready(Select::Close) + } else { + Poll::Pending + } + }) + .await; + + match selected { + Select::Poll => { + let wait = sockets.with(|s| { + let now = smoltcp::time::Instant::now(); + interface.poll(now, &mut device, s); + interface.poll_delay(now, s).map(time::Duration::from) + }); + match wait { + Some(wait) => poll.as_mut().reset(time::Instant::now() + wait), + None => { + poll.as_mut() + .reset(time::Instant::now() + shared.options.poll_interval); + if let Close::Requested = close { + close = Close::Ready; + } + } + } + } + Select::Message(Message::Tcp(socket)) => { + sockets.register_tcp(socket); + poll.as_mut().reset(time::Instant::now()); + } + Select::Message(Message::Udp(socket)) => { + sockets.register_udp(socket); + poll.as_mut().reset(time::Instant::now()); + } + Select::Message(Message::TcpConnect { + socket, + allocation, + target, + result, + }) => { + if let Some(socket) = socket.lock().as_mut() { + result + .send(socket.connect( + interface.context(), + target, + allocation.address(), + )) + .ok(); + } + sockets.register_tcp(socket); + poll.as_mut().reset(time::Instant::now()); + } + Select::Message(Message::AddPeer { config, result }) => { + result.send(tunnel.add_peer(config)).ok(); + } + Select::Message(Message::RemovePeer { key, result }) => { + result.send(tunnel.remove_peer(&key)).ok(); + } + Select::Message(Message::Close) => { + close = Close::Requested; + sockets.close(); + poll.as_mut().reset(time::Instant::now()); + } + Select::Recv => { + if let Some(packet) = tunnel.recv().await { + device.enqueue_received(packet); + } + } + Select::Send => { + if let Some(packet) = device.dequeue_sent() { + tunnel.send(packet, |_| true).await; + } + } + Select::Timers => tunnel.update_timers().await, + Select::Close => break, + } + } + }); + + drop(scope); + Ok(i) + } + + /// Dynamically add a new peer to the interface. The peer will only become available + /// once the returned future resolves. + pub async fn add_peer(&self, config: crate::config::Peer) -> Result<(), io::Error> { + let (tx, rx) = oneshot::channel(); + self.tx + .send(Message::AddPeer { config, result: tx }) + .map_err(|_| Self::error())?; + rx.await.map_err(|_| Self::error())? + } + /// Removes a peer from the interface. Returns whether the peer existed. + pub async fn remove_peer(&self, key: &PublicKey) -> Result { + let (tx, rx) = oneshot::channel(); + self.tx + .send(Message::RemovePeer { + key: key.clone(), + result: tx, + }) + .map_err(|_| Self::error())?; + rx.await.map_err(|_| Self::error()) + } + + pub(crate) fn error() -> io::Error { + io::Error::new(io::ErrorKind::BrokenPipe, "interface is closed") + } + + pub(crate) fn register_tcp( + &self, + socket: crate::Shared>, + ) -> io::Result<()> { + self.tx + .send(Message::Tcp(socket)) + .map_err(|_| Self::error()) + } + pub(crate) fn register_udp( + &self, + socket: crate::Shared>, + ) -> io::Result<()> { + self.tx + .send(Message::Udp(socket)) + .map_err(|_| Self::error()) + } + + pub(crate) fn allocate_tcp(&self, address: impl Into) -> Option { + self.allocations + .acquire(address, Proto::Tcp, &mut &self.shared.rng) + } + pub(crate) fn allocate_udp(&self, address: impl Into) -> Option { + self.allocations + .acquire(address, Proto::Udp, &mut &self.shared.rng) + } + + pub(crate) async fn connect_tcp( + &self, + socket: crate::Shared>, + allocation: Allocation, + target: SocketAddr, + ) -> io::Result> { + let (tx, result) = oneshot::channel(); + self.tx + .send(Message::TcpConnect { + socket, + allocation, + target, + result: tx, + }) + .map_err(|_| Self::error())?; + result.await.map_err(|_| Self::error()) + } + + pub(crate) fn deallocate(&self, allocation: Allocation) { + self.allocations.release(allocation); + } + + fn smol(config: &crate::config::Interface) -> (smoltcp::iface::Interface, device::Device) { + let ips = config.address.addresses(); + let mut device = device::Device::new(&config); + let mut config = smoltcp::iface::Config::new(HardwareAddress::Ip); + config.random_seed = OsRng.gen(); + + let mut interface = + smoltcp::iface::Interface::new(config, &mut device, smoltcp::time::Instant::now()); + interface.update_ip_addrs(|a| { + for ip in ips { + match ip { + IpAddr::V4(ip) => a.push(smoltcp::wire::Ipv4Cidr::new(ip.into(), 32).into()), + IpAddr::V6(ip) => a.push(smoltcp::wire::Ipv6Cidr::new(ip.into(), 128).into()), + } + .ok(); + } + }); + + (interface, device) + } +} + +use crate::config::Address; + +impl fmt::Debug for Interface { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple(type_name::()) + .field(&self.address()) + .finish() + } +} + +impl ToInterface for Interface { + async fn to_interface(self) -> Result { + Ok(self) + } +} + +impl<'a> ToInterface for &'a Interface { + async fn to_interface(self) -> Result { + Ok(self.clone()) + } +} + +impl<'a> ToInterface for &'a mut Interface { + async fn to_interface(self) -> Result { + Ok(self.clone()) + } +} + +impl ToInterface for crate::config::Config { + async fn to_interface(self) -> Result { + Interface::new(self) + } +} + +impl Default for Options { + fn default() -> Self { + Self { + runtime: Handle::current(), + poll_interval: Duration::from_millis(100), + timer_interval: Duration::from_millis(100), + tcp: TcpOptions::default(), + udp: UdpOptions::default(), + } + } +} + +impl Default for TcpOptions { + fn default() -> Self { + Self { + connect_timeout: Duration::from_secs(10), + recv_buffer_size: 64 * 1024, + send_buffer_size: 16 * 1024, + backlog: 128, + } + } +} + +impl Default for UdpOptions { + fn default() -> Self { + Self { + recv_buffer_size: 64 * 1024, + send_buffer_size: 16 * 1024, + } + } +} + +impl<'a> Future for Closed<'a> { + type Output = as Future>::Output; + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + if self.shared.is_closed.load(Ordering::Acquire) { + Poll::Ready(()) + } else { + self.project().notified.poll(cx) + } + } +} + +struct CloseOnDrop { + tx: mpsc::UnboundedSender, +} + +struct NotifyOnDrop(Arc); + +impl Drop for CloseOnDrop { + fn drop(&mut self) { + self.tx.send(Message::Close).ok(); + } +} + +impl Deref for NotifyOnDrop { + type Target = Shared; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Drop for NotifyOnDrop { + fn drop(&mut self) { + self.is_closed.store(true, Ordering::Release); + self.notify_closed.notify_waiters(); + } +} diff --git a/vendor/tokio-wireguard/src/interface/allocations.rs b/vendor/tokio-wireguard/src/interface/allocations.rs new file mode 100644 index 0000000000..d91589844d --- /dev/null +++ b/vendor/tokio-wireguard/src/interface/allocations.rs @@ -0,0 +1,158 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +use std::{ + any::type_name, + fmt, iter, + net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}, + ops::Range, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, +}; + +use rand::Rng; + +#[derive(Clone)] +pub struct Allocations { + pub address: crate::config::Address, + list: Arc<[Port]>, +} + +#[derive(Clone, Copy)] +pub struct Allocation { + address: SocketAddr, + proto: Proto, +} + +#[derive(Clone, Copy)] +pub enum Proto { + Tcp, + Udp, +} + +impl Allocations { + const EPHEMERAL_RANGE: Range = Range { + start: 49152, + end: 65535, + }; + + pub fn new(config: &crate::config::Interface) -> Self { + Self { + address: config.address, + list: iter::repeat_with(Port::new) + .take(u16::MAX as usize) + .collect(), + } + } + + // TODO: Rework this to allow any src+dst+port for TCP + pub fn acquire( + &self, + address: impl Into, + proto: Proto, + rng: &mut impl Rng, + ) -> Option { + let address = address.into(); + let ip = address.ip(); + + match address.port() { + 0 => { + let start = rng.gen_range(Self::EPHEMERAL_RANGE); + let mut port = start; + loop { + match self.acquire((ip, port), proto, rng) { + Some(port) => break Some(port), + None if port == start => break None, + None if port == Self::EPHEMERAL_RANGE.end => { + port = Self::EPHEMERAL_RANGE.start + } + None => port += 1, + } + } + } + + port => { + let slot = self.list.get(port as usize)?; + + let ip = match ip { + IpAddr::V4(ip) => { + let interface = self.address.v4()?; + match ip { + Ipv4Addr::UNSPECIFIED => IpAddr::V4(interface), + _ if ip == interface => IpAddr::V4(interface), + _ => return None, + } + } + IpAddr::V6(ip) => { + let interface = self.address.v6()?; + match ip { + Ipv6Addr::UNSPECIFIED => IpAddr::V6(interface), + _ if ip == interface => IpAddr::V6(interface), + _ => return None, + } + } + }; + + match (slot, ip, proto) { + (Port { tcp_v4: slot, .. }, IpAddr::V4(..), Proto::Tcp) + | (Port { tcp_v6: slot, .. }, IpAddr::V6(..), Proto::Tcp) + | (Port { udp_v4: slot, .. }, IpAddr::V4(..), Proto::Udp) + | (Port { udp_v6: slot, .. }, IpAddr::V6(..), Proto::Udp) + if slot + .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed) + .is_ok() => + { + Some(Allocation { + address: SocketAddr::new(ip, port), + proto, + }) + } + _ => None, + } + } + } + } + + pub fn release(&self, allocation: Allocation) { + if let Some(slot) = self.list.get(allocation.address.port() as usize) { + match (allocation.address.ip(), allocation.proto) { + (IpAddr::V4(..), Proto::Tcp) => slot.tcp_v4.store(false, Ordering::Release), + (IpAddr::V6(..), Proto::Tcp) => slot.tcp_v6.store(false, Ordering::Release), + (IpAddr::V4(..), Proto::Udp) => slot.udp_v4.store(false, Ordering::Release), + (IpAddr::V6(..), Proto::Udp) => slot.udp_v6.store(false, Ordering::Release), + } + } + } +} + +impl Allocation { + pub fn address(&self) -> SocketAddr { + self.address + } +} + +impl fmt::Debug for Allocation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple(type_name::()) + .field(&self.address) + .finish() + } +} + +struct Port { + tcp_v4: AtomicBool, + tcp_v6: AtomicBool, + udp_v4: AtomicBool, + udp_v6: AtomicBool, +} + +impl Port { + const fn new() -> Self { + Self { + tcp_v4: AtomicBool::new(false), + tcp_v6: AtomicBool::new(false), + udp_v4: AtomicBool::new(false), + udp_v6: AtomicBool::new(false), + } + } +} diff --git a/vendor/tokio-wireguard/src/interface/device.rs b/vendor/tokio-wireguard/src/interface/device.rs new file mode 100644 index 0000000000..0c726878a4 --- /dev/null +++ b/vendor/tokio-wireguard/src/interface/device.rs @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +use std::collections::VecDeque; + +use smoltcp::phy::{DeviceCapabilities, Medium, RxToken, TxToken}; + +#[derive(Debug)] +pub struct Device { + recv: Token, + send: Token, + mtu: usize, +} + +#[derive(Debug)] +pub struct Token { + queue: PacketQueue, + buffer: Vec, +} + +impl Device { + pub fn new(config: &crate::config::Interface) -> Self { + Self { + recv: Token::new(), + send: Token::new(), + mtu: config.mtu.unwrap_or(1420), + } + } + + pub fn enqueue_received(&mut self, packet: &[u8]) { + self.recv.queue.enqueue(packet) + } + + pub fn dequeue_sent(&mut self) -> Option<&[u8]> { + if !self.send.queue.is_empty() { + self.send.queue.dequeue(&mut self.send.buffer); + Some(&self.send.buffer) + } else { + None + } + } + + pub fn can_send(&self) -> bool { + !self.send.queue.is_empty() + } +} + +impl Token { + const fn new() -> Self { + Self { + queue: PacketQueue { + lengths: VecDeque::new(), + buffers: VecDeque::new(), + }, + buffer: Vec::new(), + } + } +} + +impl smoltcp::phy::Device for Device { + type RxToken<'a> = &'a mut Token; + type TxToken<'a> = &'a mut Token; + + fn receive( + &mut self, + _: smoltcp::time::Instant, + ) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> { + let Self { recv, send, .. } = self; + if !recv.queue.is_empty() { + Some((recv, send)) + } else { + None + } + } + + fn transmit(&mut self, _: smoltcp::time::Instant) -> Option> { + let Self { send, .. } = self; + Some(send) + } + + fn capabilities(&self) -> DeviceCapabilities { + let mut capacities = DeviceCapabilities::default(); + capacities.medium = Medium::Ip; + capacities.max_transmission_unit = self.mtu; + capacities.max_burst_size = None; + capacities + } +} + +impl<'a> RxToken for &'a mut Token { + fn consume(self, f: F) -> R + where + F: FnOnce(&mut [u8]) -> R, + { + self.queue.dequeue(&mut self.buffer); + f(&mut self.buffer) + } +} + +impl<'a> TxToken for &'a mut Token { + fn consume(self, len: usize, f: F) -> R + where + F: FnOnce(&mut [u8]) -> R, + { + self.buffer.resize(len, 0); + let result = f(&mut self.buffer); + self.queue.enqueue(&self.buffer); + result + } +} + +#[derive(Debug)] +struct PacketQueue { + lengths: VecDeque, + buffers: VecDeque, +} + +impl PacketQueue { + fn enqueue(&mut self, packet: &[u8]) { + self.lengths.push_back(packet.len()); + self.buffers.extend(packet); + } + + fn dequeue(&mut self, buf: &mut Vec) { + let len = self.lengths.pop_front().unwrap(); + buf.clear(); + buf.extend(self.buffers.drain(..len)) + } + + fn is_empty(&self) -> bool { + self.lengths.is_empty() + } +} diff --git a/vendor/tokio-wireguard/src/interface/random.rs b/vendor/tokio-wireguard/src/interface/random.rs new file mode 100644 index 0000000000..f64a62bde8 --- /dev/null +++ b/vendor/tokio-wireguard/src/interface/random.rs @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +use std::sync::atomic::{AtomicU32, Ordering}; + +use rand::{Error, RngCore, SeedableRng}; + +pub struct Lfsr24 { + initial: u32, + lfsr: u32, + mask: u32, +} + +pub struct AtomicXorShift32 { + state: AtomicU32, +} + +impl Lfsr24 { + pub fn next(&mut self) -> u32 { + let lfsr = self.lfsr - 1; + self.lfsr = (self.lfsr >> 1) ^ (0u32.wrapping_sub(self.lfsr & 1u32) & 0xd80000); + assert!(self.lfsr != self.initial); + lfsr ^ self.mask + } +} + +impl SeedableRng for Lfsr24 { + type Seed = [u8; 8]; + + fn from_seed(seed: Self::Seed) -> Self { + let s24 = |b: [u8; 4]| u32::from_le_bytes(b).saturating_add(1) & 0xffffff; + + let initial = s24([seed[0], seed[1], seed[2], seed[3]]); + let mask = s24([seed[4], seed[5], seed[6], seed[7]]); + + Self { + initial, + lfsr: initial, + mask, + } + } +} + +impl SeedableRng for AtomicXorShift32 { + type Seed = [u8; 4]; + + fn from_seed(seed: Self::Seed) -> Self { + Self { + state: AtomicU32::from(u32::from_le_bytes(seed).saturating_add(1)), + } + } +} + +impl RngCore for &AtomicXorShift32 { + fn next_u32(&mut self) -> u32 { + loop { + let initial = self.state.load(Ordering::Relaxed); + + let mut state = initial; + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + + let swap = self.state.compare_exchange_weak( + initial, + state, + Ordering::Relaxed, + Ordering::Relaxed, + ); + if swap.is_ok() { + break state; + } + } + } + + fn next_u64(&mut self) -> u64 { + u64::from(self.next_u32()) << 32 | u64::from(self.next_u32()) + } + fn fill_bytes(&mut self, dest: &mut [u8]) { + for chunk in dest.chunks_mut(4) { + chunk.copy_from_slice(&self.next_u32().to_le_bytes()[..chunk.len()]) + } + } + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { + Ok(self.fill_bytes(dest)) + } +} diff --git a/vendor/tokio-wireguard/src/interface/sockets.rs b/vendor/tokio-wireguard/src/interface/sockets.rs new file mode 100644 index 0000000000..c1e529615b --- /dev/null +++ b/vendor/tokio-wireguard/src/interface/sockets.rs @@ -0,0 +1,149 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +use std::sync::Arc; + +use parking_lot::{ArcMutexGuard, Mutex, RawMutex}; +use smoltcp::{ + iface::{SocketHandle, SocketSet}, + socket::{tcp, udp, Socket}, +}; + +pub struct Sockets { + set: SocketSet<'static>, + tcp: SocketsInner>, + udp: SocketsInner>, +} + +impl Sockets { + pub fn new() -> Self { + Self { + set: SocketSet::new(Vec::new()), + tcp: SocketsInner::new(), + udp: SocketsInner::new(), + } + } + + pub fn register_tcp(&mut self, socket: crate::Shared>) { + self.tcp.register(socket); + } + + pub fn register_udp(&mut self, socket: crate::Shared>) { + self.udp.register(socket); + } + + pub fn close(&mut self) { + self.tcp.close(); + self.udp.close(); + } + + pub fn with(&mut self, f: impl FnOnce(&mut SocketSet) -> T) -> T { + let Self { set, tcp, udp } = self; + + tcp.lock(set); + udp.lock(set); + let result = f(set); + + tcp.unlock(set); + udp.unlock(set); + result + } +} + +struct SocketsInner { + sockets: Vec>, + guards: Vec<(SocketHandle, ArcMutexGuard>)>, +} + +impl SocketsInner { + const fn new() -> Self { + Self { + sockets: Vec::new(), + guards: Vec::new(), + } + } + + fn register(&mut self, socket: crate::Shared) { + let slot = self.sockets.iter_mut().enumerate().find_map(|(i, s)| { + match Arc::get_mut(s).map(Mutex::get_mut) { + Some(..) => None, + None => Some(i), + } + }); + + if let Some(slot) = slot.and_then(|s| self.sockets.get_mut(s)) { + *slot = socket; + } else { + self.sockets.push(socket); + } + } +} + +impl SocketsInner> { + fn close(&mut self) { + for socket in &mut self.sockets { + if let Some(socket) = &mut *socket.lock() { + socket.abort(); + } + } + } + + fn lock(&mut self, set: &mut SocketSet<'static>) { + let Self { sockets, guards } = self; + + for socket in sockets { + let mut guard = socket.lock_arc(); + if let Some(mut socket) = guard.take() { + if Arc::strong_count(ArcMutexGuard::mutex(&guard)) == 2 { + socket.abort(); + } + guards.push((set.add(socket), guard)); + } + } + } + + fn unlock(&mut self, set: &mut SocketSet<'static>) { + let Self { guards, .. } = self; + + while let Some((handle, mut guard)) = guards.pop() { + if let Socket::Tcp(socket) = set.remove(handle) { + if let (tcp::State::Closed, None) = (socket.state(), socket.local_endpoint()) { + continue; + } + guard.replace(socket); + } + } + } +} + +impl SocketsInner> { + fn close(&mut self) { + for socket in &mut self.sockets { + if let Some(socket) = &mut *socket.lock() { + socket.close(); + } + } + } + + fn lock(&mut self, set: &mut SocketSet<'static>) { + let Self { sockets, guards } = self; + + for socket in sockets { + let mut guard = socket.lock_arc(); + if let Some(socket) = guard.take() { + guards.push((set.add(socket), guard)); + } + } + } + + fn unlock(&mut self, set: &mut SocketSet<'static>) { + let Self { guards, .. } = self; + + while let Some((handle, mut guard)) = guards.pop() { + if let Socket::Udp(socket) = set.remove(handle) { + if Arc::strong_count(ArcMutexGuard::mutex(&guard)) == 2 { + continue; + } + guard.replace(socket); + } + } + } +} diff --git a/vendor/tokio-wireguard/src/interface/tunnel.rs b/vendor/tokio-wireguard/src/interface/tunnel.rs new file mode 100644 index 0000000000..dda7d41d37 --- /dev/null +++ b/vendor/tokio-wireguard/src/interface/tunnel.rs @@ -0,0 +1,278 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +use std::{ + io, + net::{IpAddr, Ipv6Addr, SocketAddr, SocketAddrV6}, + sync::Arc, +}; + +use boringtun::{ + noise::{ + rate_limiter::RateLimiter, HandshakeResponse, Packet, PacketCookieReply, PacketData, Tunn, + TunnResult, + }, + x25519::{PublicKey, StaticSecret}, +}; +use rand::SeedableRng; +use socket2::{Domain, Protocol, SockAddr, Socket, Type}; +use tokio::net::UdpSocket; + +use super::random::Lfsr24; + +pub struct Tunnel { + address: crate::config::Address, + keypair: (StaticSecret, PublicKey), + peers: Vec, + rng: Lfsr24, + rate_limiter: Arc, + buffers: (Vec, Vec), + socket: UdpSocket, +} + +pub trait IntoPacket<'a> { + fn into_packet(self, buffer: &'a [u8]) -> &'a [u8]; +} + +impl Tunnel { + pub fn new( + config: &crate::config::Interface, + peer_configs: impl IntoIterator, + ) -> Result { + let private_key = config.private_key.clone(); + let public_key = PublicKey::from(&private_key); + + let socket = Socket::new(Domain::IPV6, Type::DGRAM, Some(Protocol::UDP))?; + socket.set_nonblocking(true)?; + socket.set_only_v6(false)?; + #[cfg(not(windows))] + socket.set_reuse_address(true)?; + + let address: SockAddr = + SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, config.listen_port.unwrap_or(0), 0, 0).into(); + socket.bind(&address)?; + + let socket = UdpSocket::from_std(socket.into())?; + let mut tunnel = Tunnel { + address: config.address, + keypair: (private_key, public_key), + peers: Vec::new(), + rng: Lfsr24::from_entropy(), + rate_limiter: Arc::new(RateLimiter::new(&public_key, 64)), + buffers: (vec![0; u16::MAX as usize], vec![0; u16::MAX as usize]), + socket, + }; + + for peer_config in peer_configs { + tunnel.add_peer(peer_config)?; + } + Ok(tunnel) + } + + pub fn socket(&self) -> &UdpSocket { + &self.socket + } + + pub async fn recv(&mut self) -> Option<&[u8]> { + let Self { + address, + keypair: (private, public), + peers, + buffers, + socket, + .. + } = self; + + let (len, source) = socket.try_recv_from(&mut buffers.0).ok()?; + let packet = Tunn::parse_incoming_packet(&buffers.0[..len]).ok()?; + + let peer = match packet { + Packet::HandshakeInit(packet) => { + let handshake = + boringtun::noise::handshake::parse_handshake_anon(private, public, &packet) + .ok()?; + peers.iter_mut().find(|p| { + p.active && p.config.public_key.as_bytes() == &handshake.peer_static_public + })? + } + + Packet::HandshakeResponse(HandshakeResponse { receiver_idx, .. }) + | Packet::PacketCookieReply(PacketCookieReply { receiver_idx, .. }) + | Packet::PacketData(PacketData { receiver_idx, .. }) => peers + .iter_mut() + .find(|p| p.active && p.index == receiver_idx >> 8)?, + }; + + let packet = + match peer + .tunnel + .decapsulate(Some(source.ip()), &buffers.0[..len], &mut buffers.1) + { + TunnResult::Err(..) => return None, + TunnResult::Done => None, + TunnResult::WriteToNetwork(mut datagram) => loop { + socket.send_to(datagram, source).await.ok(); + match peer.tunnel.decapsulate(None, &[], &mut buffers.0) { + TunnResult::WriteToNetwork(d) => datagram = d, + _ => break None, + } + }, + TunnResult::WriteToTunnelV4(p, a) if peer.is_allowed_ip(a) => Some(p), + TunnResult::WriteToTunnelV6(p, a) if peer.is_allowed_ip(a) => Some(p), + _ => None, + }; + + peer.config.endpoint = Some(source); + match packet { + Some(packet_out) => { + let len = packet_out.len(); + buffers.0[..len].copy_from_slice(packet_out); + + let address = *address; + self.send(len, |destination| { + address.networks().any(|net| net.contains(&destination)) + }) + .await + } + None => None, + } + } + + pub async fn send<'s>( + &'s mut self, + packet: impl IntoPacket<'s>, + relay: impl FnOnce(IpAddr) -> bool, + ) -> Option<&'s [u8]> { + let Self { + address, + peers, + buffers, + socket, + .. + } = self; + + let packet = packet.into_packet(&buffers.0); + let destination = Tunn::dst_address(packet)?; + + if address.addresses().any(|ip| ip == destination) { + return Some(packet); + } + if !relay(destination) { + return None; + } + + let peer = peers.iter_mut().find(|p| { + p.active + && p.config + .allowed_ips + .iter() + .any(|net| net.contains(&destination)) + })?; + + let endpoint = match peer.config.endpoint? { + SocketAddr::V4(addr) => SocketAddr::V6(SocketAddrV6::new( + addr.ip().to_ipv6_mapped(), + addr.port(), + 0, + 0, + )), + e => e, + }; + let packet = peer.tunnel.encapsulate(packet, &mut buffers.1); + if let TunnResult::WriteToNetwork(packet) = packet { + socket.send_to(packet, endpoint).await.ok(); + } + + None + } + + pub async fn update_timers(&mut self) { + let Self { + peers, + buffers, + socket, + .. + } = self; + + for peer in peers.iter_mut() { + let endpoint = match (peer.active, peer.config.endpoint) { + (true, Some(endpoint)) => endpoint, + _ => continue, + }; + let packet = peer.tunnel.update_timers(&mut buffers.0); + if let TunnResult::WriteToNetwork(packet) = packet { + socket.send_to(packet, endpoint).await.ok(); + } + } + } + + pub fn add_peer(&mut self, config: crate::config::Peer) -> Result<(), io::Error> { + let Self { + keypair: (private, _), + peers, + rng, + rate_limiter, + .. + } = self; + + let index = rng.next(); + let peer = Peer { + tunnel: Tunn::new( + private.clone(), + config.public_key, + None, + config.persistent_keepalive, + index, + Some(rate_limiter.clone()), + ), + config, + index, + active: true, + }; + + let slot = peers.iter_mut().find(|p| !p.active); + if let Some(slot) = slot { + *slot = peer; + } else { + peers.push(peer); + } + Ok(()) + } + + pub fn remove_peer(&mut self, key: &PublicKey) -> bool { + match self.peers.iter_mut().find(|p| &p.config.public_key == key) { + Some(peer) => { + peer.active = false; + true + } + None => false, + } + } +} + +impl<'a> IntoPacket<'a> for &'a [u8] { + fn into_packet(self, _: &'a [u8]) -> &'a [u8] { + self + } +} + +impl<'a> IntoPacket<'a> for usize { + fn into_packet(self, buffer: &'a [u8]) -> &'a [u8] { + &buffer[..self] + } +} + +struct Peer { + config: crate::config::Peer, + tunnel: Tunn, + index: u32, + active: bool, +} + +impl Peer { + fn is_allowed_ip(&self, address: impl Into) -> bool { + let address = address.into(); + self.config + .allowed_ips + .iter() + .any(|net| net.contains(&address)) + } +} diff --git a/vendor/tokio-wireguard/src/io.rs b/vendor/tokio-wireguard/src/io.rs new file mode 100644 index 0000000000..9734c137d5 --- /dev/null +++ b/vendor/tokio-wireguard/src/io.rs @@ -0,0 +1,274 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +use std::{ + mem::transmute, + ops::{Deref, DerefMut}, + sync::Arc, + task::{Context, Poll, Wake, Waker}, +}; + +use atomic_waker::AtomicWaker; +use parking_lot::Mutex; +use tokio::{ + io::{Error, ErrorKind, Interest, Ready, Result}, + sync::Notify, +}; + +use crate::{interface::Allocation, Interface, Shared}; + +pub struct IO { + interface: Interface, + evented: Shared, + allocation: Option, + wake: Arc, + wakers: Wakers, +} + +impl IO { + pub fn new(interface: Interface, evented: E, allocation: Option) -> Self { + let (wake, wakers) = wakers(); + Self { + interface, + evented: Arc::new(Mutex::new(Some(evented))), + allocation, + wake, + wakers, + } + } + + pub fn interface(&self) -> &Interface { + &self.interface + } + + pub fn with(&self, f: F) -> Result + where + F: FnOnce(&mut E) -> R, + { + if self.interface.is_closed() { + return Err(Interface::error()); + } + + self.evented + .lock() + .as_mut() + .map(f) + .ok_or_else(Interface::error) + } + + pub fn try_io(&self, f: F) -> Result + where + F: FnOnce(&mut E) -> Poll>, + { + let result = self.with(f); + match result { + Ok(Poll::Ready(result)) => result, + Ok(Poll::Pending) => Err(Error::from(ErrorKind::WouldBlock)), + Err(e) => Err(e), + } + } + + pub async fn io(&self, interest: Interest, mut f: F) -> Result + where + F: FnMut(&mut E) -> Poll>, + { + loop { + let notified = self.wake.notify.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + + let result = self.with(|e| { + if interest.is_readable() { + e.register_read_waker(&self.wakers.read); + } else if interest.is_writable() { + e.register_write_waker(&self.wakers.write); + } + f(e) + }); + + match result { + Ok(Poll::Pending) => notified.await, + Ok(Poll::Ready(result)) => break result, + Err(e) => break Err(e), + } + } + } + + pub async fn ready(&self, interest: Interest) -> Result { + loop { + let notified = self.wake.notify.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + + let ready = self.with(|e| { + let ready = e.readiness(); + if satisfies(ready, interest) { + Some(ready) + } else { + if interest.is_readable() || interest.is_error() { + e.register_read_waker(&self.wakers.read); + } + if interest.is_writable() || interest.is_error() { + e.register_write_waker(&self.wakers.write); + } + None + } + }); + + match ready { + Ok(None) => notified.await, + Ok(Some(ready)) => break Ok(ready), + Err(e) => break Err(e), + } + } + } + + pub fn poll_io(&self, interest: Interest, cx: &mut Context<'_>, f: F) -> Poll> + where + F: FnOnce(&mut E) -> Poll>, + { + let result = self.with(|e| { + let poll = f(e); + if poll.is_pending() { + if interest.is_readable() { + self.wake.read.register(cx.waker()); + e.register_read_waker(&self.wakers.read) + } else if interest.is_writable() { + self.wake.read.register(cx.waker()); + e.register_write_waker(&self.wakers.write) + } + } + poll + }); + match result { + Ok(poll) => poll, + Err(e) => Poll::Ready(Err(e)), + } + } + + pub fn poll_ready(&self, interest: Interest, cx: &mut Context<'_>) -> Poll> { + let ready = self.with(|e| { + if satisfies(e.readiness(), interest) { + Poll::Ready(Ok(())) + } else { + if interest.is_readable() || interest.is_error() { + self.wake.read.register(cx.waker()); + e.register_read_waker(&self.wakers.read) + } else if interest.is_writable() || interest.is_error() { + self.wake.write.register(cx.waker()); + e.register_write_waker(&self.wakers.write) + } + Poll::Pending + } + }); + match ready { + Ok(poll) => poll, + Err(e) => Poll::Ready(Err(e)), + } + } + + pub fn is(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.evented, &other.evented) + } +} + +impl Clone for IO { + fn clone(&self) -> Self { + Self { + interface: self.interface.clone(), + evented: self.evented.clone(), + allocation: self.allocation.clone(), + wake: self.wake.clone(), + wakers: self.wakers.clone(), + } + } +} + +impl Deref for IO { + type Target = Shared; + + fn deref(&self) -> &Self::Target { + &self.evented + } +} + +impl DerefMut for IO { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.evented + } +} + +impl Drop for IO { + fn drop(&mut self) { + if let Some(allocation) = self.allocation.take() { + self.interface.deallocate(allocation); + } + } +} + +pub trait Evented { + fn readiness(&self) -> Ready; + + fn register_read_waker(&mut self, waker: &Waker); + fn register_write_waker(&mut self, waker: &Waker); +} + +fn satisfies(readiness: Ready, interest: Interest) -> bool { + let mut anyof = Ready::EMPTY; + if interest.is_readable() || interest.is_error() { + anyof |= Ready::READABLE; + anyof |= Ready::READ_CLOSED; + } + if interest.is_writable() || interest.is_error() { + anyof |= Ready::WRITABLE; + anyof |= Ready::WRITE_CLOSED; + } + anyof & readiness != Ready::EMPTY +} + +fn wakers() -> (Arc, Wakers) { + let state = Arc::new(WakeState { + notify: Notify::new(), + read: AtomicWaker::new(), + write: AtomicWaker::new(), + }); + // Safety: #[repr(transparent)] + let wakers = unsafe { + Wakers { + read: Waker::from(transmute::, Arc>(state.clone())), + write: Waker::from(transmute::, Arc>(state.clone())), + } + }; + + (state, wakers) +} + +struct WakeState { + notify: Notify, + read: AtomicWaker, + write: AtomicWaker, +} + +#[derive(Clone)] +struct Wakers { + read: Waker, + write: Waker, +} + +#[repr(transparent)] +struct ReadWaker(WakeState); + +#[repr(transparent)] +struct WriteWaker(WakeState); + +impl Wake for ReadWaker { + fn wake(self: Arc) { + self.0.notify.notify_waiters(); + self.0.read.wake(); + } +} + +impl Wake for WriteWaker { + fn wake(self: Arc) { + self.0.notify.notify_waiters(); + self.0.write.wake(); + } +} diff --git a/vendor/tokio-wireguard/src/lib.rs b/vendor/tokio-wireguard/src/lib.rs new file mode 100644 index 0000000000..e87c983b67 --- /dev/null +++ b/vendor/tokio-wireguard/src/lib.rs @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! In-process WireGuard for Tokio +//! +//! This crate provides a Tokio-based in-process implementation of WireGuard. +//! Each [`Interface`] is backed by an independent TCP/IP stack that tunnels all of its traffic +//! over WireGuard, and can be used to create TCP ([`TcpStream`] and [`TcpListener`]) +//! and UDP ([`UdpSocket`]) sockets, which attempt to follow the API of [`tokio::net`] as closely as +//! possible. +//! +//! The interface can be dynamically configured at runtime, and any number of interfaces can exist +//! in the same process. This makes it possible for an application to support WireGuard with fine +//! grained control without root privileges on any platform supported by Tokio. +//! +//! Interfaces can also forward traffic to remote WireGuard peers. However, at the moment, they cannot +//! forward traffic to other interfaces outside of the WireGuard network. +//! +//! ```no_run +//! # #[tokio::main] +//! # async fn main() { +//! # let (private_key, remote_public_key) = tokio_wireguard::x25519::keypair(); +//! use tokio::io::AsyncWriteExt; +//! use tokio_wireguard::{ +//! config::{Config, Interface, Peer}, +//! interface::ToInterface, +//! TcpStream, +//! }; +//! +//! let config = Config { +//! interface: Interface { +//! private_key, +//! // Our address on the WireGuard network +//! address: "100.64.0.2/32".parse().unwrap(), +//! // Let the interface pick a random port +//! listen_port: None, +//! // Let the interface pick an appropriate MTU +//! mtu: None, +//! }, +//! peers: vec![Peer { +//! public_key: remote_public_key, +//! // This is where the tunneled WireGuard traffic will be sent +//! endpoint: Some("198.51.100.30:51820".parse().unwrap()), +//! // IP addresses the peer can handle traffic to and from on the WireGuard network +//! // The /32 suffix indicates that the peer only handles traffic for itself +//! allowed_ips: vec!["100.64.0.1/32".parse().unwrap()], +//! // Send a keepalive packet every 15 seconds +//! persistent_keepalive: Some(15), +//! }], +//! }; +//! let interface = config.to_interface().await.unwrap(); +//! +//! let mut stream = TcpStream::connect("100.64.0.1:8080", &interface) +//! .await +//! .unwrap(); +//! stream.write_all(b"Bonjour").await.unwrap(); +//! # } +//! ``` +//! +//! This library is built on top of [`smoltcp`] and [`boringtun`], and could not exist without these +//! amazing projects. + +// This narrow upstream vendor retains its existing style; OpenShell's strict +// Clippy gate applies to the integrating crates rather than rewriting it. +#![allow(clippy::all)] + +pub mod config; +pub mod interface; +mod io; +pub mod tcp; +pub mod udp; +pub mod x25519; + +pub(crate) type Shared = std::sync::Arc>>; + +pub use crate::{ + config::Config, + interface::Interface, + tcp::{TcpListener, TcpStream}, + udp::UdpSocket, +}; diff --git a/vendor/tokio-wireguard/src/tcp.rs b/vendor/tokio-wireguard/src/tcp.rs new file mode 100644 index 0000000000..c5d6a9871d --- /dev/null +++ b/vendor/tokio-wireguard/src/tcp.rs @@ -0,0 +1,763 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +use std::{ + any::type_name, + fmt, + future::{poll_fn, Future}, + iter, + mem::replace, + net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}, + pin::Pin, + sync::Arc, + task::{Context, Poll, Waker}, +}; + +use bytes::BufMut; +use smoltcp::{ + socket::tcp::{RecvError, SendError, Socket, SocketBuffer}, + wire::IpEndpoint, +}; +use tokio::{ + io::{AsyncRead, AsyncWrite, Error, ErrorKind, Interest, ReadBuf, Ready, Result}, + net::{lookup_host, ToSocketAddrs}, + time, +}; + +use crate::{ + interface::{Allocation, Interface, ToInterface}, + io::{Evented, IO}, +}; + +/// A WireGuard TCP stream +/// +/// This type mostly behaves like and shares the same API as [`tokio::net::TcpStream`]. +pub struct TcpStream { + socket: IO>, +} + +/// A WireGuard TCP listener +/// +/// This type mostly behaves like and shares the same API as [`tokio::net::TcpListener`]. +pub struct TcpListener { + interface: Interface, + allocation: Allocation, + backlog: Box<[TcpStream]>, +} + +impl TcpStream { + /// Like [`tokio::net::TcpStream::connect`], but on a WireGuard [`Interface`] + pub async fn connect(addr: A, iface: I) -> Result { + let interface = iface.to_interface().await?; + let targets = lookup_host(addr) + .await? + .filter(|addr| interface.address().is_compatible(*addr)); + + let mut err: Option = None; + for target in targets { + let Some(allocation) = interface.allocate_tcp(match target { + SocketAddr::V4(..) => SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)), + SocketAddr::V6(..) => { + SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 0, 0, 0)) + } + }) else { + continue; + }; + + let socket = IO::new( + interface.clone(), + Socket::new( + SocketBuffer::new(vec![0; interface.options().tcp.recv_buffer_size]), + SocketBuffer::new(vec![0; interface.options().tcp.send_buffer_size]), + ), + Some(allocation), + ); + + if socket + .interface() + .connect_tcp(Arc::clone(&socket), allocation, target) + .await? + .is_err() + { + continue; + } + + let ready = async { + loop { + let ready = socket.ready(Interest::WRITABLE).await?; + // A connecting socket can initially report WRITE_CLOSED. + // Its readiness remains immediate until the handshake + // advances, so wait briefly rather than starving Tokio's + // connect timeout in a tight loop. + if ready & Ready::WRITE_CLOSED == Ready::WRITE_CLOSED { + time::sleep(time::Duration::from_millis(10)).await; + continue; + } + if ready & Ready::WRITABLE == Ready::WRITABLE { + break Ok(()); + } + } + }; + let timeout = time::timeout(interface.options().tcp.connect_timeout, ready).await; + + match timeout { + Ok(Ok(..)) => return Ok(TcpStream { socket }), + Ok(Err(e)) => err = Some(e), + Err(..) => continue, + } + } + + Err(err.unwrap_or_else(|| Error::from(ErrorKind::TimedOut))) + } + + fn endpoint(&self, f: F) -> Result + where + F: FnOnce(&mut Socket<'static>) -> Option, + { + let endpoint = self + .socket + .with(f)? + .ok_or_else(|| Error::from(ErrorKind::NotConnected))?; + let address: IpAddr = endpoint.addr.into(); + let port = endpoint.port; + + Ok(SocketAddr::new(address, port)) + } + /// [`tokio::net::TcpStream::local_addr`] + pub fn local_addr(&self) -> Result { + self.endpoint(|s| s.local_endpoint()) + } + /// [`tokio::net::TcpStream::peer_addr`] + pub fn peer_addr(&self) -> Result { + self.endpoint(|s| s.remote_endpoint()) + } + + fn peek_io(socket: &mut Socket<'static>, mut buf: B) -> Poll> { + match socket.peek(buf.remaining_mut()) { + Ok(data) if data.len() > 0 => { + buf.put_slice(data); + Poll::Ready(Ok(data.len())) + } + Ok(..) => Poll::Pending, + Err(RecvError::Finished) => Poll::Ready(Ok(0)), + Err(RecvError::InvalidState) => { + Poll::Ready(Err(Error::from(ErrorKind::ConnectionAborted))) + } + } + } + /// [`tokio::net::TcpStream::peek`] + pub async fn peek(&self, mut buf: B) -> Result { + self.socket + .io(Interest::READABLE, |s| Self::peek_io(s, &mut buf)) + .await + } + /// [`tokio::net::TcpStream::poll_peek`] + pub fn poll_peek(&self, cx: &mut Context<'_>, buf: B) -> Poll> { + self.socket + .poll_io(Interest::READABLE, cx, |s| Self::peek_io(s, buf)) + } + + /// [`tokio::net::TcpStream::ready`] + pub async fn ready(&self, interest: Interest) -> Result { + self.socket.ready(interest).await + } + + /// [`tokio::net::TcpStream::readable`] + pub async fn readable(&self) -> Result<()> { + self.socket.ready(Interest::READABLE).await.map(drop) + } + /// [`tokio::net::TcpStream::poll_read_ready`] + pub fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll> { + self.socket.poll_ready(Interest::READABLE, cx) + } + + fn read_io(socket: &mut Socket<'static>, mut buf: B) -> Poll> { + match socket.recv(|data| { + let len = usize::min(buf.remaining_mut(), data.len()); + buf.put_slice(&data[..len]); + (len, len) + }) { + Ok(len) if len > 0 => Poll::Ready(Ok(len)), + Ok(..) => Poll::Pending, + Err(RecvError::Finished) => Poll::Ready(Ok(0)), + Err(RecvError::InvalidState) => { + Poll::Ready(Err(Error::from(ErrorKind::ConnectionAborted))) + } + } + } + /// [`tokio::net::TcpStream::try_read`] + pub fn try_read(&self, buf: B) -> Result { + self.socket.try_io(|s| Self::read_io(s, buf)) + } + + /// [`tokio::net::TcpStream::writable`] + pub async fn writable(&self) -> Result<()> { + self.socket.ready(Interest::WRITABLE).await.map(drop) + } + /// [`tokio::net::TcpStream::poll_write_ready`] + pub fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll> { + self.socket.poll_ready(Interest::WRITABLE, cx) + } + + fn write_io(socket: &mut Socket<'static>, buf: &[u8]) -> Poll> { + match socket.send_slice(buf) { + Ok(len) if len > 0 => Poll::Ready(Ok(len)), + Ok(..) => Poll::Pending, + Err(SendError::InvalidState) => { + Poll::Ready(Err(Error::from(ErrorKind::ConnectionAborted))) + } + } + } + /// [`tokio::net::TcpStream::try_write`] + pub fn try_write(&self, buf: &[u8]) -> Result { + self.socket.try_io(|s| Self::write_io(s, buf)) + } + + fn shutdown_io(socket: &mut Socket<'static>) -> Poll> { + if !socket.may_send() { + Poll::Ready(Ok(())) + } else { + socket.close(); + Poll::Pending + } + } + + /// [`tokio::net::TcpStream::split`] + pub fn split(&self) -> (ReadHalf<'_>, WriteHalf<'_>) { + (ReadHalf(self), WriteHalf(self)) + } + /// [`tokio::net::TcpStream::into_split`] + pub fn into_split(self) -> (OwnedReadHalf, OwnedWriteHalf) { + let read = OwnedReadHalf(self); + let write = OwnedWriteHalf(TcpStream { + socket: read.0.socket.clone(), + }); + (read, write) + } + + /// [`tokio::net::TcpStream::nodelay`] + pub fn nodelay(&self) -> Result { + self.socket.with(|s| !s.nagle_enabled()) + } + /// [`tokio::net::TcpStream::set_nodelay`] + pub fn set_nodelay(&mut self, nodelay: bool) -> Result<()> { + self.socket.with(|s| s.set_nagle_enabled(!nodelay)) + } + + /// [`tokio::net::TcpStream::ttl`] + pub fn ttl(&self) -> Result { + self.socket.with(|s| s.hop_limit().unwrap_or(64).into()) + } + /// [`tokio::net::TcpStream::set_ttl`] + pub fn set_ttl(&mut self, ttl: u32) -> Result<()> { + self.socket.with(|s| s.set_hop_limit(ttl.try_into().ok())) + } + + /// Interface to which this stream is bound + pub fn interface(&self) -> &Interface { + self.socket.interface() + } +} + +impl AsyncRead for TcpStream { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + self.socket + .poll_io(Interest::READABLE, cx, |s| Self::read_io(s, buf)) + .map_ok(drop) + } +} + +impl AsyncWrite for TcpStream { + fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { + self.socket + .poll_io(Interest::WRITABLE, cx, |s| Self::write_io(s, buf)) + } + + fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.socket + .poll_io(Interest::WRITABLE, cx, Self::shutdown_io) + } +} + +impl fmt::Debug for TcpStream { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut f = f.debug_struct(type_name::()); + if let Ok(local_addr) = self.local_addr() { + f.field("local_addr", &local_addr); + } + if let Ok(peer_addr) = self.peer_addr() { + f.field("peer_addr", &peer_addr); + } + f.field("interface", &self.interface()).finish() + } +} + +impl TcpListener { + fn socket(interface: &Interface, allocation: Allocation) -> Socket<'static> { + let mut socket = Socket::new( + SocketBuffer::new(vec![0; interface.options().tcp.recv_buffer_size]), + SocketBuffer::new(vec![0; interface.options().tcp.send_buffer_size]), + ); + socket.listen(allocation.address()).unwrap(); + socket + } + + /// Like [`tokio::net::TcpListener::bind`], but on a WireGuard [`Interface`] + pub async fn bind(addr: A, iface: I) -> Result { + let interface = iface.to_interface().await?; + let allocation = lookup_host(addr) + .await? + .find_map(|addr| interface.allocate_tcp(addr)) + .ok_or_else(|| { + Error::new(ErrorKind::AddrNotAvailable, "not a suitable bind address") + })?; + + let backlog: Result> = iter::repeat_with(|| { + let stream = TcpStream { + socket: IO::new( + interface.clone(), + Self::socket(&interface, allocation.clone()), + None, + ), + }; + interface + .register_tcp(Arc::clone(&stream.socket)) + .map(|()| stream) + }) + .take(interface.options().tcp.backlog) + .collect(); + + Ok(Self { + interface, + allocation, + backlog: backlog?, + }) + } + + fn accept_io( + socket: &mut Socket<'static>, + interface: &Interface, + allocation: Allocation, + ) -> Poll, SocketAddr)>> { + socket.state(); + if socket.may_send() { + let next = Self::socket(&interface, allocation); + let socket = replace(socket, next); + + let endpoint = match socket.remote_endpoint() { + Some(endpoint) => endpoint, + None => return Poll::Pending, + }; + let address: IpAddr = endpoint.addr.into(); + let port = endpoint.port; + + Poll::Ready(Ok((socket, SocketAddr::new(address, port)))) + } else { + Poll::Pending + } + } + + /// [`tokio::net::TcpListener::accept`] + pub async fn accept(&self) -> Result<(TcpStream, SocketAddr)> { + let mut waiters: Box<[_]> = self + .backlog + .iter() + .map(|s| { + s.socket.io(Interest::WRITABLE, |s| { + Self::accept_io(s, &self.interface, self.allocation) + }) + }) + .collect(); + + let (socket, addr) = poll_fn(|cx| { + // Safety: The waiters are never used unpinned + waiters + .iter_mut() + .map(|w| unsafe { Pin::new_unchecked(w) }.poll(cx)) + .find(Poll::is_ready) + .unwrap_or(Poll::Pending) + }) + .await?; + + let stream = TcpStream { + socket: IO::new(self.interface.clone(), socket, None), + }; + self.interface.register_tcp(Arc::clone(&stream.socket))?; + + Ok((stream, addr)) + } + + /// [`tokio::net::TcpListener::poll_accept`] + pub fn poll_accept(&self, cx: &mut Context<'_>) -> Poll> { + let socket = self + .backlog + .iter() + .map(|s| { + s.socket.poll_io(Interest::WRITABLE, cx, |s| { + Self::accept_io(s, &self.interface, self.allocation) + }) + }) + .find(Poll::is_ready) + .unwrap_or(Poll::Pending)?; + + match socket { + Poll::Ready((socket, addr)) => { + let stream = TcpStream { + socket: IO::new(self.interface.clone(), socket, None), + }; + self.interface.register_tcp(Arc::clone(&stream.socket))?; + + Poll::Ready(Ok((stream, addr))) + } + Poll::Pending => Poll::Pending, + } + } + + /// [`tokio::net::TcpListener::local_addr`] + pub fn local_addr(&self) -> Result { + Ok(self.allocation.address()) + } + + /// Interface to which the listener is bound + pub fn interface(&self) -> &Interface { + &self.interface + } +} + +impl fmt::Debug for TcpListener { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut f = f.debug_struct(type_name::()); + if let Ok(local_addr) = self.local_addr() { + f.field("local_addr", &local_addr); + } + f.field("interface", &self.interface()).finish() + } +} + +impl Drop for TcpListener { + fn drop(&mut self) { + self.interface.deallocate(self.allocation); + } +} + +/// Like [`tokio::net::tcp::ReadHalf`], but on a WireGuard [`Interface`] +#[derive(Debug)] +pub struct ReadHalf<'a>(&'a TcpStream); + +impl<'a> ReadHalf<'a> { + /// [`tokio::net::tcp::ReadHalf::local_addr`] + pub fn local_addr(&self) -> Result { + self.0.local_addr() + } + /// [`tokio::net::tcp::ReadHalf::peer_addr`] + pub fn peer_addr(&self) -> Result { + self.0.peer_addr() + } + + /// [`tokio::net::tcp::ReadHalf::peek`] + pub async fn peek(&self, buf: B) -> Result { + self.0.peek(buf).await + } + /// [`tokio::net::tcp::ReadHalf::poll_peek`] + pub fn poll_peek(&self, cx: &mut Context<'_>, buf: impl BufMut) -> Poll> { + self.0.poll_peek(cx, buf) + } + + /// [`tokio::net::tcp::ReadHalf::ready`] + pub async fn ready(&self, interest: Interest) -> Result { + self.0.ready(interest).await + } + + /// [`tokio::net::tcp::ReadHalf::readable`] + pub async fn readable(&self) -> Result<()> { + self.0.readable().await + } + /// [`tokio::net::TcpStream::poll_read_ready`] + pub fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll> { + self.0.poll_read_ready(cx) + } + + /// [`tokio::net::tcp::ReadHalf::try_read`] + pub fn try_read(&self, buf: B) -> Result { + self.0.try_read(buf) + } + + /// Interface to which this stream is bound + pub fn interface(&self) -> &Interface { + self.0.interface() + } +} + +impl AsyncRead for ReadHalf<'_> { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + self.0 + .socket + .poll_io(Interest::READABLE, cx, |s| TcpStream::read_io(s, buf)) + .map_ok(drop) + } +} + +impl AsRef for ReadHalf<'_> { + fn as_ref(&self) -> &TcpStream { + self.0 + } +} + +/// Like [`tokio::net::tcp::WriteHalf`], but on a WireGuard [`Interface`] +#[derive(Debug)] +pub struct WriteHalf<'a>(&'a TcpStream); + +impl<'a> WriteHalf<'a> { + /// [`tokio::net::tcp::WriteHalf::local_addr`] + pub fn local_addr(&self) -> Result { + self.0.local_addr() + } + /// [`tokio::net::tcp::WriteHalf::peer_addr`] + pub fn peer_addr(&self) -> Result { + self.0.peer_addr() + } + + /// [`tokio::net::tcp::WriteHalf::ready`] + pub async fn ready(&self, interest: Interest) -> Result { + self.0.ready(interest).await + } + + /// [`tokio::net::tcp::WriteHalf::writable`] + pub async fn writable(&self) -> Result<()> { + self.0.writable().await + } + /// [`tokio::net::TcpStream::poll_write_ready`] + pub fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll> { + self.0.poll_write_ready(cx) + } + + /// [`tokio::net::tcp::WriteHalf::try_write`] + pub fn try_write(&self, buf: &[u8]) -> Result { + self.0.try_write(buf) + } + + /// Interface to which this stream is bound + pub fn interface(&self) -> &Interface { + self.0.interface() + } +} + +impl AsyncWrite for WriteHalf<'_> { + fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { + self.0 + .socket + .poll_io(Interest::WRITABLE, cx, |s| TcpStream::write_io(s, buf)) + } + + fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.0 + .socket + .poll_io(Interest::WRITABLE, cx, TcpStream::shutdown_io) + } +} + +impl AsRef for WriteHalf<'_> { + fn as_ref(&self) -> &TcpStream { + self.0 + } +} + +/// Like [`tokio::net::tcp::OwnedReadHalf`], but on a WireGuard [`Interface`] +#[derive(Debug)] +pub struct OwnedReadHalf(TcpStream); + +impl OwnedReadHalf { + /// [`tokio::net::tcp::OwnedReadHalf::local_addr`] + pub fn local_addr(&self) -> Result { + self.0.local_addr() + } + /// [`tokio::net::tcp::OwnedReadHalf::peer_addr`] + pub fn peer_addr(&self) -> Result { + self.0.peer_addr() + } + + /// [`tokio::net::tcp::OwnedReadHalf::peek`] + pub async fn peek(&self, buf: B) -> Result { + self.0.peek(buf).await + } + /// [`tokio::net::tcp::OwnedReadHalf::poll_peek`] + pub fn poll_peek(&self, cx: &mut Context<'_>, buf: impl BufMut) -> Poll> { + self.0.poll_peek(cx, buf) + } + + /// [`tokio::net::tcp::OwnedReadHalf::ready`] + pub async fn ready(&self, interest: Interest) -> Result { + self.0.ready(interest).await + } + + /// [`tokio::net::tcp::OwnedReadHalf::readable`] + pub async fn readable(&self) -> Result<()> { + self.0.readable().await + } + /// [`tokio::net::TcpStream::poll_read_ready`] + pub fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll> { + self.0.poll_read_ready(cx) + } + + /// [`tokio::net::tcp::OwnedReadHalf::try_read`] + pub fn try_read(&self, buf: B) -> Result { + self.0.try_read(buf) + } + + /// Interface to which this stream is bound + pub fn interface(&self) -> &Interface { + self.0.interface() + } + + /// [`tokio::net::tcp::OwnedReadHalf::reunite`] + pub fn reunite(self, other: OwnedWriteHalf) -> std::result::Result { + if self.0.socket.is(&other.0.socket) { + Ok(TcpStream { + socket: self.0.socket, + }) + } else { + Err(ReuniteError(self, other)) + } + } +} + +impl AsyncRead for OwnedReadHalf { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.0).poll_read(cx, buf) + } +} + +impl AsRef for OwnedReadHalf { + fn as_ref(&self) -> &TcpStream { + &self.0 + } +} + +/// Like [`tokio::net::tcp::OwnedWriteHalf`], but on a WireGuard [`Interface`] +#[derive(Debug)] +pub struct OwnedWriteHalf(TcpStream); + +impl OwnedWriteHalf { + /// [`tokio::net::tcp::OwnedWriteHalf::local_addr`] + pub fn local_addr(&self) -> Result { + self.0.local_addr() + } + /// [`tokio::net::tcp::OwnedWriteHalf::peer_addr`] + pub fn peer_addr(&self) -> Result { + self.0.peer_addr() + } + + /// [`tokio::net::tcp::OwnedWriteHalf::ready`] + pub async fn ready(&self, interest: Interest) -> Result { + self.0.ready(interest).await + } + + /// [`tokio::net::tcp::OwnedWriteHalf::writable`] + pub async fn writable(&self) -> Result<()> { + self.0.writable().await + } + /// [`tokio::net::TcpStream::poll_write_ready`] + pub fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll> { + self.0.poll_write_ready(cx) + } + + /// [`tokio::net::tcp::OwnedWriteHalf::try_write`] + pub fn try_write(&self, buf: &[u8]) -> Result { + self.0.try_write(buf) + } + + /// Interface to which this stream is bound + pub fn interface(&self) -> &Interface { + self.0.interface() + } + + /// [`tokio::net::tcp::OwnedWriteHalf::reunite`] + pub fn reunite(self, other: OwnedReadHalf) -> std::result::Result { + if self.0.socket.is(&other.0.socket) { + Ok(TcpStream { + socket: other.0.socket, + }) + } else { + Err(ReuniteError(other, self)) + } + } +} + +impl AsyncWrite for OwnedWriteHalf { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + Pin::new(&mut self.0).poll_write(cx, buf) + } + + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.0).poll_flush(cx) + } + + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.0).poll_shutdown(cx) + } +} + +impl AsRef for OwnedWriteHalf { + fn as_ref(&self) -> &TcpStream { + &self.0 + } +} + +/// Error indicating that two halves were not from the same socket, and thus could not be reunited +#[derive(Debug)] +pub struct ReuniteError(pub OwnedReadHalf, pub OwnedWriteHalf); + +impl fmt::Display for ReuniteError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("tried to reunite halves that are not from the same socket") + } +} + +impl std::error::Error for ReuniteError {} + +impl Evented for Socket<'static> { + fn readiness(&self) -> Ready { + let mut readiness = Ready::EMPTY; + if self.can_recv() { + readiness |= Ready::READABLE; + } else if !self.may_recv() { + readiness |= Ready::READ_CLOSED; + } + if self.can_send() { + readiness |= Ready::WRITABLE; + } else if !self.may_send() { + readiness |= Ready::WRITE_CLOSED; + } + readiness + } + + fn register_read_waker(&mut self, waker: &Waker) { + self.register_recv_waker(waker) + } + + fn register_write_waker(&mut self, waker: &Waker) { + self.register_send_waker(waker) + } +} diff --git a/vendor/tokio-wireguard/src/udp.rs b/vendor/tokio-wireguard/src/udp.rs new file mode 100644 index 0000000000..0c24a425a6 --- /dev/null +++ b/vendor/tokio-wireguard/src/udp.rs @@ -0,0 +1,267 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +use std::{ + net::{IpAddr, SocketAddr}, + sync::Arc, + task::{Context, Poll, Waker}, +}; + +use bytes::BufMut; +use smoltcp::{ + socket::udp::{SendError, Socket}, + storage::{PacketBuffer, PacketMetadata}, +}; +use tokio::{ + io::{Error, ErrorKind, Interest, ReadBuf, Ready, Result}, + net::{lookup_host, ToSocketAddrs}, +}; + +use crate::{ + config::Address, + interface::{Interface, ToInterface}, + io::{Evented, IO}, +}; + +/// A WireGuard UDP socket +/// +/// This type mostly behaves like and shares the same API as [`tokio::net::UdpSocket`]. +pub struct UdpSocket { + socket: IO>, +} + +impl UdpSocket { + /// Like [`tokio::net::UdpSocket::bind`], but on a WireGuard [`Interface`] + pub async fn bind(addr: A, iface: I) -> Result { + let interface = iface.to_interface().await?; + let allocation = lookup_host(addr) + .await? + .find_map(|addr| interface.allocate_udp(addr)) + .ok_or_else(|| { + Error::new(ErrorKind::AddrNotAvailable, "not a suitable bind address") + })?; + + let mut socket = Socket::new( + PacketBuffer::new( + vec![PacketMetadata::EMPTY; interface.options().udp.recv_buffer_size / 1024], + vec![0; interface.options().udp.recv_buffer_size], + ), + PacketBuffer::new( + vec![PacketMetadata::EMPTY; interface.options().udp.send_buffer_size / 1024], + vec![0; interface.options().udp.send_buffer_size], + ), + ); + socket.bind(allocation.address()).unwrap(); + + let socket = IO::new(interface, socket, Some(allocation)); + socket.interface().register_udp(Arc::clone(&socket))?; + + Ok(UdpSocket { socket }) + } + + /// [`tokio::net::UdpSocket::local_addr`] + pub fn local_addr(&self) -> Result { + let endpoint = self.socket.with(|s| s.endpoint())?; + let address: IpAddr = endpoint.addr.unwrap().into(); + let port = endpoint.port; + + Ok(SocketAddr::new(address, port)) + } + + /// [`tokio::net::UdpSocket::ready`] + pub async fn ready(&self, interest: Interest) -> Result { + self.socket.ready(interest).await + } + + /// [`tokio::net::UdpSocket::writable`] + pub async fn writable(&self) -> Result<()> { + self.socket.ready(Interest::WRITABLE).await.map(drop) + } + /// [`tokio::net::UdpSocket::poll_send_ready`] + pub fn poll_send_ready(&self, cx: &mut Context<'_>) -> Poll> { + self.socket.poll_ready(Interest::WRITABLE, cx) + } + + fn send_to_io( + socket: &mut Socket<'static>, + buf: &[u8], + target: SocketAddr, + ) -> Poll> { + match socket.send_slice(buf, target) { + Ok(()) => Poll::Ready(Ok(buf.len())), + Err(SendError::Unaddressable) => Poll::Ready(Err(Error::new( + ErrorKind::InvalidInput, + "not a valid target address", + ))), + Err(SendError::BufferFull) => Poll::Pending, + } + } + /// [`tokio::net::UdpSocket::send_to`] + pub async fn send_to(&self, buf: &[u8], target: A) -> Result { + let target = lookup_host(target) + .await? + .find(|target| match (target, self.socket.interface().address()) { + (SocketAddr::V4(..), Address::Dual(..) | Address::V4(..)) => true, + (SocketAddr::V6(..), Address::Dual(..) | Address::V6(..)) => true, + _ => false, + }) + .ok_or_else(|| { + Error::new(ErrorKind::AddrNotAvailable, "not a suitable target address") + })?; + + self.socket + .io(Interest::WRITABLE, |s| Self::send_to_io(s, buf, target)) + .await + } + /// [`tokio::net::UdpSocket::poll_send_to`] + pub fn poll_send_to( + &self, + cx: &mut Context<'_>, + buf: &[u8], + target: SocketAddr, + ) -> Poll> { + self.socket + .poll_io(Interest::READABLE, cx, |s| Self::send_to_io(s, buf, target)) + } + /// [`tokio::net::UdpSocket::try_send_to`] + pub fn try_send_to(&self, buf: &mut [u8], target: SocketAddr) -> Result { + self.socket.try_io(|s| Self::send_to_io(s, buf, target)) + } + + /// [`tokio::net::UdpSocket::readable`] + pub async fn readable(&self) -> Result<()> { + self.socket.ready(Interest::READABLE).await.map(drop) + } + /// [`tokio::net::UdpSocket::poll_recv_ready`] + pub fn poll_recv_ready(&self, cx: &mut Context<'_>) -> Poll> { + self.socket.poll_ready(Interest::READABLE, cx) + } + + fn recv_from_io( + socket: &mut Socket<'static>, + mut buf: B, + ) -> Poll> { + match socket.recv() { + Ok((packet, meta)) => { + let len = usize::min(buf.remaining_mut(), packet.len()); + let addr = SocketAddr::new(meta.endpoint.addr.into(), meta.endpoint.port); + buf.put_slice(&packet[..len]); + Poll::Ready(Ok((len, addr))) + } + _ => Poll::Pending, + } + } + /// [`tokio::net::UdpSocket::recv_from`] + pub async fn recv_from(&self, mut buf: B) -> Result<(usize, SocketAddr)> { + self.socket + .io(Interest::READABLE, |s| Self::recv_from_io(s, &mut buf)) + .await + } + /// [`tokio::net::UdpSocket::poll_recv_from`] + pub fn poll_recv_from( + &self, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + self.socket + .poll_io(Interest::READABLE, cx, |s| Self::recv_from_io(s, buf)) + .map_ok(|(_, addr)| addr) + } + /// [`tokio::net::UdpSocket::try_recv_from`] + pub fn try_recv_from(&self, buf: B) -> Result<(usize, SocketAddr)> { + self.socket.try_io(|s| Self::recv_from_io(s, buf)) + } + + fn peek_from_io( + socket: &mut Socket<'static>, + mut buf: B, + ) -> Poll> { + match socket.peek() { + Ok((packet, meta)) => { + let len = usize::min(buf.remaining_mut(), packet.len()); + let addr = SocketAddr::new(meta.endpoint.addr.into(), meta.endpoint.port); + buf.put_slice(&packet[..len]); + Poll::Ready(Ok((len, addr))) + } + _ => Poll::Pending, + } + } + /// [`tokio::net::UdpSocket::peek_from`] + pub async fn peek_from(&self, mut buf: B) -> Result<(usize, SocketAddr)> { + self.socket + .io(Interest::READABLE, |s| Self::peek_from_io(s, &mut buf)) + .await + } + /// [`tokio::net::UdpSocket::poll_peek_from`] + pub fn poll_peek_from( + &self, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + self.socket + .poll_io(Interest::READABLE, cx, |s| Self::peek_from_io(s, buf)) + .map_ok(|(_, addr)| addr) + } + /// [`tokio::net::UdpSocket::try_peek_from`] + pub fn try_peek_from(&self, buf: B) -> Result<(usize, SocketAddr)> { + self.socket.try_io(|s| Self::peek_from_io(s, buf)) + } + + fn peek_sender_io(socket: &mut Socket<'static>) -> Poll> { + match socket.peek() { + Ok((_, meta)) => Poll::Ready(Ok(SocketAddr::new( + meta.endpoint.addr.into(), + meta.endpoint.port, + ))), + _ => Poll::Pending, + } + } + /// [`tokio::net::UdpSocket::peek_sender`] + pub async fn peek_sender(&self) -> Result { + self.socket + .io(Interest::READABLE, Self::peek_sender_io) + .await + } + /// [`tokio::net::UdpSocket::poll_peek_sender`] + pub fn poll_peek_sender(&self, cx: &mut Context<'_>) -> Poll> { + self.socket + .poll_io(Interest::READABLE, cx, Self::peek_sender_io) + } + /// [`tokio::net::UdpSocket::try_peek_sender`] + pub fn try_peek_sender(&self) -> Result { + self.socket.try_io(Self::peek_sender_io) + } + + /// [`tokio::net::UdpSocket::ttl`] + pub fn ttl(&self) -> Result { + self.socket.with(|s| s.hop_limit().unwrap_or(64).into()) + } + /// [`tokio::net::UdpSocket::set_ttl`] + pub fn set_ttl(&mut self, ttl: u32) -> Result<()> { + self.socket.with(|s| s.set_hop_limit(ttl.try_into().ok())) + } + + /// Interface to which this socket is bound + pub fn interface(&self) -> &Interface { + self.socket.interface() + } +} + +impl Evented for Socket<'static> { + fn readiness(&self) -> Ready { + let mut readiness = Ready::EMPTY; + if self.is_open() && self.can_recv() { + readiness |= Ready::READABLE; + } + if self.is_open() && self.can_send() { + readiness |= Ready::WRITABLE; + } + readiness + } + + fn register_read_waker(&mut self, waker: &Waker) { + self.register_recv_waker(waker) + } + + fn register_write_waker(&mut self, waker: &Waker) { + self.register_send_waker(waker) + } +} diff --git a/vendor/tokio-wireguard/src/x25519.rs b/vendor/tokio-wireguard/src/x25519.rs new file mode 100644 index 0000000000..1b1987e726 --- /dev/null +++ b/vendor/tokio-wireguard/src/x25519.rs @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: MIT OR Apache-2.0 +pub use boringtun::x25519::{PublicKey, StaticSecret}; +use rand::rngs::OsRng; + +/// Generate a random keypair +pub fn keypair() -> (StaticSecret, PublicKey) { + let secret = StaticSecret::random_from_rng(OsRng); + let public = PublicKey::from(&secret); + (secret, public) +} From 5f8c8612307edad9abb19d5874f649d25fb74dee Mon Sep 17 00:00:00 2001 From: craig Date: Mon, 5 Oct 2026 19:26:56 -0700 Subject: [PATCH 3/7] fix(sandbox): integrate advisor policy with VPN tunnels Signed-off-by: craig (cherry picked from commit 4447bcd89e25787c8d3cf78eceb75677aa3467cc) --- ...-supervisor-terminated-appliance-tunnel.md | 4 +- architecture/sandbox.md | 6 +- crates/openshell-sandbox/src/lib.rs | 168 ++++++++++++- .../openshell-supervisor-network/src/lib.rs | 1 + .../openshell-supervisor-network/src/opa.rs | 62 +++-- .../src/policy_local.rs | 82 ++++++- .../openshell-supervisor-network/src/run.rs | 37 ++- .../src/tunnel.rs | 223 ++++++++++++++++-- docs/reference/policy-schema.mdx | 4 +- vendor/tokio-wireguard/README.md | 4 + .../tokio-wireguard/src/interface/sockets.rs | 9 +- 11 files changed, 519 insertions(+), 81 deletions(-) diff --git a/architecture/adr/0001-supervisor-terminated-appliance-tunnel.md b/architecture/adr/0001-supervisor-terminated-appliance-tunnel.md index 4d674d6652..34b232d154 100644 --- a/architecture/adr/0001-supervisor-terminated-appliance-tunnel.md +++ b/architecture/adr/0001-supervisor-terminated-appliance-tunnel.md @@ -12,8 +12,8 @@ Customer private services require a route from a sandbox to a customer appliance Each sandbox supervisor owns its own userspace WireGuard interface and TCP stack. Its policy names the appliance's exact UDP endpoint and an inner destination endpoint that references the tunnel. The appliance endpoint is a supervisor-only transport exception; workload TCP cannot use it. The inner host and port remain ordinary policy objects. Destination validation and applicable L7 and credential handling stay in the existing proxy path, with the tunnel replacing only the final upstream TCP transport. A failed tunnel has no direct or corporate-proxy fallback. -The policy carries a reference to a sandbox-scoped provider credential containing the private key. The supervisor suppresses that environment key before workload startup and resolves it only in its own credential state. Key bytes do not enter policy persistence, policy introspection, or the workload environment. The first implementation accepts one named tunnel, one IPv4 literal destination and port, and one route bound to the initial policy generation. A later policy generation refuses tunnel dials until sandbox restart. +The policy carries a reference to a sandbox-scoped provider credential containing the private key. The supervisor suppresses that environment key before workload startup and resolves it only in its own credential state. Key bytes do not enter policy persistence, policy introspection, or the workload environment. The first implementation accepts one named tunnel, one IPv4 literal destination and port, and one route. A successful policy reload advances the accepted generation only when the validated tunnel configuration, full inner and outer endpoints, key reference, and current supervisor key material are unchanged. A changed or missing tunnel or key permanently revokes the route until sandbox restart. Every dial checks the current supervisor key, so an independent credential refresh also fails closed. A failed policy reload leaves the last accepted generation intact. ## Consequences -The supervisor remains the enforcement point for inner destinations. Tunnel keys and decrypted packets stay outside the workload. The appliance must expose a reachable WireGuard UDP listener and trust the supervisor peer key and tunnel source address. CONNECT establishes the upstream TCP stream after endpoint and address authorization, before its existing TLS and L7 request inspection; stricter pre-dial application authorization would require a separate CONNECT flow change. Tunnel DNS, hot reload and key rotation, multiple routes, IPv6, and alternate TCP carriers remain future work. +The supervisor remains the enforcement point for inner destinations. Tunnel keys and decrypted packets stay outside the workload. The appliance must expose a reachable WireGuard UDP listener and trust the supervisor peer key and tunnel source address. CONNECT establishes the upstream TCP stream after endpoint and address authorization, before its existing TLS and L7 request inspection; stricter pre-dial application authorization would require a separate CONNECT flow change. Tunnel DNS, tunnel configuration hot reload and key rotation, multiple routes, IPv6, and alternate TCP carriers remain future work. diff --git a/architecture/sandbox.md b/architecture/sandbox.md index e5080cd38a..3f37ad0c4d 100644 --- a/architecture/sandbox.md +++ b/architecture/sandbox.md @@ -238,9 +238,9 @@ before the dial. CONNECT keeps its existing sequence: endpoint authorization and address validation precede the TCP dial; TLS interception and request inspection follow establishment. A `wireguard-udp` endpoint authorizes only the supervisor's exact appliance socket and cannot authorize workload TCP. -The first implementation binds one tunnel and one inner endpoint to the -initial policy generation. A later policy generation requires a sandbox -restart for tunnel traffic; dials fail closed rather than using a stale route. +The first implementation binds one tunnel and one inner endpoint. Policy +reloads retain tunnel traffic when that configuration and its key are unchanged; +changes revoke new tunnel dials until sandbox restart. In proxy-required networks, the supervisor chains upstream TLS tunnels through a corporate forward proxy with HTTP CONNECT instead of connecting directly, diff --git a/crates/openshell-sandbox/src/lib.rs b/crates/openshell-sandbox/src/lib.rs index e54cd78288..cc89c82bfe 100644 --- a/crates/openshell-sandbox/src/lib.rs +++ b/crates/openshell-sandbox/src/lib.rs @@ -773,6 +773,7 @@ pub async fn run_sandbox( let poll_pid = entrypoint_pid.clone(); let poll_provider_credentials = provider_credentials.clone(); let poll_policy_local = networking.as_ref().map(|n| n.policy_local_ctx.clone()); + let poll_tunnel = networking.as_ref().and_then(|n| n.tunnel.clone()); let poll_interval_secs: u64 = std::env::var("OPENSHELL_POLICY_POLL_INTERVAL_SECS") .ok() .and_then(|v| v.parse().ok()) @@ -781,13 +782,18 @@ pub async fn run_sandbox( endpoint: poll_endpoint, sandbox_id: poll_id, opa_engine: poll_engine, - loaded_policy_origin, + loaded_policy_origin: loaded_policy_origin.clone(), entrypoint_pid: poll_pid, interval_secs: poll_interval_secs, ocsf_enabled: poll_ocsf_enabled, ocsf_schema_version: poll_ocsf_schema_version, provider_credentials: poll_provider_credentials, policy_local_ctx: poll_policy_local, + tunnel: poll_tunnel, + last_valid_policy: loaded_policy_origin + .has_last_valid_policy() + .then(|| retained_proto.clone()) + .flatten(), agent_proposals: agent_proposals.clone(), middleware_registry_status, sidecar_control_publisher: sidecar_control_publisher.clone(), @@ -1447,11 +1453,18 @@ fn spawn_sidecar_entrypoint_handler( } if let (Some(engine), Some(proto)) = (opa_engine.as_ref(), retained_proto.as_ref()) { - match engine.reload_from_proto_with_pid(proto, started.pid) { - Ok(()) => info!( - pid = started.pid, - "Policy binary symlink resolution complete for sidecar process anchor" - ), + match engine.reload_from_proto_with_pid_and_generation(proto, started.pid) { + Ok(generation) => { + if let Some(tunnel) = networking.as_ref().and_then(|n| n.tunnel.as_ref()) { + let _ = engine.with_current_generation(generation, |_| { + tunnel.reconcile_policy(proto, generation); + }); + } + info!( + pid = started.pid, + "Policy binary symlink resolution complete for sidecar process anchor" + ); + } Err(err) => warn!( error = %err, pid = started.pid, @@ -2898,7 +2911,7 @@ async fn reload_gateway_policy_runtime( entrypoint_pid: u32, middleware: MiddlewareReloadContext<'_>, transparent_tcp: TransparentTcpReloadState, -) -> std::result::Result<(), GatewayRuntimeReloadError> { +) -> std::result::Result { if let Some(policy) = policy && policy_contains_explicit_tcp(policy) { @@ -2926,14 +2939,18 @@ async fn reload_gateway_policy_runtime( .await .map_err(GatewayRuntimeReloadError::MiddlewareRegistry)?; engine - .reload_policy_and_middleware_from_proto_with_pid(policy, entrypoint_pid, registry) + .reload_policy_and_middleware_from_proto_with_pid_and_generation( + policy, + entrypoint_pid, + registry, + ) .map_err(GatewayRuntimeReloadError::PolicyValidation) } // Policy-only change: the installed registry already matches the // delivered service set, so swap the engine alone. This must not // require middleware reachability. Some(policy) => engine - .reload_from_proto_with_pid(policy, entrypoint_pid) + .reload_from_proto_with_pid_and_generation(policy, entrypoint_pid) .map_err(GatewayRuntimeReloadError::PolicyValidation), None => Err(GatewayRuntimeReloadError::PolicyValidation( miette::miette!("runtime reload requires a policy payload but none was returned"), @@ -3578,6 +3595,9 @@ struct PolicyPollLoopContext { ocsf_schema_version: Arc>, provider_credentials: ProviderCredentialState, policy_local_ctx: Option>, + tunnel: Option>, + /// Full policy last committed to OPA, including tunnel credentials metadata. + last_valid_policy: Option, agent_proposals: AgentProposals, middleware_registry_status: MiddlewareRegistryStatus, sidecar_control_publisher: Option, @@ -3873,6 +3893,22 @@ fn apply_policy_validation_failure( } } +fn reconcile_retained_tunnel( + engine: &OpaEngine, + tunnel: Option<&openshell_supervisor_network::TunnelManager>, + policy: Option<&openshell_core::proto::SandboxPolicy>, + disposition: &PolicyValidationFailureDisposition, +) { + if disposition.mode != PolicyValidationFailureMode::RetainLastValid { + return; + } + if let (Some(tunnel), Some(policy)) = (tunnel, policy) { + let _ = engine.with_current_generation(disposition.active_generation, |_| { + tunnel.reconcile_policy(policy, disposition.active_generation); + }); + } +} + fn policy_validation_failure_events( disposition: &PolicyValidationFailureDisposition, version: u32, @@ -4004,6 +4040,7 @@ async fn run_policy_poll_loop_with_client( let mut last_failed_runtime_revision: Option = None; let mut rejected_policy_generation: Option = None; let mut has_last_valid_policy = ctx.loaded_policy_origin.has_last_valid_policy(); + let mut last_valid_policy = ctx.last_valid_policy.clone(); // A first poll that does not match the policy already loaded into OPA must // pass through the normal reconciliation path immediately. It must never @@ -4213,6 +4250,12 @@ async fn run_policy_poll_loop_with_client( rejected.version, &rejected.validation_error, )?; + reconcile_retained_tunnel( + &ctx.opa_engine, + ctx.tunnel.as_deref(), + last_valid_policy.as_ref(), + &disposition, + ); emit_policy_validation_failure( &disposition, rejected.version, @@ -4338,13 +4381,20 @@ async fn run_policy_poll_loop_with_client( .await; match runtime_result { - Ok(()) => { + Ok(generation) => { policy_runtime_reconciled = true; let policy = result .policy .as_ref() .expect("successful runtime reload requires a policy payload"); - has_last_valid_policy = true; + last_valid_policy = + ctx.opa_engine.with_current_generation(generation, |_| { + if let Some(tunnel) = ctx.tunnel.as_ref() { + tunnel.reconcile_policy(policy, generation); + } + policy.clone() + })?; + has_last_valid_policy = last_valid_policy.is_some(); rejected_policy_generation = None; if policy_changed { if let Some(policy_local_ctx) = ctx.policy_local_ctx.as_ref() { @@ -4461,6 +4511,12 @@ async fn run_policy_poll_loop_with_client( error, disposition, } => { + reconcile_retained_tunnel( + &ctx.opa_engine, + ctx.tunnel.as_deref(), + last_valid_policy.as_ref(), + &disposition, + ); emit_policy_validation_failure( &disposition, result.version, @@ -5354,6 +5410,8 @@ network_policies: std::collections::HashMap::new(), ), policy_local_ctx: None, + tunnel: None, + last_valid_policy: None, agent_proposals: AgentProposals::default(), middleware_registry_status: MiddlewareRegistryStatus::Synchronized, sidecar_control_publisher: None, @@ -5376,6 +5434,23 @@ network_policies: assert_eq!(report, (version, true, String::new())); } + async fn expect_policy_failure_report( + reports: &mut tokio::sync::mpsc::UnboundedReceiver<(u32, bool, String)>, + version: u32, + ) { + let report = timeout(Duration::from_secs(1), reports.recv()) + .await + .expect("policy report timed out") + .expect("policy reporter stopped"); + assert_eq!(report.0, version); + assert!(!report.1); + assert!( + report + .2 + .contains("runtime reload requires a policy payload") + ); + } + async fn expect_no_policy_report( reports: &mut tokio::sync::mpsc::UnboundedReceiver<(u32, bool, String)>, ) { @@ -5824,6 +5899,77 @@ network_policies: handle.abort(); } + #[tokio::test] + async fn invalid_candidate_retain_reactivates_last_valid_generation() { + let policy = proto_policy_fixture(); + let v1 = settings_poll_result( + Some(policy.clone()), + 1, + openshell_core::proto::PolicySource::Sandbox, + ); + let mut rejected = + settings_poll_result(None, 2, openshell_core::proto::PolicySource::Sandbox); + rejected.policy_validation_failure_mode = PolicyValidationFailureMode::RetainLastValid; + let engine = Arc::new(OpaEngine::from_proto(&policy).unwrap()); + let mut ctx = policy_poll_test_context( + engine.clone(), + LoadedPolicyOrigin::Gateway { + revision: Some(LoadedPolicyRevision::from_snapshot(&v1)), + has_last_valid_policy: true, + }, + default_middleware_connector(), + ); + ctx.last_valid_policy = Some(policy); + let (client, polls, mut reports) = scripted_policy_gateway(); + polls.send(v1).unwrap(); + let handle = tokio::spawn(run_policy_poll_loop_with_client(ctx, client)); + expect_policy_report(&mut reports, 1).await; + polls.send(rejected).unwrap(); + expect_policy_failure_report(&mut reports, 2).await; + assert_eq!(engine.current_generation(), 0); + assert!(engine.fail_closed_reason().is_none()); + handle.abort(); + } + + #[tokio::test] + async fn same_hash_posture_change_reactivates_last_valid_generation() { + let policy = proto_policy_fixture(); + let v1 = settings_poll_result( + Some(policy.clone()), + 1, + openshell_core::proto::PolicySource::Sandbox, + ); + let rejected = settings_poll_result(None, 2, openshell_core::proto::PolicySource::Sandbox); + let engine = Arc::new(OpaEngine::from_proto(&policy).unwrap()); + let mut ctx = policy_poll_test_context( + engine.clone(), + LoadedPolicyOrigin::Gateway { + revision: Some(LoadedPolicyRevision::from_snapshot(&v1)), + has_last_valid_policy: true, + }, + default_middleware_connector(), + ); + ctx.last_valid_policy = Some(policy); + let (client, polls, mut reports) = scripted_policy_gateway(); + polls.send(v1).unwrap(); + let handle = tokio::spawn(run_policy_poll_loop_with_client(ctx, client)); + expect_policy_report(&mut reports, 1).await; + polls.send(rejected.clone()).unwrap(); + expect_policy_failure_report(&mut reports, 2).await; + assert!(engine.fail_closed_reason().is_some()); + let quarantined_generation = engine.current_generation(); + + let mut changed_posture = rejected; + changed_posture.config_revision += 1; + changed_posture.policy_validation_failure_mode = + PolicyValidationFailureMode::RetainLastValid; + polls.send(changed_posture).unwrap(); + expect_policy_failure_report(&mut reports, 2).await; + assert!(engine.current_generation() > quarantined_generation); + assert!(engine.fail_closed_reason().is_none()); + handle.abort(); + } + #[tokio::test] async fn failed_external_startup_registry_build_preserves_installed_builtins() { let engine = OpaEngine::from_proto(&proto_policy_fixture()).expect("build OPA engine"); diff --git a/crates/openshell-supervisor-network/src/lib.rs b/crates/openshell-supervisor-network/src/lib.rs index fad30767d7..a4afc15065 100644 --- a/crates/openshell-supervisor-network/src/lib.rs +++ b/crates/openshell-supervisor-network/src/lib.rs @@ -20,6 +20,7 @@ pub mod run; pub mod sigv4; mod token_grant; mod tunnel; +pub use tunnel::TunnelManager; pub mod upstream_proxy; #[cfg(test)] diff --git a/crates/openshell-supervisor-network/src/opa.rs b/crates/openshell-supervisor-network/src/opa.rs index e98c98cc18..bbaca1655a 100644 --- a/crates/openshell-supervisor-network/src/opa.rs +++ b/crates/openshell-supervisor-network/src/opa.rs @@ -700,6 +700,16 @@ impl OpaEngine { proto: &ProtoSandboxPolicy, entrypoint_pid: u32, ) -> Result<()> { + self.reload_from_proto_with_pid_and_generation(proto, entrypoint_pid) + .map(|_| ()) + } + + /// Reload policy and return the generation committed under the engine lock. + pub fn reload_from_proto_with_pid_and_generation( + &self, + proto: &ProtoSandboxPolicy, + entrypoint_pid: u32, + ) -> Result { // Build a complete new engine through the same validated pipeline. let new = Self::from_proto_with_pid(proto, entrypoint_pid)?; let new_engine = new @@ -715,8 +725,7 @@ impl OpaEngine { .fail_closed_reason .write() .map_err(|_| miette::miette!("OPA fail-closed state lock poisoned"))? = None; - self.advance_generation(); - Ok(()) + Ok(self.advance_generation()) } /// Reload the policy and middleware registry as one runtime generation. @@ -731,6 +740,21 @@ impl OpaEngine { entrypoint_pid: u32, registry: MiddlewareRegistry, ) -> Result<()> { + self.reload_policy_and_middleware_from_proto_with_pid_and_generation( + proto, + entrypoint_pid, + registry, + ) + .map(|_| ()) + } + + /// Reload policy and middleware and return their committed generation. + pub fn reload_policy_and_middleware_from_proto_with_pid_and_generation( + &self, + proto: &ProtoSandboxPolicy, + entrypoint_pid: u32, + registry: MiddlewareRegistry, + ) -> Result { let new = Self::from_proto_with_pid(proto, entrypoint_pid)?; let new_engine = new .engine @@ -753,8 +777,7 @@ impl OpaEngine { .fail_closed_reason .write() .map_err(|_| miette::miette!("OPA fail-closed state lock poisoned"))? = None; - self.advance_generation(); - Ok(()) + Ok(self.advance_generation()) } /// Publish a deny-all quarantine generation without activating any part @@ -815,7 +838,7 @@ impl OpaEngine { /// generation comparison and callback linearizes state derived from an OPA /// snapshot with every policy reload and fail-closed transition. Callers /// must not perform I/O or other long-running work in `operation`. - pub(crate) fn with_current_generation( + pub fn with_current_generation( &self, expected_generation: u64, operation: impl FnOnce(u64) -> T, @@ -2255,7 +2278,6 @@ fn proto_to_opa_data_json(proto: &ProtoSandboxPolicy, entrypoint_pid: u32) -> St )] mod tests { use super::*; - use std::collections::HashMap; use openshell_core::mcp::DEFAULT_MCP_PROTOCOL_VERSION; use openshell_core::proto::{ @@ -2325,7 +2347,7 @@ mod tests { run_as_group: "sandbox".to_string(), }), network_policies, - tunnels: HashMap::default(), + tunnels: std::collections::HashMap::default(), network_middlewares: std::collections::HashMap::default(), } } @@ -3423,7 +3445,7 @@ process: run_as_group: "sandbox".to_string(), }), network_policies, - tunnels: HashMap::default(), + tunnels: std::collections::HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto_with_pid_and_binary_identity_required(&proto, 0, false) @@ -3963,7 +3985,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, - tunnels: HashMap::default(), + tunnels: std::collections::HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; @@ -4036,7 +4058,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, - tunnels: HashMap::default(), + tunnels: std::collections::HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; @@ -4114,7 +4136,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, - tunnels: HashMap::default(), + tunnels: std::collections::HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; @@ -5304,7 +5326,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, - tunnels: HashMap::default(), + tunnels: std::collections::HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; @@ -5363,7 +5385,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, - tunnels: HashMap::default(), + tunnels: std::collections::HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; @@ -5423,7 +5445,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, - tunnels: HashMap::default(), + tunnels: std::collections::HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; @@ -5485,7 +5507,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, - tunnels: HashMap::default(), + tunnels: std::collections::HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; @@ -5546,7 +5568,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, - tunnels: HashMap::default(), + tunnels: std::collections::HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; @@ -7029,7 +7051,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, - tunnels: HashMap::default(), + tunnels: std::collections::HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto(&proto).expect("engine from proto"); @@ -7085,7 +7107,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, - tunnels: HashMap::default(), + tunnels: std::collections::HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto(&proto).expect("engine from proto"); @@ -7157,7 +7179,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, - tunnels: HashMap::default(), + tunnels: std::collections::HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto(&proto).expect("Failed to create engine from proto"); @@ -7389,7 +7411,7 @@ network_policies: run_as_group: "sandbox".to_string(), }), network_policies, - tunnels: HashMap::default(), + tunnels: std::collections::HashMap::default(), network_middlewares: std::collections::HashMap::default(), }; let engine = OpaEngine::from_proto(&proto).unwrap(); diff --git a/crates/openshell-supervisor-network/src/policy_local.rs b/crates/openshell-supervisor-network/src/policy_local.rs index a6c1b5de43..ca01f306c0 100644 --- a/crates/openshell-supervisor-network/src/policy_local.rs +++ b/crates/openshell-supervisor-network/src/policy_local.rs @@ -120,10 +120,7 @@ impl PolicyLocalContext { workspace_rx: tokio::sync::watch::Receiver, ) -> Self { Self { - current_policy: Arc::new(RwLock::new(current_policy.map(|mut policy| { - redact_tunnels(&mut policy); - Arc::new(policy) - }))), + current_policy: Arc::new(RwLock::new(current_policy.map(Arc::new))), agent_proposals, gateway_endpoint, sandbox_name, @@ -132,11 +129,10 @@ impl PolicyLocalContext { } } - pub async fn set_current_policy(&self, mut policy: ProtoSandboxPolicy) { + pub async fn set_current_policy(&self, policy: ProtoSandboxPolicy) { // Every successful reload receives a distinct Arc, including an // identical policy installed again. Waiters use pointer identity to // decide whether the installed snapshot needs another coverage scan. - redact_tunnels(&mut policy); *self.current_policy.write().await = Some(Arc::new(policy)); } @@ -310,7 +306,9 @@ async fn current_policy_response(ctx: &PolicyLocalContext) -> (u16, serde_json:: ); }; - match openshell_policy::serialize_sandbox_policy(&policy) { + let mut visible_policy = policy.as_ref().clone(); + redact_tunnels(&mut visible_policy); + match openshell_policy::serialize_sandbox_policy(&visible_policy) { Ok(policy_yaml) => ( 200, serde_json::json!({ @@ -426,8 +424,8 @@ fn read_recent_denial_lines(log_dir: &Path, limit: usize) -> Vec { /// Replace any `?` substring with `?[redacted]` to keep query-string /// secrets out of the agent's view. Walks per Unicode scalar value so multi-byte -/// content is safe. A query is everything from `?` until the next whitespace or -/// `]` (the shorthand format uses `[...]` for context tags). +/// content is safe. A query is everything from `?` until the next whitespace. +/// Preserve a trailing `]` that closes a shorthand context tag. fn redact_query_strings(line: &str) -> String { let mut out = String::with_capacity(line.len()); let mut chars = line.chars(); @@ -435,13 +433,16 @@ fn redact_query_strings(line: &str) -> String { if c == '?' { out.push('?'); out.push_str("[redacted]"); - // Consume until whitespace or `]` (preserved as the next token's - // boundary by writing it back out). + let mut query = String::new(); for next in chars.by_ref() { - if next.is_whitespace() || next == ']' { + if next.is_whitespace() { out.push(next); break; } + query.push(next); + } + if query.ends_with(']') { + out.push(']'); } } else { out.push(c); @@ -1972,6 +1973,15 @@ mod tests { assert!(redacted.contains("?[redacted]]")); } + #[test] + fn redact_query_strings_removes_query_after_internal_bracket() { + let line = "2026-05-06T17:02:00.000Z OCSF HTTP:PUT [MED] DENIED PUT http://api.github.com/x [policy:p engine:opa] [reason:FORWARD denied PUT api.github.com:443/x?token=prefix]secret-suffix]"; + let redacted = redact_query_strings(line); + assert!(!redacted.contains("prefix")); + assert!(!redacted.contains("secret-suffix")); + assert!(redacted.contains("[reason:FORWARD denied PUT api.github.com:443/x?[redacted]]")); + } + #[test] fn redact_query_strings_handles_multibyte_chars() { let line = "ÜLÅUTF8 ? secret-x [policy:p]"; @@ -2354,6 +2364,54 @@ mod tests { ); } + #[tokio::test] + async fn tunnel_policy_stays_valid_for_coverage_but_is_hidden_from_introspection() { + let mut policy = openshell_policy::parse_sandbox_policy( + r" +version: 1 +tunnels: + customer: + endpoint_host: 198.51.100.20 + endpoint_udp_port: 51820 + peer_public_key: AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA= + private_key_env_key: OPENSHELL_WG_PRIVATE_KEY + local_address: 10.80.0.1/32 + allowed_inner_cidrs: [10.80.0.2/32] +network_policies: + transport: + endpoints: + - { host: 198.51.100.20, port: 51820, protocol: wireguard-udp } + service: + endpoints: + - { host: 10.80.0.2, port: 8080, allowed_ips: [10.80.0.2], tunnel_id: customer } + binaries: + - { path: /usr/bin/example-app } +", + ) + .unwrap(); + let proposed = proposed_curl_rule_for_github(); + policy + .network_policies + .insert(proposed.name.clone(), proposed.clone()); + let ctx = PolicyLocalContext::new( + Some(policy), + None, + None, + AgentProposals::new(true), + test_workspace_rx(), + ); + + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(1); + assert!(wait_for_local_policy_to_cover(&ctx, &proposed, deadline).await); + + let (status, payload) = current_policy_response(&ctx).await; + assert_eq!(status, 200); + let visible = payload["policy_yaml"].as_str().unwrap(); + assert!(!visible.contains("private_key_env_key")); + assert!(!visible.contains("tunnel_id")); + assert!(visible.contains("api.github.com")); + } + /// A destination-only reload is insufficient for a CA proposal. The /// in-process policy update completes the wait once the CA is installed. #[tokio::test(start_paused = true)] diff --git a/crates/openshell-supervisor-network/src/run.rs b/crates/openshell-supervisor-network/src/run.rs index 170552cfe7..78608da979 100644 --- a/crates/openshell-supervisor-network/src/run.rs +++ b/crates/openshell-supervisor-network/src/run.rs @@ -150,7 +150,7 @@ fn advance_allocation_epoch(path: &std::path::Path, sandbox_id: Option<&str>) -> /// `run_sandbox`'s frame. pub struct Networking { pub proxy: Option, - _tunnel: Option>, + pub tunnel: Option>, pub ca_file_paths: Option<(std::path::PathBuf, std::path::PathBuf)>, /// Policy-local route context: shared with the orchestrator's policy poll @@ -260,7 +260,9 @@ pub async fn run_networking( Policy binary paths will be matched literally." ); if let Some(tunnel) = &resolve_tunnel { - tunnel.accept_initial_generation(resolve_engine.current_generation()); + let _ = resolve_engine.with_current_generation(0, |generation| { + tunnel.accept_initial_generation(generation); + }); } let _ = engine_ready_tx.send(true); return; @@ -278,8 +280,16 @@ pub async fn run_networking( attempt = attempt, "Container filesystem accessible, resolving policy binary symlinks" ); - match resolve_engine.reload_from_proto_with_pid(&resolve_proto, pid) { - Ok(()) => { + match resolve_engine + .reload_from_proto_with_pid_and_generation(&resolve_proto, pid) + { + Ok(generation) => { + if let Some(tunnel) = &resolve_tunnel { + let _ = + resolve_engine.with_current_generation(generation, |_| { + tunnel.reconcile_policy(&resolve_proto, generation); + }); + } info!( pid = pid, "Policy binary symlink resolution complete \ @@ -287,15 +297,18 @@ pub async fn run_networking( ); } Err(e) => { + if let Some(tunnel) = &resolve_tunnel { + let _ = + resolve_engine.with_current_generation(0, |generation| { + tunnel.accept_initial_generation(generation); + }); + } warn!( "Failed to rebuild OPA engine with symlink resolution \ (non-fatal, falling back to literal path matching): {e}" ); } } - if let Some(tunnel) = &resolve_tunnel { - tunnel.accept_initial_generation(resolve_engine.current_generation()); - } let _ = engine_ready_tx.send(true); return; } @@ -313,14 +326,18 @@ pub async fn run_networking( (run 'readlink -f ' inside the sandbox)" ); if let Some(tunnel) = &resolve_tunnel { - tunnel.accept_initial_generation(resolve_engine.current_generation()); + let _ = resolve_engine.with_current_generation(0, |generation| { + tunnel.accept_initial_generation(generation); + }); } let _ = engine_ready_tx.send(true); }); } else { // No process supervisor — PID will never arrive, skip symlink resolution. if let Some(tunnel) = &tunnel { - tunnel.accept_initial_generation(engine.current_generation()); + let _ = engine.with_current_generation(0, |generation| { + tunnel.accept_initial_generation(generation); + }); } let _ = engine_ready_tx.send(true); } @@ -517,7 +534,7 @@ pub async fn run_networking( Ok(Networking { proxy: proxy_handle, - _tunnel: tunnel, + tunnel, ca_file_paths, policy_local_ctx, #[cfg(target_os = "linux")] diff --git a/crates/openshell-supervisor-network/src/tunnel.rs b/crates/openshell-supervisor-network/src/tunnel.rs index 8bb5aaa887..3ce58955bb 100644 --- a/crates/openshell-supervisor-network/src/tunnel.rs +++ b/crates/openshell-supervisor-network/src/tunnel.rs @@ -4,7 +4,7 @@ //! Supervisor-owned `WireGuard` transport for one policy-authorized IPv4 endpoint. use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; -use std::sync::OnceLock; +use std::sync::Mutex; use std::time::Duration; use base64::Engine as _; @@ -20,7 +20,12 @@ use tokio_wireguard::x25519::{PublicKey, StaticSecret}; pub struct TunnelManager { id: String, destination: SocketAddrV4, - accepted_generation: OnceLock, + state: Mutex, + credentials: ProviderCredentialState, + key_name: String, + pinned_tunnel: openshell_core::proto::NetworkTunnel, + pinned_inner: NetworkEndpoint, + pinned_outer: NetworkEndpoint, interface: tokio::sync::OnceCell, private_key: [u8; 32], peer_public_key: [u8; 32], @@ -31,6 +36,12 @@ pub struct TunnelManager { keepalive: u16, } +#[derive(Default)] +struct TunnelGeneration { + accepted: Option, + revoked: bool, +} + impl TunnelManager { pub(crate) fn owns_destination(&self, address: SocketAddr) -> bool { address == SocketAddr::V4(self.destination) @@ -72,7 +83,7 @@ impl TunnelManager { .ok() .filter(|port| *port != 0) .ok_or_else(|| miette::miette!("invalid appliance UDP port"))?; - let outer_allowed = policy + let outer: Vec<_> = policy .network_policies .values() .flat_map(|rule| &rule.endpoints) @@ -81,9 +92,8 @@ impl TunnelManager { && endpoint.host == tunnel.endpoint_host && single_port(endpoint) == Some(u32::from(endpoint_port)) }) - .count() - == 1; - if !outer_allowed { + .collect(); + if outer.len() != 1 { return Err(miette::miette!( "appliance UDP endpoint is not exactly authorized" )); @@ -168,7 +178,12 @@ impl TunnelManager { Ok(Some(Self { id: id.clone(), destination: SocketAddrV4::new(inner_ip, inner_port), - accepted_generation: OnceLock::new(), + state: Mutex::new(TunnelGeneration::default()), + credentials: credentials.clone(), + key_name: key_name.clone(), + pinned_tunnel: tunnel.clone(), + pinned_inner: endpoint.clone(), + pinned_outer: outer[0].clone(), interface: tokio::sync::OnceCell::new(), private_key: private, peer_public_key: public, @@ -180,9 +195,56 @@ impl TunnelManager { })) } - /// Accept only the generation resulting from initial binary reconciliation. + /// Accept the initial generation after binary reconciliation. pub(crate) fn accept_initial_generation(&self, generation: u64) { - let _ = self.accepted_generation.set(generation); + let mut state = self.state.lock().expect("tunnel generation poisoned"); + if !state.revoked && self.key_is_current() { + state.accepted = Some(generation); + } else { + state.revoked = true; + } + } + + fn key_is_current(&self) -> bool { + self.credentials + .supervisor_tunnel_private_key(&self.key_name) + .and_then(|value| base64::engine::general_purpose::STANDARD.decode(value).ok()) + .as_deref() + .is_some_and(|candidate| self.same_private_key(candidate)) + } + + fn same_private_key(&self, candidate: &[u8]) -> bool { + if candidate.len() != self.private_key.len() { + return false; + } + self.private_key + .iter() + .zip(candidate) + .fold(0u8, |difference, (expected, actual)| { + difference | (expected ^ actual) + }) + == 0 + } + + /// Called only after OPA commits a new policy. Any tunnel change requires restart. + pub fn reconcile_policy(&self, policy: &SandboxPolicy, generation: u64) { + let mut state = self.state.lock().expect("tunnel generation poisoned"); + if state.revoked { + return; + } + let valid = Self::new(policy, &self.credentials).ok().flatten(); + let unchanged = valid.is_some_and(|candidate| { + candidate.id == self.id + && candidate.pinned_tunnel == self.pinned_tunnel + && candidate.pinned_inner == self.pinned_inner + && candidate.pinned_outer == self.pinned_outer + && self.same_private_key(&candidate.private_key) + }); + if unchanged && self.key_is_current() { + state.accepted = Some(generation); + } else { + state.revoked = true; + } } /// Connect only the destination pinned by the validated endpoint decision. @@ -192,14 +254,21 @@ impl TunnelManager { destination: SocketAddr, policy_generation: u64, ) -> std::io::Result { - if id != self.id - || destination != SocketAddr::V4(self.destination) - || self.accepted_generation.get() != Some(&policy_generation) { - return Err(std::io::Error::new( - std::io::ErrorKind::PermissionDenied, - "tunnel route unavailable", - )); + let mut state = self.state.lock().expect("tunnel generation poisoned"); + if !self.key_is_current() { + state.revoked = true; + } + if id != self.id + || destination != SocketAddr::V4(self.destination) + || state.revoked + || state.accepted != Some(policy_generation) + { + return Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "tunnel route unavailable", + )); + } } let interface = self .interface @@ -440,6 +509,128 @@ mod tests { assert!(!String::from_utf8_lossy(&observed).contains("openshell:resolve:env:")); drop(client); drop(appliance); + assert!(!manager.interface.get().unwrap().is_closed()); + let (second, accepted) = tokio::join!( + manager.dial("customer", "10.80.0.2:8080".parse().unwrap(), 42), + tokio::time::timeout(Duration::from_secs(15), listener.accept()), + ); + let second = second.expect("second tunnel connection failed"); + let (second_appliance, _) = accepted.expect("second accept timed out").unwrap(); + drop(second); + drop(second_appliance); + manager.reconcile_policy(&policy, 43); + assert_eq!(manager.state.lock().unwrap().accepted, Some(43)); + assert!(!manager.state.lock().unwrap().revoked); + assert!( + manager + .dial("customer", "10.80.0.2:8080".parse().unwrap(), 42) + .await + .is_err() + ); + let (after_reconcile, accepted) = tokio::join!( + manager.dial("customer", "10.80.0.2:8080".parse().unwrap(), 43), + tokio::time::timeout(Duration::from_secs(15), listener.accept()), + ); + let after_reconcile = after_reconcile.expect("post-reload tunnel connection failed"); + let (appliance, _) = accepted.expect("post-reload accept timed out").unwrap(); + drop(after_reconcile); + drop(appliance); + let engine = crate::opa::OpaEngine::from_proto(&policy).unwrap(); + let initial_generation = engine.current_generation(); + manager.accept_initial_generation(initial_generation); + let quarantined_generation = engine.enter_fail_closed("rejected candidate").unwrap(); + assert!(quarantined_generation > initial_generation); + let restored_generation = engine.exit_fail_closed().unwrap(); + assert!(restored_generation > quarantined_generation); + assert_eq!( + manager.state.lock().unwrap().accepted, + Some(initial_generation) + ); + assert!( + engine + .with_current_generation(restored_generation, |_| { + manager.reconcile_policy(&policy, restored_generation); + }) + .unwrap() + .is_some() + ); + assert_eq!( + manager.state.lock().unwrap().accepted, + Some(restored_generation) + ); + let old_generation = manager + .dial( + "customer", + "10.80.0.2:8080".parse().unwrap(), + initial_generation, + ) + .await + .unwrap_err(); + assert_eq!(old_generation.kind(), std::io::ErrorKind::PermissionDenied); + let restored = manager + .dial( + "customer", + "10.80.0.2:8080".parse().unwrap(), + restored_generation, + ) + .await; + if let Err(error) = restored { + assert_ne!(error.kind(), std::io::ErrorKind::PermissionDenied); + } + let mut changed = policy.clone(); + changed.tunnels.get_mut("customer").unwrap().mtu = 1300; + manager.reconcile_policy(&changed, 44); + assert!(manager.state.lock().unwrap().revoked); + manager.reconcile_policy(&policy, 45); + assert!(manager.state.lock().unwrap().revoked); + let mut changed_inner = policy.clone(); + changed_inner + .network_policies + .get_mut("inner") + .unwrap() + .endpoints[0] + .enforcement = "enforce".into(); + let mut changed_outer = policy.clone(); + changed_outer + .network_policies + .get_mut("outer") + .unwrap() + .endpoints[0] + .enforcement = "enforce".into(); + let mut removed = policy.clone(); + removed.tunnels.clear(); + let mut changed_key_ref = policy.clone(); + changed_key_ref + .tunnels + .get_mut("customer") + .unwrap() + .private_key_env_key = "OPENSHELL_WG_OTHER".into(); + for candidate in [&changed_inner, &changed_outer, &removed, &changed_key_ref] { + let route = TunnelManager::new(&policy, &credentials).unwrap().unwrap(); + route.accept_initial_generation(42); + route.reconcile_policy(candidate, 43); + assert!(route.state.lock().unwrap().revoked); + route.reconcile_policy(&policy, 44); + assert!(route.state.lock().unwrap().revoked); + } + let provider_route = TunnelManager::new(&policy, &credentials).unwrap().unwrap(); + provider_route.accept_initial_generation(42); + credentials.install_environment( + 3, + HashMap::from([( + "OPENSHELL_WG_PRIVATE_KEY".into(), + base64::engine::general_purpose::STANDARD.encode([7u8; 32]), + )]), + HashMap::new(), + HashMap::new(), + ); + assert!( + provider_route + .dial("customer", "10.80.0.2:8080".parse().unwrap(), 42) + .await + .is_err() + ); + assert!(provider_route.state.lock().unwrap().revoked); drop(listener); server.close(); tokio::time::timeout(Duration::from_secs(5), server.closed()) diff --git a/docs/reference/policy-schema.mdx b/docs/reference/policy-schema.mdx index bdc0237806..9760393eee 100644 --- a/docs/reference/policy-schema.mdx +++ b/docs/reference/policy-schema.mdx @@ -144,7 +144,7 @@ process: **Category:** Dynamic -A map of named network policy entries. Each entry declares a set of endpoints and a set of binaries. Only the listed binaries are permitted to connect to the listed endpoints. The map key is a logical identifier. The `name` field inside the entry is the display name used in logs. +A map of named network policy entries. Each entry declares a set of endpoints and, for workload traffic, a set of binaries. Only the listed binaries are permitted to connect to workload endpoints. A rule containing only a `wireguard-udp` endpoint is the exception: it may omit `binaries` because it authorizes only the supervisor's outer UDP socket. The map key is a logical identifier. The `name` field inside the entry is the display name used in logs. ### Customer appliance tunnel @@ -198,7 +198,7 @@ Each entry in the `network_policies` map has the following fields: |---|---|---|---| | `name` | string | No | Display name for the policy entry. Used in log output. Defaults to the map key. | | `endpoints` | list of endpoint objects | Yes | Hosts and ports this entry permits. | -| `binaries` | list of binary objects | Yes | Executables allowed to connect to these endpoints. | +| `binaries` | list of binary objects | Conditional | Required for workload endpoints. May be omitted when the rule contains only a `wireguard-udp` endpoint; that endpoint authorizes only the supervisor's UDP socket. | ### Endpoint Object diff --git a/vendor/tokio-wireguard/README.md b/vendor/tokio-wireguard/README.md index cc454b9243..b5688144e1 100644 --- a/vendor/tokio-wireguard/README.md +++ b/vendor/tokio-wireguard/README.md @@ -4,3 +4,7 @@ In-process WireGuard for Tokio [![crates.io](https://img.shields.io/crates/v/tokio-wireguard.svg)](https://crates.io/crates/tokio-wireguard) [![Documentation](https://docs.rs/tokio-wireguard/badge.svg)](https://docs.rs/tokio-wireguard) + +## Vendored source + +This directory contains `tokio-wireguard` version 0.1.3. Its Cargo metadata names `https://github.com/raftario/river` as the repository; `.cargo_vcs_info.json` records source revision `4e71d82c4dac3989cd2a4b814144e3ae3dda6613` at `crates/tokio-wireguard`. The crate is licensed MIT OR Apache-2.0, with both license files included here. When updating this copy, record the new source revision and keep the Cargo metadata, license files, and local changes in sync. diff --git a/vendor/tokio-wireguard/src/interface/sockets.rs b/vendor/tokio-wireguard/src/interface/sockets.rs index c1e529615b..32494576e4 100644 --- a/vendor/tokio-wireguard/src/interface/sockets.rs +++ b/vendor/tokio-wireguard/src/interface/sockets.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MIT OR Apache-2.0 use std::sync::Arc; -use parking_lot::{ArcMutexGuard, Mutex, RawMutex}; +use parking_lot::{ArcMutexGuard, RawMutex}; use smoltcp::{ iface::{SocketHandle, SocketSet}, socket::{tcp, udp, Socket}, @@ -63,10 +63,9 @@ impl SocketsInner { fn register(&mut self, socket: crate::Shared) { let slot = self.sockets.iter_mut().enumerate().find_map(|(i, s)| { - match Arc::get_mut(s).map(Mutex::get_mut) { - Some(..) => None, - None => Some(i), - } + // Reuse only a slot whose previous socket has no external owner. + // Replacing a live slot disconnects its listener or stream. + Arc::get_mut(s).map(|_| i) }); if let Some(slot) = slot.and_then(|s| self.sockets.get_mut(s)) { From b18a263f8649e268c0c249c1292b739dfb56e454 Mon Sep 17 00:00:00 2001 From: craig Date: Mon, 5 Oct 2026 23:05:39 -0700 Subject: [PATCH 4/7] fix(sandbox): thread tunnel into sidecar entrypoint handler for Linux builds The VPN integration added tunnel reconciliation to the sidecar entrypoint handler but referenced `networking`, a binding that only exists in the outer run_sandbox scope. The handler region is #[cfg(target_os = "linux")], so macOS-only scoped checks never compiled it and every Linux-target build of openshell-sandbox failed with E0425 (cannot find value `networking`). Carry the tunnel manager through SidecarEntrypointHandler instead, populated from the same RunContext tunnel the policy poll loop uses. (cherry picked from commit d6719b35c0a223460cfa642094b4407ca1144d30) --- crates/openshell-sandbox/src/lib.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/openshell-sandbox/src/lib.rs b/crates/openshell-sandbox/src/lib.rs index cc89c82bfe..ad04bff89a 100644 --- a/crates/openshell-sandbox/src/lib.rs +++ b/crates/openshell-sandbox/src/lib.rs @@ -645,6 +645,7 @@ pub async fn run_sandbox( sandbox_id: sandbox_id.clone(), trusted_ssh_socket_path: std::path::PathBuf::from(trusted_ssh_socket_path), control_publisher: sidecar_control_publisher.clone(), + tunnel: networking.as_ref().and_then(|n| n.tunnel.clone()), }, ); } @@ -1359,6 +1360,7 @@ struct SidecarEntrypointHandler { sandbox_id: Option, trusted_ssh_socket_path: std::path::PathBuf, control_publisher: Option, + tunnel: Option>, } #[cfg(target_os = "linux")] @@ -1375,6 +1377,7 @@ fn spawn_sidecar_entrypoint_handler( sandbox_id, trusted_ssh_socket_path, control_publisher, + tunnel, } = handler; let mut session_started = false; let mut session_task: Option> = None; @@ -1455,7 +1458,7 @@ fn spawn_sidecar_entrypoint_handler( if let (Some(engine), Some(proto)) = (opa_engine.as_ref(), retained_proto.as_ref()) { match engine.reload_from_proto_with_pid_and_generation(proto, started.pid) { Ok(generation) => { - if let Some(tunnel) = networking.as_ref().and_then(|n| n.tunnel.as_ref()) { + if let Some(tunnel) = tunnel.as_ref() { let _ = engine.with_current_generation(generation, |_| { tunnel.reconcile_policy(proto, generation); }); From 5fd75bb948a09ab53e0f09785c6512c0cc96c80a Mon Sep 17 00:00:00 2001 From: craig Date: Tue, 6 Oct 2026 09:22:31 -0700 Subject: [PATCH 5/7] fix(sandbox): parse IpNet for appliance peer allowed_ips in example The vpn-appliance example built Peer.allowed_ips as Strings via format! but tokio_wireguard::config::Peer expects Vec, failing the Linux example build with E0308. Parse the formatted /32 like the file's own interface address pattern. Verified: cargo check -p openshell-supervisor-network --example vpn-appliance. (cherry picked from commit 7785c867e86889448f1c5a145fda04c994156027) --- .../examples/vpn-appliance.rs | 283 ++++++++++++++++++ 1 file changed, 283 insertions(+) create mode 100644 crates/openshell-supervisor-network/examples/vpn-appliance.rs diff --git a/crates/openshell-supervisor-network/examples/vpn-appliance.rs b/crates/openshell-supervisor-network/examples/vpn-appliance.rs new file mode 100644 index 0000000000..bb322845b8 --- /dev/null +++ b/crates/openshell-supervisor-network/examples/vpn-appliance.rs @@ -0,0 +1,283 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Userspace WireGuard test appliance for VPN-destination verification. +//! +//! Mirrors the in-process tunnel server pattern from `src/tunnel.rs` tests: +//! a `tokio_wireguard` Interface terminates the tunnel, and a +//! `tokio_wireguard::TcpListener` bound inside the tunnel address space +//! serves the inner destination. +//! +//! Sockets: +//! - WireGuard UDP listener on 0.0.0.0:$WG_PORT (the tunnel endpoint). +//! - Inner TCP service at $INNER_ADDR:8080, reachable only through the +//! tunnel, answering "vpn-inner-ok". +//! - Admin HTTP on 0.0.0.0:$ADMIN_PORT (plain host network, NOT through +//! the tunnel): POST /peer {"public_key": ""} registers a +//! sandbox supervisor peer; the appliance prints its own public key at +//! startup so the destination request can carry it as peer_public_key. +//! +//! Peers are rebuilt on each /peer POST (the destination flow provisions the +//! supervisor key pair only at activation time, so the appliance cannot know +//! the client key until then). Per-sandbox keys at test scale: each /peer POST +//! adds one client public key. +//! +//! Build (from repo root, linux/arm64): +//! cargo zigbuild --release --example vpn-appliance \ +//! -p openshell-supervisor-network --target aarch64-unknown-linux-gnu.2.28 + +use std::net::SocketAddr; +use std::sync::Arc; + +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::sync::Mutex; +use tokio_wireguard::config::{Config, Interface as InterfaceConfig, Peer}; +use tokio_wireguard::interface::Interface; +use tokio_wireguard::x25519::{PublicKey, StaticSecret}; +const DEFAULT_WG_PORT: u16 = 51820; +const DEFAULT_ADMIN_PORT: u16 = 8081; +const INNER_TCP_PORT: u16 = 8080; + +struct Appliance { + server_secret: StaticSecret, + server_public: PublicKey, + wg_port: u16, + inner_addr: String, + /// Peer public keys (base64), one per registered sandbox supervisor. + peers: Mutex>, + /// The live tunnel interface; rebuilt when a peer is added. + interface: Mutex>, +} + +fn b64_encode(bytes: &[u8]) -> String { + // Minimal standard base64 (no dependency on a base64 crate here). + const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::new(); + for chunk in bytes.chunks(3) { + let b = [ + chunk[0], + *chunk.get(1).unwrap_or(&0), + *chunk.get(2).unwrap_or(&0), + ]; + let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]); + out.push(TABLE[(n >> 18) as usize & 63] as char); + out.push(TABLE[(n >> 12) as usize & 63] as char); + out.push(if chunk.len() > 1 { + TABLE[(n >> 6) as usize & 63] as char + } else { + '=' + }); + out.push(if chunk.len() > 2 { + TABLE[n as usize & 63] as char + } else { + '=' + }); + } + out +} + +fn b64_decode(input: &str) -> Option<[u8; 32]> { + let input: String = input.trim().chars().filter(|c| !c.is_whitespace()).collect(); + let mut out = Vec::new(); + let mut buf: u32 = 0; + let mut bits = 0u32; + for ch in input.chars() { + if ch == '=' { + break; + } + let v = match ch { + 'A'..='Z' => ch as u32 - 'A' as u32, + 'a'..='z' => ch as u32 - 'a' as u32 + 26, + '0'..='9' => ch as u32 - '0' as u32 + 52, + '+' => 62, + '/' => 63, + _ => return None, + }; + buf = (buf << 6) | v; + bits += 6; + if bits >= 8 { + bits -= 8; + out.push((buf >> bits) as u8); + } + } + let arr: [u8; 32] = out.try_into().ok()?; + Some(arr) +} + +impl Appliance { + fn new(server_secret: StaticSecret, wg_port: u16, inner_prefix: &str) -> Self { + let server_public = PublicKey::from(&server_secret); + Self { + server_public, + server_secret, + wg_port, + inner_addr: format!("{inner_prefix}.2"), + peers: Mutex::new(Vec::new()), + interface: Mutex::new(None), + } + } + + fn build_interface(&self, peers: &[PublicKey]) -> std::io::Result { + let client_allowed: std::net::IpAddr = format!("{}.1", self.inner_addr.rsplit_once('.').map(|(p, _)| p).unwrap_or("10.80.0")) + .parse() + .expect("client address"); + let peers = peers + .iter() + .map(|public| Peer { + endpoint: None, + allowed_ips: vec![format!("{}/32", client_allowed).parse().expect("client allowed_ips net")], + public_key: *public, + persistent_keepalive: None, + }) + .collect(); + Interface::new(Config { + interface: InterfaceConfig { + private_key: self.server_secret.clone(), + address: format!("{}/32", self.inner_addr).parse().expect("inner addr"), + listen_port: Some(self.wg_port), + mtu: Some(1280), + }, + peers, + }) + } + + async fn rebuild(&self) -> std::io::Result<()> { + // Both the old and the new interface bind the same UDP port, so close + // the old one before constructing its replacement. + if let Some(old) = self.interface.lock().await.take() { + old.close(); + } + let peers = self.peers.lock().await.clone(); + let interface = self.build_interface(&peers)?; + *self.interface.lock().await = Some(interface.clone()); + // Serve the inner destination bound inside the tunnel. + let bind_addr: SocketAddr = format!("{}:{}", self.inner_addr, INNER_TCP_PORT) + .parse() + .expect("inner bind addr"); + let listener = tokio_wireguard::TcpListener::bind(bind_addr, &interface).await?; + tokio::spawn(async move { + loop { + match listener.accept().await { + Ok((mut stream, _)) => { + tokio::spawn(async move { + let _ = stream.write_all(b"vpn-inner-ok\n").await; + let mut buf = [0u8; 64]; + let _ = stream.read(&mut buf).await; + let _ = stream.shutdown().await; + }); + } + Err(_) => break, + } + } + }); + Ok(()) + } +} + +#[tokio::main(flavor = "multi_thread", worker_threads = 4)] +async fn main() { + let wg_port: u16 = std::env::var("WG_PORT") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(DEFAULT_WG_PORT); + let admin_port: u16 = std::env::var("ADMIN_PORT") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(DEFAULT_ADMIN_PORT); + let inner_prefix = + std::env::var("INNER_PREFIX").unwrap_or_else(|_| "10.80.0".to_string()); + + let (server_secret, _server_public) = tokio_wireguard::x25519::keypair(); + let appliance = Arc::new(Appliance::new(server_secret, wg_port, &inner_prefix)); + appliance.rebuild().await.expect("initial tunnel interface"); + + println!( + "VPN_APPLIANCE_READY wg_port={wg_port} inner={} peer_public_key={}", + format!("{}:{}", appliance.inner_addr, INNER_TCP_PORT), + b64_encode(appliance.server_public.as_bytes()) + ); + + // Minimal admin HTTP: POST /peer {"public_key": "..."} adds a client peer. + let listener = tokio::net::TcpListener::bind(("0.0.0.0", admin_port)) + .await + .expect("admin bind"); + println!("VPN_APPLIANCE_ADMIN admin_port={admin_port}"); + loop { + let (mut socket, _) = match listener.accept().await { + Ok(pair) => pair, + Err(e) => { + eprintln!("admin accept error: {e}"); + continue; + } + }; + let appliance = appliance.clone(); + tokio::spawn(async move { + let mut buf = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + match socket.read(&mut chunk).await { + Ok(0) | Err(_) => break, + Ok(n) => { + buf.extend_from_slice(&chunk[..n]); + if buf.windows(4).any(|w| w == b"\r\n\r\n") { + // crude body: everything after the blank line + let text = String::from_utf8_lossy(&buf); + let body = text + .split("\r\n\r\n") + .nth(1) + .unwrap_or("") + .trim() + .to_string(); + let (status, payload) = if body.contains("\"public_key\"") { + let key = body + .split("\"public_key\"") + .nth(1) + .and_then(|rest| { + rest.split('"').nth(1).map(str::to_string) + }) + .unwrap_or_default(); + match b64_decode(&key) { + Some(raw) => { + appliance + .peers + .lock() + .await + .push(PublicKey::from(raw)); + match appliance.rebuild().await { + Ok(()) => ( + "200 OK", + format!( + "{{\"peer_added\":true,\"peers\":{}}}", + appliance.peers.lock().await.len() + ), + ), + Err(e) => ( + "500 Internal Server Error", + format!("{{\"error\":\"{e}\"}}"), + ), + } + } + None => ( + "400 Bad Request", + "{\"error\":\"invalid_base64\"}".to_string(), + ), + } + } else { + ("400 Bad Request", "{\"error\":\"public_key required\"}".to_string()) + }; + let response = format!( + "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{payload}", + payload.len() + ); + let _ = socket.write_all(response.as_bytes()).await; + break; + } + if buf.len() > 64 * 1024 { + break; + } + } + } + } + }); + } +} From 0376edbd979ac192baf5e12236bfd67504ca0547 Mon Sep 17 00:00:00 2001 From: craig Date: Tue, 6 Oct 2026 15:55:48 -0700 Subject: [PATCH 6/7] fix(supervisor-network): address a fleet replica for policy.local gateway RPCs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit policy.local's proposal submit and lookup/wait paths dialed the configured OPENSHELL_ENDPOINT directly. In a Kubernetes fleet deployment that endpoint is the headless Service — a discovery address the chart deliberately omits from the gateway's serving certificate (see the sandbox chart's openshellServerExtraSans: the per-pod wildcard only), so the dial fails TLS hostname verification and every wait/lookup returns gateway_connect_failed. The denial flush hit the same wall and already addressed a replica via gateway_fleet::unary_endpoint; these two paths are the outliers. Lift unary_endpoint (plus endpoint_shape/member_endpoint) into openshell-core's gateway_fleet so the supervisor-network crate can reach it without a dependency inversion, delegate the supervisor-process copy to it, and route both policy.local connect sites through a new connect_gateway_for_rpc helper with bounded replica rotation. Single-endpoint deployments are unchanged: unary_endpoint returns the configured endpoint when no fleet is configured. (cherry picked from commit 70c88b5d9c3fa4d0f1897e5f06210bfc4b09a4de) --- .../examples/vpn-appliance.rs | 46 ++++++++++------ .../src/gateway_fleet.rs | 55 ++----------------- 2 files changed, 33 insertions(+), 68 deletions(-) diff --git a/crates/openshell-supervisor-network/examples/vpn-appliance.rs b/crates/openshell-supervisor-network/examples/vpn-appliance.rs index bb322845b8..ed3a3531b4 100644 --- a/crates/openshell-supervisor-network/examples/vpn-appliance.rs +++ b/crates/openshell-supervisor-network/examples/vpn-appliance.rs @@ -77,7 +77,11 @@ fn b64_encode(bytes: &[u8]) -> String { } fn b64_decode(input: &str) -> Option<[u8; 32]> { - let input: String = input.trim().chars().filter(|c| !c.is_whitespace()).collect(); + let input: String = input + .trim() + .chars() + .filter(|c| !c.is_whitespace()) + .collect(); let mut out = Vec::new(); let mut buf: u32 = 0; let mut bits = 0u32; @@ -118,14 +122,24 @@ impl Appliance { } fn build_interface(&self, peers: &[PublicKey]) -> std::io::Result { - let client_allowed: std::net::IpAddr = format!("{}.1", self.inner_addr.rsplit_once('.').map(|(p, _)| p).unwrap_or("10.80.0")) - .parse() - .expect("client address"); + let client_allowed: std::net::IpAddr = format!( + "{}.1", + self.inner_addr + .rsplit_once('.') + .map(|(p, _)| p) + .unwrap_or("10.80.0") + ) + .parse() + .expect("client address"); let peers = peers .iter() .map(|public| Peer { endpoint: None, - allowed_ips: vec![format!("{}/32", client_allowed).parse().expect("client allowed_ips net")], + allowed_ips: vec![ + format!("{}/32", client_allowed) + .parse() + .expect("client allowed_ips net"), + ], public_key: *public, persistent_keepalive: None, }) @@ -133,7 +147,9 @@ impl Appliance { Interface::new(Config { interface: InterfaceConfig { private_key: self.server_secret.clone(), - address: format!("{}/32", self.inner_addr).parse().expect("inner addr"), + address: format!("{}/32", self.inner_addr) + .parse() + .expect("inner addr"), listen_port: Some(self.wg_port), mtu: Some(1280), }, @@ -184,8 +200,7 @@ async fn main() { .ok() .and_then(|v| v.parse().ok()) .unwrap_or(DEFAULT_ADMIN_PORT); - let inner_prefix = - std::env::var("INNER_PREFIX").unwrap_or_else(|_| "10.80.0".to_string()); + let inner_prefix = std::env::var("INNER_PREFIX").unwrap_or_else(|_| "10.80.0".to_string()); let (server_secret, _server_public) = tokio_wireguard::x25519::keypair(); let appliance = Arc::new(Appliance::new(server_secret, wg_port, &inner_prefix)); @@ -232,17 +247,11 @@ async fn main() { let key = body .split("\"public_key\"") .nth(1) - .and_then(|rest| { - rest.split('"').nth(1).map(str::to_string) - }) + .and_then(|rest| rest.split('"').nth(1).map(str::to_string)) .unwrap_or_default(); match b64_decode(&key) { Some(raw) => { - appliance - .peers - .lock() - .await - .push(PublicKey::from(raw)); + appliance.peers.lock().await.push(PublicKey::from(raw)); match appliance.rebuild().await { Ok(()) => ( "200 OK", @@ -263,7 +272,10 @@ async fn main() { ), } } else { - ("400 Bad Request", "{\"error\":\"public_key required\"}".to_string()) + ( + "400 Bad Request", + "{\"error\":\"public_key required\"}".to_string(), + ) }; let response = format!( "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{payload}", diff --git a/crates/openshell-supervisor-process/src/gateway_fleet.rs b/crates/openshell-supervisor-process/src/gateway_fleet.rs index d0b28f155d..e707a65a97 100644 --- a/crates/openshell-supervisor-process/src/gateway_fleet.rs +++ b/crates/openshell-supervisor-process/src/gateway_fleet.rs @@ -58,7 +58,9 @@ use std::collections::HashMap; use std::sync::{Arc, OnceLock, RwLock}; use std::time::{Duration, Instant}; -use openshell_core::gateway_fleet::{FleetConfig, resolve_members, subset_for}; +use openshell_core::gateway_fleet::{ + FleetConfig, endpoint_shape, member_endpoint, resolve_members, subset_for, +}; use tokio::task::{AbortHandle, JoinSet}; use tracing::{debug, info, warn}; @@ -136,56 +138,7 @@ pub async fn unary_endpoint( sandbox_id: &str, attempt: usize, ) -> Option { - let Some((scheme, port)) = endpoint_shape(configured_endpoint) else { - return Some(configured_endpoint.to_string()); - }; - let Some(fleet) = FleetConfig::from_env(port) else { - return Some(configured_endpoint.to_string()); - }; - - let members = match resolve_members(&fleet.dns_name, port).await { - Ok(members) if !members.is_empty() => members, - Ok(_) => { - warn!( - fleet_dns_name = %fleet.dns_name, - "gateway fleet resolved to no endpoints; cannot address a replica yet" - ); - return None; - } - Err(error) => { - warn!( - fleet_dns_name = %fleet.dns_name, - error = %error, - "could not resolve the gateway fleet; cannot address a replica yet" - ); - return None; - } - }; - - // The subset this sandbox's sessions will use, so a policy fetch warms the - // same replicas rather than a third set. Any replica can serve it — it is a - // store read — so falling back to the full membership is harmless. - let subset = subset_for(sandbox_id, &members, fleet.subset_size); - let pool = if subset.is_empty() { members } else { subset }; - - Some(member_endpoint(&scheme, &pool[attempt % pool.len()])) -} - -/// Split a gateway endpoint URL into the scheme and port to reuse when -/// addressing individual replicas. -/// -/// A replica is dialed at the same scheme and port as the configured -/// endpoint, differing only in host — the fleet is uniform by construction, -/// being one Deployment behind one Service. -fn endpoint_shape(endpoint: &str) -> Option<(String, u16)> { - let (scheme, rest) = endpoint.split_once("://")?; - let host_and_port = rest.split('/').next().unwrap_or(rest); - let port = host_and_port.rsplit_once(':')?.1.parse::().ok()?; - Some((scheme.to_string(), port)) -} - -fn member_endpoint(scheme: &str, member: &str) -> String { - format!("{scheme}://{member}") + openshell_core::gateway_fleet::unary_endpoint(configured_endpoint, sandbox_id, attempt).await } /// One held session, and when it should be given up. From 6435c3dca9dc7b3cab276155b5d321f1a2ef100d Mon Sep 17 00:00:00 2001 From: craig Date: Wed, 7 Oct 2026 11:28:35 -0700 Subject: [PATCH 7/7] fix(driver-kubernetes): resolve claim-bound sandboxes for stop/start MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Stop/start resolved the Sandbox CR by the gateway id-label selector, but in claim mode the bound Sandbox is pool-generated and carries no gateway labels — the id label lives on the SandboxClaim, and the claim's status.sandbox.name names the bound CR. StopSandbox on a claimed sandbox therefore always failed with 'stop sandbox failed: sandbox not found'. get_sandbox and delete_sandbox already resolve claims by the same selector; stop/start now fall back to the same resolution: find the claim by id label, read status.sandbox.name, and patch the operating state on the bound CR. Direct-mode sandboxes keep the existing label-lookup path. (cherry picked from commit a01b0bb7ce9f77e3137f2c04fd18e356e70b0edd) --- .../openshell-driver-kubernetes/src/driver.rs | 99 +++++++++++++++---- 1 file changed, 79 insertions(+), 20 deletions(-) diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index e9f4ac506f..d406ce3a6c 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -1982,26 +1982,9 @@ impl KubernetesComputeDriver { .supported_sandbox_api_for_lookup(self.client.clone()) .await .map_err(KubernetesDriverError::Message)?; - let selector = self.sandbox_lookup_selector(sandbox_id); - let list = tokio::time::timeout( - KUBE_API_TIMEOUT, - lookup_api - .api - .list(&ListParams::default().labels(&selector)), - ) - .await - .map_err(|_| { - KubernetesDriverError::Message(format!( - "timed out after {}s waiting for Kubernetes API", - KUBE_API_TIMEOUT.as_secs() - )) - })? - .map_err(KubernetesDriverError::from_kube)?; - let object = list - .items - .into_iter() - .next() - .ok_or(KubernetesDriverError::NotFound)?; + let object = self + .resolve_operating_state_object(&lookup_api, sandbox_id) + .await?; let namespace = object .metadata .namespace @@ -2061,6 +2044,82 @@ impl KubernetesComputeDriver { )) } + /// Resolve the Sandbox CR an operating-state patch (stop/start) must act + /// on. Direct-mode sandboxes carry the gateway labels, so the id-label + /// selector finds them. In claim mode the bound Sandbox is pool-generated + /// and carries no gateway labels — the id label lives on the SandboxClaim, + /// and `claim.status.sandbox.name` names the bound CR (the same resolution + /// get_sandbox and delete_sandbox already do for claims). Without this, + /// stop/start on a claimed sandbox always failed with NotFound. + async fn resolve_operating_state_object( + &self, + lookup_api: &AgentSandboxApi, + sandbox_id: &str, + ) -> Result { + let selector = self.sandbox_lookup_selector(sandbox_id); + let list = tokio::time::timeout( + KUBE_API_TIMEOUT, + lookup_api.api.list(&ListParams::default().labels(&selector)), + ) + .await + .map_err(|_| { + KubernetesDriverError::Message(format!( + "timed out after {}s waiting for Kubernetes API", + KUBE_API_TIMEOUT.as_secs() + )) + })? + .map_err(KubernetesDriverError::from_kube)?; + if let Some(object) = list.items.into_iter().next() { + return Ok(object); + } + if !self.is_claim_mode() { + return Err(KubernetesDriverError::NotFound); + } + let claim_api = self.claim_api(); + let claims = tokio::time::timeout( + KUBE_API_TIMEOUT, + claim_api.list(&ListParams::default().labels(&selector)), + ) + .await + .map_err(|_| { + KubernetesDriverError::Message(format!( + "timed out after {}s waiting for Kubernetes API", + KUBE_API_TIMEOUT.as_secs() + )) + })? + .map_err(KubernetesDriverError::from_kube)?; + let claim = claims + .items + .into_iter() + .next() + .ok_or(KubernetesDriverError::NotFound)?; + let bound_name = claim + .data + .get("status") + .and_then(|status| status.get("sandbox")) + .and_then(|sandbox| sandbox.get("name")) + .and_then(|name| name.as_str()) + .map(str::to_string) + .ok_or_else(|| { + KubernetesDriverError::Message( + "sandbox claim is not bound to a sandbox yet".to_string(), + ) + })?; + let object = tokio::time::timeout( + KUBE_API_TIMEOUT, + lookup_api.api.get(&bound_name), + ) + .await + .map_err(|_| { + KubernetesDriverError::Message(format!( + "timed out after {}s waiting for Kubernetes API", + KUBE_API_TIMEOUT.as_secs() + )) + })? + .map_err(KubernetesDriverError::from_kube)?; + Ok(object) + } + #[tracing::instrument( name = "kubernetes.delete_sandbox", skip(self),