feat(security): pin resolved addresses and check every redirect hop (#294) (#322)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 54s
CI / Deploy MCP (push) Successful in 3m41s
CI / Deploy Dashboard (push) Successful in 5m20s
CI / Deploy Agent (push) Successful in 6m41s

This commit was merged in pull request #322.
This commit is contained in:
sharang committed 2026-09-21 20:26:43 +00:00
1 parent 0444f18a8e
commit 40c7557349
25 files changed
+663 -69

No files matched your search

@@ -211,6 +211,7 @@ pub async fn build_embeddings(
&agent_clone.config.git_clone_base_path,
&tenant_id,
creds,
agent_clone.net_guard,
);
let repo_path = match git_ops.clone_or_fetch(&view.git_url, &view.name) {
Ok(p) => p,
+1 -1
View File
@@ -169,7 +169,7 @@ pub async fn trigger_scan(
let tenant_id = tenant.0.tenant_id.clone();
let usage_agent = agent.clone();
tokio::spawn(async move {
let orchestrator = compliance_dast::DastOrchestrator::new(100);
let orchestrator = compliance_dast::DastOrchestrator::new(100, guard);
match orchestrator.run_scan(&target, Vec::new()).await {
Ok((scan_run, findings)) => {
if let Err(e) = db.dast_scan_runs().insert_one(&scan_run).await {
@@ -419,6 +419,7 @@ pub async fn trigger_build(
&agent_clone.config.git_clone_base_path,
&tenant_id,
creds,
agent_clone.net_guard,
);
let repo_path = match git_ops.clone_or_fetch(&view.git_url, &view.name) {
Ok(p) => p,
@@ -231,13 +231,19 @@ pub async fn create_session(
});
let llm = agent.llm.clone();
let net_guard = agent.net_guard;
let db_for_orchestrator = db.clone();
let session_clone = session.clone();
let target_clone = target.clone();
let agent_ref = agent.clone();
tokio::spawn(async move {
let orchestrator =
PentestOrchestrator::new(llm, db_for_orchestrator, event_tx, Some(pause_rx));
let orchestrator = PentestOrchestrator::new(
llm,
db_for_orchestrator,
event_tx,
Some(pause_rx),
net_guard,
);
orchestrator
.run_session_guarded(&session_clone, &target_clone, &initial_message)
.await;
@@ -312,13 +318,19 @@ pub async fn create_session(
});
let llm = agent.llm.clone();
let net_guard = agent.net_guard;
let db_for_orchestrator = db.clone();
let session_clone = session.clone();
let target_clone = target.clone();
let agent_ref = agent.clone();
tokio::spawn(async move {
let orchestrator =
PentestOrchestrator::new(llm, db_for_orchestrator, event_tx, Some(pause_rx));
let orchestrator = PentestOrchestrator::new(
llm,
db_for_orchestrator,
event_tx,
Some(pause_rx),
net_guard,
);
orchestrator
.run_session_guarded(&session_clone, &target_clone, &initial_message)
.await;
@@ -519,6 +531,7 @@ pub async fn send_message(
// Spawn orchestrator to continue the session
let llm = agent.llm.clone();
let net_guard = agent.net_guard;
let db_for_orchestrator = db.clone();
let message = req.message.clone();
@@ -534,7 +547,8 @@ pub async fn send_message(
.unwrap_or_else(|| agent.register_session_stream(&session_id));
tokio::spawn(async move {
let orchestrator = PentestOrchestrator::new(llm, db_for_orchestrator, event_tx, None);
let orchestrator =
PentestOrchestrator::new(llm, db_for_orchestrator, event_tx, None, net_guard);
orchestrator
.run_session_guarded(&session, &target, &message)
.await;
+1 -1
View File
@@ -150,7 +150,7 @@ fn ingest_git(
.check_git_url(&artifact.source_ref)
.map_err(|e| AgentError::Other(e.to_string()))?;
let creds = credentials_for(artifact, &ctx.secrets);
let git_ops = GitOps::new(ctx.git_clone_base, ctx.tenant_id, creds);
let git_ops = GitOps::new(ctx.git_clone_base, ctx.tenant_id, creds, ctx.net_guard);
let repo_path = git_ops.clone_or_fetch(&artifact.source_ref, &artifact.id)?;
let head = GitOps::get_head_sha(&repo_path).ok();
Ok(IngestedArtifact {
+3 -1
View File
@@ -7,6 +7,7 @@ use tokio::sync::{broadcast, watch};
use compliance_core::models::dast::DastTarget;
use compliance_core::models::pentest::*;
use compliance_core::traits::pentest_tool::PentestToolContext;
use compliance_core::NetGuard;
use compliance_dast::ToolRegistry;
use crate::database::Database;
@@ -33,9 +34,10 @@ impl PentestOrchestrator {
db: Database,
event_tx: broadcast::Sender<PentestEvent>,
pause_rx: Option<watch::Receiver<bool>>,
net_guard: NetGuard,
) -> Self {
Self {
tool_registry: ToolRegistry::new(),
tool_registry: ToolRegistry::new(net_guard),
llm,
db,
event_tx,
+92 -13
View File
@@ -1,6 +1,8 @@
use std::path::{Path, PathBuf};
use git2::{Cred, FetchOptions, RemoteCallbacks, Repository};
use git2::{Cred, FetchOptions, RemoteCallbacks, RemoteRedirect, Repository};
use compliance_core::NetGuard;
use crate::error::AgentError;
use crate::tenant_path::{name_segment, tenant_segment};
@@ -81,6 +83,8 @@ impl RepoCredentials {
fn fetch_options(&self) -> FetchOptions<'_> {
let mut fetch_opts = FetchOptions::new();
// A redirect could lead anywhere, past the check in `GitOps::check_remote`.
fetch_opts.follow_redirects(RemoteRedirect::None);
if self.has_credentials() {
fetch_opts.remote_callbacks(self.make_callbacks());
}
@@ -97,17 +101,46 @@ pub struct GitOps {
/// The tenant every checkout this instance makes belongs to.
tenant_id: String,
credentials: RepoCredentials,
/// Where a clone or fetch may connect (#256, #294).
net_guard: NetGuard,
}
impl GitOps {
pub fn new(base_path: &str, tenant_id: &str, credentials: RepoCredentials) -> Self {
pub fn new(
base_path: &str,
tenant_id: &str,
credentials: RepoCredentials,
net_guard: NetGuard,
) -> Self {
Self {
base_path: PathBuf::from(base_path),
tenant_id: tenant_id.to_string(),
credentials,
net_guard,
}
}
/// Refuse a remote whose host is internal or resolves to a non-public
/// address, right before connecting to it.
///
/// libgit2 resolves the host itself and cannot be given a pinned address,
/// so a name that changes its answer between this check and libgit2's own
/// lookup (DNS rebinding at near-zero TTL) is not covered; redirects are
/// off, so the connection cannot be sent anywhere else. Checked on every
/// fetch too, because a remote's DNS can change after the clone.
fn check_remote(&self, git_url: &str) -> Result<(), AgentError> {
let remote = self
.net_guard
.check_git_url(git_url)
.map_err(|e| AgentError::Other(e.to_string()))?;
let port = remote
.port
.unwrap_or(if remote.scheme == "http" { 80 } else { 443 });
self.net_guard
.check_resolved(&remote.host, port)
.map_err(|e| AgentError::Other(e.to_string()))
}
/// Where this instance's tenant keeps its checkout of `repo_name`.
pub fn clone_path(&self, repo_name: &str) -> PathBuf {
clone_dir(&self.base_path, &self.tenant_id, repo_name)
@@ -123,6 +156,9 @@ impl GitOps {
tracing::info!("fetching updates for existing repo");
self.fetch(&repo_path)?;
} else {
// Before creating the directory: a refused remote must not leave
// an empty checkout behind for the next run to try to fetch.
self.check_remote(git_url)?;
std::fs::create_dir_all(&repo_path)?;
self.clone_repo(git_url, &repo_path)?;
tracing::info!("Cloned {git_url} to {}", repo_path.display());
@@ -144,6 +180,7 @@ impl GitOps {
fn fetch(&self, repo_path: &Path) -> Result<(), AgentError> {
let repo = Repository::open(repo_path)?;
let mut remote = repo.find_remote("origin")?;
self.check_remote(remote.url().unwrap_or_default())?;
let mut fetch_opts = self.credentials.fetch_options();
remote.fetch(&[] as &[&str], Some(&mut fetch_opts), None)?;
@@ -160,16 +197,6 @@ impl GitOps {
Ok(())
}
/// Test that we can access a remote repository (used during add validation)
pub fn test_access(git_url: &str, credentials: &RepoCredentials) -> Result<(), AgentError> {
reject_ssh_url(git_url)?;
let mut remote = git2::Remote::create_detached(git_url)?;
let callbacks = credentials.make_callbacks();
remote.connect_auth(git2::Direction::Fetch, Some(callbacks), None)?;
remote.disconnect()?;
Ok(())
}
/// Build credentials from a repo view's own HTTPS token. There is no
/// agent-wide fallback credential any more — see [`reject_ssh_url`].
pub fn make_repo_credentials(repo: &crate::pipeline::repo_view::RepoView) -> RepoCredentials {
@@ -292,7 +319,8 @@ pub struct DiffFile {
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::{clone_dir, reject_ssh_url};
use super::{clone_dir, reject_ssh_url, GitOps, RepoCredentials};
use compliance_core::NetGuard;
use std::path::Path;
const BASE: &str = "/data/repos";
@@ -370,4 +398,55 @@ mod tests {
assert!(reject_ssh_url(url).is_ok(), "{url} should be accepted");
}
}
/// A scratch clone base, removed on drop.
struct Scratch(std::path::PathBuf);
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn git_ops(base: &Path) -> GitOps {
GitOps::new(
&base.to_string_lossy(),
"tenant-a",
RepoCredentials::default(),
NetGuard::public_only(),
)
}
#[test]
fn a_remote_on_a_private_address_is_refused_before_connecting() {
let scratch =
Scratch(std::env::temp_dir().join(format!("cs-git-{}", uuid::Uuid::new_v4())));
let ops = git_ops(&scratch.0);
let err = ops
.clone_or_fetch("http://169.254.169.254/latest/x.git", "metadata")
.expect_err("metadata address must be refused");
assert!(err.to_string().contains("not a public address"), "{err}");
assert!(
!ops.clone_path("metadata").exists(),
"a refused clone leaves no checkout behind"
);
}
#[test]
fn a_fetch_rechecks_the_stored_remote() {
// An existing checkout whose `origin` now points somewhere private (a
// remote's DNS or config can change after the clone): the fetch must
// be refused, not trusted because the clone once passed.
let scratch =
Scratch(std::env::temp_dir().join(format!("cs-git-{}", uuid::Uuid::new_v4())));
let ops = git_ops(&scratch.0);
let path = ops.clone_path("existing");
let repo = git2::Repository::init(&path).expect("init");
repo.remote("origin", "http://10.0.0.5/internal.git")
.expect("set origin");
let err = ops
.clone_or_fetch("https://example.com/org/repo.git", "existing")
.expect_err("private origin must be refused");
assert!(err.to_string().contains("10.0.0.5"), "{err}");
}
}
+2 -1
View File
@@ -91,8 +91,9 @@ impl PipelineOrchestrator {
for target in targets {
let db = self.db.clone();
let scan_run_id = scan_run_id.to_string();
let net_guard = self.net_guard;
tokio::spawn(async move {
let orchestrator = compliance_dast::DastOrchestrator::new(100);
let orchestrator = compliance_dast::DastOrchestrator::new(100, net_guard);
match orchestrator.run_scan(&target, Vec::new()).await {
Ok((mut scan_run, findings)) => {
scan_run.sast_scan_run_id = Some(scan_run_id);
@@ -52,9 +52,13 @@ impl PipelineOrchestrator {
let token = repo.tracker_token.clone()?;
let base_url = extract_base_url(&repo.git_url)?;
let secret = secrecy::SecretString::from(token);
Some(TrackerDispatch::Gitea(trackers::gitea::GiteaTracker::new(
base_url, secret,
)))
match trackers::gitea::GiteaTracker::new(base_url, secret, self.net_guard) {
Ok(t) => Some(TrackerDispatch::Gitea(t)),
Err(e) => {
tracing::warn!("Failed to build Gitea tracker: {e}");
None
}
}
}
TrackerType::Jira => {
let base_url = self.config.jira_url.clone()?;
+11 -2
View File
@@ -5,7 +5,7 @@ use tracing::Instrument;
use compliance_core::models::*;
use compliance_core::traits::Scanner;
use compliance_core::AgentConfig;
use compliance_core::{AgentConfig, NetGuard};
use crate::database::Database;
use crate::error::AgentError;
@@ -42,6 +42,8 @@ pub struct PipelineOrchestrator {
pub(super) http: reqwest::Client,
/// Opens the target's sealed credentials (git and tracker tokens).
pub(super) secrets: SecretBox,
/// Where clones and tracker calls may connect (#256, #294).
pub(super) net_guard: NetGuard,
}
impl PipelineOrchestrator {
@@ -53,6 +55,7 @@ impl PipelineOrchestrator {
http: reqwest::Client,
) -> Self {
let secrets = SecretBox::from_config(&config);
let net_guard = NetGuard::from_env(config.app_env);
Self {
config,
tenant_id: tenant_id.to_string(),
@@ -60,6 +63,7 @@ impl PipelineOrchestrator {
llm,
http,
secrets,
net_guard,
}
}
@@ -70,7 +74,12 @@ impl PipelineOrchestrator {
// Stage 0: Change detection
tracing::info!("[{repo_id}] Stage 0: Change detection");
let creds = GitOps::make_repo_credentials(repo);
let git_ops = GitOps::new(&self.config.git_clone_base_path, &self.tenant_id, creds);
let git_ops = GitOps::new(
&self.config.git_clone_base_path,
&self.tenant_id,
creds,
self.net_guard,
);
let repo_path = git_ops.clone_or_fetch(&repo.git_url, &repo.name)?;
if !GitOps::has_new_commits(&repo_path, repo.last_scanned_commit.as_deref())? {
+6 -1
View File
@@ -37,7 +37,12 @@ impl PipelineOrchestrator {
// Clone/fetch the repo
let creds = GitOps::make_repo_credentials(repo);
let git_ops = GitOps::new(&self.config.git_clone_base_path, &self.tenant_id, creds);
let git_ops = GitOps::new(
&self.config.git_clone_base_path,
&self.tenant_id,
creds,
self.net_guard,
);
let repo_path = git_ops.clone_or_fetch(&repo.git_url, &repo.name)?;
// Get diff between base and head
+18 -4
View File
@@ -1,6 +1,8 @@
use compliance_core::error::CoreError;
use compliance_core::guarded_net::guarded_client_builder;
use compliance_core::models::{TrackerIssue, TrackerType};
use compliance_core::traits::issue_tracker::{IssueTracker, ReviewComment};
use compliance_core::NetGuard;
use secrecy::{ExposeSecret, SecretString};
pub struct GiteaTracker {
@@ -10,12 +12,24 @@ pub struct GiteaTracker {
}
impl GiteaTracker {
pub fn new(base_url: String, token: SecretString) -> Self {
Self {
/// A tracker for the Gitea instance at `base_url`.
///
/// The base URL is the host of the tenant's git remote, so the client is
/// guarded like any other tenant-chosen address (#294): it connects only to
/// approved addresses and re-checks every redirect.
///
/// # Errors
///
/// [`CoreError::IssueTracker`] if the HTTP client cannot be built.
pub fn new(base_url: String, token: SecretString, guard: NetGuard) -> Result<Self, CoreError> {
let http = guarded_client_builder(guard)
.build()
.map_err(|e| CoreError::IssueTracker(format!("Failed to create Gitea client: {e}")))?;
Ok(Self {
base_url: base_url.trim_end_matches('/').to_string(),
http: reqwest::Client::new(),
http,
token,
}
})
}
fn api_url(&self, path: &str) -> String {
+8 -3
View File
@@ -27,11 +27,16 @@ secrets = [
"dep:base64",
"dep:tracing",
]
axum = [
"dep:axum",
"dep:jsonwebtoken",
# Connections to tenant-chosen addresses (`guarded_net`): a DNS resolver that
# only returns guard-approved addresses, and guarded redirects.
net = [
"dep:reqwest",
"dep:tokio",
]
axum = [
"net",
"dep:axum",
"dep:jsonwebtoken",
"dep:tracing",
]
+403
View File
@@ -0,0 +1,403 @@
//! Connections to tenant-chosen addresses that stay where the guard said (#294).
//!
//! [`NetGuard`] decides whether an address is acceptable, but a check made
//! before a request leaves two gaps:
//!
//! - **DNS rebinding.** The HTTP client resolves the name again when it
//! connects, so a record that answers a public address to the check and
//! `169.254.169.254` to the connection gets through.
//! - **Redirects.** A public URL can answer `302 http://mongo:27017/`, and the
//! client follows it.
//!
//! Here the resolver *is* the check: [`guarded_client_builder`] gives reqwest a
//! resolver that returns only addresses the guard approved, so there is no
//! second lookup to win, and a redirect policy that re-checks every hop. Plain
//! TCP callers (ICS probes, the TLS analyzer) use [`resolve_approved`] and
//! connect to the returned address themselves.
use std::future::Future;
use std::io;
use std::net::{IpAddr, SocketAddr};
use std::pin::Pin;
use std::sync::Arc;
use reqwest::dns::{Addrs, Name, Resolve, Resolving};
use reqwest::redirect;
use crate::net_guard::{NetGuard, NetGuardError};
/// Most redirects a guarded client follows before giving up.
pub const MAX_REDIRECTS: usize = 5;
/// A boxed future, so [`Lookup`] can be used as a trait object.
pub type LookupFuture = Pin<Box<dyn Future<Output = io::Result<Vec<IpAddr>>> + Send>>;
/// Name resolution, behind a trait so tests can answer without live DNS.
pub trait Lookup: Send + Sync + 'static {
/// Every address `host` resolves to.
fn lookup(&self, host: &str) -> LookupFuture;
}
/// The operating system's resolver.
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemLookup;
impl Lookup for SystemLookup {
fn lookup(&self, host: &str) -> LookupFuture {
let host = host.to_string();
Box::pin(async move {
// Port 0: only the addresses matter; callers supply their own port.
let addrs = tokio::net::lookup_host((host.as_str(), 0)).await?;
Ok(addrs.map(|a| a.ip()).collect())
})
}
}
/// Resolve `host` and return its addresses only if the guard accepts **every**
/// one of them. An IP literal is classified without a lookup.
///
/// # Errors
///
/// [`NetGuardError`] if the host is refused by name, does not resolve, or any
/// address it resolves to is refused.
pub async fn resolve_approved(
guard: NetGuard,
lookup: &dyn Lookup,
host: &str,
) -> Result<Vec<IpAddr>, NetGuardError> {
let host = host.trim().trim_matches(['[', ']']);
guard.check_host(host)?;
if let Ok(ip) = host.parse::<IpAddr>() {
return Ok(vec![ip]);
}
let addrs = lookup
.lookup(host)
.await
.map_err(|e| NetGuardError::Unresolvable {
host: host.to_string(),
reason: e.to_string(),
})?;
if addrs.is_empty() {
return Err(NetGuardError::Unresolvable {
host: host.to_string(),
reason: "no addresses".to_string(),
});
}
// One refused answer refuses the name: which address a connection would
// pick is not ours to decide.
for ip in &addrs {
guard
.check_ip(*ip)
.map_err(|_| NetGuardError::PrivateAddress {
host: host.to_string(),
ip: *ip,
})?;
}
Ok(addrs)
}
/// A reqwest resolver that returns only guard-approved addresses.
struct GuardedResolver {
guard: NetGuard,
lookup: Arc<dyn Lookup>,
}
impl Resolve for GuardedResolver {
fn resolve(&self, name: Name) -> Resolving {
let guard = self.guard;
let lookup = Arc::clone(&self.lookup);
Box::pin(async move {
let ips = resolve_approved(guard, lookup.as_ref(), name.as_str()).await?;
// reqwest sets the port from the URL; 0 is a placeholder.
let addrs: Addrs = Box::new(ips.into_iter().map(|ip| SocketAddr::new(ip, 0)));
Ok(addrs)
})
}
}
/// Whether a guarded client may follow a redirect to `hop`, after
/// `hops_so_far` redirects.
///
/// Checks the scheme and the host name (an IP literal is classified here,
/// because reqwest connects to a literal without asking the resolver); a named
/// host is checked again by the resolver when the hop connects.
///
/// # Errors
///
/// [`NetGuardError::TooManyRedirects`] past [`MAX_REDIRECTS`], or
/// [`NetGuardError::RedirectRefused`] naming the hop.
pub fn check_redirect(guard: NetGuard, hop: &str, hops_so_far: usize) -> Result<(), NetGuardError> {
if hops_so_far >= MAX_REDIRECTS {
return Err(NetGuardError::TooManyRedirects(MAX_REDIRECTS));
}
guard
.check_url(hop)
.map(drop)
.map_err(|reason| NetGuardError::RedirectRefused {
hop: hop.to_string(),
reason: reason.to_string(),
})
}
/// A client builder for requests to tenant-chosen URLs: guarded resolver,
/// guarded redirects, no proxy (a proxy would resolve the name itself).
/// Callers add their own timeouts and TLS settings.
///
/// An IP-literal URL never reaches the resolver, so check the *first* URL with
/// [`NetGuard::check_url`] before sending, as every call site already does.
pub fn guarded_client_builder(guard: NetGuard) -> reqwest::ClientBuilder {
guarded_client_builder_with(guard, Arc::new(SystemLookup))
}
/// [`guarded_client_builder`] with a custom [`Lookup`] (tests).
pub fn guarded_client_builder_with(
guard: NetGuard,
lookup: Arc<dyn Lookup>,
) -> reqwest::ClientBuilder {
let policy = redirect::Policy::custom(move |attempt| {
// `previous()` includes the original request, so it holds one more
// URL than the redirects already followed.
let followed = attempt.previous().len().saturating_sub(1);
match check_redirect(guard, attempt.url().as_str(), followed) {
Ok(()) => attempt.follow(),
Err(e) => attempt.error(e),
}
});
reqwest::Client::builder()
.no_proxy()
.dns_resolver(Arc::new(GuardedResolver { guard, lookup }))
.redirect(policy)
}
// The tests serve over axum, which only the `axum` feature brings in.
#[cfg(all(test, feature = "axum"))]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
use axum::routing::get;
/// An error and its sources, as the user-facing messages read.
fn chain(e: &(dyn std::error::Error + 'static)) -> String {
let mut out = e.to_string();
let mut source = e.source();
while let Some(s) = source {
out.push_str(": ");
out.push_str(&s.to_string());
source = s.source();
}
out
}
/// Answers from a table; each host's answers are consumed in order, the
/// last one repeating, so a record can "flip" between lookups.
#[derive(Default)]
struct StubLookup {
answers: Mutex<HashMap<String, Vec<Vec<IpAddr>>>>,
calls: AtomicUsize,
}
impl StubLookup {
fn answer(self, host: &str, answers: &[&[&str]]) -> Self {
let parsed = answers
.iter()
.map(|a| a.iter().map(|ip| ip.parse().unwrap()).collect())
.collect();
self.answers
.lock()
.unwrap()
.insert(host.to_string(), parsed);
self
}
}
impl Lookup for StubLookup {
fn lookup(&self, host: &str) -> LookupFuture {
self.calls.fetch_add(1, Ordering::SeqCst);
let mut table = self.answers.lock().unwrap();
let result = match table.get_mut(host) {
Some(queue) if queue.len() > 1 => Ok(queue.remove(0)),
Some(queue) => Ok(queue[0].clone()),
None => Err(io::Error::new(io::ErrorKind::NotFound, "no such host")),
};
Box::pin(async move { result })
}
}
/// A local server counting the requests that reach it.
async fn counting_server(router: axum::Router) -> (SocketAddr, Arc<AtomicUsize>) {
let hits = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&hits);
let app = router.layer(axum::middleware::from_fn(
move |req: axum::extract::Request, next: axum::middleware::Next| {
let counter = Arc::clone(&counter);
async move {
counter.fetch_add(1, Ordering::SeqCst);
next.run(req).await
}
},
));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.ok() });
(addr, hits)
}
#[tokio::test]
async fn every_answer_must_be_public() {
let guard = NetGuard::public_only();
let lookup = StubLookup::default()
.answer("public.example", &[&["93.184.215.14"]])
.answer("mixed.example", &[&["93.184.215.14", "10.0.0.5"]])
.answer("metadata.example", &[&["169.254.169.254"]]);
assert!(resolve_approved(guard, &lookup, "public.example")
.await
.is_ok());
for host in ["mixed.example", "metadata.example"] {
let err = resolve_approved(guard, &lookup, host).await.unwrap_err();
assert!(
matches!(err, NetGuardError::PrivateAddress { .. }),
"{host}: {err}"
);
}
assert!(matches!(
resolve_approved(guard, &lookup, "missing.example").await,
Err(NetGuardError::Unresolvable { .. })
));
// Literals are classified without a lookup.
let before = lookup.calls.load(Ordering::SeqCst);
assert!(resolve_approved(guard, &lookup, "127.0.0.1").await.is_err());
assert_eq!(lookup.calls.load(Ordering::SeqCst), before);
}
#[tokio::test]
async fn a_rebinding_name_never_reaches_the_private_address() {
// The attack: answer a public address to the check, then the private
// one (where the server listens) to the connection. With the guard as
// the resolver there is exactly one lookup per connection, and the
// connection goes where that lookup said.
let (addr, hits) =
counting_server(axum::Router::new().route("/", get(|| async { "x" }))).await;
let lookup = Arc::new(
StubLookup::default().answer("rebind.example", &[&["1.1.1.1"], &["127.0.0.1"]]),
);
let client = guarded_client_builder_with(NetGuard::public_only(), lookup.clone())
.connect_timeout(std::time::Duration::from_millis(300))
.build()
.unwrap();
let result = client
.get(format!("http://rebind.example:{}/", addr.port()))
.send()
.await;
assert!(result.is_err(), "must not connect to the private address");
assert_eq!(hits.load(Ordering::SeqCst), 0);
assert_eq!(lookup.calls.load(Ordering::SeqCst), 1, "no second lookup");
// Once the name answers private it is refused outright.
let refused = client
.get(format!("http://rebind.example:{}/", addr.port()))
.send()
.await
.unwrap_err();
assert!(
chain(&refused).contains("not a public address"),
"{}",
chain(&refused)
);
assert_eq!(hits.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn the_resolver_is_what_connects() {
// Positive control: when the guard allows it, the stubbed name really
// is how the request finds the server.
let (addr, hits) =
counting_server(axum::Router::new().route("/", get(|| async { "x" }))).await;
let lookup = Arc::new(StubLookup::default().answer("plc.example", &[&["127.0.0.1"]]));
let client = guarded_client_builder_with(NetGuard::allow_private(), lookup)
.build()
.unwrap();
let body = client
.get(format!("http://plc.example:{}/", addr.port()))
.send()
.await
.unwrap()
.text()
.await
.unwrap();
assert_eq!(body, "x");
assert_eq!(hits.load(Ordering::SeqCst), 1);
}
#[test]
fn redirect_hops_are_checked_and_named() {
let guard = NetGuard::public_only();
assert!(check_redirect(guard, "https://example.com/next", 0).is_ok());
for hop in [
"http://169.254.169.254/latest/meta-data/",
"http://10.0.0.5/",
"http://mongo:27017/",
"http://metadata.google.internal/",
"ftp://example.com/x",
"file:///etc/passwd",
] {
let err = check_redirect(guard, hop, 0).unwrap_err();
assert!(
matches!(&err, NetGuardError::RedirectRefused { hop: h, .. } if h == hop),
"{hop}: {err}"
);
assert!(err.to_string().contains(hop), "{err}");
}
assert!(matches!(
check_redirect(guard, "https://example.com/", MAX_REDIRECTS),
Err(NetGuardError::TooManyRedirects(MAX_REDIRECTS))
));
}
#[tokio::test]
async fn a_client_stops_at_a_refused_hop_and_at_the_cap() {
// allow_private lets the test reach its local server; scheme and hop
// count are enforced regardless of that policy.
let router = axum::Router::new()
.route(
"/to-ftp",
get(|| async { axum::response::Redirect::temporary("ftp://example.com/x") }),
)
.route(
"/loop",
get(|| async { axum::response::Redirect::temporary("/loop") }),
);
let (addr, hits) = counting_server(router).await;
let client = guarded_client_builder_with(NetGuard::allow_private(), Arc::new(SystemLookup))
.build()
.unwrap();
let err = client
.get(format!("http://{addr}/to-ftp"))
.send()
.await
.unwrap_err();
assert!(
chain(&err).contains("ftp://example.com/x"),
"{}",
chain(&err)
);
let before = hits.load(Ordering::SeqCst);
let err = client
.get(format!("http://{addr}/loop"))
.send()
.await
.unwrap_err();
assert!(chain(&err).contains("more than"), "{}", chain(&err));
// The first request plus exactly MAX_REDIRECTS followed hops.
assert_eq!(hits.load(Ordering::SeqCst) - before, MAX_REDIRECTS + 1);
}
}
+2
View File
@@ -3,6 +3,8 @@ pub mod control_check;
pub mod db;
pub mod error;
pub mod exec_policy;
#[cfg(feature = "net")]
pub mod guarded_net;
pub mod models;
pub mod net_guard;
pub mod scan_matrix;
+8 -4
View File
@@ -21,10 +21,10 @@
//! 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.
//! 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};
@@ -53,6 +53,10 @@ pub enum NetGuardError {
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).
+1 -1
View File
@@ -7,7 +7,7 @@ edition = "2021"
workspace = true
[dependencies]
compliance-core = { workspace = true }
compliance-core = { workspace = true, features = ["net"] }
serde = { workspace = true }
serde_json = { workspace = true }
chrono = { workspace = true }
@@ -1,9 +1,11 @@
use chrono::Utc;
use compliance_core::error::CoreError;
use compliance_core::guarded_net::guarded_client_builder;
use compliance_core::models::dast::{
DastFinding, DastScanPhase, DastScanRun, DastScanStatus, DastTarget,
};
use compliance_core::traits::dast_agent::DastContext;
use compliance_core::NetGuard;
use tracing::{error, info};
use crate::crawler::WebCrawler;
@@ -16,9 +18,16 @@ pub struct DastOrchestrator {
}
impl DastOrchestrator {
pub fn new(rate_limit_ms: u64) -> Self {
/// A scanner whose HTTP traffic goes through `guard`: approved addresses
/// only, every redirect hop re-checked (#294).
#[allow(clippy::expect_used)]
pub fn new(rate_limit_ms: u64, guard: NetGuard) -> Self {
Self {
http: reqwest::Client::new(),
// Only fails if the TLS backend cannot initialise, the same case in
// which `reqwest::Client::new()` panics.
http: guarded_client_builder(guard)
.build()
.expect("failed to build HTTP client"),
rate_limit_ms,
}
}
+7 -3
View File
@@ -1,13 +1,17 @@
use compliance_core::error::CoreError;
use compliance_core::guarded_net::guarded_client_builder;
use compliance_core::models::dast::{DastEvidence, DastFinding, DastVulnType};
use compliance_core::models::Severity;
use compliance_core::traits::pentest_tool::{PentestTool, PentestToolContext, PentestToolResult};
use compliance_core::NetGuard;
use serde_json::json;
use tracing::info;
/// Tool that inspects cookies set by a target for security issues.
pub struct CookieAnalyzerTool {
http: reqwest::Client,
/// Builds the tool's own no-redirect client with the same guard (#294).
guard: NetGuard,
}
/// Parsed attributes from a Set-Cookie header.
@@ -25,8 +29,8 @@ struct ParsedCookie {
}
impl CookieAnalyzerTool {
pub fn new(http: reqwest::Client) -> Self {
Self { http }
pub fn new(http: reqwest::Client, guard: NetGuard) -> Self {
Self { http, guard }
}
/// Parse a Set-Cookie header value into a structured representation.
@@ -224,7 +228,7 @@ impl PentestTool for CookieAnalyzerTool {
for check_url in &urls_to_check {
// Use a client that does NOT follow redirects so we catch cookies on redirect responses
let no_redirect_client = reqwest::Client::builder()
let no_redirect_client = guarded_client_builder(self.guard)
.danger_accept_invalid_certs(true)
.redirect(reqwest::redirect::Policy::none())
.timeout(std::time::Duration::from_secs(15))
+17 -11
View File
@@ -18,7 +18,9 @@ pub mod xss;
use std::collections::HashMap;
use compliance_core::guarded_net::guarded_client_builder;
use compliance_core::traits::pentest_tool::PentestTool;
use compliance_core::NetGuard;
/// A definition describing a tool for LLM tool_use registration.
#[derive(Debug, Clone)]
@@ -36,18 +38,19 @@ pub struct ToolRegistry {
impl Default for ToolRegistry {
fn default() -> Self {
Self::new()
Self::new(NetGuard::public_only())
}
}
impl ToolRegistry {
/// Create a new registry with all built-in tools pre-registered.
/// Create a new registry with all built-in tools pre-registered. Every
/// tool's HTTP traffic goes to the target through `guard`: approved
/// addresses only, every redirect hop re-checked (#294).
#[allow(clippy::expect_used)]
pub fn new() -> Self {
let http = reqwest::Client::builder()
pub fn new(guard: NetGuard) -> Self {
let http = guarded_client_builder(guard)
.danger_accept_invalid_certs(true)
.timeout(std::time::Duration::from_secs(30))
.redirect(reqwest::redirect::Policy::limited(5))
.build()
.expect("failed to build HTTP client");
@@ -82,7 +85,7 @@ impl ToolRegistry {
);
register(
&mut tools,
Box::new(tls_analyzer::TlsAnalyzerTool::new(http.clone())),
Box::new(tls_analyzer::TlsAnalyzerTool::new(http.clone(), guard)),
);
register(
&mut tools,
@@ -90,7 +93,10 @@ impl ToolRegistry {
);
register(
&mut tools,
Box::new(cookie_analyzer::CookieAnalyzerTool::new(http.clone())),
Box::new(cookie_analyzer::CookieAnalyzerTool::new(
http.clone(),
guard,
)),
);
register(
&mut tools,
@@ -149,7 +155,7 @@ mod tests {
#[test]
fn registry_has_all_expected_tools() {
let registry = ToolRegistry::new();
let registry = ToolRegistry::new(NetGuard::public_only());
let names = registry.list_names();
let expected = [
@@ -182,7 +188,7 @@ mod tests {
#[test]
fn registry_get_returns_tool() {
let registry = ToolRegistry::new();
let registry = ToolRegistry::new(NetGuard::public_only());
assert!(registry.get("recon").is_some());
assert!(registry.get("browser").is_some());
assert!(registry.get("nonexistent").is_none());
@@ -190,7 +196,7 @@ mod tests {
#[test]
fn all_definitions_have_valid_schemas() {
let registry = ToolRegistry::new();
let registry = ToolRegistry::new(NetGuard::public_only());
let defs = registry.all_definitions();
assert!(!defs.is_empty());
@@ -218,7 +224,7 @@ mod tests {
#[test]
fn browser_tool_schema_has_action_enum() {
let registry = ToolRegistry::new();
let registry = ToolRegistry::new(NetGuard::public_only());
let browser = registry.get("browser");
assert!(browser.is_some());
let schema = browser.map(|t| t.input_schema()).unwrap_or_default();
+18 -5
View File
@@ -1,7 +1,9 @@
use compliance_core::error::CoreError;
use compliance_core::guarded_net::{resolve_approved, SystemLookup};
use compliance_core::models::dast::{DastEvidence, DastFinding, DastVulnType};
use compliance_core::models::Severity;
use compliance_core::traits::pentest_tool::{PentestTool, PentestToolContext, PentestToolResult};
use compliance_core::NetGuard;
use serde_json::json;
use tokio::net::TcpStream;
use tracing::{info, warn};
@@ -13,11 +15,13 @@ use tracing::{info, warn};
/// for common TLS misconfigurations.
pub struct TlsAnalyzerTool {
http: reqwest::Client,
/// Where the raw TLS connection may go (#294).
guard: NetGuard,
}
impl TlsAnalyzerTool {
pub fn new(http: reqwest::Client) -> Self {
Self { http }
pub fn new(http: reqwest::Client, guard: NetGuard) -> Self {
Self { http, guard }
}
/// Extract the hostname from a URL.
@@ -39,10 +43,19 @@ impl TlsAnalyzerTool {
/// TLS client hello. We test SSLv3 / old protocol support by attempting
/// connection with the system's native-tls which typically negotiates the
/// best available, then inspect what was negotiated.
async fn check_tls(host: &str, port: u16) -> Result<TlsInfo, CoreError> {
async fn check_tls(guard: NetGuard, host: &str, port: u16) -> Result<TlsInfo, CoreError> {
let addr = format!("{host}:{port}");
let tcp = TcpStream::connect(&addr)
// Resolve once through the guard and connect to what it approved, so
// a second lookup cannot send the connection somewhere else (#294).
let ips = resolve_approved(guard, &SystemLookup, host)
.await
.map_err(|e| CoreError::Dast(format!("TCP connection to {addr} refused: {e}")))?;
let approved: Vec<std::net::SocketAddr> = ips
.into_iter()
.map(|ip| std::net::SocketAddr::new(ip, port))
.collect();
let tcp = TcpStream::connect(approved.as_slice())
.await
.map_err(|e| CoreError::Dast(format!("TCP connection to {addr} failed: {e}")))?;
@@ -246,7 +259,7 @@ impl PentestTool for TlsAnalyzerTool {
}
// Perform TLS analysis
match Self::check_tls(&host, port).await {
match Self::check_tls(self.guard, &host, port).await {
Ok(tls_info) => {
tls_data["host"] = json!(host);
tls_data["port"] = json!(port);
+6 -1
View File
@@ -86,7 +86,12 @@ refuses:
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.
address is refused. For HTTP (DAST, pentest tools, issue-tracker calls) and the
PLC probe, the scanner connects to exactly the address it checked, so a name
cannot answer one address to the check and another to the connection. Every
redirect is checked the same way, at most five are followed, and a refused
redirect names the address it pointed to. Git clones and fetches are checked
right before each connection and never follow redirects.
**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
+1 -1
View File
@@ -8,7 +8,7 @@ description = "Shared dynamic-execution logic: soft-PLC provisioning + industria
workspace = true
[dependencies]
compliance-core = { workspace = true }
compliance-core = { workspace = true, features = ["net"] }
compliance-dast = { path = "../compliance-dast" }
tokio = { workspace = true }
reqwest = { workspace = true }
+14 -4
View File
@@ -12,6 +12,7 @@ pub mod portscan;
use std::time::Duration;
use compliance_core::guarded_net::{resolve_approved, SystemLookup};
use compliance_core::models::{Finding, ScanType, Severity};
use compliance_core::{AppEnv, NetGuard};
@@ -35,10 +36,19 @@ pub async fn probe_target(endpoint: &str, repo_id: &str, budget: Duration) -> Ve
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();
}
// Resolve once through the guard and probe the address it approved; each
// probe connecting by name would resolve again and could reach a different
// host (#294). Findings therefore name the address actually probed.
let host = match resolve_approved(guard, &SystemLookup, &host).await {
Ok(ips) => match ips.first() {
Some(ip) => ip.to_string(),
None => return Vec::new(),
},
Err(e) => {
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);
+5 -2
View File
@@ -22,7 +22,7 @@ use secrecy::ExposeSecret;
use compliance_core::models::dast::{DastFinding, DastScanRun, DastTarget, DastTargetType};
use compliance_core::models::Finding;
use compliance_core::PlcRuntimeConfig;
use compliance_core::{NetGuard, PlcRuntimeConfig};
use crate::error::ExecError;
@@ -247,7 +247,10 @@ async fn run_webvisu_dast(handle: &ProvisionedRuntime, target_id: &str) -> Optio
dt.repo_id = Some(target_id.to_string());
dt.max_crawl_depth = 2; // shallow — the instance is ephemeral
let orchestrator = compliance_dast::DastOrchestrator::new(100);
// The WebVisu endpoint is the soft-PLC this run started on its own
// network, so a private address is expected; schemes and the redirect cap
// are still enforced.
let orchestrator = compliance_dast::DastOrchestrator::new(100, NetGuard::allow_private());
match orchestrator.run_scan(&dt, Vec::new()).await {
Ok((mut scan_run, mut findings)) => {
scan_run.target_id = target_id.to_string();