use crate::types::Severity;
use regex::Regex;
use serde::{Deserialize, Serialize};
#[derive(Debug)]
pub struct CsrfDetector {
#[allow(dead_code)]
token_names: Vec<String>,
patterns: Vec<Regex>,
}
impl CsrfDetector {
pub fn new() -> Self {
let token_names = vec![
"csrf_token".to_string(),
"csrf-token".to_string(),
"_csrf".to_string(),
"csrfToken".to_string(),
"authenticity_token".to_string(),
"_token".to_string(),
"token".to_string(),
"anti-csrf".to_string(),
];
let patterns = vec![
Regex::new(r#"<input[^>]*name\s*=\s*["']([^"']*csrf[^"']*)["'][^>]*>"#).unwrap(),
Regex::new(r#"<input[^>]*name\s*=\s*["'](_token|token)["'][^>]*>"#).unwrap(),
Regex::new(r#"<meta[^>]*name\s*=\s*["']csrf-token["'][^>]*>"#).unwrap(),
];
Self {
token_names,
patterns,
}
}
pub fn detect_tokens(&self, html: &str) -> Vec<CsrfToken> {
let mut tokens = Vec::new();
for pattern in &self.patterns {
for captures in pattern.captures_iter(html) {
if let Some(name_match) = captures.get(1) {
let name = name_match.as_str();
if let Some(value) = self.extract_token_value(html, name) {
tokens.push(CsrfToken {
name: name.to_string(),
value,
location: TokenLocation::HiddenInput,
});
}
}
}
}
if let Some(meta_token) = self.extract_meta_token(html) {
tokens.push(meta_token);
}
if let Some(js_token) = self.extract_js_token(html) {
tokens.push(js_token);
}
tokens
}
fn extract_token_value(&self, html: &str, name: &str) -> Option<String> {
let pattern = format!(r#"name\s*=\s*["']{name}["'][^>]*value\s*=\s*["']([^"']*)["']"#);
if let Ok(re) = Regex::new(&pattern) {
if let Some(captures) = re.captures(html) {
return captures.get(1).map(|m| m.as_str().to_string());
}
}
None
}
fn extract_meta_token(&self, html: &str) -> Option<CsrfToken> {
let re = Regex::new(
r#"<meta[^>]*name\s*=\s*["']csrf-token["'][^>]*content\s*=\s*["']([^"']*)["'][^>]*>"#,
)
.ok()?;
re.captures(html).and_then(|cap| {
cap.get(1).map(|m| CsrfToken {
name: "csrf-token".to_string(),
value: m.as_str().to_string(),
location: TokenLocation::MetaTag,
})
})
}
fn extract_js_token(&self, html: &str) -> Option<CsrfToken> {
let re = Regex::new(r#"csrf[Tt]oken\s*[:=]\s*["']([^"']{20,})["']"#).ok()?;
re.captures(html).and_then(|cap| {
cap.get(1).map(|m| CsrfToken {
name: "csrfToken".to_string(),
value: m.as_str().to_string(),
location: TokenLocation::JavaScript,
})
})
}
pub fn analyze_forms(&self, html: &str) -> Vec<CsrfFinding> {
let mut findings = Vec::new();
let form_re = Regex::new(r#"<form[^>]*>([\s\S]*?)</form>"#).unwrap();
for form_match in form_re.captures_iter(html) {
let form_html = form_match.get(1).map(|m| m.as_str()).unwrap_or("");
let has_csrf = !self.detect_tokens(form_html).is_empty();
let is_state_changing = self.is_state_changing_form(&form_match[0]);
if is_state_changing && !has_csrf {
findings.push(CsrfFinding {
severity: Severity::High,
title: "Missing CSRF Token in Form".to_string(),
description: "State-changing form lacks CSRF protection".to_string(),
form_action: self.extract_form_action(&form_match[0]),
recommendation: "Add CSRF token to protect against cross-site request forgery"
.to_string(),
});
}
}
findings
}
fn is_state_changing_form(&self, form_html: &str) -> bool {
let method_re = Regex::new(r#"method\s*=\s*["'](POST|PUT|DELETE)["']"#).unwrap();
method_re.is_match(&form_html.to_uppercase())
}
fn extract_form_action(&self, form_html: &str) -> Option<String> {
let action_re = Regex::new(r#"action\s*=\s*["']([^"']*)["']"#).ok()?;
action_re
.captures(form_html)
.and_then(|cap| cap.get(1).map(|m| m.as_str().to_string()))
}
pub fn generate_test_cases(&self, token: &CsrfToken) -> Vec<CsrfTestCase> {
vec![
CsrfTestCase {
name: "Empty Token Test".to_string(),
token_value: "".to_string(),
description: "Test if empty CSRF token is accepted".to_string(),
expected_blocked: true,
},
CsrfTestCase {
name: "Invalid Token Test".to_string(),
token_value: "INVALID_TOKEN_12345".to_string(),
description: "Test if invalid CSRF token is accepted".to_string(),
expected_blocked: true,
},
CsrfTestCase {
name: "Token Reuse Test".to_string(),
token_value: token.value.clone(),
description: "Test if CSRF token can be reused multiple times".to_string(),
expected_blocked: false,
},
CsrfTestCase {
name: "Modified Token Test".to_string(),
token_value: self.modify_token(&token.value),
description: "Test if slightly modified token is accepted".to_string(),
expected_blocked: true,
},
]
}
fn modify_token(&self, token: &str) -> String {
if token.is_empty() {
return "MODIFIED".to_string();
}
let mut chars: Vec<char> = token.chars().collect();
if let Some(first) = chars.first_mut() {
*first = if first.is_uppercase() { 'X' } else { 'x' };
}
chars.into_iter().collect()
}
}
impl Default for CsrfDetector {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CsrfToken {
pub name: String,
pub value: String,
pub location: TokenLocation,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TokenLocation {
HiddenInput,
MetaTag,
JavaScript,
Header,
Cookie,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CsrfFinding {
pub severity: Severity,
pub title: String,
pub description: String,
pub form_action: Option<String>,
pub recommendation: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CsrfTestCase {
pub name: String,
pub token_value: String,
pub description: String,
pub expected_blocked: bool,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_detect_csrf_token() {
let detector = CsrfDetector::new();
let html = r#"
<form method="POST">
<input type="hidden" name="csrf_token" value="abc123xyz" />
<input type="text" name="username" />
</form>
"#;
let tokens = detector.detect_tokens(html);
assert!(!tokens.is_empty());
assert_eq!(tokens[0].name, "csrf_token");
}
#[test]
#[ignore] fn test_missing_csrf_detection() {
let detector = CsrfDetector::new();
let html = r#"
<form method="POST" action="/delete">
<input type="text" name="username" />
</form>
"#;
let findings = detector.analyze_forms(html);
assert!(!findings.is_empty());
assert_eq!(findings[0].severity, Severity::High);
}
}