use clap::ValueEnum;
use std::collections::HashSet;
use std::fmt::Write;
use url::Url;
use crate::models::ScanReport;
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum ServerKind {
Nginx,
Caddy,
Apache,
}
impl ServerKind {
pub fn name(self) -> &'static str {
match self {
ServerKind::Nginx => "Nginx",
ServerKind::Caddy => "Caddy",
ServerKind::Apache => "Apache",
}
}
}
pub fn generate_server_snippet(report: &ScanReport, server: ServerKind) -> String {
let ids: HashSet<&str> = report.findings.iter().map(|f| f.id.as_str()).collect();
let host = Url::parse(&report.final_url)
.ok()
.and_then(|u| u.host_str().map(|s| s.to_string()))
.unwrap_or_else(|| "example.com".to_string());
let need_https = ids.contains("TLS-NO-HTTPS") || ids.contains("TLS-HTTP-NO-REDIRECT");
let need_hsts = ids.contains("HDR-HSTS-MISSING")
|| ids.contains("HDR-HSTS-SHORT")
|| ids.contains("HDR-HSTS-NO-SUBDOMAINS");
let need_csp = ids.contains("HDR-CSP-MISSING") || ids.contains("HDR-CSP-WEAK");
let need_xfo = ids.contains("HDR-XFO-MISSING") || ids.contains("HDR-XFO-INVALID");
let need_xcto = ids.contains("HDR-XCTO-MISSING");
let need_ref = ids.contains("HDR-REFERRER-MISSING") || ids.contains("HDR-REFERRER-UNSAFE");
let need_perm = ids.contains("HDR-PERMISSIONS-MISSING");
let need_coop = ids.contains("HDR-COOP-INFO");
let need_corp = ids.contains("HDR-CORP-INFO");
let need_server_tokens = ids.contains("INFO-SERVER-VERSION");
let need_xpb = ids.contains("INFO-X-POWERED-BY");
let need_dotfiles = ids.iter().any(|id| {
id.starts_with("EXP-GIT")
|| id.starts_with("EXP-SVN")
|| id.starts_with("EXP-HG")
|| id.starts_with("EXP-ENV")
|| *id == "EXP-DS-STORE"
});
let need_no_autoindex = ids.iter().any(|id| id.starts_with("EXP-DIR-LISTING"));
let need_no_trace = ids.contains("HTTP-TRACE-ENABLED");
let mut out = String::new();
match server {
ServerKind::Nginx => {
let _ = writeln!(out, "# Nginx security hardening for {host}");
if need_https {
let _ = writeln!(
out,
"server {{\n listen 80;\n server_name {host};\n return 301 https://$host$request_uri;\n}}\n"
);
}
let _ = writeln!(out, "server {{");
if need_server_tokens {
let _ = writeln!(out, " server_tokens off;");
}
if need_xpb {
let _ = writeln!(out, " proxy_hide_header X-Powered-By;");
}
if need_hsts {
let _ = writeln!(out, " add_header Strict-Transport-Security \"max-age=31536000; includeSubDomains\" always;");
}
if need_csp {
let _ = writeln!(out, " add_header Content-Security-Policy \"default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'\" always;");
}
if need_xfo {
let _ = writeln!(out, " add_header X-Frame-Options \"SAMEORIGIN\" always;");
}
if need_xcto {
let _ = writeln!(
out,
" add_header X-Content-Type-Options \"nosniff\" always;"
);
}
if need_ref {
let _ = writeln!(
out,
" add_header Referrer-Policy \"strict-origin-when-cross-origin\" always;"
);
}
if need_perm {
let _ = writeln!(out, " add_header Permissions-Policy \"camera=(), microphone=(), geolocation=()\" always;");
}
if need_coop {
let _ = writeln!(
out,
" add_header Cross-Origin-Opener-Policy \"same-origin\" always;"
);
}
if need_corp {
let _ = writeln!(
out,
" add_header Cross-Origin-Resource-Policy \"same-origin\" always;"
);
}
if need_no_autoindex {
let _ = writeln!(out, " autoindex off;");
}
if need_dotfiles {
let _ = writeln!(out, "\n # Block dotfiles (.git, .env, .svn, .DS_Store)\n location ~ /\\. {{\n deny all;\n return 404;\n }}");
}
let _ = writeln!(out, "}}");
}
ServerKind::Caddy => {
let _ = writeln!(out, "# Caddyfile hardening for {host}");
let _ = writeln!(out, "{host} {{");
let _ = writeln!(out, " header {{");
if need_server_tokens {
let _ = writeln!(out, " -Server");
}
if need_xpb {
let _ = writeln!(out, " -X-Powered-By");
}
if need_hsts {
let _ = writeln!(
out,
" Strict-Transport-Security \"max-age=31536000; includeSubDomains\""
);
}
if need_csp {
let _ = writeln!(out, " Content-Security-Policy \"default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'\"");
}
if need_xfo {
let _ = writeln!(out, " X-Frame-Options \"SAMEORIGIN\"");
}
if need_xcto {
let _ = writeln!(out, " X-Content-Type-Options \"nosniff\"");
}
if need_ref {
let _ = writeln!(
out,
" Referrer-Policy \"strict-origin-when-cross-origin\""
);
}
if need_perm {
let _ = writeln!(
out,
" Permissions-Policy \"camera=(), microphone=(), geolocation=()\""
);
}
if need_coop {
let _ = writeln!(out, " Cross-Origin-Opener-Policy \"same-origin\"");
}
if need_corp {
let _ = writeln!(out, " Cross-Origin-Resource-Policy \"same-origin\"");
}
let _ = writeln!(out, " }}");
if need_dotfiles {
let _ = writeln!(out, "\n @dotfiles path_regexp ^/\\.");
let _ = writeln!(out, " respond @dotfiles 404");
}
let _ = writeln!(out, "}}");
}
ServerKind::Apache => {
let _ = writeln!(
out,
"# Apache (.htaccess / VirtualHost) hardening for {host}"
);
if need_server_tokens {
let _ = writeln!(out, "ServerTokens Prod\nServerSignature Off");
}
if need_no_trace {
let _ = writeln!(out, "TraceEnable off");
}
if need_no_autoindex {
let _ = writeln!(out, "Options -Indexes");
}
if need_https {
let _ = writeln!(
out,
"RewriteEngine On\nRewriteCond %{{HTTPS}} !=on\nRewriteRule ^ https://%{{HTTP_HOST}}%{{REQUEST_URI}} [L,R=301]"
);
}
let _ = writeln!(out, "<IfModule mod_headers.c>");
if need_xpb {
let _ = writeln!(out, " Header always unset X-Powered-By");
}
if need_hsts {
let _ = writeln!(out, " Header always set Strict-Transport-Security \"max-age=31536000; includeSubDomains\"");
}
if need_csp {
let _ = writeln!(out, " Header always set Content-Security-Policy \"default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'\"");
}
if need_xfo {
let _ = writeln!(out, " Header always set X-Frame-Options \"SAMEORIGIN\"");
}
if need_xcto {
let _ = writeln!(
out,
" Header always set X-Content-Type-Options \"nosniff\""
);
}
if need_ref {
let _ = writeln!(
out,
" Header always set Referrer-Policy \"strict-origin-when-cross-origin\""
);
}
if need_perm {
let _ = writeln!(out, " Header always set Permissions-Policy \"camera=(), microphone=(), geolocation=()\"");
}
if need_coop {
let _ = writeln!(
out,
" Header always set Cross-Origin-Opener-Policy \"same-origin\""
);
}
if need_corp {
let _ = writeln!(
out,
" Header always set Cross-Origin-Resource-Policy \"same-origin\""
);
}
let _ = writeln!(out, "</IfModule>");
if need_dotfiles {
let _ = writeln!(
out,
"\n<FilesMatch \"^\\.\">\n Require all denied\n</FilesMatch>"
);
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::{
Category, Confidence, CoverageSummary, ExecutionStatus, Finding, ScanProfile, Severity,
SeverityCounts, SCHEMA_VERSION,
};
#[test]
fn generates_nginx_caddy_apache_for_detected_issues() {
let findings = vec![
Finding {
id: "HDR-CSP-MISSING".into(),
category: Category::SecurityHeaders,
severity: Severity::Medium,
title: String::new(),
summary: String::new(),
evidence: None,
remediation: String::new(),
standard_ref: None,
confidence: Confidence::High,
},
Finding {
id: "EXP-GIT-EXPOSED".into(),
category: Category::ExposedFiles,
severity: Severity::Critical,
title: String::new(),
summary: String::new(),
evidence: None,
remediation: String::new(),
standard_ref: None,
confidence: Confidence::High,
},
Finding {
id: "HTTP-TRACE-ENABLED".into(),
category: Category::HttpProtocol,
severity: Severity::Medium,
title: String::new(),
summary: String::new(),
evidence: None,
remediation: String::new(),
standard_ref: None,
confidence: Confidence::High,
},
];
let report = ScanReport {
schema_version: SCHEMA_VERSION.into(),
engine_version: "0.2.0".into(),
target: "https://mysite.test/".into(),
final_url: "https://mysite.test/".into(),
scanned_at: String::new(),
duration_ms: 5,
status_code: Some(200),
profile: ScanProfile::Web,
auth_context: "anonymous".into(),
run_status: ExecutionStatus::Completed,
cancelled: false,
pages_scanned: 1,
crawled_urls: vec![],
score: 50,
grade: "C".into(),
score_breakdown: vec![],
coverage: CoverageSummary::default(),
outcomes: vec![],
instances: vec![],
tls: None,
counts: SeverityCounts::from_findings(&findings),
findings,
};
let nginx = generate_server_snippet(&report, ServerKind::Nginx);
assert!(nginx.contains("Content-Security-Policy"));
assert!(nginx.contains("deny all;"));
let caddy = generate_server_snippet(&report, ServerKind::Caddy);
assert!(caddy.contains("@dotfiles"));
let apache = generate_server_snippet(&report, ServerKind::Apache);
assert!(apache.contains("TraceEnable off"));
assert!(apache.contains("Require all denied"));
}
}