use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
use std::path::PathBuf;
use std::time::Duration;
use uuid::Uuid;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
Info,
Low,
Medium,
High,
Critical,
}
impl Severity {
pub fn score(&self) -> u8 {
match self {
Severity::Info => 0,
Severity::Low => 1,
Severity::Medium => 2,
Severity::High => 3,
Severity::Critical => 4,
}
}
}
impl std::fmt::Display for Severity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Severity::Info => write!(f, "info"),
Severity::Low => write!(f, "low"),
Severity::Medium => write!(f, "medium"),
Severity::High => write!(f, "high"),
Severity::Critical => write!(f, "critical"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TemplateLanguage {
Yaml,
Python,
Rust,
Shell,
JavaScript,
C,
Cpp,
Java,
Go,
Ruby,
Perl,
Php,
}
impl std::fmt::Display for TemplateLanguage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TemplateLanguage::Yaml => write!(f, "yaml"),
TemplateLanguage::Python => write!(f, "python"),
TemplateLanguage::Rust => write!(f, "rust"),
TemplateLanguage::Shell => write!(f, "shell"),
TemplateLanguage::JavaScript => write!(f, "javascript"),
TemplateLanguage::C => write!(f, "c"),
TemplateLanguage::Cpp => write!(f, "cpp"),
TemplateLanguage::Java => write!(f, "java"),
TemplateLanguage::Go => write!(f, "go"),
TemplateLanguage::Ruby => write!(f, "ruby"),
TemplateLanguage::Perl => write!(f, "perl"),
TemplateLanguage::Php => write!(f, "php"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Protocol {
Http,
Https,
Tcp,
Udp,
Dns,
Ssh,
Ftp,
Smtp,
Smb,
Rdp,
Custom(String),
}
impl std::fmt::Display for Protocol {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Protocol::Http => write!(f, "http"),
Protocol::Https => write!(f, "https"),
Protocol::Tcp => write!(f, "tcp"),
Protocol::Udp => write!(f, "udp"),
Protocol::Dns => write!(f, "dns"),
Protocol::Ssh => write!(f, "ssh"),
Protocol::Ftp => write!(f, "ftp"),
Protocol::Smtp => write!(f, "smtp"),
Protocol::Smb => write!(f, "smb"),
Protocol::Rdp => write!(f, "rdp"),
Protocol::Custom(name) => write!(f, "{}", name),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Target {
pub id: Uuid,
pub address: String,
pub port: Option<u16>,
pub protocol: Protocol,
pub metadata: HashMap<String, String>,
}
impl Target {
pub fn new<S: Into<String>>(address: S, protocol: Protocol) -> Self {
Self {
id: Uuid::new_v4(),
address: address.into(),
port: None,
protocol,
metadata: HashMap::new(),
}
}
pub fn with_port<S: Into<String>>(address: S, port: u16, protocol: Protocol) -> Self {
Self {
id: Uuid::new_v4(),
address: address.into(),
port: Some(port),
protocol,
metadata: HashMap::new(),
}
}
pub fn url(&self) -> String {
match &self.protocol {
Protocol::Http | Protocol::Https => {
let scheme = if self.protocol == Protocol::Https {
"https"
} else {
"http"
};
if let Some(port) = self.port {
format!("{}://{}:{}", scheme, self.address, port)
} else {
format!("{}://{}", scheme, self.address)
}
}
_ => {
if let Some(port) = self.port {
format!("{}:{}", self.address, port)
} else {
self.address.clone()
}
}
}
}
pub fn socket_addr(&self) -> Option<SocketAddr> {
if let Ok(ip) = self.address.parse::<IpAddr>() {
Some(SocketAddr::new(ip, self.port.unwrap_or(0)))
} else {
None
}
}
pub fn with_both_schemes(&self) -> Vec<Target> {
if matches!(self.protocol, Protocol::Http | Protocol::Https) {
vec![
Target {
protocol: Protocol::Http,
..self.clone()
},
Target {
protocol: Protocol::Https,
..self.clone()
},
]
} else {
vec![self.clone()]
}
}
pub fn infer_scheme(&self) -> Protocol {
match self.port {
Some(443) | Some(8443) => Protocol::Https,
Some(80) | Some(8080) | Some(8000) => Protocol::Http,
_ => self.protocol.clone(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Context {
pub scan_id: Uuid,
pub aggressive_mode: bool,
pub stealth_mode: bool,
pub passive_mode: bool,
pub safe_mode: bool,
pub max_retries: u32,
pub timeout: Duration,
pub variables: HashMap<String, String>,
pub rate_limit: Option<u32>,
pub additional_ports: Vec<u16>,
pub override_ports: Option<Vec<u16>>,
#[serde(default)]
pub headers: Vec<(String, String)>,
#[serde(default)]
pub cookies: Vec<(String, String)>,
}
impl Default for Context {
fn default() -> Self {
Self {
scan_id: Uuid::new_v4(),
aggressive_mode: false,
stealth_mode: false,
passive_mode: false,
safe_mode: false,
max_retries: 1,
timeout: Duration::from_secs(30),
variables: HashMap::new(),
rate_limit: None,
additional_ports: Vec::new(),
override_ports: None,
headers: Vec::new(),
cookies: Vec::new(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Evidence {
pub request: Option<String>,
pub response: Option<String>,
pub matched_patterns: Vec<String>,
pub data: HashMap<String, serde_json::Value>,
pub timestamp: DateTime<Utc>,
}
impl Evidence {
pub fn new() -> Self {
Self {
request: None,
response: None,
matched_patterns: Vec::new(),
data: HashMap::new(),
timestamp: Utc::now(),
}
}
pub fn add_match(&mut self, pattern: String) {
self.matched_patterns.push(pattern);
}
pub fn add_data<K: Into<String>>(&mut self, key: K, value: serde_json::Value) {
self.data.insert(key.into(), value);
}
}
impl Default for Evidence {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Finding {
pub id: Uuid,
pub target: String,
pub template_id: String,
pub severity: Severity,
pub confidence: u8,
pub title: String,
pub description: String,
pub evidence: Evidence,
pub cve_ids: Vec<String>,
pub cwe_ids: Vec<String>,
pub cvss_score: Option<f32>,
pub remediation: Option<String>,
pub references: Vec<String>,
pub tags: Vec<String>,
pub timestamp: DateTime<Utc>,
}
impl Finding {
pub fn new<S: Into<String>>(
target: S,
template_id: S,
severity: Severity,
title: S,
description: S,
) -> Self {
Self {
id: Uuid::new_v4(),
target: target.into(),
template_id: template_id.into(),
severity,
confidence: 90,
title: title.into(),
description: description.into(),
evidence: Evidence::new(),
cve_ids: Vec::new(),
cwe_ids: Vec::new(),
cvss_score: None,
remediation: None,
references: Vec::new(),
tags: Vec::new(),
timestamp: Utc::now(),
}
}
pub fn with_confidence(mut self, confidence: u8) -> Self {
self.confidence = confidence.min(100);
self
}
pub fn with_evidence(mut self, evidence: Evidence) -> Self {
self.evidence = evidence;
self
}
pub fn add_cve<S: Into<String>>(mut self, cve_id: S) -> Self {
self.cve_ids.push(cve_id.into());
self
}
pub fn add_cwe<S: Into<String>>(mut self, cwe_id: S) -> Self {
self.cwe_ids.push(cwe_id.into());
self
}
pub fn with_cvss_score(mut self, score: f32) -> Self {
self.cvss_score = Some(score);
self
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ScanStatistics {
pub targets_scanned: usize,
pub templates_executed: usize,
pub findings_by_severity: HashMap<Severity, usize>,
pub network_requests: usize,
pub data_transferred: u64,
pub duration: Duration,
pub success_rate: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScanResults {
pub scan_id: Uuid,
pub started_at: DateTime<Utc>,
pub completed_at: Option<DateTime<Utc>>,
pub findings: Vec<Finding>,
pub statistics: ScanStatistics,
pub errors: Vec<String>,
}
impl ScanResults {
pub fn new(scan_id: Uuid) -> Self {
Self {
scan_id,
started_at: Utc::now(),
completed_at: None,
findings: Vec::new(),
statistics: ScanStatistics::default(),
errors: Vec::new(),
}
}
pub fn add_finding(&mut self, finding: Finding) {
*self
.statistics
.findings_by_severity
.entry(finding.severity)
.or_insert(0) += 1;
self.findings.push(finding);
}
pub fn complete(&mut self) {
self.completed_at = Some(Utc::now());
if let Some(completed) = self.completed_at {
self.statistics.duration = (completed - self.started_at)
.to_std()
.unwrap_or(Duration::from_secs(0));
}
}
pub fn critical_findings(&self) -> Vec<&Finding> {
self.findings
.iter()
.filter(|f| f.severity == Severity::Critical)
.collect()
}
pub fn high_findings(&self) -> Vec<&Finding> {
self.findings
.iter()
.filter(|f| f.severity == Severity::High)
.collect()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemplateMetadata {
pub id: String,
pub name: String,
pub author: AuthorInfo,
pub severity: Severity,
pub description: String,
#[serde(default)]
pub cve_ids: Vec<String>,
#[serde(default)]
pub cwe_ids: Vec<String>,
pub cvss_score: Option<f32>,
#[serde(default)]
pub tags: Vec<String>,
pub language: TemplateLanguage,
#[serde(default)]
pub file_path: PathBuf,
#[serde(default = "default_datetime")]
pub created: DateTime<Utc>,
#[serde(default = "default_datetime")]
pub updated: DateTime<Utc>,
#[serde(default = "default_version")]
pub version: String,
pub confidence: Option<u8>,
#[serde(default)]
pub context_vars: Vec<String>,
#[serde(default)]
pub vuln_class: Option<String>,
#[serde(default)]
pub hypothesis_tags: Vec<String>,
#[serde(default)]
pub batch_group: Option<String>,
#[serde(default)]
pub auto_probe: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthorInfo {
pub name: String,
pub email: Option<String>,
pub github: Option<String>,
}
fn default_datetime() -> DateTime<Utc> {
Utc::now()
}
fn default_version() -> String {
"1.0".to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_severity_ordering() {
assert!(Severity::Critical > Severity::High);
assert!(Severity::High > Severity::Medium);
assert!(Severity::Medium > Severity::Low);
assert!(Severity::Low > Severity::Info);
}
#[test]
fn test_target_url() {
let target = Target::with_port("example.com", 443, Protocol::Https);
assert_eq!(target.url(), "https://example.com:443");
let target = Target::new("example.com", Protocol::Http);
assert_eq!(target.url(), "http://example.com");
}
#[test]
fn test_finding_creation() {
let finding = Finding::new(
"192.168.1.1",
"CVE-2024-1234",
Severity::Critical,
"Test Finding",
"Test description",
);
assert_eq!(finding.severity, Severity::Critical);
assert_eq!(finding.confidence, 90);
}
}