use crate::tools::web::ssrf;
use rho_browser::guard::NavigationCheck;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::sync::Arc;
use url::{Host, Url};
pub(crate) fn check() -> NavigationCheck {
Arc::new(|url| Box::pin(async move { allowed(&url).await }))
}
pub(crate) async fn allowed(url: &str) -> Result<(), String> {
let Ok(url) = Url::parse(url) else {
return Ok(());
};
if !matches!(url.scheme(), "http" | "https") {
return Ok(());
}
let addresses = match url.host() {
None => return Ok(()),
Some(Host::Ipv4(address)) => vec![IpAddr::V4(address)],
Some(Host::Ipv6(address)) => vec![IpAddr::V6(address)],
Some(Host::Domain(name)) if is_localhost(name) => return Ok(()),
Some(Host::Domain(name)) => ssrf::resolve_host(name).await.unwrap_or_default(),
};
match addresses
.into_iter()
.find(|address| is_link_local_or_metadata(*address))
{
Some(address) => Err(refusal(&url, address)),
None => Ok(()),
}
}
pub(super) fn is_localhost(name: &str) -> bool {
let name = name.strip_suffix('.').unwrap_or(name);
name == "localhost" || name.ends_with(".localhost")
}
pub(super) fn is_link_local_or_metadata(ip: IpAddr) -> bool {
let v4 = match ssrf::normalize_ip(ip) {
IpAddr::V4(v4) => Some(v4),
IpAddr::V6(v6) => ssrf::embedded_ipv4(v6),
};
if let Some(v4) = v4 {
return v4.is_link_local() || v4 == Ipv4Addr::new(100, 100, 100, 200);
}
let IpAddr::V6(v6) = ip else {
return false;
};
(v6.segments()[0] & 0xffc0) == 0xfe80 || v6 == Ipv6Addr::new(0xfd00, 0x0ec2, 0, 0, 0, 0, 0, 0x0254)
}
fn refusal(url: &Url, address: IpAddr) -> String {
let host = url.host_str().unwrap_or_default();
let at = if host.trim_matches(['[', ']']) == address.to_string() {
String::new()
} else {
format!(" ({address})")
};
format!("{host}{at} is a link-local or cloud-metadata address, which the browser does not load")
}
#[cfg(test)]
#[path = "navigation_tests.rs"]
mod tests;