537 lines
19 KiB
Rust
537 lines
19 KiB
Rust
//! 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 by itself: 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. `crate::guarded_net` closes both for HTTP
|
|
//! clients and raw TCP connections (#294).
|
|
|
|
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),
|
|
#[error("redirect to {hop} refused: {reason}")]
|
|
RedirectRefused { hop: String, reason: String },
|
|
#[error("more than {0} redirects")]
|
|
TooManyRedirects(usize),
|
|
}
|
|
|
|
/// Schemes the scanner will fetch over HTTP(S).
|
|
const HTTP_SCHEMES: &[&str] = &["http", "https"];
|
|
/// Schemes a live endpoint may use: a web application (DAST) or a PLC the ICS
|
|
/// probe talks Modbus/TCP or OPC UA to.
|
|
const LIVE_SCHEMES: &[&str] = &["http", "https", "modbus", "opc.tcp"];
|
|
/// 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. `ssh://` is refused too, because
|
|
/// the agent holds no git SSH key — see `pipeline::git::reject_ssh_url`, which
|
|
/// gives the same answer for the scp-style form that carries no scheme.
|
|
const GIT_SCHEMES: &[&str] = &["http", "https"];
|
|
|
|
/// 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<u16>,
|
|
/// 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<GuardedUrl, NetGuardError> {
|
|
self.check_url_with_schemes(raw, HTTP_SCHEMES)
|
|
}
|
|
|
|
/// Check a live endpoint: an `http(s)` web application or a
|
|
/// `modbus://` / `opc.tcp://` PLC. The host rules are the same as for
|
|
/// [`Self::check_url`].
|
|
pub fn check_live_url(self, raw: &str) -> Result<GuardedUrl, NetGuardError> {
|
|
self.check_url_with_schemes(raw, LIVE_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<GuardedUrl, NetGuardError> {
|
|
self.check_url_with_schemes(raw, GIT_SCHEMES)
|
|
}
|
|
|
|
fn check_url_with_schemes(
|
|
self,
|
|
raw: &str,
|
|
allowed: &[&str],
|
|
) -> Result<GuardedUrl, NetGuardError> {
|
|
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::<IpAddr>() {
|
|
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::<IpAddr>().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<u16>), 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::<u16>())
|
|
.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::<u16>()
|
|
.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 live_endpoints_accept_plc_protocols_with_the_same_host_rules() {
|
|
let g = guard();
|
|
for ok in [
|
|
"modbus://plc.example.com:502",
|
|
"opc.tcp://plc.example.com:4840/",
|
|
"https://hmi.example.com/",
|
|
] {
|
|
assert!(g.check_live_url(ok).is_ok(), "{ok}");
|
|
}
|
|
for refused in [
|
|
"modbus://plc-sim:502",
|
|
"modbus://10.0.0.5:502",
|
|
"opc.tcp://169.254.169.254/",
|
|
"ftp://plc.example.com/",
|
|
] {
|
|
assert!(g.check_live_url(refused).is_err(), "{refused}");
|
|
}
|
|
// Plain HTTP fetches keep refusing PLC schemes.
|
|
assert!(g.check_url("modbus://plc.example.com:502").is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn git_urls_refuse_file_git_and_ssh_schemes() {
|
|
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());
|
|
// The agent has no SSH key to offer, so an SSH remote could only
|
|
// authenticate as somebody else.
|
|
assert!(guard()
|
|
.check_git_url("ssh://git@example.com:22222/org/repo.git")
|
|
.is_err());
|
|
// …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());
|
|
}
|
|
}
|