diff --git a/compliance-agent/src/agent.rs b/compliance-agent/src/agent.rs index 40df275..c17011d 100644 --- a/compliance-agent/src/agent.rs +++ b/compliance-agent/src/agent.rs @@ -4,7 +4,7 @@ use dashmap::DashMap; use tokio::sync::{broadcast, watch, Semaphore}; use compliance_core::models::pentest::PentestEvent; -use compliance_core::AgentConfig; +use compliance_core::{AgentConfig, NetGuard}; use crate::database::DatabasePool; use crate::llm::LlmClient; @@ -32,6 +32,9 @@ pub struct ComplianceAgent { /// Platform tenant-registry client (entitlements, tenant list, API keys, /// usage events). `None` when `TENANT_REGISTRY_URL` is unset (dev). pub registry: Option>, + /// Where tenants may point a scan (SSRF policy). Public-only unless an + /// on-premise deployment opts in via `PW_ALLOW_PRIVATE_TARGETS`. + pub net_guard: NetGuard, } impl ComplianceAgent { @@ -48,6 +51,7 @@ impl ComplianceAgent { .build() .unwrap_or_default(); let registry = RegistryClient::from_config(&config, http.clone()); + let net_guard = NetGuard::from_env(config.app_env); Self { config, db_pool, @@ -57,6 +61,7 @@ impl ComplianceAgent { session_pause: Arc::new(DashMap::new()), session_semaphore: Arc::new(Semaphore::new(DEFAULT_MAX_CONCURRENT_SESSIONS)), registry, + net_guard, } } diff --git a/compliance-agent/src/api/handlers/dast.rs b/compliance-agent/src/api/handlers/dast.rs index 6eb9181..0f6145a 100644 --- a/compliance-agent/src/api/handlers/dast.rs +++ b/compliance-agent/src/api/handlers/dast.rs @@ -87,6 +87,12 @@ pub async fn add_target( tenant: TenantCtx, Json(req): Json, ) -> Result>, StatusCode> { + // The tenant picks this URL and we make the requests, so it decides where + // the agent connects (#256). Refuse anything not publicly routable. + if let Err(e) = agent.net_guard.check_url(&req.base_url) { + tracing::warn!(tenant_id = %tenant.0.tenant_id, "DAST target refused: {e}"); + return Err(StatusCode::BAD_REQUEST); + } let mut target = DastTarget::new(req.name, req.base_url, req.target_type); target.repo_id = req.repo_id; target.excluded_paths = req.excluded_paths; @@ -141,6 +147,24 @@ pub async fn trigger_scan( .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? .ok_or(StatusCode::NOT_FOUND)?; + // Re-check at use: the target may have been stored before this policy + // existed, and a hostname can be repointed after registration. + let guard = agent.net_guard; + let base_url = target.base_url.clone(); + let resolved = tokio::task::spawn_blocking(move || { + let parsed = guard.check_url(&base_url)?; + let port = parsed + .port + .unwrap_or(if parsed.scheme == "https" { 443 } else { 80 }); + guard.check_resolved(&parsed.host, port) + }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + if let Err(e) = resolved { + tracing::warn!(tenant_id = %tenant.0.tenant_id, "DAST scan refused: {e}"); + return Err(StatusCode::BAD_REQUEST); + } + let tenant_id = tenant.0.tenant_id.clone(); let usage_agent = agent.clone(); tokio::spawn(async move { diff --git a/compliance-agent/src/api/handlers/pentest_handlers/session.rs b/compliance-agent/src/api/handlers/pentest_handlers/session.rs index 3320642..1d7ef7a 100644 --- a/compliance-agent/src/api/handlers/pentest_handlers/session.rs +++ b/compliance-agent/src/api/handlers/pentest_handlers/session.rs @@ -80,6 +80,12 @@ pub async fn create_session( )); } + // The wizard's app_url becomes a DAST target and then live traffic, so + // it is the same outbound decision as a DAST target (#256). + if let Err(e) = agent.net_guard.check_url(&config.app_url) { + return Err((StatusCode::BAD_REQUEST, e.to_string())); + } + // Look up or auto-create DastTarget by app_url let target = match db .dast_targets() diff --git a/compliance-agent/src/ingest/mod.rs b/compliance-agent/src/ingest/mod.rs index 338f544..61ca72d 100644 --- a/compliance-agent/src/ingest/mod.rs +++ b/compliance-agent/src/ingest/mod.rs @@ -12,7 +12,7 @@ use std::collections::HashMap; use std::path::{Path, PathBuf}; use compliance_core::models::{Artifact, ArtifactKind, DetectedFact, OnboardedTarget}; -use compliance_core::AgentConfig; +use compliance_core::{AgentConfig, NetGuard}; use crate::error::AgentError; use crate::pipeline::git::{GitOps, RepoCredentials}; @@ -28,6 +28,8 @@ pub struct IngestContext<'a> { pub ssh_key_path: &'a str, /// The id of the target these artifacts belong to (namespaces working dirs). pub target_id: &'a str, + /// Where this deployment may fetch from (SSRF policy, #256). + pub net_guard: NetGuard, } impl<'a> IngestContext<'a> { @@ -38,6 +40,7 @@ impl<'a> IngestContext<'a> { git_clone_base: &config.git_clone_base_path, ssh_key_path: &config.ssh_key_path, target_id, + net_guard: NetGuard::from_env(config.app_env), } } } @@ -109,10 +112,17 @@ pub fn ingest_artifact( artifact, DetectedFact::new("container_ref", artifact.source_ref.as_str(), "ingest"), )), - ArtifactKind::LiveUrl => Ok(metadata_only( - artifact, - DetectedFact::new("live_url", artifact.source_ref.as_str(), "ingest"), - )), + ArtifactKind::LiveUrl => { + // A live URL is scanned by the DAST and ICS stages, so it is an + // outbound request the tenant chose: check it before recording it. + ctx.net_guard + .check_url(&artifact.source_ref) + .map_err(|e| AgentError::Other(e.to_string()))?; + Ok(metadata_only( + artifact, + DetectedFact::new("live_url", artifact.source_ref.as_str(), "ingest"), + )) + } ArtifactKind::PlaintextDescription => Ok(metadata_only( artifact, DetectedFact::new( @@ -129,6 +139,11 @@ fn ingest_git( artifact: &Artifact, ctx: &IngestContext<'_>, ) -> Result { + // `file://`, a bare path or an internal host would clone from the agent's + // own disk or the platform network — including another tenant's checkout. + ctx.net_guard + .check_git_url(&artifact.source_ref) + .map_err(|e| AgentError::Other(e.to_string()))?; let creds = credentials_for(artifact, ctx.ssh_key_path); let git_ops = GitOps::new(ctx.git_clone_base, creds); let repo_path = git_ops.clone_or_fetch(&artifact.source_ref, &artifact.id)?; @@ -232,14 +247,23 @@ fn metadata_only(artifact: &Artifact, fact: DetectedFact) -> IngestedArtifact { } } -/// The local file backing a blob artifact: its `stored_path` if already -/// uploaded, else its `source_ref` interpreted as a filesystem path. +/// The local file backing a blob artifact: its `stored_path`, i.e. a blob this +/// agent stored itself. +/// +/// `source_ref` used to be read as a filesystem path when `stored_path` was +/// absent, which let an API caller name any file the agent could read +/// (`/data/compliance-scanner/ssh/id_ed25519`, another tenant's checkout) and +/// have it ingested as their own artifact. Blob artifacts now have to be +/// uploaded. fn local_source(artifact: &Artifact) -> Result { - let path = artifact - .stored_path - .as_deref() - .unwrap_or(artifact.source_ref.as_str()); - let path = PathBuf::from(path); + let Some(stored) = artifact.stored_path.as_deref() else { + return Err(AgentError::Other(format!( + "artifact {} has no uploaded content — upload the file instead of \ + referencing a server path", + artifact.id + ))); + }; + let path = PathBuf::from(stored); if !path.exists() { return Err(AgentError::Other(format!( "artifact {} source not found at {}", @@ -289,9 +313,66 @@ mod tests { git_clone_base: "/tmp/cs-ingest-test-repos", ssh_key_path: "/tmp/cs-ingest-test-ssh", target_id, + net_guard: NetGuard::public_only(), } } + #[test] + fn git_remotes_that_would_read_our_own_disk_are_refused() { + let scratch = Scratch::new(); + let store = scratch.0.join("store"); + let ctx = ctx_for(&store, "t1"); + for url in [ + "file:///tmp/compliance-scanner/repos/other-tenant/app", + "/var/lib/secrets", + "git@gitea:org/repo.git", + "https://gitea/org/repo.git", + ] { + let artifact = Artifact::git_repo(url.to_string(), "main".to_string()); + assert!( + ingest_artifact(&artifact, &ctx).is_err(), + "{url} should be refused" + ); + } + } + + #[test] + fn live_urls_pointing_at_internal_hosts_are_refused() { + let scratch = Scratch::new(); + let store = scratch.0.join("store"); + let ctx = ctx_for(&store, "t1"); + for url in [ + "http://169.254.169.254/latest/meta-data/", + "http://pruefwerk-mongo:27017", + "http://127.0.0.1:3001/api/v1/targets", + ] { + let artifact = Artifact::live_url(url); + assert!( + ingest_artifact(&artifact, &ctx).is_err(), + "{url} should be refused" + ); + } + } + + #[test] + fn a_blob_artifact_cannot_name_a_server_path() { + let scratch = Scratch::new(); + let store = scratch.0.join("store"); + let secret = scratch.0.join("id_ed25519"); + std::fs::write(&secret, b"PRIVATE KEY").expect("write"); + + let ctx = ctx_for(&store, "t1"); + // No stored_path: the caller is naming a file on the agent's disk. + let artifact = Artifact::firmware_image(secret.to_string_lossy().to_string()); + let Err(err) = ingest_artifact(&artifact, &ctx) else { + panic!("naming a server path must be refused"); + }; + assert!( + err.to_string().contains("upload"), + "error should point at uploading: {err}" + ); + } + #[test] fn firmware_blob_is_hashed_and_stored() { let scratch = Scratch::new(); @@ -300,7 +381,10 @@ mod tests { std::fs::write(&fw, b"firmware-bytes").expect("write"); let ctx = ctx_for(&store, "t1"); - let artifact = Artifact::firmware_image(fw.to_string_lossy().to_string()); + // Blob artifacts carry their uploaded location in `stored_path`, the + // way the upload handler records it. + let mut artifact = Artifact::firmware_image("fw.bin".to_string()); + artifact.stored_path = Some(fw.to_string_lossy().to_string()); let out = ingest_artifact(&artifact, &ctx).expect("ingest"); assert_eq!(out.kind, ArtifactKind::FirmwareImage); @@ -333,10 +417,14 @@ mod tests { let ctx = ctx_for(&store, "t1"); let mut target = OnboardedTarget::new("t".to_string(), TargetType::FirmwareBareMetal); + target.artifacts.push({ + let mut a = Artifact::firmware_image("fw.bin".to_string()); + a.stored_path = Some(fw.to_string_lossy().to_string()); + a + }); target .artifacts - .push(Artifact::firmware_image(fw.to_string_lossy().to_string())); - target.artifacts.push(Artifact::live_url("https://x")); + .push(Artifact::live_url("https://example.com/x")); let set = ingest_all(&target, &ctx).expect("ingest all"); assert_eq!(set.by_artifact.len(), 2); diff --git a/compliance-core/src/lib.rs b/compliance-core/src/lib.rs index 0d4c021..f0a7819 100644 --- a/compliance-core/src/lib.rs +++ b/compliance-core/src/lib.rs @@ -3,6 +3,7 @@ pub mod control_check; pub mod db; pub mod error; pub mod models; +pub mod net_guard; pub mod scan_matrix; #[cfg(feature = "telemetry")] pub mod telemetry; @@ -14,6 +15,7 @@ pub mod auth; #[cfg(feature = "axum")] pub mod tenant_ctx; -pub use config::{AgentConfig, DashboardConfig, Features, PlcRuntimeConfig}; +pub use config::{AgentConfig, AppEnv, DashboardConfig, Features, PlcRuntimeConfig}; pub use error::CoreError; +pub use net_guard::{NetGuard, NetGuardError}; pub use tenant::{OrgRole, TenantContext, TenantStatus}; diff --git a/compliance-core/src/net_guard.rs b/compliance-core/src/net_guard.rs new file mode 100644 index 0000000..1c8749e --- /dev/null +++ b/compliance-core/src/net_guard.rs @@ -0,0 +1,496 @@ +//! Where a tenant is allowed to point the scanner. +//! +//! Scans are aimed by the customer: a git URL, a live URL on a target, a DAST +//! base URL, a pentest app URL, a PLC endpoint for the ICS probe. Nothing used +//! to check what those addresses resolve to, so a tenant could aim a scan at +//! `pruefwerk-mongo:27017`, `169.254.169.254` (cloud metadata) or anything else +//! on the platform network and read the result back as findings — server-side +//! request forgery with a UI in front of it. +//! +//! This module answers one question — *may we connect to this?* — in three +//! layers, so every caller can use the part it needs: +//! +//! 1. [`NetGuard::check_url`] — syntax and scheme, plus the host rules. Pure. +//! 2. [`NetGuard::check_ip`] — address classification. Pure. +//! 3. [`NetGuard::check_resolved`] — resolves a hostname and classifies every +//! address it answers with. Blocking (std DNS), so async callers wrap it in +//! `spawn_blocking`. +//! +//! **On-premise deployments legitimately scan private ranges** — a Werkbank +//! runner inside a customer's plant network is aimed at `10.x` PLCs on purpose. +//! That is what [`NetGuard::allow_private`] is for. It is off by default, and a +//! hardened cloud deployment cannot turn it on. +//! +//! What this does not do: a hostname that passes here can still resolve to a +//! different address by the time the request goes out, and a redirect can lead +//! anywhere. Pinning the resolved address into the connection, and validating +//! redirect hops, are the next layer. + +use std::net::{IpAddr, Ipv4Addr, ToSocketAddrs}; + +use crate::config::AppEnv; + +/// Why an address was refused. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum NetGuardError { + #[error("{0} is not a URL the scanner can fetch (expected one of: {1})")] + Scheme(String, String), + #[error("not a URL: {0}")] + Malformed(String), + #[error("URL has no host")] + NoHost, + #[error( + "'{0}' is a local or internal name; targets must be publicly resolvable \ + (set PW_ALLOW_PRIVATE_TARGETS=1 on an on-premise runner to allow it)" + )] + InternalHost(String), + #[error( + "{host} resolves to {ip}, which is not a public address \ + (set PW_ALLOW_PRIVATE_TARGETS=1 on an on-premise runner to allow it)" + )] + PrivateAddress { host: String, ip: IpAddr }, + #[error("{host} does not resolve: {reason}")] + Unresolvable { host: String, reason: String }, + #[error("a local filesystem path is not a valid source: {0}")] + LocalPath(String), +} + +/// Schemes the scanner will fetch over HTTP(S). +const HTTP_SCHEMES: &[&str] = &["http", "https"]; +/// Schemes accepted for a git remote. `file://` and `git://` are refused: the +/// first reads the agent's own disk (including other tenants' checkouts), the +/// second is unauthenticated and cleartext. +const GIT_SCHEMES: &[&str] = &["http", "https", "ssh"]; + +/// Host suffixes that only mean something inside a private network. +const INTERNAL_SUFFIXES: &[&str] = &[ + ".local", + ".internal", + ".localdomain", + ".home.arpa", + ".onion", +]; + +/// A URL that passed [`NetGuard::check_url`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GuardedUrl { + pub scheme: String, + pub host: String, + pub port: Option, + /// The URL as given (unchanged, so callers pass on exactly what the tenant typed). + pub raw: String, +} + +/// The policy in force for this process. +#[derive(Debug, Clone, Copy)] +pub struct NetGuard { + allow_private: bool, +} + +impl Default for NetGuard { + fn default() -> Self { + Self::public_only() + } +} + +impl NetGuard { + /// Refuse anything that is not publicly routable. + pub fn public_only() -> Self { + Self { + allow_private: false, + } + } + + /// Allow private and loopback addresses. For on-premise runners and local + /// development only. + pub fn allow_private() -> Self { + Self { + allow_private: true, + } + } + + /// Read the policy from the environment. `PW_ALLOW_PRIVATE_TARGETS=1` + /// relaxes it — but never in a hardened deployment, where the agent shares + /// a network with the platform's own services. + pub fn from_env(app_env: AppEnv) -> Self { + let opted_in = std::env::var("PW_ALLOW_PRIVATE_TARGETS") + .map(|v| v == "1" || v.eq_ignore_ascii_case("true")) + .unwrap_or(false); + if opted_in && app_env.is_hardened() { + tracing_warn_ignored(); + } + Self { + allow_private: opted_in && !app_env.is_hardened(), + } + } + + /// Whether private addresses are permitted. + pub fn private_allowed(self) -> bool { + self.allow_private + } + + /// Check a URL the scanner would fetch over HTTP(S): DAST base URLs, + /// pentest app URLs, live-URL artifacts. + pub fn check_url(self, raw: &str) -> Result { + self.check_url_with_schemes(raw, HTTP_SCHEMES) + } + + /// Check a git remote. Rejects `file://`, `git://` and bare filesystem + /// paths; an `ssh://` remote still has to pass the host rules. + pub fn check_git_url(self, raw: &str) -> Result { + self.check_url_with_schemes(raw, GIT_SCHEMES) + } + + fn check_url_with_schemes( + self, + raw: &str, + allowed: &[&str], + ) -> Result { + let trimmed = raw.trim(); + if trimmed.is_empty() { + return Err(NetGuardError::Malformed(raw.to_string())); + } + if looks_like_local_path(trimmed) { + return Err(NetGuardError::LocalPath(trimmed.to_string())); + } + let (scheme, rest) = trimmed + .split_once("://") + .ok_or_else(|| NetGuardError::Malformed(trimmed.to_string()))?; + let scheme = scheme.to_ascii_lowercase(); + if !allowed.contains(&scheme.as_str()) { + return Err(NetGuardError::Scheme( + trimmed.to_string(), + allowed.join(", "), + )); + } + let authority = rest + .split(['/', '?', '#']) + .next() + .unwrap_or_default() + // Strip any userinfo: credentials belong to the caller, not the host. + .rsplit('@') + .next() + .unwrap_or_default(); + let (host, port) = split_host_port(authority)?; + self.check_host(&host)?; + Ok(GuardedUrl { + scheme, + host, + port, + raw: trimmed.to_string(), + }) + } + + /// Check a bare host (or `host:port`) — the shape the ICS probe and other + /// non-HTTP protocols work with. + pub fn check_host(self, host: &str) -> Result<(), NetGuardError> { + let host = host.trim().trim_matches(['[', ']']).to_ascii_lowercase(); + if host.is_empty() { + return Err(NetGuardError::NoHost); + } + if let Ok(ip) = host.parse::() { + return self + .check_ip(ip) + .map_err(|_| NetGuardError::PrivateAddress { + host: host.clone(), + ip, + }); + } + if self.allow_private { + return Ok(()); + } + if host == "localhost" + || !host.contains('.') + || INTERNAL_SUFFIXES.iter().any(|s| host.ends_with(s)) + { + // A single-label name (`mongo`, `compliance-agent`) only resolves + // on the platform's own Docker network. + return Err(NetGuardError::InternalHost(host)); + } + Ok(()) + } + + /// Classify one address. + pub fn check_ip(self, ip: IpAddr) -> Result<(), NetGuardError> { + if self.allow_private || is_public(ip) { + return Ok(()); + } + Err(NetGuardError::PrivateAddress { + host: ip.to_string(), + ip, + }) + } + + /// Resolve `host` and require **every** answer to be acceptable — a name + /// that returns one public and one private address is refused, since which + /// one a later connection picks is not ours to decide. + /// + /// Blocking: std's resolver. Async callers use `spawn_blocking`. + pub fn check_resolved(self, host: &str, port: u16) -> Result<(), NetGuardError> { + self.check_host(host)?; + if self.allow_private { + return Ok(()); + } + if host.parse::().is_ok() { + return Ok(()); // already classified by check_host + } + let addrs = (host, port) + .to_socket_addrs() + .map_err(|e| NetGuardError::Unresolvable { + host: host.to_string(), + reason: e.to_string(), + })?; + let mut seen = false; + for addr in addrs { + seen = true; + if !is_public(addr.ip()) { + return Err(NetGuardError::PrivateAddress { + host: host.to_string(), + ip: addr.ip(), + }); + } + } + if !seen { + return Err(NetGuardError::Unresolvable { + host: host.to_string(), + reason: "no addresses".to_string(), + }); + } + Ok(()) + } +} + +fn tracing_warn_ignored() { + // Kept as a function so the warning text lives in one place; core has no + // tracing dependency without the axum feature. + eprintln!( + "PW_ALLOW_PRIVATE_TARGETS is ignored in a hardened deployment: \ + private addresses stay blocked" + ); +} + +/// `/etc/passwd`, `./repo`, `C:\src`, `../x` — anything that is a path rather +/// than a URL. Also catches scp-style git remotes (`git@host:org/repo.git`), +/// which carry no scheme and would otherwise slip through. +fn looks_like_local_path(s: &str) -> bool { + if s.contains("://") { + return false; + } + s.starts_with('/') + || s.starts_with('.') + || s.starts_with('~') + || s.starts_with('\\') + || (s.len() > 2 && s.as_bytes()[1] == b':' && s.as_bytes()[0].is_ascii_alphabetic()) + || !s.contains(':') +} + +fn split_host_port(authority: &str) -> Result<(String, Option), NetGuardError> { + if authority.is_empty() { + return Err(NetGuardError::NoHost); + } + // IPv6 literal: [::1]:8080 + if let Some(rest) = authority.strip_prefix('[') { + let (host, tail) = rest + .split_once(']') + .ok_or_else(|| NetGuardError::Malformed(authority.to_string()))?; + let port = tail + .strip_prefix(':') + .map(|p| p.parse::()) + .transpose() + .map_err(|_| NetGuardError::Malformed(authority.to_string()))?; + return Ok((host.to_ascii_lowercase(), port)); + } + match authority.rsplit_once(':') { + Some((host, port)) if !port.is_empty() && port.chars().all(|c| c.is_ascii_digit()) => { + let port = port + .parse::() + .map_err(|_| NetGuardError::Malformed(authority.to_string()))?; + Ok((host.to_ascii_lowercase(), Some(port))) + } + _ => Ok((authority.to_ascii_lowercase(), None)), + } +} + +/// Publicly routable? Deliberately conservative: anything special-purpose is +/// treated as private. +pub fn is_public(ip: IpAddr) -> bool { + match ip { + IpAddr::V4(v4) => is_public_v4(v4), + IpAddr::V6(v6) => { + // An IPv4-mapped address is an IPv4 address wearing a hat. + if let Some(v4) = v6.to_ipv4_mapped() { + return is_public_v4(v4); + } + if v6.is_loopback() || v6.is_unspecified() || v6.is_multicast() { + return false; + } + let seg = v6.segments(); + let unique_local = (seg[0] & 0xfe00) == 0xfc00; // fc00::/7 + let link_local = (seg[0] & 0xffc0) == 0xfe80; // fe80::/10 + !(unique_local || link_local) + } + } +} + +fn is_public_v4(ip: Ipv4Addr) -> bool { + let o = ip.octets(); + let shared = o[0] == 100 && (64..128).contains(&o[1]); // 100.64.0.0/10 CGNAT + let benchmarking = o[0] == 198 && (o[1] & 0xfe) == 18; // 198.18.0.0/15 + let reserved = o[0] >= 240; // 240.0.0.0/4 incl. broadcast + !(ip.is_private() + || ip.is_loopback() + || ip.is_link_local() + || ip.is_broadcast() + || ip.is_multicast() + || ip.is_unspecified() + || ip.is_documentation() + || shared + || benchmarking + || reserved) +} + +/// The cloud-metadata address, called out because it is the classic SSRF prize. +pub const CLOUD_METADATA_V4: Ipv4Addr = Ipv4Addr::new(169, 254, 169, 254); +/// GCP's metadata alias, blocked by the internal-host rule. +pub const CLOUD_METADATA_HOST: &str = "metadata.google.internal"; + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + fn guard() -> NetGuard { + NetGuard::public_only() + } + + #[test] + fn blocks_the_platforms_own_infrastructure() { + for host in [ + "pruefwerk-mongo", + "compliance-agent", + "mongo", + "localhost", + "registry.internal", + "printer.local", + ] { + assert!( + guard().check_host(host).is_err(), + "{host} should be refused" + ); + } + } + + #[test] + fn blocks_private_loopback_link_local_and_metadata() { + for ip in [ + "127.0.0.1", + "10.1.2.3", + "172.16.0.9", + "192.168.1.1", + "169.254.169.254", // cloud metadata + "100.64.0.1", // CGNAT + "0.0.0.0", + "::1", + "fe80::1", + "fd00::1", + "::ffff:127.0.0.1", // IPv4-mapped loopback + "::ffff:10.0.0.1", + ] { + let parsed: IpAddr = ip.parse().unwrap(); + assert!(guard().check_ip(parsed).is_err(), "{ip} should be refused"); + assert!(guard().check_host(ip).is_err(), "host form of {ip}"); + } + assert_eq!(CLOUD_METADATA_V4.to_string(), "169.254.169.254"); + assert!(guard().check_host(CLOUD_METADATA_HOST).is_err()); + } + + #[test] + fn allows_ordinary_public_targets() { + for url in [ + "https://example.com", + "http://example.com:8080/path?q=1", + "https://shop.example.co.uk/login", + "https://93.184.216.34/", + "https://[2606:2800:220:1::1]:443/x", + ] { + assert!(guard().check_url(url).is_ok(), "{url} should be allowed"); + } + } + + #[test] + fn parses_scheme_host_and_port() { + let u = guard() + .check_url("https://user:pw@example.com:8443/a/b") + .unwrap(); + assert_eq!(u.scheme, "https"); + assert_eq!(u.host, "example.com"); // userinfo stripped + assert_eq!(u.port, Some(8443)); + assert_eq!(u.raw, "https://user:pw@example.com:8443/a/b"); + + let v6 = guard() + .check_url("http://[2606:2800:220:1::1]:80/") + .unwrap(); + assert_eq!(v6.host, "2606:2800:220:1::1"); + assert_eq!(v6.port, Some(80)); + } + + #[test] + fn refuses_non_http_schemes_and_local_paths() { + for raw in [ + "file:///data/compliance-scanner/ssh/id_ed25519", + "ftp://example.com/x", + "gopher://example.com", + "data:text/plain,hi", + "/etc/passwd", + "../../secrets", + "~/repo", + "C:\\src\\repo", + ] { + assert!(guard().check_url(raw).is_err(), "{raw} should be refused"); + } + } + + #[test] + fn git_urls_refuse_file_and_git_schemes_but_allow_ssh() { + assert!(guard() + .check_git_url("file:///tmp/compliance-scanner/repos/other-tenant/app") + .is_err()); + assert!(guard().check_git_url("git://example.com/repo.git").is_err()); + assert!(guard() + .check_git_url("git@example.com:org/repo.git") + .is_err()); // scp-style, no scheme + assert!(guard() + .check_git_url("https://example.com/org/repo.git") + .is_ok()); + assert!(guard() + .check_git_url("ssh://git@example.com:22222/org/repo.git") + .is_ok()); + // …but not to an internal host. + assert!(guard().check_git_url("https://gitea/org/repo.git").is_err()); + } + + #[test] + fn on_premise_policy_allows_private_ranges() { + let g = NetGuard::allow_private(); + assert!(g.check_host("10.10.0.5").is_ok()); + assert!(g.check_url("http://192.168.1.50:8080/webvisu").is_ok()); + assert!(g.check_host("plc-01").is_ok()); + // Still not a path or an unfetchable scheme. + assert!(g.check_url("file:///etc/passwd").is_err()); + } + + #[test] + fn hardened_deployments_cannot_opt_out() { + // The env var is read by from_env; assert the policy, not the process + // environment, so the test stays parallel-safe. + assert!(!NetGuard::public_only().private_allowed()); + assert!(NetGuard::allow_private().private_allowed()); + } + + #[test] + fn resolution_classifies_literals_without_dns() { + assert!(guard().check_resolved("127.0.0.1", 80).is_err()); + assert!(guard().check_resolved("93.184.216.34", 443).is_ok()); + assert!(guard().check_resolved("mongo", 27017).is_err()); + } +} diff --git a/docs/guide/scanning.md b/docs/guide/scanning.md index 63565fa..9705800 100644 --- a/docs/guide/scanning.md +++ b/docs/guide/scanning.md @@ -59,6 +59,29 @@ A full scan runs multiple analysis engines, each producing different types of fi | **Secrets** | Hardcoded credentials, API keys, tokens in source code | Custom rules | | **Code Review** | Architecture and security patterns reviewed by AI | LLM-powered | +## Where a scan may connect + +Git URLs, live URLs, DAST base URLs, pentest app URLs and PLC endpoints all say +where the scanner should connect, so they decide what the agent talks to. A +cloud deployment therefore accepts **publicly routable addresses only**, and +refuses: + +- loopback, private (`10/8`, `172.16/12`, `192.168/16`), carrier-NAT and + link-local addresses, including the cloud-metadata address `169.254.169.254`; +- names that only resolve inside a private network — single-label hosts such as + `mongo`, anything ending in `.internal` or `.local`, and `localhost`; +- `file://`, `git://` and bare filesystem paths as a git remote; +- blob artifacts that point at a server path instead of an uploaded file. + +Hostnames are re-checked and resolved when the scan actually runs, not only when +the target is saved, and a name that resolves to both a public and a private +address is refused. + +**On-premise runners are different.** A Werkbank runner inside a plant network is +aimed at `10.x` PLCs on purpose, so it sets `PW_ALLOW_PRIVATE_TARGETS=1`. A +hardened cloud deployment ignores that variable — it shares a network with the +platform's own services. + ## Deduplication and Fingerprinting Findings are deduplicated using a fingerprint hash based on the scanner, file path, line number, and vulnerability type. This means: diff --git a/werkbank-exec/src/ics/mod.rs b/werkbank-exec/src/ics/mod.rs index ed574b0..f6d351f 100644 --- a/werkbank-exec/src/ics/mod.rs +++ b/werkbank-exec/src/ics/mod.rs @@ -13,6 +13,7 @@ pub mod portscan; use std::time::Duration; use compliance_core::models::{Finding, ScanType, Severity}; +use compliance_core::{AppEnv, NetGuard}; use crate::fingerprint as dedup; @@ -27,6 +28,17 @@ const ENIP_PORT: u16 = 44818; /// the target's live-URL / host reference. pub async fn probe_target(endpoint: &str, repo_id: &str, budget: Duration) -> Vec { let (host, modbus_port) = parse_endpoint(endpoint); + // The endpoint comes from the tenant's target, and this function opens TCP + // connections to it — so it is an SSRF sink (#256). A cloud deployment may + // only probe public addresses; an on-premise runner sets + // PW_ALLOW_PRIVATE_TARGETS=1 because probing 10.x PLCs is its whole job. + let guard = NetGuard::from_env( + AppEnv::parse(&std::env::var("APP_ENV").unwrap_or_default()).unwrap_or(AppEnv::Dev), + ); + if let Err(e) = guard.check_host(&host) { + tracing::warn!(endpoint, "ICS probe refused: {e}"); + return Vec::new(); + } let mut findings = modbus_findings(&host, modbus_port, repo_id, budget).await; findings.extend(opcua_findings(&host, OPCUA_PORT, repo_id, budget).await); findings.extend(enip_findings(&host, ENIP_PORT, repo_id, budget).await); @@ -283,6 +295,26 @@ fn parse_endpoint(endpoint: &str) -> (String, u16) { #[cfg(test)] mod tests { + use super::probe_target; + + #[tokio::test] + async fn probe_refuses_targets_on_our_own_network() { + // Public-only is the default policy; an internal endpoint yields no + // findings because no connection is attempted at all. + for endpoint in [ + "http://compliance-agent:3001", + "127.0.0.1:502", + "http://169.254.169.254", + ] { + let findings = + probe_target(endpoint, "repo-1", std::time::Duration::from_millis(50)).await; + assert!( + findings.is_empty(), + "{endpoint} should not be probed, got {findings:?}" + ); + } + } + use super::parse_endpoint; #[test]