use std::net::IpAddr;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum SsrfError {
#[error("URL exceeds maximum length of {max} characters (actual: {actual})")]
UrlTooLong {
max: usize,
actual: usize,
},
#[error("Invalid URL '{url}': {reason}")]
InvalidUrl {
url: String,
reason: String,
},
#[error("Invalid URL scheme '{scheme}'. Only http and https are allowed")]
InvalidScheme {
scheme: String,
},
#[error("URL is missing host component: {url}")]
MissingHost {
url: String,
},
#[error("Hostname '{hostname}' is blocked")]
BlockedHostname {
hostname: String,
},
#[error("DNS resolution failed for '{hostname}': {reason}")]
DnsResolutionFailed {
hostname: String,
reason: String,
},
#[error("No IP addresses resolved for hostname '{hostname}'")]
NoIpResolved {
hostname: String,
},
#[error("DNS rebinding attack detected: hostname '{hostname}' resolved to mixed private/public IPs: {ips:?}")]
DnsRebindingDetected {
hostname: String,
ips: Vec<String>,
},
#[error("Private IP access is not allowed: {ip}")]
PrivateIpAccess {
ip: String,
},
#[error("Redirect to internal URL is not allowed: {url}")]
RedirectToInternal {
url: String,
},
#[error("Maximum redirect limit ({limit}) exceeded")]
MaxRedirectsExceeded {
limit: u8,
},
#[error(
"TOCTOU attack detected: connection IP {actual} does not match validated IP {expected}"
)]
ToctouAttack {
expected: IpAddr,
actual: IpAddr,
},
#[error("Domain '{domain}' is in blacklist")]
DomainBlacklisted {
domain: String,
},
#[error("Port {port} is not allowed")]
PortNotAllowed {
port: u16,
},
#[error("SSRF validation error: {0}")]
ValidationFailed(String),
}
impl SsrfError {
pub fn kind(&self) -> &'static str {
match self {
Self::UrlTooLong { .. } => "url_too_long",
Self::InvalidUrl { .. } => "invalid_url",
Self::InvalidScheme { .. } => "invalid_scheme",
Self::MissingHost { .. } => "missing_host",
Self::BlockedHostname { .. } => "blocked_hostname",
Self::DnsResolutionFailed { .. } => "dns_resolution_failed",
Self::NoIpResolved { .. } => "no_ip_resolved",
Self::DnsRebindingDetected { .. } => "dns_rebinding",
Self::PrivateIpAccess { .. } => "private_ip_access",
Self::RedirectToInternal { .. } => "redirect_to_internal",
Self::MaxRedirectsExceeded { .. } => "max_redirects_exceeded",
Self::ToctouAttack { .. } => "toctou_attack",
Self::DomainBlacklisted { .. } => "domain_blacklisted",
Self::PortNotAllowed { .. } => "port_not_allowed",
Self::ValidationFailed(_) => "validation_failed",
}
}
pub fn is_attack(&self) -> bool {
matches!(
self,
Self::DnsRebindingDetected { .. }
| Self::ToctouAttack { .. }
| Self::RedirectToInternal { .. }
)
}
pub fn is_retryable(&self) -> bool {
matches!(
self,
Self::DnsResolutionFailed { .. } | Self::NoIpResolved { .. }
)
}
pub fn severity(&self) -> &'static str {
match self {
Self::DnsRebindingDetected { .. }
| Self::ToctouAttack { .. }
| Self::RedirectToInternal { .. } => "critical",
Self::BlockedHostname { .. }
| Self::PrivateIpAccess { .. }
| Self::InvalidScheme { .. } => "high",
Self::InvalidUrl { .. } | Self::MissingHost { .. } | Self::DomainBlacklisted { .. } => {
"medium"
}
_ => "low",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_attack() {
let error = SsrfError::DnsRebindingDetected {
hostname: "evil.com".to_string(),
ips: vec!["10.0.0.1".to_string(), "8.8.8.8".to_string()],
};
assert!(error.is_attack());
let error = SsrfError::PrivateIpAccess {
ip: "10.0.0.1".to_string(),
};
assert!(!error.is_attack());
}
#[test]
fn test_kind_is_sanitized() {
let cases: Vec<(SsrfError, &'static str)> = vec![
(
SsrfError::PrivateIpAccess {
ip: "10.0.0.1".to_string(),
},
"private_ip_access",
),
(
SsrfError::DnsRebindingDetected {
hostname: "internal.corp".to_string(),
ips: vec!["10.0.0.1".to_string()],
},
"dns_rebinding",
),
(
SsrfError::BlockedHostname {
hostname: "localhost".to_string(),
},
"blocked_hostname",
),
(SsrfError::PortNotAllowed { port: 5432 }, "port_not_allowed"),
(
SsrfError::ValidationFailed("http://10.0.0.1 bad".to_string()),
"validation_failed",
),
];
for (error, expected_kind) in cases {
assert_eq!(error.kind(), expected_kind);
assert!(!error.kind().contains("10.0.0.1"));
assert!(!error.kind().contains("localhost"));
assert!(!error.kind().contains("internal.corp"));
}
}
#[test]
fn test_is_retryable() {
let error = SsrfError::DnsResolutionFailed {
hostname: "example.com".to_string(),
reason: "timeout".to_string(),
};
assert!(error.is_retryable());
let error = SsrfError::PrivateIpAccess {
ip: "10.0.0.1".to_string(),
};
assert!(!error.is_retryable());
}
#[test]
fn test_severity() {
let error = SsrfError::DnsRebindingDetected {
hostname: "evil.com".to_string(),
ips: vec![],
};
assert_eq!(error.severity(), "critical");
let error = SsrfError::BlockedHostname {
hostname: "localhost".to_string(),
};
assert_eq!(error.severity(), "high");
let error = SsrfError::InvalidUrl {
url: "invalid".to_string(),
reason: "parse error".to_string(),
};
assert_eq!(error.severity(), "medium");
let error = SsrfError::UrlTooLong {
max: 2048,
actual: 3000,
};
assert_eq!(error.severity(), "low");
}
}