mod error;
mod redirect;
mod static_validator;
mod types;
pub use error::SsrfError;
pub use redirect::{RedirectPolicy, RedirectValidator};
pub use static_validator::is_internal_url;
pub use types::{SsrfConfig, SsrfValidationResult, ValidatedUrl};
use std::net::IpAddr;
use tokio::net::lookup_host;
use url::Url;
use crate::infrastructure::dns::DnsCacheService;
use std::sync::Arc;
pub fn is_private_ip(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(ipv4) => is_private_ipv4(ipv4),
IpAddr::V6(ipv6) => is_private_ipv6(ipv6),
}
}
fn is_private_ipv4(ipv4: std::net::Ipv4Addr) -> bool {
let octets = ipv4.octets();
octets[0] == 10
|| (octets[0] == 172 && (16..=31).contains(&octets[1]))
|| (octets[0] == 192 && octets[1] == 168)
|| ipv4.is_loopback()
|| ipv4.is_link_local()
|| (224..=239).contains(&octets[0])
|| (octets[0] == 100 && (64..=127).contains(&octets[1]))
|| octets[0] == 0
|| (octets[0] == 255 && octets[1] == 255 && octets[2] == 255 && octets[3] == 255)
}
fn is_private_ipv6(ipv6: std::net::Ipv6Addr) -> bool {
let segs = ipv6.segments();
ipv6.is_loopback()
|| (segs[0] & 0xfe00) == 0xfc00 || (segs[0] & 0xffc0) == 0xfe80 || (segs[0] & 0xff00) == 0xff00 || (segs[0] & 0xffc0) == 0xfec0 || segs == [0, 0, 0, 0, 0, 0, 0, 0] || (segs[0] == 0x2001 && segs[1] == 0x0db8) || ipv6
.to_ipv4_mapped()
.map(is_private_ipv4)
.unwrap_or(false)
|| (segs[0..6] == [0, 0, 0, 0, 0, 0]
&& (segs[6] != 0 || segs[7] != 0)
&& {
let ipv4 = std::net::Ipv4Addr::new(
(segs[6] >> 8) as u8,
(segs[6] & 0xff) as u8,
(segs[7] >> 8) as u8,
(segs[7] & 0xff) as u8,
);
is_private_ipv4(ipv4)
})
}
pub fn get_blocked_hostnames() -> &'static [&'static str] {
&[
"localhost",
"localhost.localdomain",
"ip6-localhost",
"ip6-loopback",
"0.0.0.0",
"::1",
"::",
"169.254.169.254", "metadata.google.internal", "metadata.azure.com", "metadata.msftidentity.com", "metadata.nova.canonical.com", "metadata.packet.csi.com", ]
}
pub fn is_blocked_hostname(host: &str) -> bool {
let host_lower = host.to_lowercase();
let blocked = get_blocked_hostnames();
if blocked.iter().any(|&b| host_lower == b) {
return true;
}
let host_for_parse = host_lower
.strip_prefix('[')
.and_then(|h| h.strip_suffix(']'))
.unwrap_or(&host_lower);
if let Ok(ip) = host_for_parse.parse::<std::net::IpAddr>() {
return is_private_ip(ip);
}
false
}
async fn resolve_dns_direct(hostname: &str, port: u16) -> Result<Vec<IpAddr>, SsrfError> {
let addr_str = format!("{}:{}", hostname, port);
let addrs: Vec<IpAddr> = lookup_host(&addr_str)
.await
.map_err(|e| SsrfError::DnsResolutionFailed {
hostname: hostname.to_string(),
reason: e.to_string(),
})?
.map(|socket_addr| socket_addr.ip())
.collect();
Ok(addrs)
}
#[derive(Clone, Default)]
pub struct SsrfValidator {
dns_cache: Option<Arc<DnsCacheService>>,
config: SsrfConfig,
}
impl SsrfValidator {
pub fn new() -> Self {
Self::default()
}
pub fn with_dns_cache(dns_cache: Arc<DnsCacheService>) -> Self {
Self {
dns_cache: Some(dns_cache),
config: SsrfConfig::default(),
}
}
pub fn with_config(config: SsrfConfig) -> Self {
Self {
dns_cache: None,
config,
}
}
pub fn with_dns_cache_and_config(dns_cache: Arc<DnsCacheService>, config: SsrfConfig) -> Self {
Self {
dns_cache: Some(dns_cache),
config,
}
}
pub async fn validate(&self, url_str: &str) -> Result<ValidatedUrl, SsrfError> {
if url_str.len() > self.config.max_url_length {
return Err(SsrfError::UrlTooLong {
max: self.config.max_url_length,
actual: url_str.len(),
});
}
let url = Url::parse(url_str).map_err(|e| SsrfError::InvalidUrl {
url: url_str.to_string(),
reason: e.to_string(),
})?;
match url.scheme() {
"http" | "https" => {}
scheme => {
return Err(SsrfError::InvalidScheme {
scheme: scheme.to_string(),
});
}
}
let host = url.host_str().ok_or_else(|| SsrfError::MissingHost {
url: url_str.to_string(),
})?;
if ssrf_protection_disabled() {
let port = url.port_or_known_default().unwrap_or(80);
let resolved_ips = self.resolve_host_permissive(host, port).await?;
return Ok(ValidatedUrl {
url: url_str.to_string(),
parsed_url: url,
resolved_ips,
port,
});
}
if is_blocked_hostname(host) {
return Err(SsrfError::BlockedHostname {
hostname: host.to_string(),
});
}
let port = url.port_or_known_default().unwrap_or(80);
let resolved_ips = self.resolve_and_validate_ips(host, port).await?;
Ok(ValidatedUrl {
url: url_str.to_string(),
parsed_url: url,
resolved_ips,
port,
})
}
async fn resolve_host_permissive(
&self,
hostname: &str,
port: u16,
) -> Result<Vec<IpAddr>, SsrfError> {
self.resolve_hostname_ips(hostname, port).await
}
async fn resolve_and_validate_ips(
&self,
hostname: &str,
port: u16,
) -> Result<Vec<IpAddr>, SsrfError> {
let ips = self.resolve_hostname_ips(hostname, port).await?;
if ips.is_empty() {
return Err(SsrfError::NoIpResolved {
hostname: hostname.to_string(),
});
}
check_resolved_ips_not_internal(hostname, &ips)?;
if ips.len() > 1 {
log::debug!(
"DNS resolution returned {} IPs for hostname {}",
ips.len(),
hostname
);
}
Ok(ips)
}
async fn resolve_hostname_ips(
&self,
hostname: &str,
port: u16,
) -> Result<Vec<IpAddr>, SsrfError> {
if let Some(cache) = &self.dns_cache {
cache
.lookup_host(hostname, port)
.await
.map_err(|e| SsrfError::DnsResolutionFailed {
hostname: hostname.to_string(),
reason: e.to_string(),
})
} else {
resolve_dns_direct(hostname, port).await
}
}
pub fn validate_redirect(&self, redirect_url: &str) -> Result<(), SsrfError> {
if is_internal_url(redirect_url) {
return Err(SsrfError::RedirectToInternal {
url: redirect_url.to_string(),
});
}
Ok(())
}
pub fn validate_connection_ip(&self, ip: IpAddr) -> Result<(), SsrfError> {
if is_private_ip(ip) {
return Err(SsrfError::PrivateIpAccess { ip: ip.to_string() });
}
Ok(())
}
pub fn is_internal_url_sync(&self, url_str: &str) -> bool {
is_internal_url(url_str)
}
}
pub async fn validate_url(url_str: &str) -> Result<ValidatedUrl, SsrfError> {
let validator = SsrfValidator::new();
validator.validate(url_str).await
}
pub(crate) fn ssrf_protection_disabled() -> bool {
#[cfg(test)]
{
let _guard = crate::common::test_support::ENV_MUTEX
.lock()
.unwrap_or_else(|e| e.into_inner());
std::env::var(crate::common::constants::env_vars::DISABLE_SSRF_PROTECTION).is_ok()
}
#[cfg(not(test))]
{
use std::sync::OnceLock;
static DISABLED: OnceLock<bool> = OnceLock::new();
*DISABLED.get_or_init(|| {
let disabled =
std::env::var(crate::common::constants::env_vars::DISABLE_SSRF_PROTECTION).is_ok();
if disabled {
log::warn!(
"{}",
crate::i18n::tr_log_args(
"ssrf-protection-disabled",
&[(
"env",
crate::common::constants::env_vars::DISABLE_SSRF_PROTECTION.to_string(),
)],
)
);
}
disabled
})
}
}
fn check_resolved_ips_not_internal(hostname: &str, ips: &[IpAddr]) -> Result<(), SsrfError> {
let has_private = ips.iter().any(|ip| is_private_ip(*ip));
let has_public = ips.iter().any(|ip| !is_private_ip(*ip));
if has_private && has_public {
log::warn!(
"DNS rebinding attack detected: hostname {} resolved to mixed private/public IPs",
hostname
);
return Err(SsrfError::DnsRebindingDetected {
hostname: hostname.to_string(),
ips: ips.iter().map(|ip| ip.to_string()).collect(),
});
}
for ip in ips {
if is_private_ip(*ip) {
return Err(SsrfError::PrivateIpAccess { ip: ip.to_string() });
}
}
Ok(())
}
pub fn validate_domain_blacklist(url_str: &str, blacklist: &[String]) -> Result<(), SsrfError> {
let url = Url::parse(url_str).map_err(|e| SsrfError::InvalidUrl {
url: url_str.to_string(),
reason: e.to_string(),
})?;
let host = url.host_str().ok_or_else(|| SsrfError::MissingHost {
url: url_str.to_string(),
})?;
for domain in blacklist {
if host == domain || host.ends_with(&format!(".{}", domain)) {
return Err(SsrfError::BlockedHostname {
hostname: host.to_string(),
});
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::types::MAX_URL_LENGTH;
use super::*;
#[test]
fn test_is_internal_url_localhost() {
assert!(is_internal_url("http://localhost"));
assert!(is_internal_url("http://localhost:8080"));
assert!(is_internal_url("http://127.0.0.1"));
assert!(is_internal_url("http://127.0.0.1:3000"));
}
#[test]
fn test_is_internal_url_private_ipv4() {
assert!(is_internal_url("http://10.0.0.1"));
assert!(is_internal_url("http://10.255.255.255"));
assert!(is_internal_url("http://172.16.0.1"));
assert!(is_internal_url("http://172.31.255.255"));
assert!(is_internal_url("http://192.168.0.1"));
assert!(is_internal_url("http://192.168.255.255"));
assert!(!is_internal_url("http://172.15.0.1"));
assert!(!is_internal_url("http://172.32.0.1"));
}
#[test]
fn test_is_internal_url_link_local() {
assert!(is_internal_url("http://169.254.0.1"));
assert!(is_internal_url("http://169.254.255.255"));
}
#[test]
fn test_is_internal_url_ipv6() {
assert!(is_internal_url("http://[::1]"));
assert!(is_internal_url("http://[::1]:8080"));
assert!(is_internal_url("http://[fe80::1]"));
assert!(is_internal_url("http://[febf::1]"));
assert!(is_internal_url("http://[fc00::1]"));
assert!(is_internal_url("http://[fd00::1]"));
}
#[test]
fn test_is_internal_url_external() {
assert!(!is_internal_url("http://8.8.8.8"));
assert!(!is_internal_url("http://1.1.1.1"));
assert!(!is_internal_url("http://google.com"));
assert!(!is_internal_url("https://www.example.com"));
}
#[test]
fn test_is_internal_url_invalid_scheme() {
assert!(is_internal_url("file:///etc/passwd"));
assert!(is_internal_url("ftp://example.com"));
assert!(is_internal_url("gopher://localhost"));
}
#[test]
fn test_validate_domain_blacklist() {
let blacklist = vec!["example.com".to_string(), "malicious.net".to_string()];
assert!(validate_domain_blacklist("http://example.com", &blacklist).is_err());
assert!(validate_domain_blacklist("http://malicious.net/path", &blacklist).is_err());
assert!(validate_domain_blacklist("http://sub.example.com", &blacklist).is_err());
assert!(validate_domain_blacklist("http://api.malicious.net", &blacklist).is_err());
assert!(validate_domain_blacklist("http://google.com", &blacklist).is_ok());
assert!(validate_domain_blacklist("http://example.org", &blacklist).is_ok());
assert!(validate_domain_blacklist("http://myexample.com", &blacklist).is_ok());
}
#[tokio::test]
async fn test_validate_url_ssrf() {
let validator = SsrfValidator::new();
assert!(validator.validate("http://localhost").await.is_err());
assert!(validator
.validate("http://localhost.localdomain")
.await
.is_err());
assert!(validator.validate("http://127.0.0.1").await.is_err());
assert!(validator.validate("http://0.0.0.0").await.is_err());
assert!(validator.validate("http://10.0.0.1").await.is_err());
assert!(validator.validate("http://192.168.1.1").await.is_err());
assert!(validator.validate("http://172.16.0.1").await.is_err());
assert!(validator.validate("http://169.254.169.254").await.is_err());
assert!(validator
.validate("http://metadata.google.internal")
.await
.is_err());
assert!(validator.validate("file:///etc/passwd").await.is_err());
assert!(validator.validate("ftp://example.com").await.is_err());
assert!(validator.validate("gopher://localhost").await.is_err());
}
#[tokio::test]
async fn test_validate_url_too_long() {
let validator = SsrfValidator::new();
let long_url = format!("http://example.com/{}", "a".repeat(3000));
let result = validator.validate(&long_url).await;
assert!(matches!(result, Err(SsrfError::UrlTooLong { .. })));
}
#[test]
fn test_ssrf_validator_default() {
let validator = SsrfValidator::default();
assert!(validator.dns_cache.is_none());
assert_eq!(validator.config.max_url_length, MAX_URL_LENGTH);
}
#[test]
fn test_ssrf_validator_with_config() {
let config = SsrfConfig::new().with_max_url_length(512);
let validator = SsrfValidator::with_config(config);
assert!(validator.dns_cache.is_none());
assert_eq!(validator.config.max_url_length, 512);
}
#[test]
fn test_validate_connection_ip_private() {
let validator = SsrfValidator::new();
assert!(validator
.validate_connection_ip("10.0.0.1".parse().unwrap())
.is_err());
assert!(validator
.validate_connection_ip("192.168.1.1".parse().unwrap())
.is_err());
assert!(validator
.validate_connection_ip("127.0.0.1".parse().unwrap())
.is_err());
assert!(validator
.validate_connection_ip("169.254.169.254".parse().unwrap())
.is_err());
assert!(validator
.validate_connection_ip("::1".parse().unwrap())
.is_err());
}
#[test]
fn test_validate_connection_ip_public() {
let validator = SsrfValidator::new();
assert!(validator
.validate_connection_ip("8.8.8.8".parse().unwrap())
.is_ok());
assert!(validator
.validate_connection_ip("1.1.1.1".parse().unwrap())
.is_ok());
}
#[test]
fn test_is_internal_url_sync_method() {
let validator = SsrfValidator::new();
assert!(validator.is_internal_url_sync("http://localhost"));
assert!(validator.is_internal_url_sync("http://10.0.0.1"));
assert!(validator.is_internal_url_sync("http://192.168.1.1"));
assert!(!validator.is_internal_url_sync("http://example.com"));
assert!(!validator.is_internal_url_sync("https://8.8.8.8"));
}
#[test]
fn test_validate_redirect_method_blocks_internal() {
let validator = SsrfValidator::new();
assert!(validator.validate_redirect("http://localhost").is_err());
assert!(validator.validate_redirect("http://192.168.1.1").is_err());
assert!(validator.validate_redirect("http://10.0.0.1").is_err());
}
#[test]
fn test_validate_redirect_method_allows_external() {
let validator = SsrfValidator::new();
assert!(validator.validate_redirect("http://example.com").is_ok());
assert!(validator.validate_redirect("https://google.com").is_ok());
}
#[tokio::test]
async fn test_validate_url_convenience_function() {
assert!(validate_url("http://localhost").await.is_err());
assert!(validate_url("http://10.0.0.1").await.is_err());
assert!(validate_url("file:///etc/passwd").await.is_err());
let long_url = format!("http://example.com/{}", "a".repeat(3000));
assert!(validate_url(&long_url).await.is_err());
}
#[tokio::test]
async fn test_validate_invalid_url_format() {
let validator = SsrfValidator::new();
let result = validator.validate("http://[invalid").await;
assert!(result.is_err());
assert!(matches!(result, Err(SsrfError::InvalidUrl { .. })));
}
#[test]
fn test_validate_domain_blacklist_invalid_url() {
let result = validate_domain_blacklist("not-a-valid-url", &[]);
assert!(result.is_err());
assert!(matches!(result, Err(SsrfError::InvalidUrl { .. })));
}
#[test]
fn test_validate_domain_blacklist_missing_host() {
let result = validate_domain_blacklist("mailto:foo@bar.com", &[]);
assert!(result.is_err());
assert!(matches!(result, Err(SsrfError::MissingHost { .. })));
}
async fn make_dns_cache() -> Arc<DnsCacheService> {
let cache: Arc<crate::infrastructure::oxcache::DnsCache> = Arc::new(
oxcache::Cache::builder()
.capacity(100)
.ttl(std::time::Duration::from_secs(300))
.build()
.await
.expect("Failed to build oxcache for test"),
);
Arc::new(DnsCacheService::new(cache, 300).expect("failed to create DnsCacheService"))
}
#[tokio::test]
async fn test_with_dns_cache_constructor() {
let dns_cache = make_dns_cache().await;
let validator = SsrfValidator::with_dns_cache(dns_cache);
assert!(validator.dns_cache.is_some());
assert_eq!(validator.config.max_url_length, MAX_URL_LENGTH);
}
#[tokio::test]
async fn test_with_dns_cache_and_config_constructor() {
let dns_cache = make_dns_cache().await;
let config = SsrfConfig::new().with_max_url_length(512);
let validator = SsrfValidator::with_dns_cache_and_config(dns_cache, config);
assert!(validator.dns_cache.is_some());
assert_eq!(validator.config.max_url_length, 512);
}
#[tokio::test]
async fn test_validate_with_dns_cache_blocks_internal() {
let dns_cache = make_dns_cache().await;
let validator = SsrfValidator::with_dns_cache(dns_cache);
assert!(validator.validate("http://localhost").await.is_err());
assert!(validator.validate("http://127.0.0.1").await.is_err());
assert!(validator.validate("http://10.0.0.1").await.is_err());
assert!(validator.validate("file:///etc/passwd").await.is_err());
}
#[tokio::test]
async fn test_validate_with_dns_cache_url_too_long() {
let dns_cache = make_dns_cache().await;
let validator = SsrfValidator::with_dns_cache(dns_cache);
let long_url = format!("http://example.com/{}", "a".repeat(3000));
let result = validator.validate(&long_url).await;
assert!(matches!(result, Err(SsrfError::UrlTooLong { .. })));
}
#[tokio::test]
async fn test_validate_with_dns_cache_invalid_url() {
let dns_cache = make_dns_cache().await;
let validator = SsrfValidator::with_dns_cache(dns_cache);
let result = validator.validate("http://[invalid").await;
assert!(result.is_err());
assert!(matches!(result, Err(SsrfError::InvalidUrl { .. })));
}
#[tokio::test]
async fn test_validate_with_dns_cache_invalid_scheme() {
let dns_cache = make_dns_cache().await;
let validator = SsrfValidator::with_dns_cache(dns_cache);
let result = validator.validate("ftp://example.com").await;
assert!(result.is_err());
assert!(matches!(result, Err(SsrfError::InvalidScheme { .. })));
}
#[tokio::test]
async fn test_validate_with_dns_cache_blocked_hostname() {
let dns_cache = make_dns_cache().await;
let validator = SsrfValidator::with_dns_cache(dns_cache);
let result = validator.validate("http://metadata.google.internal").await;
assert!(result.is_err());
assert!(matches!(result, Err(SsrfError::BlockedHostname { .. })));
}
#[tokio::test]
async fn test_validate_with_dns_cache_and_config_blocks_internal() {
let dns_cache = make_dns_cache().await;
let config = SsrfConfig::new().with_max_url_length(1024);
let validator = SsrfValidator::with_dns_cache_and_config(dns_cache, config);
assert!(validator.validate("http://10.0.0.1").await.is_err());
assert!(validator.validate("http://192.168.1.1").await.is_err());
}
#[tokio::test]
async fn test_validate_missing_host_with_dns_cache() {
let dns_cache = make_dns_cache().await;
let validator = SsrfValidator::with_dns_cache(dns_cache);
let result = validator.validate("http://").await;
assert!(result.is_err());
}
#[test]
fn test_ssrf_validator_clone() {
let validator = SsrfValidator::new();
let cloned = validator.clone();
assert_eq!(
validator.config.max_url_length,
cloned.config.max_url_length
);
}
}