use std::borrow::Cow;
use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use rustls::pki_types::ServerName;
#[derive(Debug, Clone)]
pub(crate) struct Authority {
socket: SocketAddr,
name: Option<Arc<str>>,
tls: bool,
}
impl Authority {
pub(crate) fn new(socket: SocketAddr) -> Self {
Self {
socket,
name: None,
tls: false,
}
}
pub(crate) fn for_tunnel(
socket: SocketAddr,
tunnel: Option<crate::fingerprint::Tunnel>,
) -> Self {
Self {
socket,
name: None,
tls: matches!(tunnel, Some(crate::fingerprint::Tunnel::Tls)),
}
}
pub(crate) fn named(mut self, name: Option<Arc<str>>) -> Self {
self.name = name;
self
}
pub(crate) fn through_tls(&self) -> Self {
Self {
tls: true,
..self.clone()
}
}
pub(crate) fn is_tls(&self) -> bool {
self.tls
}
pub(crate) fn server_name(&self) -> ServerName<'static> {
self.name
.as_deref()
.and_then(|name| ServerName::try_from(name.to_string()).ok())
.unwrap_or_else(|| ServerName::IpAddress(self.socket.ip().into()))
}
pub(crate) fn sni(&self) -> Option<String> {
match self.server_name() {
ServerName::DnsName(name) => Some(name.as_ref().to_owned()),
_ => None,
}
}
pub(crate) fn addressed<'a>(&self, payload: &'a [u8]) -> Cow<'a, [u8]> {
self.with_host(payload, |_| true)
}
pub(crate) fn readdressed<'a>(&self, payload: &'a [u8]) -> Cow<'a, [u8]> {
self.with_host(payload, |value| self.stands_for_this_port(value))
}
fn with_host<'a>(&self, payload: &'a [u8], replace: impl Fn(&[u8]) -> bool) -> Cow<'a, [u8]> {
let Some(head) = find(payload, b"\r\n\r\n") else {
return Cow::Borrowed(payload);
};
let Some(line_end) = find(&payload[..head], b"\r\n") else {
return Cow::Borrowed(payload);
};
if find(&payload[..line_end], b" HTTP/1.").is_none() {
return Cow::Borrowed(payload);
}
let mut at = line_end + 2;
while at < head {
let end = find(&payload[at..head], b"\r\n").map_or(head, |n| at + n);
let line = &payload[at..end];
if let Some(colon) = line.iter().position(|&byte| byte == b':')
&& line[..colon].eq_ignore_ascii_case(b"host")
{
if !replace(&line[colon + 1..]) {
return Cow::Borrowed(payload);
}
let mut addressed = Vec::with_capacity(payload.len() + 64);
addressed.extend_from_slice(&payload[..at + colon + 1]);
addressed.push(b' ');
addressed.extend_from_slice(self.header().as_bytes());
addressed.extend_from_slice(&payload[end..]);
return Cow::Owned(addressed);
}
at = end + 2;
}
Cow::Borrowed(payload)
}
pub(crate) fn socket(&self) -> SocketAddr {
self.socket
}
fn scheme(&self) -> &'static str {
match self.tls {
true => "https",
false => "http",
}
}
fn default_port(&self) -> u16 {
match self.tls {
true => 443,
false => 80,
}
}
fn host(&self) -> String {
if let Some(name) = &self.name {
return name.to_string();
}
match self.socket.ip() {
IpAddr::V4(v4) => v4.to_string(),
IpAddr::V6(v6) => format!("[{v6}]"),
}
}
pub(crate) fn header(&self) -> String {
match self.socket.port() == self.default_port() {
true => self.host(),
false => format!("{}:{}", self.host(), self.socket.port()),
}
}
pub(crate) fn path_of(&self, url: &str) -> Option<String> {
let rest = match url.split_once("://") {
Some((scheme, rest)) if scheme.eq_ignore_ascii_case(self.scheme()) => rest,
Some(_) => return None,
None => url.strip_prefix("//")?,
};
let (authority, path) = match rest.find(['/', '?', '#']) {
Some(at) => rest.split_at(at),
None => (rest, ""),
};
if authority.contains('@') {
return None;
}
let (host, port) = split_authority(authority)?;
let port = match port {
Some(port) => port,
None => self.default_port(),
};
if port != self.socket.port() || !self.names(host) {
return None;
}
Some(match path {
"" => "/".to_string(),
query if !query.starts_with('/') => format!("/{query}"),
path => path.to_string(),
})
}
fn stands_for_this_port(&self, value: &[u8]) -> bool {
let Ok(value) = std::str::from_utf8(value) else {
return false;
};
let value = value.trim();
if value.is_empty()
|| value
.parse::<IpAddr>()
.is_ok_and(|address| address == self.socket.ip())
{
return true;
}
split_authority(value)
.is_some_and(|(host, _)| host.eq_ignore_ascii_case("localhost") || self.names(host))
}
fn names(&self, host: &str) -> bool {
if host
.parse::<IpAddr>()
.is_ok_and(|address| address == self.socket.ip())
{
return true;
}
let bare = |name: &str| name.strip_suffix('.').unwrap_or(name).to_owned();
self.name
.as_deref()
.is_some_and(|name| bare(name).eq_ignore_ascii_case(&bare(host)))
}
}
fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
haystack
.windows(needle.len())
.position(|window| window == needle)
}
fn split_authority(authority: &str) -> Option<(&str, Option<u16>)> {
let (host, port) = match authority.strip_prefix('[') {
Some(bracketed) => {
let (host, after) = bracketed.split_once(']')?;
match after {
"" => (host, None),
port => (host, Some(port.strip_prefix(':')?)),
}
}
None => match authority.rsplit_once(':') {
Some((host, port)) => (host, Some(port)),
None => (authority, None),
},
};
if host.is_empty() {
return None;
}
let port = match port {
None | Some("") => None,
Some(port) => Some(port.parse().ok()?),
};
Some((host, port))
}
#[cfg(test)]
mod tests {
use super::*;
fn at(socket: &str) -> Authority {
Authority::new(socket.parse().expect("a literal socket address"))
}
#[test]
fn a_host_header_names_the_port_only_where_the_scheme_does_not() {
assert_eq!(at("192.0.2.1:80").header(), "192.0.2.1");
assert_eq!(at("192.0.2.1:8080").header(), "192.0.2.1:8080");
assert_eq!(at("[2001:db8::1]:80").header(), "[2001:db8::1]");
assert_eq!(at("[2001:db8::1]:8080").header(), "[2001:db8::1]:8080");
}
#[test]
fn a_named_port_is_asked_for_by_its_name() {
let named = at("192.0.2.1:8443").named(Some(Arc::from("box.example")));
assert_eq!(named.header(), "box.example:8443");
assert_eq!(named.through_tls().header(), "box.example:8443");
let https = at("192.0.2.1:443").named(Some(Arc::from("box.example")));
assert_eq!(https.through_tls().header(), "box.example");
assert_eq!(https.header(), "box.example:443");
}
#[test]
fn a_handshake_carries_the_name_and_never_an_address() {
let named = at("192.0.2.1:443").named(Some(Arc::from("box.example")));
assert!(
matches!(named.server_name(), ServerName::DnsName(dns) if dns.as_ref() == "box.example")
);
assert!(matches!(
at("192.0.2.1:443").server_name(),
ServerName::IpAddress(_)
));
assert_eq!(named.sni().as_deref(), Some("box.example"));
assert_eq!(at("192.0.2.1:443").sni(), None);
}
#[test]
fn an_authored_request_is_addressed_to_the_port_asked() {
let named = at("192.0.2.1:80").named(Some(Arc::from("box.example")));
let probe = b"GET / HTTP/1.1\r\nHost: localhost\r\nAccept: */*\r\n\r\n";
assert_eq!(
&*named.addressed(probe),
b"GET / HTTP/1.1\r\nHost: box.example\r\nAccept: */*\r\n\r\n"
);
let last = b"GET /v2/ HTTP/1.1\r\nhost:localhost\r\n\r\n";
assert_eq!(
&*at("[2001:db8::1]:5000").addressed(last),
b"GET /v2/ HTTP/1.1\r\nhost: [2001:db8::1]:5000\r\n\r\n"
);
for untouched in [
&b"GET / HTTP/1.0\r\n\r\n"[..],
b"0011git-upload-pack /\0host=localhost\0",
b"<stream:stream to='localhost'>",
b"PING\r\nHost: localhost\r\n\r\n",
] {
assert!(matches!(named.addressed(untouched), Cow::Borrowed(_)));
}
}
#[test]
fn a_detection_request_is_addressed_only_where_it_stands_for_the_port() {
let named = at("[2001:db8::1]:8080").named(Some(Arc::from("box.example")));
let request = |host: &str| format!("GET / HTTP/1.1\r\nHost: {host}\r\n\r\n").into_bytes();
let addressed = request("box.example:8080");
for stand_in in [
"localhost",
"LOCALHOST:80",
"2001:db8::1",
"[2001:db8::1]:8080",
"box.example",
"",
] {
assert_eq!(
&*named.readdressed(&request(stand_in)),
&addressed[..],
"`{stand_in}` stands for the port"
);
}
for other in ["evil.example", "192.0.2.9", "[2001:db8::2]"] {
assert!(
matches!(named.readdressed(&request(other)), Cow::Borrowed(_)),
"`{other}` names another site"
);
}
}
#[test]
fn a_url_naming_the_name_asked_for_leads_back() {
let named = at("192.0.2.1:80").named(Some(Arc::from("box.example")));
assert_eq!(
named.path_of("http://BOX.example./login").as_deref(),
Some("/login")
);
assert_eq!(
named.path_of("http://192.0.2.1/login").as_deref(),
Some("/login")
);
assert_eq!(named.path_of("http://dev.box.example/"), None);
assert_eq!(at("192.0.2.1:80").path_of("http://box.example/"), None);
}
#[test]
fn a_url_leads_back_whatever_spelling_names_the_same_address_and_port() {
let v6 = at("[2001:db8::1]:80");
assert_eq!(v6.path_of("http://[2001:db8::1]/a").as_deref(), Some("/a"));
assert_eq!(
v6.path_of("http://[2001:DB8:0::1]:80/a").as_deref(),
Some("/a")
);
assert_eq!(v6.path_of("HTTP://[2001:db8::1]").as_deref(), Some("/"));
assert_eq!(v6.path_of("//[2001:db8::1]?x=1").as_deref(), Some("/?x=1"));
}
#[test]
fn a_url_naming_anything_else_does_not_lead_back() {
let here = at("192.0.2.1:8080");
for url in [
"http://192.0.2.2:8080/",
"http://192.0.2.1/",
"http://192.0.2.1:8081/",
"https://192.0.2.1:8080/",
"http://user@192.0.2.1:8080/",
"http://192.0.2.1:port/",
"http://:8080/",
"http://[2001:db8::1]:8080/",
] {
assert_eq!(here.path_of(url), None, "`{url}` does not lead back");
}
}
}