use futures::future::BoxFuture;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum ActionKind {
Navigate,
Reload,
History,
Click,
DoubleClick,
Hover,
Drag,
Wheel,
Press,
TypeText,
Fill,
Select,
Upload,
Eval,
}
#[derive(Clone, Debug)]
pub struct AdmissionRequest {
pub session_id: String,
pub page_id: String,
pub action: ActionKind,
pub url: Option<String>,
pub target: Option<String>,
pub detail: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Decision {
Allow,
Deny(String),
}
pub type AdmissionHook =
Arc<dyn Fn(AdmissionRequest) -> BoxFuture<'static, Decision> + Send + Sync>;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum AddressClass {
Public,
Loopback,
LinkLocal,
Private,
Reserved,
Unspecified,
Multicast,
}
pub fn classify_ip(ip: IpAddr) -> AddressClass {
match ip {
IpAddr::V4(v4) => classify_v4(v4),
IpAddr::V6(v6) => classify_v6(v6),
}
}
fn classify_v4(ip: Ipv4Addr) -> AddressClass {
let [a, b, c, _] = ip.octets();
if a == 127 {
AddressClass::Loopback
} else if a == 0 {
AddressClass::Unspecified
} else if a == 169 && b == 254 {
AddressClass::LinkLocal
} else if a == 10
|| (a == 172 && (16..=31).contains(&b))
|| (a == 192 && b == 168)
|| (a == 100 && (64..=127).contains(&b))
{
AddressClass::Private
} else if (224..=239).contains(&a) {
AddressClass::Multicast
} else if a >= 240
|| (a == 192 && b == 0 && c == 0)
|| (a == 192 && b == 0 && c == 2)
|| (a == 198 && (b == 18 || b == 19))
|| (a == 198 && b == 51 && c == 100)
|| (a == 203 && b == 0 && c == 113)
{
AddressClass::Reserved
} else {
AddressClass::Public
}
}
fn v4_from_segments(hi: u16, lo: u16) -> Ipv4Addr {
Ipv4Addr::new((hi >> 8) as u8, hi as u8, (lo >> 8) as u8, lo as u8)
}
fn classify_v6(v6: Ipv6Addr) -> AddressClass {
let s = v6.segments();
if v6.is_loopback() {
return AddressClass::Loopback;
}
if v6.is_unspecified() {
return AddressClass::Unspecified;
}
if let Some(v4) = v6.to_ipv4_mapped() {
return classify_v4(v4);
}
if s[..6] == [0, 0, 0, 0, 0, 0] {
return classify_v4(v4_from_segments(s[6], s[7]));
}
if s[..6] == [0x64, 0xff9b, 0, 0, 0, 0] {
return classify_v4(v4_from_segments(s[6], s[7]));
}
if s[0] == 0x2002 {
return classify_v4(v4_from_segments(s[1], s[2]));
}
if v6.is_multicast() {
AddressClass::Multicast
} else if s[0] & 0xffc0 == 0xfe80 {
AddressClass::LinkLocal
} else if s[0] & 0xfe00 == 0xfc00 || s[0] & 0xffc0 == 0xfec0 {
AddressClass::Private
} else if (s[0] == 0x2001 && s[1] == 0x0db8) || (s[0] == 0x2001 && s[1] == 0) {
AddressClass::Reserved
} else {
AddressClass::Public
}
}
fn is_metadata_host(host: &str) -> bool {
matches!(
host,
"metadata" | "metadata.google.internal" | "metadata.goog" | "instance-data"
) || host.ends_with(".metadata.google.internal")
}
fn normalize_host(host: &str) -> String {
let h = host.trim_matches(['[', ']']).to_ascii_lowercase();
h.strip_suffix('.').map(str::to_string).unwrap_or(h)
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BlockReason {
InvalidUrl(String),
Scheme(String),
NoHost,
Unresolved {
host: String,
},
Address {
host: String,
ip: IpAddr,
class: AddressClass,
},
MetadataHost {
host: String,
},
Callback(String),
}
impl BlockReason {
pub fn is_hard(&self, hard_block_link_local: bool) -> bool {
hard_block_link_local
&& matches!(
self,
BlockReason::MetadataHost { .. }
| BlockReason::Address {
class: AddressClass::LinkLocal,
..
}
)
}
}
impl fmt::Display for BlockReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BlockReason::InvalidUrl(e) => write!(f, "unparseable url: {e}"),
BlockReason::Scheme(s) => write!(f, "scheme '{s}' is blocked"),
BlockReason::NoHost => write!(f, "request has no host"),
BlockReason::Unresolved { host } => write!(f, "host '{host}' did not resolve"),
BlockReason::Address { host, ip, class } => {
if host == &ip.to_string() {
write!(f, "address {ip} is {class:?}")
} else {
write!(f, "host '{host}' resolves to {class:?} address {ip}")
}
}
BlockReason::MetadataHost { host } => {
write!(f, "host '{host}' is a cloud metadata endpoint")
}
BlockReason::Callback(r) => write!(f, "denied by policy callback: {r}"),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PolicyDenial {
pub url: String,
pub resource_type: String,
pub reason: BlockReason,
}
impl fmt::Display for PolicyDenial {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} ({}): {}", self.url, self.resource_type, self.reason)
}
}
#[derive(Clone, Debug)]
pub struct BrowserRequest {
pub url: String,
pub scheme: String,
pub host: String,
pub port: Option<u16>,
pub class: Option<AddressClass>,
pub addresses: Vec<IpAddr>,
pub resource_type: String,
pub default_block: Option<BlockReason>,
}
pub type NetworkRequest = BrowserRequest;
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum PolicyDecision {
Allow,
Deny(String),
Default,
}
impl From<bool> for PolicyDecision {
fn from(b: bool) -> Self {
if b {
PolicyDecision::Allow
} else {
PolicyDecision::Default
}
}
}
pub type AllowCallback = Arc<dyn Fn(&BrowserRequest) -> PolicyDecision + Send + Sync>;
pub type Resolver = Arc<dyn Fn(&str) -> Vec<IpAddr> + Send + Sync>;
type ResolvedCache = Arc<Mutex<HashMap<String, (Instant, Vec<IpAddr>)>>>;
#[derive(Clone)]
pub struct NetworkPolicy {
pub allow_hosts: Vec<String>,
pub allow_classes: Vec<AddressClass>,
pub allowed_schemes: Vec<String>,
pub allow_request: Option<AllowCallback>,
pub hard_block_link_local: bool,
pub unrestricted: bool,
pub resolver: Option<Resolver>,
resolved: ResolvedCache,
approved: Arc<Mutex<HashMap<String, Vec<IpAddr>>>>,
destinations: Option<DestinationFilter>,
}
impl Default for NetworkPolicy {
fn default() -> Self {
Self {
allow_hosts: Vec::new(),
allow_classes: Vec::new(),
allowed_schemes: vec!["http".into(), "https".into()],
allow_request: None,
hard_block_link_local: true,
unrestricted: false,
resolver: None,
resolved: ResolvedCache::default(),
approved: Arc::default(),
destinations: None,
}
}
}
impl fmt::Debug for NetworkPolicy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NetworkPolicy")
.field("allow_hosts", &self.allow_hosts)
.field("allow_classes", &self.allow_classes)
.field("allowed_schemes", &self.allowed_schemes)
.field("allow_request", &self.allow_request.is_some())
.field("hard_block_link_local", &self.hard_block_link_local)
.field("unrestricted", &self.unrestricted)
.field("destinations", &self.destinations)
.finish()
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BlockedRequest {
pub url: String,
pub reason: String,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum ResourceClass {
Document,
Script,
Connect,
Passive,
}
impl ResourceClass {
pub const ALL: [ResourceClass; 4] = [
ResourceClass::Document,
ResourceClass::Script,
ResourceClass::Connect,
ResourceClass::Passive,
];
pub fn of(resource_type: &str) -> Self {
match resource_type {
"Navigation" | "Document" => ResourceClass::Document,
"Script" | "Worker" | "SharedWorker" | "ServiceWorker" => ResourceClass::Script,
"Stylesheet" | "Image" | "Media" | "Font" | "TextTrack" | "Manifest" => {
ResourceClass::Passive
}
_ => ResourceClass::Connect,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
enum HostMatch {
Exact(String),
Subdomains(String),
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DestinationRule {
host: HostMatch,
ports: Vec<u16>,
classes: Vec<ResourceClass>,
}
fn check_rule_host(host: &str) -> crate::error::Result<String> {
let h = normalize_host(host);
let ok = !h.is_empty()
&& h.len() <= 253
&& h.parse::<IpAddr>().is_err()
&& h.split('.').count() >= 2
&& h.split('.').all(|l| {
!l.is_empty()
&& l.len() <= 63
&& !l.starts_with('-')
&& !l.ends_with('-')
&& l.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
});
if ok {
Ok(h)
} else {
Err(crate::error::BrowserError::Invalid(
"a destination rule host must be a plain DNS name of two labels or more (no wildcard, scheme, port, path or IP address)"
.into(),
))
}
}
impl DestinationRule {
pub fn exact(host: &str) -> crate::error::Result<Self> {
Ok(Self {
host: HostMatch::Exact(check_rule_host(host)?),
ports: vec![443],
classes: ResourceClass::ALL.to_vec(),
})
}
pub fn subdomains_of(domain: &str) -> crate::error::Result<Self> {
Ok(Self {
host: HostMatch::Subdomains(check_rule_host(domain)?),
ports: vec![443],
classes: ResourceClass::ALL.to_vec(),
})
}
pub fn on_ports(mut self, ports: &[u16]) -> Self {
self.ports = ports.to_vec();
self
}
pub fn for_classes(mut self, classes: &[ResourceClass]) -> Self {
self.classes = classes.to_vec();
self
}
fn matches(&self, host: &str, port: u16, class: ResourceClass) -> bool {
let host_ok = match &self.host {
HostMatch::Exact(h) => host == h,
HostMatch::Subdomains(d) => {
host == d
|| host
.strip_suffix(d.as_str())
.is_some_and(|prefix| prefix.ends_with('.'))
}
};
host_ok && self.ports.contains(&port) && self.classes.contains(&class)
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct DestinationFilter {
rules: Vec<DestinationRule>,
}
impl DestinationFilter {
pub fn new() -> Self {
Self::default()
}
pub fn rule(mut self, rule: DestinationRule) -> Self {
self.rules.push(rule);
self
}
pub fn rules(&self) -> &[DestinationRule] {
&self.rules
}
pub fn permits(&self, request: &BrowserRequest) -> bool {
if !matches!(request.scheme.as_str(), "https" | "wss") || request.host.is_empty() {
return false;
}
let Some(port) = request.port else {
return false;
};
let class = ResourceClass::of(&request.resource_type);
self.rules
.iter()
.any(|rule| rule.matches(&request.host, port, class))
}
pub fn decide(&self, request: &BrowserRequest) -> PolicyDecision {
if self.permits(request) {
return PolicyDecision::Default;
}
let target = match request.port {
Some(port) => format!("{}:{port}", request.host),
None => request.host.clone(),
};
PolicyDecision::Deny(format!(
"{:?} destination {target} is not on the destination list",
ResourceClass::of(&request.resource_type)
))
}
}
impl NetworkPolicy {
pub fn unrestricted() -> Self {
Self {
unrestricted: true,
..Self::default()
}
}
pub fn allow_host(mut self, host: impl Into<String>) -> Self {
self.allow_hosts.push(normalize_host(&host.into()));
self
}
pub fn allow_class(mut self, class: AddressClass) -> Self {
self.allow_classes.push(class);
self
}
pub fn allow_scheme(mut self, scheme: impl Into<String>) -> Self {
self.allowed_schemes
.push(scheme.into().to_ascii_lowercase());
self
}
pub fn hard_block_link_local(mut self, on: bool) -> Self {
self.hard_block_link_local = on;
self
}
pub fn with_resolver(
mut self,
f: impl Fn(&str) -> Vec<IpAddr> + Send + Sync + 'static,
) -> Self {
self.resolver = Some(Arc::new(f));
self
}
pub fn allow_with<D: Into<PolicyDecision>>(
mut self,
f: impl Fn(&BrowserRequest) -> D + Send + Sync + 'static,
) -> Self {
self.allow_request = Some(Arc::new(move |r| f(r).into()));
self
}
pub fn with_destination_filter(mut self, filter: DestinationFilter) -> Self {
self.unrestricted = false;
self.destinations = Some(filter);
self
}
fn scheme_allowed(&self, scheme: &str) -> bool {
self.allowed_schemes.iter().any(|s| s == scheme)
}
fn address_allowed(&self, host: &str, class: AddressClass) -> bool {
class == AddressClass::Public
|| self.allow_classes.contains(&class)
|| self.allow_hosts.iter().any(|h| h == host)
}
pub async fn check(&self, url: &str, resource_type: &str) -> Result<(), BlockReason> {
if self.unrestricted {
return Ok(());
}
let parsed = url::Url::parse(url).map_err(|e| BlockReason::InvalidUrl(e.to_string()))?;
let scheme = parsed.scheme().to_ascii_lowercase();
let is_document = matches!(resource_type, "Navigation" | "Document");
if scheme == "about" && parsed.path() == "blank" {
return Ok(());
}
if matches!(scheme.as_str(), "data" | "blob") && !is_document {
return Ok(()); }
let networked = matches!(scheme.as_str(), "http" | "https" | "ws" | "wss");
let mut default_block =
(!self.scheme_allowed(&scheme)).then(|| BlockReason::Scheme(scheme.clone()));
let mut host = String::new();
let mut class = None;
let mut addresses = Vec::new();
if networked {
host = normalize_host(parsed.host_str().unwrap_or(""));
if host.is_empty() {
return Err(BlockReason::NoHost);
}
if is_metadata_host(&host) {
let r = BlockReason::MetadataHost { host: host.clone() };
if r.is_hard(self.hard_block_link_local) {
return Err(r);
}
default_block.get_or_insert(r);
}
let (c, worst, ips) = self.host_class(&host).await;
class = Some(c);
addresses = ips;
if addresses.is_empty() {
return Err(BlockReason::Unresolved { host });
}
if !self.address_allowed(&host, c)
|| (c == AddressClass::LinkLocal && self.hard_block_link_local)
{
let r = BlockReason::Address {
host: host.clone(),
ip: worst,
class: c,
};
if r.is_hard(self.hard_block_link_local) {
return Err(r);
}
default_block.get_or_insert(r);
}
}
let decision = if self.allow_request.is_some() || self.destinations.is_some() {
let request = BrowserRequest {
url: url.to_string(),
scheme: scheme.clone(),
host: host.clone(),
port: parsed.port_or_known_default(),
class,
addresses: addresses.clone(),
resource_type: resource_type.to_string(),
default_block: default_block.clone(),
};
let listed = match &self.destinations {
Some(filter) => filter.decide(&request),
None => PolicyDecision::Default,
};
match (listed, &self.allow_request) {
(PolicyDecision::Deny(reason), _) => PolicyDecision::Deny(reason),
(_, Some(cb)) => cb(&request),
(_, None) => PolicyDecision::Default,
}
} else {
PolicyDecision::Default
};
let allowed = match decision {
PolicyDecision::Allow => true,
PolicyDecision::Deny(r) => return Err(BlockReason::Callback(r)),
PolicyDecision::Default => match default_block {
Some(r) => return Err(r),
None => true,
},
};
if allowed && networked && class != Some(AddressClass::Public) {
self.approved
.lock()
.unwrap()
.entry(host)
.or_default()
.extend(addresses);
}
Ok(())
}
pub(crate) async fn pin(&self, host: &str) -> Result<Vec<IpAddr>, BlockReason> {
let host = normalize_host(host);
if self.hard_block_link_local && is_metadata_host(&host) {
return Err(BlockReason::MetadataHost { host });
}
let (_, _, ips) = self.host_class(&host).await;
if ips.is_empty() {
return Err(BlockReason::Unresolved { host });
}
let approved = self
.approved
.lock()
.unwrap()
.get(&host)
.cloned()
.unwrap_or_default();
for ip in &ips {
let class = classify_ip(*ip);
let hard = self.hard_block_link_local && class == AddressClass::LinkLocal;
let ok = !hard && (self.address_allowed(&host, class) || approved.contains(ip));
if !ok {
return Err(BlockReason::Address {
host,
ip: *ip,
class,
});
}
}
Ok(ips)
}
async fn host_class(&self, host: &str) -> (AddressClass, IpAddr, Vec<IpAddr>) {
let unspecified = IpAddr::V4(Ipv4Addr::UNSPECIFIED);
if let Ok(ip) = host.parse::<IpAddr>() {
return (classify_ip(ip), ip, vec![ip]);
}
if host == "localhost" || host.ends_with(".localhost") {
let ip = IpAddr::V4(Ipv4Addr::LOCALHOST);
return (AddressClass::Loopback, ip, vec![ip]);
}
let addrs = self.resolve(host).await;
let worst = addrs
.iter()
.copied()
.find(|ip| classify_ip(*ip) != AddressClass::Public);
match worst {
Some(ip) => (classify_ip(ip), ip, addrs),
None => (
AddressClass::Public,
addrs.first().copied().unwrap_or(unspecified),
addrs,
),
}
}
async fn resolve(&self, host: &str) -> Vec<IpAddr> {
const TTL: Duration = Duration::from_secs(30);
if let Some((at, v)) = self.resolved.lock().unwrap().get(host) {
if at.elapsed() < TTL {
return v.clone();
}
}
let found: Vec<IpAddr> = if let Some(r) = &self.resolver {
r(host)
} else {
match tokio::time::timeout(Duration::from_secs(3), tokio::net::lookup_host((host, 0)))
.await
{
Ok(Ok(it)) => it.map(|a| a.ip()).collect(),
_ => Vec::new(), }
};
self.resolved
.lock()
.unwrap()
.insert(host.to_string(), (Instant::now(), found.clone()));
found
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum LifecycleKind {
Start,
Stop,
Crash,
Denied,
}
impl LifecycleKind {
pub fn label(self) -> &'static str {
match self {
LifecycleKind::Start => "start",
LifecycleKind::Stop => "stop",
LifecycleKind::Crash => "crash",
LifecycleKind::Denied => "denied",
}
}
}
#[derive(Clone, Debug)]
pub struct BrowserEvent {
pub kind: LifecycleKind,
pub session_id: String,
pub reason: String,
pub at: SystemTime,
pub page_id: Option<String>,
pub pid: Option<u32>,
pub what: Option<String>,
pub blocked: Option<BlockReason>,
}
impl BrowserEvent {
pub(crate) fn new(kind: LifecycleKind, session_id: &str, reason: impl Into<String>) -> Self {
Self {
kind,
session_id: session_id.to_string(),
reason: reason.into(),
at: SystemTime::now(),
page_id: None,
pid: None,
what: None,
blocked: None,
}
}
pub fn timestamp_ms(&self) -> u64 {
self.at
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0)
}
pub fn to_json(&self) -> serde_json::Value {
serde_json::json!({
"event": self.kind.label(),
"session_id": self.session_id,
"reason": self.reason,
"ts_ms": self.timestamp_ms(),
"page_id": self.page_id,
"pid": self.pid,
"what": self.what,
})
}
}
pub type EventSink = Arc<dyn Fn(&BrowserEvent) + Send + Sync>;
pub(crate) struct Guard {
pub session_id: String,
pub admission: Option<AdmissionHook>,
pub network: NetworkPolicy,
pub events: Option<EventSink>,
pub page_allowed: Mutex<HashSet<(String, u16)>>,
}
fn networked_pair(url: &str) -> Option<(String, u16)> {
let parsed = url::Url::parse(url).ok()?;
if !matches!(parsed.scheme(), "http" | "https" | "ws" | "wss") {
return None;
}
let host = normalize_host(parsed.host_str()?);
Some((host, parsed.port_or_known_default()?))
}
fn connect_url(host: &str, port: u16) -> String {
let host = normalize_host(host);
if host.contains(':') {
format!("https://[{host}]:{port}/")
} else {
format!("https://{host}:{port}/")
}
}
impl Guard {
pub fn emit(&self, e: BrowserEvent) {
if let Some(s) = &self.events {
s(&e);
}
}
pub fn emit_kind(
&self,
kind: LifecycleKind,
reason: impl Into<String>,
f: impl FnOnce(&mut BrowserEvent),
) {
let mut e = BrowserEvent::new(kind, &self.session_id, reason);
f(&mut e);
self.emit(e);
}
pub fn denied_network(&self, page_id: Option<&str>, what: &str, reason: &BlockReason) {
self.emit_kind(LifecycleKind::Denied, reason.to_string(), |e| {
e.page_id = page_id.map(str::to_string);
e.what = Some(what.to_string());
e.blocked = Some(reason.clone());
});
}
pub async fn admit(&self, req: AdmissionRequest) -> crate::error::Result<()> {
let what = format!("{:?}", req.action);
let page_id = req.page_id.clone();
if let Some(hook) = &self.admission {
if let Decision::Deny(reason) = hook(req).await {
self.emit_kind(LifecycleKind::Denied, reason.clone(), |e| {
e.page_id = Some(page_id);
e.what = Some(what);
});
return Err(crate::error::BrowserError::Denied(reason));
}
}
Ok(())
}
pub async fn check_request(&self, url: &str, kind: &str) -> Result<(), BlockReason> {
self.network.check(url, kind).await?;
if let Some(pair) = networked_pair(url) {
self.page_allowed.lock().unwrap().insert(pair);
}
Ok(())
}
pub(crate) async fn admit_proxied(
&self,
host: &str,
port: u16,
url: Option<&str>,
) -> Result<Vec<IpAddr>, BlockReason> {
let decide = (self.network.allow_request.is_some() || self.network.destinations.is_some())
&& !self
.page_allowed
.lock()
.unwrap()
.contains(&(normalize_host(host), port));
if decide {
let connect;
let url = match url {
Some(url) => url,
None => {
connect = connect_url(host, port);
&connect
}
};
self.network.check(url, "Connect").await?;
}
self.network.pin(host).await
}
pub async fn check_url(
&self,
page_id: Option<&str>,
url: &str,
kind: &str,
) -> crate::error::Result<()> {
match self.check_request(url, kind).await {
Ok(()) => Ok(()),
Err(reason) => {
self.denied_network(page_id, kind, &reason);
Err(crate::error::BrowserError::Blocked(PolicyDenial {
url: url.to_string(),
resource_type: kind.to_string(),
reason,
}))
}
}
}
}