19.2 KiB · text History 7ce364f
//! Fetching a page (or picture) at a URL somebody else chose.
//!
//! Staff attach a link to a post ([`crate::link_cards`]) and the server
//! fetches it to build the card. That is a request to an address a person
//! picked, from inside our network, so it is server-side request forgery
//! unless it is fenced in. Everything here is that fence (party-slut's
//! `media::fetch`, which guards its dragged-in pictures):
//!
//! * http and https only;
//! * public addresses only: loopback, private, link-local (where cloud
//!   metadata lives), CGNAT, unique-local and the rest are refused, whether
//!   written literally or reached through a name;
//! * every redirect hop is checked again (followed by hand, never by the
//!   client);
//! * the connection goes to the addresses that were checked, not to a
//!   second lookup, so a name that answers "public" to the check and
//!   "private" to the connect (DNS rebinding) gets nowhere;
//! * a hard cap on bytes, enforced while reading, and a timeout;
//! * no proxy from the environment, which would skip all of the above.
use std::future::Future;
use std::net::{IpAddr, SocketAddr};
use std::time::Duration;

use reqwest::redirect::Policy;
use url::{Host, Url};

/// Longest we'll wait for one hop, connect to last byte.
const TIMEOUT: Duration = Duration::from_secs(10);
/// Redirects to follow. Each hop is re-checked, so this only bounds effort.
const MAX_HOPS: usize = 4;

/// Who we say we are. Plenty of sites refuse a request with no User-Agent
/// (reqwest sends none by default), and an operator who doesn't want us
/// should have something to block.
pub fn user_agent(public_url: &str) -> String {
    format!("recourse-link-preview/1.0 (+{})", public_url.trim_end_matches('/'))
}

#[derive(Debug, PartialEq, Eq)]
pub enum FetchError {
    /// Not http(s), or not a URL.
    BadUrl,
    /// A private, local or otherwise non-public address. Logged, never shown
    /// to a person differently from `Unreachable`: telling them apart would
    /// make this a scanner for what the server can reach.
    Blocked,
    Unreachable,
    TooLarge,
}

impl std::fmt::Display for FetchError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::BadUrl => "not an http(s) URL",
            Self::Blocked => "not a public address",
            Self::Unreachable => "could not be fetched",
            Self::TooLarge => "too large",
        })
    }
}

/// Looks a host name up. The system resolver in production; tests supply
/// their own to play a rebinding name.
pub trait Resolve: Send + Sync {
    fn lookup(&self, host: &str, port: u16) -> impl Future<Output = std::io::Result<Vec<SocketAddr>>> + Send;
}

/// `getaddrinfo`, via tokio.
pub struct SystemResolver;

impl Resolve for SystemResolver {
    async fn lookup(&self, host: &str, port: u16) -> std::io::Result<Vec<SocketAddr>> {
        Ok(tokio::net::lookup_host((host, port)).await?.collect())
    }
}

/// Which addresses may be reached. Production is always `PublicOnly`; the
/// other exists so this module's tests can talk to a server on loopback.
#[derive(Clone, Copy, Debug)]
pub enum Reach {
    PublicOnly,
    #[cfg(test)]
    Only(IpAddr),
}

impl Reach {
    fn allows(self, ip: IpAddr) -> bool {
        match self {
            Self::PublicOnly => is_public(ip),
            #[cfg(test)]
            Self::Only(allowed) => ip == allowed,
        }
    }
}

/// A fetched body and the URL that finally answered (a relative `og:image`
/// resolves against that, not against what was asked for).
#[derive(Debug)]
pub struct Fetched {
    pub body: Vec<u8>,
    pub final_url: Url,
}

/// How much of a body to read.
#[derive(Clone, Copy, Debug)]
pub struct Limit {
    pub bytes: usize,
    /// Past the cap: keep what was read (a page, whose `<head>` is at the
    /// top) rather than fail (a picture, which is useless cut short).
    pub truncate: bool,
}

/// GET `url` (public addresses only), reading at most `limit`.
pub async fn fetch(url: &str, limit: Limit, user_agent: &str) -> Result<Fetched, FetchError> {
    fetch_with(url, limit, user_agent, Reach::PublicOnly, &SystemResolver).await
}

pub async fn fetch_with<R: Resolve>(
    url: &str,
    limit: Limit,
    user_agent: &str,
    reach: Reach,
    resolver: &R,
) -> Result<Fetched, FetchError> {
    let mut next = Url::parse(url).map_err(|_| FetchError::BadUrl)?;

    for _ in 0..=MAX_HOPS {
        let addrs = checked_addresses(&next, reach, resolver).await?;

        let mut client = reqwest::Client::builder()
            .timeout(TIMEOUT)
            .connect_timeout(Duration::from_secs(5))
            .user_agent(user_agent)
            // Followed by hand below, so each hop is checked; a client that
            // followed them itself would check the first host and then go
            // wherever it was told, 169.254.169.254 included.
            .redirect(Policy::none())
            // HTTP(S)_PROXY from the environment would carry the request
            // past the address check.
            .no_proxy();
        // Connect to exactly the addresses just checked. Without this the
        // client resolves the name again, and a name can answer differently
        // the second time.
        if let Some(Host::Domain(domain)) = next.host() {
            client = client.resolve_to_addrs(domain, &addrs);
        }
        let client = client.build().map_err(|_| FetchError::Unreachable)?;

        let mut response = client.get(next.clone()).send().await.map_err(|_| FetchError::Unreachable)?;

        if response.status().is_redirection() {
            let location = response
                .headers()
                .get(reqwest::header::LOCATION)
                .and_then(|v| v.to_str().ok())
                .ok_or(FetchError::Unreachable)?;
            next = next.join(location).map_err(|_| FetchError::BadUrl)?;
            continue;
        }
        if !response.status().is_success() {
            return Err(FetchError::Unreachable);
        }

        // Read incrementally and stop at the cap, rather than trusting
        // Content-Length, which a hostile server may understate.
        let mut body = Vec::new();
        while let Some(chunk) = response.chunk().await.map_err(|_| FetchError::Unreachable)? {
            if body.len() + chunk.len() > limit.bytes {
                if !limit.truncate {
                    return Err(FetchError::TooLarge);
                }
                body.extend_from_slice(&chunk[..limit.bytes - body.len()]);
                break;
            }
            body.extend_from_slice(&chunk);
        }
        if body.is_empty() {
            return Err(FetchError::Unreachable);
        }
        return Ok(Fetched { body, final_url: next });
    }
    Err(FetchError::Unreachable)
}

/// The addresses `url` may be fetched from, or why not. Every address a name
/// resolves to must pass: one private answer among public ones is refused.
async fn checked_addresses<R: Resolve>(url: &Url, reach: Reach, resolver: &R) -> Result<Vec<SocketAddr>, FetchError> {
    if !matches!(url.scheme(), "http" | "https") {
        return Err(FetchError::BadUrl);
    }
    let port = url.port_or_known_default().ok_or(FetchError::BadUrl)?;
    let addrs: Vec<SocketAddr> = match url.host().ok_or(FetchError::BadUrl)? {
        Host::Ipv4(ip) => vec![SocketAddr::new(IpAddr::V4(ip), port)],
        Host::Ipv6(ip) => vec![SocketAddr::new(IpAddr::V6(ip), port)],
        Host::Domain(name) => resolver.lookup(name, port).await.map_err(|_| FetchError::Unreachable)?,
    };
    if addrs.is_empty() {
        return Err(FetchError::Unreachable);
    }
    if addrs.iter().any(|a| !reach.allows(a.ip())) {
        return Err(FetchError::Blocked);
    }
    Ok(addrs)
}

/// Whether an address is on the public internet. Everything else (loopback,
/// private ranges, link-local, CGNAT, documentation, multicast, unique-local,
/// and IPv4 in an IPv6 costume) is refused.
pub fn is_public(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(v4) => {
            let o = v4.octets();
            !(v4.is_loopback()
                || v4.is_private()
                || v4.is_link_local()
                || v4.is_broadcast()
                || v4.is_documentation()
                || v4.is_unspecified()
                || v4.is_multicast()
                // 0.0.0.0/8
                || o[0] == 0
                // 100.64.0.0/10, carrier-grade NAT
                || (o[0] == 100 && (o[1] & 0xC0) == 64)
                // 192.0.0.0/24, protocol assignments
                || (o[0] == 192 && o[1] == 0 && o[2] == 0)
                // 198.18.0.0/15, benchmarking
                || (o[0] == 198 && (o[1] & 0xFE) == 18)
                // 240.0.0.0/4, reserved
                || o[0] >= 240)
        }
        IpAddr::V6(v6) => {
            if let Some(mapped) = v6.to_ipv4_mapped() {
                return is_public(IpAddr::V4(mapped));
            }
            let s = v6.segments();
            // 64:ff9b::/96, NAT64: the IPv4 address is in the last 32 bits.
            if s[0] == 0x64 && s[1] == 0xff9b && s[2..6] == [0, 0, 0, 0] {
                let v4 = std::net::Ipv4Addr::new((s[6] >> 8) as u8, s[6] as u8, (s[7] >> 8) as u8, s[7] as u8);
                return is_public(IpAddr::V4(v4));
            }
            !(v6.is_loopback()
                || v6.is_unspecified()
                || v6.is_multicast()
                // ::/96, IPv4-compatible (deprecated)
                || s[..6] == [0, 0, 0, 0, 0, 0]
                // fc00::/7, unique local
                || (s[0] & 0xFE00) == 0xFC00
                // fe80::/10, link local
                || (s[0] & 0xFFC0) == 0xFE80
                // fec0::/10, site local (deprecated)
                || (s[0] & 0xFFC0) == 0xFEC0
                // 2001:db8::/32, documentation
                || (s[0] == 0x2001 && s[1] == 0x0db8))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    const UA: &str = "recourse-link-preview/1.0 (+https://forum.test)";
    const K: Limit = Limit { bytes: 1024, truncate: false };

    #[test]
    fn private_and_local_addresses_are_refused() {
        for blocked in [
            "127.0.0.1",
            "127.8.9.10",
            "0.0.0.0",
            "10.1.2.3",
            "172.16.0.1",
            "192.168.1.1",
            // Cloud metadata: the address this whole fence exists for.
            "169.254.169.254",
            "100.64.0.1",
            "198.18.0.1",
            "255.255.255.255",
            "::1",
            "::",
            "fe80::1",
            "fc00::1",
            "fd12:3456::1",
            // A private address wearing an IPv6 costume.
            "::ffff:127.0.0.1",
            "::ffff:10.0.0.1",
            "::ffff:169.254.169.254",
            "64:ff9b::a9fe:a9fe",
            "::127.0.0.1",
        ] {
            let ip: IpAddr = blocked.parse().unwrap();
            assert!(!is_public(ip), "{blocked} should be refused");
        }
    }

    #[test]
    fn ordinary_public_addresses_are_allowed() {
        for allowed in ["1.1.1.1", "8.8.8.8", "93.184.216.34", "2606:4700::1111", "64:ff9b::808:808"] {
            let ip: IpAddr = allowed.parse().unwrap();
            assert!(is_public(ip), "{allowed} should be allowed");
        }
    }

    #[tokio::test]
    async fn only_http_and_https_are_fetched() {
        for bad in ["file:///etc/passwd", "ftp://example.com/x", "data:text/html,x", "javascript:alert(1)", "not a url"] {
            assert_eq!(fetch(bad, K, UA).await.unwrap_err(), FetchError::BadUrl, "{bad}");
        }
    }

    /// Literal private addresses are refused before anything connects.
    #[tokio::test]
    async fn literal_private_addresses_are_refused() {
        for url in [
            "http://127.0.0.1/",
            "http://10.0.0.1/",
            "http://169.254.169.254/latest/meta-data/",
            "http://[::1]/",
            "http://[fd00::1]:8080/",
            "http://[::ffff:127.0.0.1]/",
            "http://0x7f000001/",
            "http://2130706433/",
        ] {
            assert_eq!(fetch(url, K, UA).await.unwrap_err(), FetchError::Blocked, "{url}");
        }
    }

    /// A name pointing at loopback is the usual way past a check that only
    /// reads the URL's text.
    #[tokio::test]
    async fn a_name_resolving_to_loopback_is_refused() {
        assert_eq!(fetch("http://localhost:5439/", K, UA).await.unwrap_err(), FetchError::Blocked);
    }

    /// Answers from a fixed table, counting lookups. `flip` switches every
    /// answer after the first to `then` (DNS rebinding).
    struct Table {
        first: Vec<IpAddr>,
        then: Option<Vec<IpAddr>>,
        calls: AtomicUsize,
    }

    impl Resolve for Table {
        async fn lookup(&self, _host: &str, port: u16) -> std::io::Result<Vec<SocketAddr>> {
            let n = self.calls.fetch_add(1, Ordering::SeqCst);
            let ips = match (&self.then, n) {
                (Some(then), n) if n > 0 => then,
                _ => &self.first,
            };
            Ok(ips.iter().map(|ip| SocketAddr::new(*ip, port)).collect())
        }
    }

    fn table(first: &[&str], then: Option<&[&str]>) -> Table {
        let p = |v: &[&str]| v.iter().map(|s| s.parse().unwrap()).collect();
        Table { first: p(first), then: then.map(p), calls: AtomicUsize::new(0) }
    }

    /// One private answer among public ones is enough to refuse.
    #[tokio::test]
    async fn a_name_with_any_private_answer_is_refused() {
        let r = table(&["93.184.216.34", "10.0.0.7"], None);
        let err = fetch_with("http://mixed.test/", K, UA, Reach::PublicOnly, &r).await.unwrap_err();
        assert_eq!(err, FetchError::Blocked);
        let r = table(&["fd00::2"], None);
        let err = fetch_with("http://ula.test/", K, UA, Reach::PublicOnly, &r).await.unwrap_err();
        assert_eq!(err, FetchError::Blocked);
    }

    async fn serve(app: axum::Router) -> (SocketAddr, tokio::task::JoinHandle<()>) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let handle = tokio::spawn(async move {
            let _ = axum::serve(listener, app).await;
        });
        (addr, handle)
    }

    /// DNS rebinding: the name answers with an allowed address when checked
    /// and a forbidden one afterwards. The fetch must connect to what was
    /// checked. Here 127.0.0.1 plays "public" (the only allowed address, and
    /// where the server listens) and 127.0.0.2 plays the private target
    /// (nothing listens there). If the client looked the name up again, it
    /// would either fail to resolve `rebind.test` at all or be handed
    /// 127.0.0.2 and be refused a connection; it succeeds only by using the
    /// checked address.
    #[tokio::test]
    async fn the_connection_goes_to_the_checked_address() {
        use axum::routing::get;
        let (addr, server) = serve(axum::Router::new().route("/", get(|| async { "<title>ok</title>" }))).await;
        let r = table(&["127.0.0.1"], Some(&["127.0.0.2"]));
        let url = format!("http://rebind.test:{}/", addr.port());
        let got = fetch_with(&url, K, UA, Reach::Only("127.0.0.1".parse().unwrap()), &r)
            .await
            .expect("the checked address answers");
        assert_eq!(got.body, b"<title>ok</title>");
        assert_eq!(r.calls.load(Ordering::SeqCst), 1, "one lookup per hop: the one that was checked");
        server.abort();
    }

    /// A public page that redirects into the private network is refused at
    /// the hop that goes there.
    #[tokio::test]
    async fn a_redirect_into_private_space_is_refused() {
        use axum::response::Redirect;
        use axum::routing::get;
        let app = axum::Router::new()
            .route("/meta", get(|| async { Redirect::temporary("http://169.254.169.254/latest/meta-data/") }))
            .route("/ten", get(|| async { Redirect::permanent("http://10.0.0.1/admin") }))
            .route("/six", get(|| async { Redirect::temporary("http://[fd00::1]/") }))
            .route("/name", get(|| async { Redirect::temporary("http://localhost/") }));
        let (addr, server) = serve(app).await;
        let reach = Reach::Only("127.0.0.1".parse().unwrap());
        for path in ["meta", "ten", "six"] {
            let err = fetch_with(&format!("http://{addr}/{path}"), K, UA, reach, &SystemResolver).await.unwrap_err();
            assert_eq!(err, FetchError::Blocked, "{path}");
        }
        // Through a name, with the real resolver and the real rule: the
        // first hop is our test server, the second "localhost".
        let r = table(&["127.0.0.1"], Some(&["::1"]));
        let err = fetch_with(&format!("http://start.test:{}/name", addr.port()), K, UA, reach, &r)
            .await
            .unwrap_err();
        assert_eq!(err, FetchError::Blocked);
        server.abort();
    }

    #[tokio::test]
    async fn follows_a_redirect_and_reports_where_it_ended() {
        use axum::response::Redirect;
        use axum::routing::get;
        let app = axum::Router::new()
            .route("/moved", get(|| async { Redirect::temporary("/page") }))
            .route("/page", get(|| async { "<title>here</title>" }));
        let (addr, server) = serve(app).await;
        let got = fetch_with(&format!("http://{addr}/moved"), K, UA, Reach::Only(addr.ip()), &SystemResolver)
            .await
            .unwrap();
        assert_eq!(got.body, b"<title>here</title>");
        assert_eq!(got.final_url.path(), "/page");
        server.abort();
    }

    /// The cap is enforced while reading, not from Content-Length.
    #[tokio::test]
    async fn stops_reading_at_the_size_cap() {
        use axum::routing::get;
        let app = axum::Router::new()
            .route("/big", get(|| async { vec![b'x'; 200_000] }))
            .route("/gone", get(|| async { axum::http::StatusCode::NOT_FOUND }))
            .route("/empty", get(|| async { "" }))
            .route("/loop", get(|| async { axum::response::Redirect::temporary("/loop") }));
        let (addr, server) = serve(app).await;
        let reach = Reach::Only(addr.ip());
        let get = |p: &str| format!("http://{addr}/{p}");
        assert_eq!(fetch_with(&get("big"), Limit { bytes: 50_000, truncate: false }, UA, reach, &SystemResolver).await.unwrap_err(), FetchError::TooLarge);
        // A page is cut at the cap instead: its <head> is at the top.
        let cut = fetch_with(&get("big"), Limit { bytes: 50_000, truncate: true }, UA, reach, &SystemResolver).await.unwrap();
        assert_eq!(cut.body.len(), 50_000);
        for p in ["gone", "empty", "loop"] {
            assert_eq!(fetch_with(&get(p), K, UA, reach, &SystemResolver).await.unwrap_err(), FetchError::Unreachable, "{p}");
        }
        server.abort();
    }

    /// Requests say who they are (Wikipedia, among others, refuses one that
    /// doesn't).
    #[tokio::test]
    async fn requests_carry_a_user_agent() {
        use axum::http::HeaderMap;
        use axum::routing::get;
        let app = axum::Router::new().route(
            "/",
            get(|h: HeaderMap| async move { h.get("user-agent").and_then(|v| v.to_str().ok()).unwrap_or("").to_string() }),
        );
        let (addr, server) = serve(app).await;
        let got = fetch_with(&format!("http://{addr}/"), K, UA, Reach::Only(addr.ip()), &SystemResolver).await.unwrap();
        assert_eq!(String::from_utf8(got.body).unwrap(), UA);
        server.abort();
    }
}