feat(dast): scans log in with the target's credentials (#1000) #1003

Merged
sharang merged 1 commits from feat/dast-auth-headers into main 2026-11-16 02:31:38 +00:00
16 changed files with 684 additions and 38 deletions

No files matched your search

+8
View File
@@ -140,6 +140,10 @@ jobs:
run: cargo clippy -p control-map --all-targets -- -D warnings
- name: Clippy (graph)
run: cargo clippy -p compliance-graph --all-targets -- -D warnings
# The library only: its test modules still predate the lint
# (items_after_test_module); --all-targets once they are moved.
- name: Clippy (dast)
run: cargo clippy -p compliance-dast -- -D warnings
# Security audit
- name: Security Audit
@@ -153,6 +157,10 @@ jobs:
# compliance-core's integration tests need no services.
- name: Tests (core integration)
run: cargo test -p compliance-core --tests
# compliance-dast: unit tests, doc tests and the scan tests against
# local fake sites (no services).
- name: Tests (dast)
run: cargo test -p compliance-dast
# The dashboard crate compiles as the library and as its test harness at
# once, each rustc at about 1.65 GB: two of them exceed the job's 3 GiB
# and get OOM-killed (signal 9). One at a time for these two steps.
Generated
+2
View File
@@ -727,6 +727,7 @@ dependencies = [
name = "compliance-dast"
version = "0.4.15"
dependencies = [
"axum",
"base64 0.22.1",
"chrono",
"compliance-core",
@@ -735,6 +736,7 @@ dependencies = [
"reqwest",
"scraper",
"serde_json",
"thiserror 2.0.18",
"tokio",
"tokio-native-tls",
"tokio-tungstenite 0.26.2",
+23 -7
View File
@@ -6,7 +6,9 @@ use axum::Json;
use mongodb::bson::doc;
use serde::Deserialize;
use compliance_core::models::dast::{DastFinding, DastScanRun, DastTarget, DastTargetType};
use compliance_core::models::dast::{
DastAuthConfig, DastFinding, DastScanRun, DastTarget, DastTargetType,
};
use compliance_core::models::Credentials;
use compliance_core::tenant_ctx::TenantCtx;
@@ -32,6 +34,11 @@ pub struct AddTargetRequest {
pub rate_limit: u32,
#[serde(default)]
pub allow_destructive: bool,
/// The login every scan request carries (#1000): `basic` (username,
/// password), `bearer` (token), `cookie` (token = `name=value`), plus
/// optional extra headers. Stored sealed, never returned.
#[serde(default)]
pub auth: Option<DastAuthConfig>,
}
fn default_target_type() -> DastTargetType {
@@ -94,12 +101,22 @@ pub async fn add_target(
tracing::warn!(tenant_id = %tenant.0.tenant_id, "DAST target refused: {e}");
return Err(StatusCode::BAD_REQUEST);
}
// A login the scan could not send is refused now, not at the first scan.
if let Err(e) = compliance_dast::auth::login_headers(req.auth.as_ref()) {
tracing::warn!(tenant_id = %tenant.0.tenant_id, "DAST target login 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;
target.max_crawl_depth = req.max_crawl_depth;
target.rate_limit = req.rate_limit;
target.allow_destructive = req.allow_destructive;
target.auth_config = req.auth;
agent
.secrets
.seal_unsealed(&mut target)
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
let db = tenant_db(&agent, &tenant).await?;
let res = db
@@ -107,11 +124,8 @@ pub async fn add_target(
.insert_one(&target)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let target_id = res
.inserted_id
.as_object_id()
.map(|id| id.to_hex())
.unwrap_or_default();
target.id = res.inserted_id.as_object_id();
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
agent.emit_usage(
&tenant.0.tenant_id,
"target.added",
@@ -141,12 +155,14 @@ pub async fn trigger_scan(
let oid = mongodb::bson::oid::ObjectId::parse_str(&id).map_err(|_| StatusCode::BAD_REQUEST)?;
let db = tenant_db(&agent, &tenant).await?;
let target = db
let mut target = db
.dast_targets()
.find_one(doc! { "_id": oid })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::NOT_FOUND)?;
// The login is used here, in memory only.
agent.secrets.open_in_place(&mut target);
// Re-check at use: the target may have been stored before this policy
// existed, and a hostname can be repointed after registration.
+2 -1
View File
@@ -130,7 +130,8 @@ impl PipelineOrchestrator {
return;
}
for target in targets {
for mut target in targets {
self.secrets.open_in_place(&mut target);
let db = self.db.clone();
let scan_run_id = scan_run_id.to_string();
let net_guard = self.net_guard;
+10 -2
View File
@@ -2662,15 +2662,23 @@ impl PipelineOrchestrator {
dast.allow_destructive = web.allow_destructive;
}
if let Some(auth) = &url.auth {
// The artifact keeps one secret (sealed): a password for a basic
// login, otherwise the token or cookie.
let basic = auth.method.eq_ignore_ascii_case("basic");
dast.auth_config = Some(DastAuthConfig {
method: auth.method.clone(),
login_url: auth.login_url.clone(),
username: auth.username.clone(),
password: None,
token: auth.secret.clone(),
password: auth.secret.clone().filter(|_| basic),
token: auth.secret.clone().filter(|_| !basic),
headers: auth.headers.clone(),
});
}
// The copied secret is sealed already; the login headers are not.
if let Err(e) = self.secrets.seal_unsealed(&mut dast) {
tracing::warn!(error = %e, "Unified pipeline: DAST login not stored");
return;
}
if let Err(e) = self.db.dast_targets().insert_one(&dast).await {
tracing::warn!(error = %e, "Unified pipeline: failed to provision DAST target");
}
@@ -46,3 +46,78 @@ async fn list_dast_findings_empty() {
server.cleanup().await;
}
#[tokio::test]
async fn a_targets_login_is_stored_sealed_and_never_returned() {
let server = TestServer::start().await;
let resp = server
.post(
"/api/v1/dast/targets",
&json!({
"name": "members",
"base_url": "https://members.example.com",
"auth": {
"method": "bearer",
"token": "tok-secret",
"headers": { "X-Api-Key": "key-secret" },
},
}),
)
.await;
assert_eq!(resp.status(), 200);
let body: serde_json::Value = resp.json().await.unwrap();
let id = body["data"]["_id"]["$oid"].as_str().expect("the new id");
let returned = body.to_string();
assert!(
!returned.contains("tok-secret") && !returned.contains("key-secret"),
"{returned}"
);
let mongodb_uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let client = mongodb::Client::with_uri_str(&mongodb_uri).await.unwrap();
let stored = client
.database(&server.tenant_db_name())
.collection::<mongodb::bson::Document>("dast_targets")
.find_one(mongodb::bson::doc! {
"_id": mongodb::bson::oid::ObjectId::parse_str(id).unwrap()
})
.await
.unwrap()
.expect("stored under the returned id");
let auth = stored.get_document("auth_config").unwrap();
let token = auth.get_str("token").unwrap();
let header = auth
.get_document("headers")
.unwrap()
.get_str("X-Api-Key")
.unwrap();
assert!(token != "tok-secret" && header != "key-secret", "{auth}");
server.cleanup().await;
}
#[tokio::test]
async fn a_login_the_scan_cannot_send_is_refused() {
let server = TestServer::start().await;
for auth in [
json!({ "method": "form", "login_url": "https://members.example.com/login" }),
json!({ "method": "bearer" }),
json!({ "method": "ntlm", "token": "t" }),
] {
let resp = server
.post(
"/api/v1/dast/targets",
&json!({ "name": "m", "base_url": "https://members.example.com", "auth": auth }),
)
.await;
assert_eq!(resp.status(), 400, "{auth}");
}
let resp = server.get("/api/v1/dast/targets").await;
let body: serde_json::Value = resp.json().await.unwrap();
assert!(body["data"].as_array().unwrap().is_empty());
server.cleanup().await;
}
+28
View File
@@ -6,6 +6,8 @@
//! every one before a record leaves the service, and a field added later only
//! has to be listed here.
use std::collections::HashMap;
use super::dast::{DastAuthConfig, DastTarget};
use super::onboarding::{
Artifact, ArtifactAuth, IssueTrackerConfig, OnboardedTarget, TargetScanConfig,
@@ -17,6 +19,12 @@ pub trait Credentials {
/// Every credential field of the record, for sealing before a write.
fn credentials_mut(&mut self) -> Vec<&mut Option<String>>;
/// Maps whose every value is a credential (login headers), sealed and
/// opened value by value. None by default.
fn credential_maps_mut(&mut self) -> Vec<&mut HashMap<String, String>> {
Vec::new()
}
/// Remove every credential before the record leaves the service.
fn redact(&mut self) {
for slot in self.credentials_mut() {
@@ -39,6 +47,12 @@ impl<T: Credentials> Credentials for Option<T> {
self.as_mut().map(T::credentials_mut).unwrap_or_default()
}
fn credential_maps_mut(&mut self) -> Vec<&mut HashMap<String, String>> {
self.as_mut()
.map(T::credential_maps_mut)
.unwrap_or_default()
}
fn redact(&mut self) {
if let Some(inner) = self {
inner.redact();
@@ -51,6 +65,10 @@ impl<T: Credentials> Credentials for Vec<T> {
self.iter_mut().flat_map(T::credentials_mut).collect()
}
fn credential_maps_mut(&mut self) -> Vec<&mut HashMap<String, String>> {
self.iter_mut().flat_map(T::credential_maps_mut).collect()
}
fn redact(&mut self) {
self.iter_mut().for_each(T::redact);
}
@@ -139,6 +157,12 @@ impl Credentials for DastAuthConfig {
vec![&mut self.password, &mut self.token]
}
/// Login headers (an API key, a session cookie) are sent with every scan
/// request, so they are sealed like the token (#1000).
fn credential_maps_mut(&mut self) -> Vec<&mut HashMap<String, String>> {
self.headers.as_mut().into_iter().collect()
}
fn redact(&mut self) {
self.password = None;
self.token = None;
@@ -151,6 +175,10 @@ impl Credentials for DastTarget {
self.auth_config.credentials_mut()
}
fn credential_maps_mut(&mut self) -> Vec<&mut HashMap<String, String>> {
self.auth_config.credential_maps_mut()
}
fn redact(&mut self) {
self.auth_config.redact();
}
+84
View File
@@ -206,6 +206,17 @@ impl SecretBox {
for slot in record.credentials_mut() {
*slot = self.open_opt(slot.as_ref(), "stored record");
}
for map in record.credential_maps_mut() {
map.retain(
|_, value| match self.open_opt(Some(value), "stored header") {
Some(plaintext) => {
*value = plaintext;
true
}
None => false,
},
);
}
}
/// Seal every credential of `record` that is not sealed yet.
@@ -227,6 +238,16 @@ impl SecretBox {
*slot = Some(sealed);
changed = true;
}
for value in record
.credential_maps_mut()
.into_iter()
.flat_map(|map| map.values_mut())
{
if !Self::is_sealed(value) {
*value = self.seal(value)?;
changed = true;
}
}
Ok(changed)
}
}
@@ -349,4 +370,67 @@ mod tests {
assert_eq!(secrets.open(&token).unwrap(), "plain-tracker");
assert!(!secrets.seal_unsealed(&mut target).unwrap());
}
#[test]
fn dast_login_headers_are_sealed_and_opened_value_by_value() {
use crate::models::dast::{DastAuthConfig, DastTarget, DastTargetType};
use std::collections::HashMap;
let secrets = keyed();
let mut target = DastTarget::new(
"t".into(),
"https://app.example.com".into(),
DastTargetType::WebApp,
);
target.auth_config = Some(DastAuthConfig {
method: "bearer".into(),
login_url: None,
username: None,
password: None,
token: Some("tok".into()),
headers: Some(HashMap::from([("X-Api-Key".into(), "key-1".into())])),
});
assert!(secrets.seal_unsealed(&mut target).unwrap());
let auth = target.auth_config.as_ref().unwrap();
let stored = &auth.headers.as_ref().unwrap()["X-Api-Key"];
assert!(SecretBox::is_sealed(stored), "{stored}");
assert!(SecretBox::is_sealed(auth.token.as_deref().unwrap()));
assert!(!secrets.seal_unsealed(&mut target).unwrap(), "sealed once");
secrets.open_in_place(&mut target);
let auth = target.auth_config.as_ref().unwrap();
assert_eq!(auth.headers.as_ref().unwrap()["X-Api-Key"], "key-1");
assert_eq!(auth.token.as_deref(), Some("tok"));
}
#[test]
fn a_header_that_does_not_open_is_dropped() {
use crate::models::dast::{DastAuthConfig, DastTarget, DastTargetType};
use std::collections::HashMap;
let mut target = DastTarget::new(
"t".into(),
"https://app.example.com".into(),
DastTargetType::WebApp,
);
target.auth_config = Some(DastAuthConfig {
method: "none".into(),
login_url: None,
username: None,
password: None,
token: None,
headers: Some(HashMap::from([
("X-Sealed".into(), keyed().seal("k").unwrap()),
("X-Plain".into(), "legacy".into()),
])),
});
// Another key cannot open the sealed value.
SecretBox::from_key(&[7u8; 32])
.unwrap()
.open_in_place(&mut target);
let headers = target.auth_config.unwrap().headers.unwrap();
assert_eq!(headers.len(), 1);
assert_eq!(headers["X-Plain"], "legacy");
}
}
+4
View File
@@ -14,6 +14,7 @@ tracing = { workspace = true }
uuid = { workspace = true }
tokio = { workspace = true }
reqwest = { workspace = true }
thiserror = { workspace = true }
# HTML parsing
scraper = "0.25"
@@ -29,3 +30,6 @@ base64 = "0.22"
# Serialization
url = "2"
[dev-dependencies]
axum = "0.8"
+10 -5
View File
@@ -89,14 +89,19 @@ impl DastAgent for AuthBypassAgent {
}
}
// Test 2: HTTP method tampering
let methods = ["PUT", "PATCH", "DELETE", "OPTIONS"];
// Test 2: HTTP method tampering. A write method changes the target's
// data, so it is sent only with destructive tests allowed.
let methods: &[&str] = if target.allow_destructive {
&["PUT", "PATCH", "DELETE"]
} else {
&[]
};
for endpoint in &context.endpoints {
if endpoint.method != "GET" && endpoint.method != "POST" {
continue;
}
for method in &methods {
for method in methods {
let response = match self
.http
.request(
@@ -113,8 +118,8 @@ impl DastAgent for AuthBypassAgent {
let status = response.status().as_u16();
// If a non-standard method returns 200 when it shouldn't
if status == 200 && *method == "DELETE" && !target.allow_destructive {
// A stranger's write accepted on a page meant to be read.
if (200..300).contains(&status) {
let evidence = DastEvidence {
request_method: method.to_string(),
request_url: endpoint.url.clone(),
+211
View File
@@ -0,0 +1,211 @@
//! The login a DAST scan sends with every request to its target (#1000).
//!
//! A target's [`DastAuthConfig`] becomes default headers on the scan's HTTP
//! client. The crawler and the agents stay on the target's origin, and
//! reqwest drops `Authorization` and `Cookie` on a redirect to another host, so
//! the login only reaches the target.
use base64::Engine;
use compliance_core::models::dast::DastAuthConfig;
use reqwest::header::{HeaderMap, HeaderName, HeaderValue, AUTHORIZATION, COOKIE};
/// Why a target's login cannot be sent.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum LoginError {
/// A method this scanner does not know.
#[error("login method `{0}` is not known (none, basic, bearer, cookie)")]
UnknownMethod(String),
/// Form login drives a browser and is not available yet.
#[error("form login is not supported yet")]
FormNotSupported,
/// The method lacks a value it needs.
#[error("the {method} login needs {missing}")]
Missing {
method: &'static str,
missing: &'static str,
},
/// A header name or value that HTTP cannot carry.
#[error("header `{0}` cannot be sent")]
InvalidHeader(String),
}
/// The headers that log a scan in with `auth`; empty without a login.
///
/// # Arguments
///
/// * `auth` - the target's login, its secrets already opened
///
/// # Returns
///
/// `Authorization` (basic, bearer) or `Cookie` (cookie), plus the login's
/// extra headers. Secret values are marked sensitive, so they never appear in
/// a `Debug` print of the headers.
///
/// # Errors
///
/// [`LoginError`] when the method is unknown or form login, a value the
/// method needs is missing, or a header cannot be sent.
///
/// # Examples
///
/// ```
/// use compliance_core::models::dast::DastAuthConfig;
/// let auth = DastAuthConfig {
/// method: "bearer".into(),
/// login_url: None,
/// username: None,
/// password: None,
/// token: Some("t0ken".into()),
/// headers: None,
/// };
/// let headers = compliance_dast::auth::login_headers(Some(&auth)).unwrap();
/// assert_eq!(headers["authorization"], "Bearer t0ken");
/// ```
pub fn login_headers(auth: Option<&DastAuthConfig>) -> Result<HeaderMap, LoginError> {
let mut headers = HeaderMap::new();
let Some(auth) = auth else {
return Ok(headers);
};
match auth.method.to_ascii_lowercase().as_str() {
"" | "none" => {}
"basic" => {
let user = secret("basic", auth.username.as_ref(), "a username")?;
let password = secret("basic", auth.password.as_ref(), "a password")?;
let encoded =
base64::engine::general_purpose::STANDARD.encode(format!("{user}:{password}"));
headers.insert(
AUTHORIZATION,
sensitive("Authorization", &format!("Basic {encoded}"))?,
);
}
"bearer" => {
let token = secret("bearer", auth.token.as_ref(), "a token")?;
headers.insert(
AUTHORIZATION,
sensitive("Authorization", &format!("Bearer {token}"))?,
);
}
"cookie" => {
let cookie = secret("cookie", auth.token.as_ref(), "the cookie (name=value)")?;
headers.insert(COOKIE, sensitive("Cookie", cookie)?);
}
"form" => return Err(LoginError::FormNotSupported),
other => return Err(LoginError::UnknownMethod(other.to_string())),
}
for (name, value) in auth.headers.iter().flatten() {
let header = HeaderName::try_from(name.as_str())
.map_err(|_| LoginError::InvalidHeader(name.clone()))?;
headers.insert(header, sensitive(name, value)?);
}
Ok(headers)
}
/// `value` when set and not empty, else what the `method` login is missing.
fn secret<'a>(
method: &'static str,
value: Option<&'a String>,
missing: &'static str,
) -> Result<&'a str, LoginError> {
value
.map(String::as_str)
.filter(|v| !v.is_empty())
.ok_or(LoginError::Missing { method, missing })
}
/// A header value marked sensitive.
fn sensitive(name: &str, value: &str) -> Result<HeaderValue, LoginError> {
let mut value =
HeaderValue::from_str(value).map_err(|_| LoginError::InvalidHeader(name.to_string()))?;
value.set_sensitive(true);
Ok(value)
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use std::collections::HashMap;
use super::*;
fn auth(method: &str) -> DastAuthConfig {
DastAuthConfig {
method: method.into(),
login_url: None,
username: None,
password: None,
token: None,
headers: None,
}
}
#[test]
fn no_login_sends_nothing() {
assert!(login_headers(None).unwrap().is_empty());
assert!(login_headers(Some(&auth("none"))).unwrap().is_empty());
}
#[test]
fn basic_login_encodes_user_and_password() {
let mut a = auth("basic");
a.username = Some("scan".into());
a.password = Some("pw".into());
let headers = login_headers(Some(&a)).unwrap();
// base64("scan:pw")
assert_eq!(headers[AUTHORIZATION], "Basic c2Nhbjpwdw==");
assert!(headers[AUTHORIZATION].is_sensitive());
}
#[test]
fn cookie_and_extra_headers_are_sent_and_sensitive() {
let mut a = auth("Cookie");
a.token = Some("session=abc".into());
a.headers = Some(HashMap::from([("X-Api-Key".into(), "k".into())]));
let headers = login_headers(Some(&a)).unwrap();
assert_eq!(headers[COOKIE], "session=abc");
assert_eq!(headers["x-api-key"], "k");
assert!(headers["x-api-key"].is_sensitive());
assert!(!format!("{headers:?}").contains("abc"));
}
#[test]
fn a_login_without_its_secret_is_refused() {
assert_eq!(
login_headers(Some(&auth("bearer"))),
Err(LoginError::Missing {
method: "bearer",
missing: "a token"
})
);
let mut a = auth("basic");
a.username = Some("scan".into());
assert!(matches!(
login_headers(Some(&a)),
Err(LoginError::Missing {
missing: "a password",
..
})
));
}
#[test]
fn form_and_unknown_methods_are_refused() {
assert_eq!(
login_headers(Some(&auth("form"))),
Err(LoginError::FormNotSupported)
);
assert_eq!(
login_headers(Some(&auth("ntlm"))),
Err(LoginError::UnknownMethod("ntlm".into()))
);
}
#[test]
fn a_header_http_cannot_carry_is_refused() {
let mut a = auth("none");
a.headers = Some(HashMap::from([("X-Bad".into(), "a\nb".into())]));
assert_eq!(
login_headers(Some(&a)),
Err(LoginError::InvalidHeader("X-Bad".into()))
);
}
}
+8 -5
View File
@@ -128,6 +128,11 @@ impl WebCrawler {
let form_url = self
.resolve_url(&base, &url, action)
.unwrap_or_else(|| url.clone());
// A form that posts to another site is out of scope: the
// agents would send their payloads (and the login) there.
if !self.is_same_origin(&base, &form_url) {
continue;
}
let mut params = Vec::new();
for input in form.select(&input_selector) {
@@ -185,11 +190,9 @@ impl WebCrawler {
current.join(href).ok().map(|u| u.to_string())
}
/// Scheme, host and port all equal: another port on the same host is
/// another service, not the target.
fn is_same_origin(&self, base: &Url, url: &str) -> bool {
if let Ok(parsed) = Url::parse(url) {
parsed.host() == base.host() && parsed.scheme() == base.scheme()
} else {
false
}
Url::parse(url).is_ok_and(|parsed| parsed.origin() == base.origin())
}
}
+1
View File
@@ -1,4 +1,5 @@
pub mod agents;
pub mod auth;
pub mod crawler;
pub mod orchestrator;
pub mod recon;
@@ -13,7 +13,9 @@ use crate::recon::ReconAgent;
/// State machine orchestrator for DAST scanning
pub struct DastOrchestrator {
/// Without the target's login: the auth-bypass checks ask as a stranger.
http: reqwest::Client,
guard: NetGuard,
rate_limit_ms: u64,
}
@@ -28,10 +30,29 @@ impl DastOrchestrator {
http: guarded_client_builder(guard)
.build()
.expect("failed to build HTTP client"),
guard,
rate_limit_ms,
}
}
/// The client that carries `target`'s login (#1000), or the anonymous one
/// when it has none.
///
/// # Errors
///
/// Why the login cannot be sent, for the scan run's error message.
fn login_client(&self, target: &DastTarget) -> Result<reqwest::Client, String> {
let headers =
crate::auth::login_headers(target.auth_config.as_ref()).map_err(|e| e.to_string())?;
if headers.is_empty() {
return Ok(self.http.clone());
}
guarded_client_builder(self.guard)
.default_headers(headers)
.build()
.map_err(|e| format!("no HTTP client: {e}"))
}
/// Run a complete DAST scan against a target
pub async fn run_scan(
&self,
@@ -48,9 +69,22 @@ impl DastOrchestrator {
info!(target = %target.base_url, "Starting DAST scan");
// A login that cannot be sent fails the scan: testing anonymously
// instead would look like a logged-in scan that found nothing.
let http = match self.login_client(target) {
Ok(http) => http,
Err(e) => {
error!(error = %e, "DAST login unusable");
scan_run.status = DastScanStatus::Failed;
scan_run.error_message = Some(format!("Login: {e}"));
scan_run.completed_at = Some(Utc::now());
return Ok((scan_run, all_findings));
}
};
// Phase 1: Reconnaissance
scan_run.current_phase = DastScanPhase::Reconnaissance;
let recon = ReconAgent::new(self.http.clone());
let recon = ReconAgent::new(http.clone());
let recon_result = match recon.scan(&target.base_url).await {
Ok(r) => r,
Err(e) => {
@@ -73,11 +107,7 @@ impl DastOrchestrator {
// Phase 2: Crawling
scan_run.current_phase = DastScanPhase::Crawling;
let crawler = WebCrawler::new(
self.http.clone(),
target.max_crawl_depth,
self.rate_limit_ms,
);
let crawler = WebCrawler::new(http.clone(), target.max_crawl_depth, self.rate_limit_ms);
let endpoints = match crawler
.crawl(&target.base_url, &target.excluded_paths)
.await
@@ -105,7 +135,9 @@ impl DastOrchestrator {
// Phase 3: Vulnerability Analysis
scan_run.current_phase = DastScanPhase::VulnerabilityAnalysis;
let vuln_findings = self.run_vulnerability_agents(target, &context).await?;
let vuln_findings = self
.run_vulnerability_agents(target, &context, http)
.await?;
all_findings.extend(vuln_findings);
scan_run
.phases_completed
@@ -136,15 +168,16 @@ impl DastOrchestrator {
}
/// Run all vulnerability testing agents in parallel
/// `http` carries the target's login; the auth-bypass agent gets the
/// anonymous client instead, since it asks what a stranger may do.
async fn run_vulnerability_agents(
&self,
target: &DastTarget,
context: &DastContext,
http: reqwest::Client,
) -> Result<Vec<DastFinding>, CoreError> {
use compliance_core::traits::DastAgent;
let http = self.http.clone();
// Spawn each agent as a separate tokio task
let t1 = target.clone();
let c1 = context.clone();
@@ -163,7 +196,7 @@ impl DastOrchestrator {
let t3 = target.clone();
let c3 = context.clone();
let h3 = http.clone();
let h3 = self.http.clone();
let auth_handle = tokio::spawn(async move {
crate::agents::auth_bypass::AuthBypassAgent::new(h3)
.run(&t3, &c3)
+161
View File
@@ -0,0 +1,161 @@
//! A DAST scan logs in with the target's credentials (#1000), stays on the
//! target's origin, and never sends a write method unless destructive tests
//! are allowed.
#![allow(clippy::unwrap_used, clippy::expect_used)]
use std::sync::{Arc, Mutex};
use axum::extract::{Request, State};
use axum::http::StatusCode;
use axum::response::{Html, IntoResponse, Response};
use axum::Router;
use compliance_core::models::dast::{DastAuthConfig, DastScanStatus, DastTarget, DastTargetType};
use compliance_core::NetGuard;
use compliance_dast::crawler::WebCrawler;
use compliance_dast::DastOrchestrator;
/// What the fake site saw: method, path, and whether the login came along.
type Seen = Arc<Mutex<Vec<(String, String, bool)>>>;
const TOKEN: &str = "Bearer t0ken";
/// A site whose pages are only for a logged-in visitor. `/` links to
/// `/secret` and carries a form to itself, one to another site and one to
/// another port of the same host.
async fn fake_site(seen: Seen) -> String {
async fn any(State(seen): State<Seen>, request: Request) -> Response {
let authed = request
.headers()
.get("authorization")
.is_some_and(|v| v == TOKEN);
let path = request.uri().path().to_string();
seen.lock()
.unwrap()
.push((request.method().to_string(), path.clone(), authed));
if !authed {
return StatusCode::UNAUTHORIZED.into_response();
}
match path.as_str() {
"/" => Html(
r#"<html><body>
<a href="/secret">secret</a>
<form action="/search" method="get"><input name="q"></form>
<form action="https://elsewhere.invalid/steal" method="post"><input name="x"></form>
<form action="http://127.0.0.1:1/other" method="post"><input name="y"></form>
</body></html>"#,
)
.into_response(),
"/secret" => Html("<html><body>only for members</body></html>").into_response(),
_ => StatusCode::NOT_FOUND.into_response(),
}
}
let app = Router::new().fallback(any).with_state(seen);
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.unwrap() });
format!("http://{addr}")
}
fn bearer() -> DastAuthConfig {
DastAuthConfig {
method: "bearer".into(),
login_url: None,
username: None,
password: None,
token: Some("t0ken".into()),
headers: None,
}
}
fn target(base: &str, auth: Option<DastAuthConfig>) -> DastTarget {
let mut t = DastTarget::new("site".into(), base.into(), DastTargetType::WebApp);
t.auth_config = auth;
t.max_crawl_depth = 2;
t
}
#[tokio::test]
async fn the_logged_in_crawl_reaches_member_pages_and_keeps_to_the_origin() {
let seen: Seen = Arc::default();
let base = fake_site(seen.clone()).await;
let headers = compliance_dast::auth::login_headers(Some(&bearer())).unwrap();
let http = reqwest::Client::builder()
.default_headers(headers)
.build()
.unwrap();
let endpoints = WebCrawler::new(http, 2, 0).crawl(&base, &[]).await.unwrap();
let urls: Vec<&str> = endpoints.iter().map(|e| e.url.as_str()).collect();
assert!(
urls.contains(&format!("{base}/secret").as_str()),
"{urls:?}"
);
assert!(
urls.contains(&format!("{base}/search").as_str()),
"{urls:?}"
);
assert!(
urls.iter().all(|u| u.starts_with(&base)),
"a form to another site or port is out of scope: {urls:?}"
);
assert!(endpoints.iter().all(|e| !e.requires_auth));
}
#[tokio::test]
async fn a_scan_sends_the_login_except_for_the_strangers_checks() {
let seen: Seen = Arc::default();
let base = fake_site(seen.clone()).await;
let (run, _findings) = DastOrchestrator::new(0, NetGuard::allow_private())
.run_scan(&target(&base, Some(bearer())), Vec::new())
.await
.unwrap();
assert_eq!(
run.status,
DastScanStatus::Completed,
"{:?}",
run.error_message
);
let seen = seen.lock().unwrap();
assert!(
seen.iter().any(|(_, p, authed)| p == "/secret" && *authed),
"the member page was asked for with the login: {seen:?}"
);
// The auth-bypass agent's path probes ask as a stranger.
assert!(
seen.iter()
.filter(|(_, p, _)| p.eq_ignore_ascii_case("/admin"))
.all(|(_, _, authed)| !authed),
"{seen:?}"
);
// Destructive tests are off: no write method reached the site.
assert!(
seen.iter()
.all(|(m, _, _)| !["PUT", "PATCH", "DELETE"].contains(&m.as_str())),
"{seen:?}"
);
}
#[tokio::test]
async fn an_unusable_login_fails_the_scan_before_any_request() {
let seen: Seen = Arc::default();
let base = fake_site(seen.clone()).await;
let mut form = bearer();
form.method = "form".into();
let (run, findings) = DastOrchestrator::new(0, NetGuard::allow_private())
.run_scan(&target(&base, Some(form)), Vec::new())
.await
.unwrap();
assert_eq!(run.status, DastScanStatus::Failed);
assert_eq!(
run.error_message.as_deref(),
Some("Login: form login is not supported yet")
);
assert!(findings.is_empty());
assert!(seen.lock().unwrap().is_empty());
}
+14 -8
View File
@@ -39,15 +39,21 @@ Each target supports these settings:
### Authentication
DAST supports authenticated scanning so it can test pages behind login:
A scan can log in, so it reaches the pages and API routes behind a login. Every request of the crawl and of the tests carries the login. The exception is the authentication-bypass checks, which ask as a stranger on purpose.
| Method | Description |
|--------|------------|
| **None** | No authentication |
| **Basic** | HTTP Basic Auth with username and password |
| **Bearer** | Bearer token in the Authorization header |
| **Cookie** | Session cookie value |
| **Form** | Login form with URL, field names, and credentials |
| Method | What is sent | Fields |
|--------|--------------|--------|
| **None** | nothing | – |
| **Basic** | `Authorization: Basic …` | `username`, `password` |
| **Bearer** | `Authorization: Bearer …` | `token` |
| **Cookie** | `Cookie: …` | `token` (e.g. `session=abc123`) |
| **Form** | not available yet: logging in through a login page (incl. Keycloak) is the next step | – |
Every method can add extra headers (`headers`, e.g. an API key). The password, the token and the header values are stored encrypted and never returned by the API.
A login that cannot be sent fails the scan with the reason ("Login: …"); the scan never runs without the login instead. Through the API, the login goes in the `auth` block of `POST /api/v1/dast/targets`, and the answer returns the new target with its id.
The scan stays on the target's origin (scheme, host and port): links and forms that lead elsewhere are not followed. Write requests (`PUT`, `PATCH`, `DELETE`) are sent only when **Destructive Tests** is on.
::: warning
Authenticated scans access more of the application surface. Only test applications you own or have explicit authorization to test.