Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 67 additions & 1 deletion crates/plugin-web/src/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
//! (IPv4-mapped `::ffff:a.b.c.d` or IPv4-compatible `::a.b.c.d`) is reduced to
//! its embedded IPv4 value and reclassified, so a non-global IPv4 in IPv6
//! form cannot slip past the table.
//!
//! IPv6 is an allow-list: an address outside [`GLOBAL_UNICAST`],
//! `2000::/3`, is refused even when no entry of the table names it, so a
//! special range that the table misses fails closed. The table still holds
//! the special ranges inside `2000::/3`.

use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

Expand Down Expand Up @@ -65,6 +70,7 @@ const BLOCKED_NETS: &[IpNet] = &[
v6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0], 96), // 64:ff9b::/96, NAT64
v6([0x64, 0xff9b, 1, 0, 0, 0, 0, 0], 48), // 64:ff9b:1::/48, NAT64
v6([0x100, 0, 0, 0, 0, 0, 0, 0], 64), // 100::/64, discard-only
v6([0x2001, 0, 0, 0, 0, 0, 0, 0], 23), // 2001::/23, IETF protocol assignments
v6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0], 32), // 2001:db8::/32, documentation
v6([0x2002, 0, 0, 0, 0, 0, 0, 0], 16), // 2002::/16, 6to4
v6([0x3fff, 0, 0, 0, 0, 0, 0, 0], 20), // 3fff::/20, documentation (RFC 9637)
Expand All @@ -74,6 +80,10 @@ const BLOCKED_NETS: &[IpNet] = &[
v6([0xff00, 0, 0, 0, 0, 0, 0, 0], 8), // ff00::/8, multicast
];

/// The IPv6 global unicast range, `2000::/3`. An IPv6 address outside it
/// is refused whether or not [`BLOCKED_NETS`] names its range.
const GLOBAL_UNICAST: IpNet = v6([0x2000, 0, 0, 0, 0, 0, 0, 0], 3);

/// The IPv4 range whose first address has these four `octets`, with a
/// prefix of `prefix` bits. In a constant, a prefix over 32 fails the
/// build.
Expand Down Expand Up @@ -104,7 +114,9 @@ fn embedded_ipv4(ip: IpAddr) -> Option<Ipv4Addr> {
///
/// The address is checked directly, then, if it re-encodes an IPv4 address, its
/// embedded IPv4 value is checked too, so a non-global IPv4 in an IPv6 hat is
/// caught even where the table has no matching IPv6 entry.
/// caught even where the table has no matching IPv6 entry. Last, an IPv6
/// address outside [`GLOBAL_UNICAST`] is blocked, reported as outside
/// `2000::/3`.
fn builtin_blocked(ip: IpAddr) -> Option<String> {
if let Some(net) = BLOCKED_NETS.iter().find(|net| net.contains(&ip)) {
return Some(net.to_string());
Expand All @@ -115,6 +127,9 @@ fn builtin_blocked(ip: IpAddr) -> Option<String> {
return Some(format!("{net} (embedded ipv4 {v4})"));
}
}
if ip.is_ipv6() && !GLOBAL_UNICAST.contains(&ip) {
return Some(format!("outside {GLOBAL_UNICAST}"));
}
None
}

Expand Down Expand Up @@ -210,6 +225,7 @@ mod tests {
"64:ff9b::/96", // NAT64
"64:ff9b:1::/48", // NAT64
"100::/64", // discard-only
"2001::/23", // IETF protocol assignments
"2001:db8::/32", // documentation
"2002::/16", // 6to4
"3fff::/20", // documentation (RFC 9637)
Expand Down Expand Up @@ -272,6 +288,11 @@ mod tests {
"64:ff9b:1:ffff:ffff:ffff:ffff:ffff",
),
("100::/64", "100::", "100::ffff:ffff:ffff:ffff"),
(
"2001::/23",
"2001::",
"2001:1ff:ffff:ffff:ffff:ffff:ffff:ffff",
),
(
"2001:db8::/32",
"2001:db8::",
Expand Down Expand Up @@ -363,6 +384,51 @@ mod tests {
}
}

/// IPv6 outside `2000::/3` is refused even where no table entry names
/// its range, and IPv6 inside it that no entry names is allowed.
#[test]
fn ipv6_outside_global_unicast_is_refused() {
let cfg = FetchConfig::default();

let refused = [
"1::1", // below 2000::/3, no table entry
"1fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", // last address below 2000::/3
"4000::", // first address above 2000::/3
"8000::1",
"c000::1",
"fb00::1", // below fc00::/7, no table entry
];
for addr in refused {
assert!(!addr_allowed(ip(addr), &cfg), "{addr} must be denied");
}

let allowed = [
"2000::1", // first block of 2000::/3
"2001:200::1", // just past 2001::/23
"2400:cb00:2048:1::c629:d7a2", // ordinary global unicast
"3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", // last address of 2000::/3
];
for addr in allowed {
assert!(addr_allowed(ip(addr), &cfg), "{addr} must be allowed");
}
}

/// The range that blocks an IPv6 address outside `2000::/3` with no
/// table entry names the rule.
#[test]
fn blocked_range_names_the_global_unicast_rule() {
let cfg = FetchConfig::default();
assert_eq!(
super::blocked_range(ip("4000::1"), &cfg).as_deref(),
Some("outside 2000::/3")
);
assert_eq!(
super::blocked_range(ip("fe80::1"), &cfg).as_deref(),
Some("fe80::/10"),
"a table entry is reported before the 2000::/3 rule"
);
}

#[test]
fn allow_exact_admits_only_the_named_host() {
let target = ip("127.0.0.1");
Expand Down
11 changes: 10 additions & 1 deletion crates/plugin-web/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,13 @@ impl std::fmt::Display for SafeUrl {
/// secret survives into `Debug` or `Display`.
#[derive(Debug, thiserror::Error)]
pub(crate) enum FetchError {
/// The URL is longer than the admission limit.
#[error("the URL is {length} characters long, and the limit is {limit}", limit = crate::url_policy::MAX_URL_CHARS)]
UrlTooLong {
/// The URL's length in characters.
length: usize,
},

/// The URL could not be parsed.
#[error("invalid url")]
InvalidUrl(#[source] url::ParseError),
Expand Down Expand Up @@ -247,6 +254,7 @@ impl FetchError {
| FetchError::RedirectRefused { .. }
| FetchError::BlockedScheme(_) => Disposition::SoftOutput,
FetchError::InvalidUrl(_)
| FetchError::UrlTooLong { .. }
| FetchError::Userinfo
| FetchError::BlockedPort(_)
| FetchError::IpLiteral(_)
Expand Down Expand Up @@ -352,8 +360,9 @@ mod tests {
);
}

let hard: [FetchError; 6] = [
let hard: [FetchError; 7] = [
FetchError::InvalidUrl(parse),
FetchError::UrlTooLong { length: 2001 },
FetchError::Userinfo,
FetchError::BlockedPort(22),
FetchError::IpLiteral("1.2.3.4".into()),
Expand Down
59 changes: 54 additions & 5 deletions crates/plugin-web/src/url_policy.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
//! URL admission policy applied before any network access.
//!
//! [`check_url`] parses a model-supplied URL and rejects anything the policy
//! forbids (a bad scheme, embedded userinfo, a disallowed port, or a
//! non-global IP-literal host) before a request is ever made. It runs at the top
//! forbids (a URL over [`MAX_URL_CHARS`], a bad scheme, embedded userinfo, a
//! disallowed port, or a non-global IP-literal host) before a request is ever
//! made. It runs at the top
//! of the fetch path and again on every redirect target, so a rejected URL
//! never reaches the network.
//!
Expand All @@ -21,27 +22,38 @@ use crate::address::{addr_allowed_for_host, blocked_range};
use crate::config::FetchConfig;
use crate::error::FetchError;

/// The longest URL, in characters, that [`check_url`] admits. It bounds how
/// much data one request can carry out in its URL.
pub(crate) const MAX_URL_CHARS: usize = 2000;

/// Parses `raw` and enforces the URL-admission policy in `config`.
///
/// On success the returned [`Url`] has its fragment dropped (a fragment never
/// travels to the server) and its query left untouched. The checks run before
/// any network access, so a rejected URL costs no request.
///
/// The policy: the scheme must be `https`, or `http` when the config
/// The policy: the URL must be at most [`MAX_URL_CHARS`] characters; the
/// scheme must be `https`, or `http` when the config
/// permits it; the URL must have no userinfo; the effective port must be
/// on the allowlist; and an IP-literal host is refused unless literals are
/// enabled, in which case the literal's address is classified against the
/// address policy and a non-global address is still refused.
///
/// # Errors
/// Returns [`FetchError::InvalidUrl`] if `raw` does not parse;
/// Returns [`FetchError::UrlTooLong`] if `raw` is over [`MAX_URL_CHARS`]
/// characters; [`FetchError::InvalidUrl`] if `raw` does not parse;
/// [`FetchError::BlockedScheme`] if the scheme is not permitted;
/// [`FetchError::Userinfo`] if the URL contains a `user:pass@` component;
/// [`FetchError::BlockedPort`] if the effective port is not on the allowlist;
/// [`FetchError::IpLiteral`] if the host is an IP literal and literals are not
/// allowed; and [`FetchError::BlockedAddress`] if an admitted literal names a
/// non-global address.
pub(crate) fn check_url(raw: &str, config: &FetchConfig) -> Result<Url, FetchError> {
let length = raw.chars().count();
if length > MAX_URL_CHARS {
return Err(FetchError::UrlTooLong { length });
}

let mut url = Url::parse(raw).map_err(FetchError::InvalidUrl)?;

let scheme = url.scheme();
Expand Down Expand Up @@ -96,7 +108,7 @@ pub(crate) fn check_url(raw: &str, config: &FetchConfig) -> Result<Url, FetchErr
mod tests {
use std::net::IpAddr;

use super::check_url;
use super::{MAX_URL_CHARS, check_url};
use crate::config::FetchConfig;
use crate::error::FetchError;

Expand All @@ -107,6 +119,43 @@ mod tests {
assert!(want(&err), "unexpected error for {raw}: {err}");
}

/// `https://example.com/` followed by `a` to `total` characters.
fn url_of_length(total: usize) -> String {
let base = "https://example.com/";
format!("{base}{}", "a".repeat(total - base.len()))
}

#[test]
fn accepts_a_url_at_the_length_limit() {
let raw = url_of_length(MAX_URL_CHARS);
check_url(&raw, &FetchConfig::default()).expect("a URL of 2000 characters is admitted");
}

#[test]
fn rejects_a_url_over_the_length_limit() {
let raw = url_of_length(MAX_URL_CHARS + 1);
let err = check_url(&raw, &FetchConfig::default())
.expect_err("a URL of 2001 characters is refused");
assert!(
matches!(err, FetchError::UrlTooLong { length: 2001 }),
"unexpected error: {err}"
);
assert_eq!(
err.model_facing(),
"the URL is 2001 characters long, and the limit is 2000"
);
}

/// The limit counts characters, not bytes.
#[test]
fn the_length_limit_counts_characters() {
let base = "https://example.com/";
let raw = format!("{base}{}", "é".repeat(MAX_URL_CHARS - base.len()));
assert!(raw.len() > MAX_URL_CHARS, "the URL is longer in bytes");
check_url(&raw, &FetchConfig::default())
.expect("a URL of 2000 characters is admitted whatever its bytes");
}

#[test]
fn rejects_userinfo() {
assert_rejected(
Expand Down
Loading