use reqwest::header::CONTENT_TYPE;
use reqwest::Method;
use tokio::task::JoinSet;
use url::Url;
use crate::models::{
Category, CheckOutcome, Confidence, ExecutionStatus, Finding, Severity, Verdict,
};
use crate::transport::{AuthMode, HttpTransport, TransportError};
#[derive(Clone, Copy)]
enum ProbeKind {
SecurityTxt,
RobotsTxt,
GitHead,
GitConfig,
SvnEntries,
SvnWcDb,
HgRequires,
DotEnv,
DsStore,
PhpInfo,
ServerStatus,
DockerCompose,
PackageJson,
ComposerJson,
OpenApiJson,
SwaggerUi,
DirListing,
}
struct ProbeSpec {
path: &'static str,
kind: ProbeKind,
}
const PROBES: &[ProbeSpec] = &[
ProbeSpec {
path: "/.well-known/security.txt",
kind: ProbeKind::SecurityTxt,
},
ProbeSpec {
path: "/robots.txt",
kind: ProbeKind::RobotsTxt,
},
ProbeSpec {
path: "/.git/HEAD",
kind: ProbeKind::GitHead,
},
ProbeSpec {
path: "/.git/config",
kind: ProbeKind::GitConfig,
},
ProbeSpec {
path: "/.svn/entries",
kind: ProbeKind::SvnEntries,
},
ProbeSpec {
path: "/.svn/wc.db",
kind: ProbeKind::SvnWcDb,
},
ProbeSpec {
path: "/.hg/requires",
kind: ProbeKind::HgRequires,
},
ProbeSpec {
path: "/.env",
kind: ProbeKind::DotEnv,
},
ProbeSpec {
path: "/.env.production",
kind: ProbeKind::DotEnv,
},
ProbeSpec {
path: "/.env.local",
kind: ProbeKind::DotEnv,
},
ProbeSpec {
path: "/.DS_Store",
kind: ProbeKind::DsStore,
},
ProbeSpec {
path: "/phpinfo.php",
kind: ProbeKind::PhpInfo,
},
ProbeSpec {
path: "/server-status",
kind: ProbeKind::ServerStatus,
},
ProbeSpec {
path: "/docker-compose.yml",
kind: ProbeKind::DockerCompose,
},
ProbeSpec {
path: "/compose.yml",
kind: ProbeKind::DockerCompose,
},
ProbeSpec {
path: "/package.json",
kind: ProbeKind::PackageJson,
},
ProbeSpec {
path: "/composer.json",
kind: ProbeKind::ComposerJson,
},
ProbeSpec {
path: "/openapi.json",
kind: ProbeKind::OpenApiJson,
},
ProbeSpec {
path: "/swagger.json",
kind: ProbeKind::OpenApiJson,
},
ProbeSpec {
path: "/swagger-ui.html",
kind: ProbeKind::SwaggerUi,
},
ProbeSpec {
path: "/assets/",
kind: ProbeKind::DirListing,
},
ProbeSpec {
path: "/uploads/",
kind: ProbeKind::DirListing,
},
ProbeSpec {
path: "/static/",
kind: ProbeKind::DirListing,
},
ProbeSpec {
path: "/files/",
kind: ProbeKind::DirListing,
},
];
pub async fn check_exposed_paths(
transport: &std::sync::Arc<HttpTransport>,
base_url: &Url,
auth_context: &str,
) -> (Vec<Finding>, Vec<CheckOutcome>) {
let mut findings = Vec::new();
let mut outcomes = Vec::new();
let mut set = JoinSet::new();
for spec in PROBES {
let Ok(target_url) = transport.resolve_in_scope(base_url, spec.path) else {
continue;
};
let tr = std::sync::Arc::clone(transport);
let kind = spec.kind;
let path = spec.path;
let auth_ctx = auth_context.to_string();
set.spawn(async move {
let loc = tr.redactor.sanitize_url(&target_url);
let resp = match tr
.send(Method::GET, &target_url, AuthMode::Anonymous, &[], Some(65_536))
.await
{
Ok(r) => r,
Err(TransportError::Cancelled) => {
return (
None,
CheckOutcome {
check_id: format!("exposed-probe:{}", path),
category: Category::ExposedFiles,
location: loc,
auth_context: auth_ctx,
status: ExecutionStatus::Cancelled,
verdict: Verdict::Inconclusive,
reason: Some("cancelled".into()),
},
);
}
Err(e) => {
return (
None,
CheckOutcome {
check_id: format!("exposed-probe:{}", path),
category: Category::ExposedFiles,
location: loc,
auth_context: auth_ctx,
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some(e.to_string()),
},
);
}
};
if !(200..300).contains(&resp.status) {
if matches!(kind, ProbeKind::SecurityTxt) {
let f = Finding {
id: "EXP-NO-SECURITY-TXT".into(),
category: Category::ExposedFiles,
severity: Severity::Info,
title: "/.well-known/security.txt not found".into(),
summary: "security.txt (RFC 9116) provides a standard contact channel for security reports.".into(),
evidence: None,
remediation: "Optionally publish /.well-known/security.txt with a Contact: mailto:security@yourdomain entry.".into(),
standard_ref: Some("RFC 9116".into()),
confidence: Confidence::High,
};
return (
Some(f),
CheckOutcome {
check_id: format!("exposed-probe:{}", path),
category: Category::ExposedFiles,
location: loc,
auth_context: auth_ctx,
status: ExecutionStatus::Completed,
verdict: Verdict::Pass,
reason: Some(format!("HTTP {}", resp.status)),
},
);
}
return (
None,
CheckOutcome {
check_id: format!("exposed-probe:{}", path),
category: Category::ExposedFiles,
location: loc,
auth_context: auth_ctx,
status: ExecutionStatus::Completed,
verdict: Verdict::Pass,
reason: Some(format!("HTTP {}", resp.status)),
},
);
}
let content_type = resp
.headers
.get(CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_ascii_lowercase();
let finding = evaluate_probe(kind, path, &target_url, &content_type, &resp.body);
let is_fail = finding
.as_ref()
.map(|f| f.severity != Severity::Pass && f.severity != Severity::Info)
.unwrap_or(false);
(
finding,
CheckOutcome {
check_id: format!("exposed-probe:{}", path),
category: Category::ExposedFiles,
location: loc,
auth_context: auth_ctx,
status: ExecutionStatus::Completed,
verdict: if is_fail { Verdict::Fail } else { Verdict::Pass },
reason: None,
},
)
});
}
while let Some(res) = set.join_next().await {
if let Ok((maybe_finding, outcome)) = res {
if let Some(f) = maybe_finding {
findings.push(f);
}
outcomes.push(outcome);
}
}
(findings, outcomes)
}
fn evaluate_probe(
kind: ProbeKind,
path: &str,
url: &Url,
content_type: &str,
bytes: &[u8],
) -> Option<Finding> {
let text = std::str::from_utf8(bytes).unwrap_or("");
let trimmed_start = text.trim_start();
let is_html = content_type.contains("text/html")
|| trimmed_start.starts_with("<!DOCTYPE")
|| trimmed_start.starts_with("<!doctype")
|| trimmed_start.starts_with("<html");
match kind {
ProbeKind::SecurityTxt => {
if !is_html
&& text
.lines()
.any(|l| l.trim_start().to_ascii_lowercase().starts_with("contact:"))
{
Some(Finding {
id: "EXP-SECURITY-TXT-OK".into(),
category: Category::ExposedFiles,
severity: Severity::Pass,
title: "Valid /.well-known/security.txt found".into(),
summary: "Security contact policy is published per RFC 9116.".into(),
evidence: Some(url.to_string()),
remediation: String::new(),
standard_ref: Some("RFC 9116".into()),
confidence: Confidence::High,
})
} else {
None
}
}
ProbeKind::RobotsTxt => {
let lower = text.to_ascii_lowercase();
if !is_html && (lower.contains("user-agent:") || lower.contains("disallow:")) {
let sensitive_disallow: Vec<String> = text
.lines()
.filter_map(|l| {
let lt = l.trim();
if lt.to_ascii_lowercase().starts_with("disallow:") {
let val = lt[9..].trim().to_string();
let lv = val.to_ascii_lowercase();
if [
"/admin",
"/backup",
"/config",
"/db",
"/internal",
"/.git",
"/private",
]
.iter()
.any(|kw| lv.contains(kw))
{
return Some(val);
}
}
None
})
.take(5)
.collect();
if !sensitive_disallow.is_empty() {
Some(Finding {
id: "EXP-ROBOTS-SENSITIVE-HINTS".into(),
category: Category::ExposedFiles,
severity: Severity::Info,
title: "/robots.txt Disallow rules mention potentially sensitive paths".into(),
summary: "Disallow entries are public hints for crawlers and do not enforce access control.".into(),
evidence: Some(format!("{url} -> {}", sensitive_disallow.join(", "))),
remediation: "Ensure listed routes are protected by server-side authentication and authorization.".into(),
standard_ref: Some("OWASP WSTG-INFO-03".into()),
confidence: Confidence::High,
})
} else {
Some(Finding {
id: "EXP-ROBOTS-TXT".into(),
category: Category::ExposedFiles,
severity: Severity::Info,
title: "/robots.txt is present".into(),
summary: "No obvious sensitive path hints found in Disallow rules.".into(),
evidence: Some(url.to_string()),
remediation: String::new(),
standard_ref: Some("OWASP WSTG-INFO-03".into()),
confidence: Confidence::High,
})
}
} else {
None
}
}
ProbeKind::GitHead => {
let trimmed = text.trim();
let looks_like_git = !is_html
&& (trimmed.starts_with("ref: refs/")
|| (trimmed.len() == 40 && trimmed.chars().all(|c| c.is_ascii_hexdigit())));
if looks_like_git {
Some(Finding {
id: "EXP-GIT-EXPOSED".into(),
category: Category::ExposedFiles,
severity: Severity::Critical,
title: "Publicly exposed .git repository (/.git/HEAD)".into(),
summary: "An exposed .git directory allows anyone to reconstruct source code and commit history.".into(),
evidence: Some(format!("{url} -> {trimmed}")),
remediation: "Block access to dotfiles in your web server (e.g., `location ~ /\\. { deny all; }` in Nginx).".into(),
standard_ref: Some("OWASP ASVS V14.3 / WSTG-CONF-04".into()),
confidence: Confidence::High,
})
} else {
None
}
}
ProbeKind::GitConfig => {
if !is_html
&& text.contains("[core]")
&& (text.contains("repositoryformatversion") || text.contains("[remote"))
{
Some(Finding {
id: "EXP-GIT-CONFIG".into(),
category: Category::ExposedFiles,
severity: Severity::Critical,
title: "Publicly exposed /.git/config".into(),
summary:
".git/config may disclose repository remotes and embedded credentials."
.into(),
evidence: Some(url.to_string()),
remediation: "Deny access to /.git/ in web server configuration.".into(),
standard_ref: Some("OWASP ASVS V14.3 / WSTG-CONF-04".into()),
confidence: Confidence::High,
})
} else {
None
}
}
ProbeKind::SvnEntries => {
if !is_html
&& (text.contains("svn://")
|| text.starts_with("10\n")
|| text.starts_with("12\n")
|| text.contains("dir\n"))
{
Some(Finding {
id: "EXP-SVN-EXPOSED".into(),
category: Category::ExposedFiles,
severity: Severity::Critical,
title: "Exposed Subversion metadata (/.svn/entries)".into(),
summary:
"An exposed .svn directory can leak repository layout and source files."
.into(),
evidence: Some(url.to_string()),
remediation: "Block /.svn/ in web server rules.".into(),
standard_ref: Some("OWASP WSTG-CONF-04".into()),
confidence: Confidence::High,
})
} else {
None
}
}
ProbeKind::SvnWcDb => {
if bytes.starts_with(b"SQLite format 3\0") {
Some(Finding {
id: "EXP-SVN-WC-DB".into(),
category: Category::ExposedFiles,
severity: Severity::Critical,
title: "Exposed Subversion database (/.svn/wc.db)".into(),
summary: "wc.db contains the working copy file index of the repository.".into(),
evidence: Some(url.to_string()),
remediation: "Block access to dotfiles on the web server.".into(),
standard_ref: Some("OWASP WSTG-CONF-04".into()),
confidence: Confidence::High,
})
} else {
None
}
}
ProbeKind::HgRequires => {
if !is_html && text.contains("revlogv1") {
Some(Finding {
id: "EXP-HG-EXPOSED".into(),
category: Category::ExposedFiles,
severity: Severity::Critical,
title: "Exposed Mercurial repository (/.hg/requires)".into(),
summary: "An exposed .hg directory may allow source code disclosure.".into(),
evidence: Some(url.to_string()),
remediation: "Block /.hg/ in web server configuration.".into(),
standard_ref: Some("OWASP WSTG-CONF-04".into()),
confidence: Confidence::High,
})
} else {
None
}
}
ProbeKind::DotEnv => {
if !is_html && looks_like_env_file(text) {
Some(Finding {
id: format!("EXP-ENV-{}", path.trim_start_matches('/').replace('.', "_").to_ascii_uppercase()),
category: Category::ExposedFiles,
severity: Severity::Critical,
title: format!("Publicly exposed configuration file {path}"),
summary: ".env files commonly store database credentials, API keys, and application secrets.".into(),
evidence: Some(url.to_string()),
remediation: "Block access immediately, move the file outside webroot, and rotate any exposed secrets.".into(),
standard_ref: Some("OWASP ASVS V14.3 / WSTG-CONF-05".into()),
confidence: Confidence::High,
})
} else {
None
}
}
ProbeKind::DsStore => {
if bytes.len() >= 8 && &bytes[..8] == b"\x00\x00\x00\x01Bud1" {
Some(Finding {
id: "EXP-DS-STORE".into(),
category: Category::ExposedFiles,
severity: Severity::Low,
title: "Publicly exposed /.DS_Store metadata file".into(),
summary: "macOS .DS_Store files can leak directory and file names.".into(),
evidence: Some(url.to_string()),
remediation:
"Exclude .DS_Store from deployments and block dotfiles on the web server."
.into(),
standard_ref: Some("OWASP WSTG-CONF-05".into()),
confidence: Confidence::High,
})
} else {
None
}
}
ProbeKind::PhpInfo => {
if text.contains("PHP Version") && text.contains("phpinfo()") {
Some(Finding {
id: "EXP-PHPINFO".into(),
category: Category::ExposedFiles,
severity: Severity::High,
title: "Debug page phpinfo.php is exposed".into(),
summary: "phpinfo() reveals environment variables, PHP modules, and server filesystem paths.".into(),
evidence: Some(url.to_string()),
remediation: "Remove phpinfo.php from production servers.".into(),
standard_ref: Some("OWASP ASVS V14.3 / WSTG-INFO-08".into()),
confidence: Confidence::High,
})
} else {
None
}
}
ProbeKind::ServerStatus => {
if text.contains("Apache Server Status") {
Some(Finding {
id: "EXP-SERVER-STATUS".into(),
category: Category::ExposedFiles,
severity: Severity::Medium,
title: format!("Server status page {path} is publicly accessible"),
summary: "The server-status page exposes active requests, client IPs, and internal URLs.".into(),
evidence: Some(url.to_string()),
remediation: "Restrict /server-status to localhost or internal management IPs.".into(),
standard_ref: Some("OWASP WSTG-CONF-05".into()),
confidence: Confidence::High,
})
} else {
None
}
}
ProbeKind::DockerCompose => {
if !is_html
&& text.contains("services:")
&& (text.contains("image:") || text.contains("build:") || text.contains("ports:"))
{
Some(Finding {
id: "EXP-DOCKER-COMPOSE".into(),
category: Category::ExposedFiles,
severity: Severity::High,
title: format!("Publicly exposed {path} infrastructure file"),
summary: "Docker Compose manifests reveal service topology, internal ports, and often environment variables.".into(),
evidence: Some(url.to_string()),
remediation: "Move compose manifests outside the public webroot.".into(),
standard_ref: Some("OWASP ASVS V14.3 / WSTG-CONF-05".into()),
confidence: Confidence::High,
})
} else {
None
}
}
ProbeKind::PackageJson => {
if !is_html {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(text) {
if val.get("name").is_some()
&& (val.get("dependencies").is_some()
|| val.get("devDependencies").is_some()
|| val.get("scripts").is_some())
{
return Some(Finding {
id: "EXP-PACKAGE-JSON".into(),
category: Category::ExposedFiles,
severity: Severity::Low,
title: "Publicly exposed /package.json".into(),
summary:
"Discloses exact Node.js / frontend dependency names and versions."
.into(),
evidence: Some(url.to_string()),
remediation: "Exclude package.json from the public static webroot."
.into(),
standard_ref: Some("OWASP WSTG-CONF-05".into()),
confidence: Confidence::High,
});
}
}
}
None
}
ProbeKind::ComposerJson => {
if !is_html {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(text) {
if val.get("require").is_some() || val.get("require-dev").is_some() {
return Some(Finding {
id: "EXP-COMPOSER-JSON".into(),
category: Category::ExposedFiles,
severity: Severity::Low,
title: "Publicly exposed /composer.json".into(),
summary:
"Discloses PHP runtime constraints and backend library versions."
.into(),
evidence: Some(url.to_string()),
remediation:
"Serve from `public/` and block direct access to composer.json."
.into(),
standard_ref: Some("OWASP WSTG-CONF-05".into()),
confidence: Confidence::High,
});
}
}
}
None
}
ProbeKind::OpenApiJson => {
if !is_html {
if let Ok(val) = serde_json::from_str::<serde_json::Value>(text) {
if val.get("openapi").is_some() || val.get("swagger").is_some() {
return Some(Finding {
id: "EXP-OPENAPI-PUBLIC".into(),
category: Category::ExposedFiles,
severity: Severity::Info,
title: format!("OpenAPI/Swagger specification is publicly accessible ({path})"),
summary: "Normal for public APIs; for private/internal APIs, restrict specification access.".into(),
evidence: Some(url.to_string()),
remediation: "Restrict Swagger/OpenAPI endpoints in production unless intentionally public.".into(),
standard_ref: Some("OWASP WSTG-INFO".into()),
confidence: Confidence::High,
});
}
}
}
None
}
ProbeKind::SwaggerUi => {
if text.contains("SwaggerUIBundle") || text.contains("swagger-ui") {
Some(Finding {
id: "EXP-SWAGGER-UI".into(),
category: Category::ExposedFiles,
severity: Severity::Info,
title: "Swagger UI is publicly accessible".into(),
summary: "Verify interactive API documentation is intentionally public.".into(),
evidence: Some(url.to_string()),
remediation: "Disable or protect Swagger UI in production if not intended for public use.".into(),
standard_ref: Some("OWASP WSTG-INFO".into()),
confidence: Confidence::Medium,
})
} else {
None
}
}
ProbeKind::DirListing => {
if text.contains("<title>Index of /") || text.contains("<h1>Index of /") {
Some(Finding {
id: format!("EXP-DIR-LISTING-{}", path.trim_matches('/').to_ascii_uppercase()),
category: Category::ExposedFiles,
severity: Severity::Medium,
title: format!("Directory listing enabled at {path}"),
summary: "Directory indexing exposes file inventories and potentially forgotten assets.".into(),
evidence: Some(url.to_string()),
remediation: "Disable directory indexing (`autoindex off;` in Nginx or `Options -Indexes` in Apache).".into(),
standard_ref: Some("OWASP ASVS V14.3 / WSTG-CONF-04".into()),
confidence: Confidence::High,
})
} else {
None
}
}
}
}
fn looks_like_env_file(text: &str) -> bool {
let mut kv_lines = 0usize;
for line in text.lines().take(40) {
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
if let Some((k, _)) = trimmed.split_once('=') {
let key = k.trim();
if !key.is_empty()
&& key.len() <= 64
&& key
.chars()
.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
{
kv_lines += 1;
}
}
}
kv_lines >= 2
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn env_signature_rejects_html_and_accepts_dotenv() {
assert!(looks_like_env_file(
"APP_ENV=production\nDB_HOST=127.0.0.1\n"
));
assert!(!looks_like_env_file(
"<html><body>hello=world</body></html>"
));
}
#[test]
fn git_head_rejects_spa_html_fallback() {
let url = Url::parse("https://example.test/.git/HEAD").unwrap();
let spa_html = b"<!DOCTYPE html><html><body>ref: refs/heads/main</body></html>";
assert!(evaluate_probe(
ProbeKind::GitHead,
"/.git/HEAD",
&url,
"text/html",
spa_html
)
.is_none());
let real_git = b"ref: refs/heads/main\n";
let f = evaluate_probe(
ProbeKind::GitHead,
"/.git/HEAD",
&url,
"text/plain",
real_git,
);
assert!(f.is_some());
assert_eq!(f.unwrap().severity, Severity::Critical);
}
#[test]
fn detects_directory_listing_and_package_json() {
let dir_url = Url::parse("https://example.test/uploads/").unwrap();
let dir_body = b"<html><head><title>Index of /uploads/</title></head><body></body></html>";
let df = evaluate_probe(
ProbeKind::DirListing,
"/uploads/",
&dir_url,
"text/html",
dir_body,
);
assert!(df.is_some());
assert_eq!(df.unwrap().severity, Severity::Medium);
let pkg_url = Url::parse("https://example.test/package.json").unwrap();
let pkg_body = br#"{"name":"my-app","dependencies":{"react":"18.2.0"}}"#;
let pf = evaluate_probe(
ProbeKind::PackageJson,
"/package.json",
&pkg_url,
"application/json",
pkg_body,
);
assert!(pf.is_some());
assert_eq!(pf.unwrap().id, "EXP-PACKAGE-JSON");
}
}