use std::net::IpAddr;
use std::sync::{Arc, OnceLock};
use rustls::pki_types::CertificateDer;
pub fn builder(url: &str) -> ureq::AgentBuilder {
let builder = ureq::AgentBuilder::new().tls_config(tls_config());
let env = |key: &str| std::env::var(key).ok().filter(|v| !v.trim().is_empty());
match proxy_for(url, &env).and_then(|p| ureq::Proxy::new(p).ok()) {
Some(proxy) => builder.proxy(proxy),
None => builder,
}
}
pub fn get(url: &str) -> ureq::Request {
builder(url).build().get(url)
}
pub fn read_capped(reader: impl std::io::Read, max: u64) -> std::io::Result<Vec<u8>> {
use std::io::Read;
let mut bytes = Vec::new();
reader.take(max.saturating_add(1)).read_to_end(&mut bytes)?;
if bytes.len() as u64 > max {
return Err(std::io::Error::new(
std::io::ErrorKind::FileTooLarge,
format!("the download is larger than its {} limit", size_label(max)),
));
}
Ok(bytes)
}
pub fn too_large(e: &std::io::Error) -> bool {
e.kind() == std::io::ErrorKind::FileTooLarge
}
pub fn sha256_hex(bytes: &[u8]) -> String {
use sha2::Digest;
format!("{:x}", sha2::Sha256::digest(bytes))
}
pub fn sha256_matches(bytes: &[u8], expected: &str) -> bool {
let expected = expected.trim().to_ascii_lowercase();
expected.len() == 64 && sha256_hex(bytes) == expected
}
fn size_label(max: u64) -> String {
const MIB: u64 = 1024 * 1024;
if max >= MIB && max.is_multiple_of(MIB) {
format!("{} MiB", max / MIB)
} else {
format!("{max} bytes")
}
}
pub fn describe(err: &ureq::Error) -> String {
let t = match err {
ureq::Error::Status(code, _) => return format!("HTTP {code}"),
ureq::Error::Transport(t) => t,
};
let mut why = t.kind().to_string();
if let Some(message) = t.message() {
why.push_str(&format!(": {message}"));
}
let source = std::error::Error::source(t);
if let Some(source) = source {
why.push_str(&format!(": {source}"));
}
let bad_cert = source
.and_then(|e| e.downcast_ref::<std::io::Error>())
.and_then(|e| e.get_ref())
.and_then(|e| e.downcast_ref::<rustls::Error>())
.is_some_and(|e| matches!(e, rustls::Error::InvalidCertificate(_)));
if bad_cert {
why.push_str(
" (behind a TLS-inspecting proxy? add its CA to the system store or SSL_CERT_FILE)",
);
}
why
}
fn tls_config() -> Arc<rustls::ClientConfig> {
static CONFIG: OnceLock<Arc<rustls::ClientConfig>> = OnceLock::new();
let config = CONFIG.get_or_init(|| {
let native = rustls_native_certs::load_native_certs();
for e in &native.errors {
crate::lsp::log_file::log(&format!("net: reading the platform CA store: {e}"));
}
client_config(native.certs)
});
Arc::clone(config)
}
fn client_config(platform: Vec<CertificateDer<'static>>) -> Arc<rustls::ClientConfig> {
let provider = Arc::new(rustls::crypto::ring::default_provider());
Arc::new(
rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.expect("ring supports TLS 1.2 and 1.3")
.with_root_certificates(root_store(platform))
.with_no_client_auth(),
)
}
fn root_store(platform: Vec<CertificateDer<'static>>) -> rustls::RootCertStore {
let mut roots = rustls::RootCertStore {
roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
};
roots.add_parsable_certificates(platform);
roots
}
fn proxy_for(url: &str, env: &dyn Fn(&str) -> Option<String>) -> Option<String> {
let url = url::Url::parse(url).ok()?;
let keys = match url.scheme() {
"https" => ["https_proxy", "HTTPS_PROXY", "all_proxy", "ALL_PROXY"],
"http" => ["http_proxy", "HTTP_PROXY", "all_proxy", "ALL_PROXY"],
_ => return None,
};
let proxy = keys.iter().find_map(|k| env(k))?;
let no_proxy = env("no_proxy")
.or_else(|| env("NO_PROXY"))
.unwrap_or_default();
(!bypasses(&url.host()?, &no_proxy)).then_some(proxy)
}
fn bypasses(host: &url::Host<&str>, no_proxy: &str) -> bool {
let (name, ip): (&str, Option<IpAddr>) = match *host {
url::Host::Domain(d) => (d, None),
url::Host::Ipv4(a) => ("", Some(a.into())),
url::Host::Ipv6(a) => ("", Some(a.into())),
};
if name == "localhost" || ip.is_some_and(|ip| ip.is_loopback()) {
return true;
}
let entries = no_proxy
.split(',')
.map(|e| e.trim().trim_matches(['[', ']']));
entries.filter(|e| !e.is_empty()).any(|entry| {
if entry == "*" {
return true;
}
match (ip, entry.split_once('/')) {
(Some(ip), Some((net, bits))) => in_cidr(ip, net, bits),
(Some(ip), None) => entry.parse::<IpAddr>().is_ok_and(|e| e == ip),
(None, _) => {
let domain = entry.trim_start_matches('*').trim_start_matches('.');
let domain = domain.to_ascii_lowercase();
let sub = |p: &str| p.ends_with('.');
!domain.is_empty()
&& (name == domain || name.strip_suffix(&*domain).is_some_and(sub))
}
}
})
}
fn in_cidr(ip: IpAddr, net: &str, bits: &str) -> bool {
let (Ok(net), Ok(bits)) = (net.parse::<IpAddr>(), bits.parse::<u32>()) else {
return false;
};
match (ip, net) {
(IpAddr::V4(a), IpAddr::V4(n)) if bits <= 32 => {
let mask = u32::MAX.checked_shl(32 - bits).unwrap_or(0);
u32::from(a) & mask == u32::from(n) & mask
}
(IpAddr::V6(a), IpAddr::V6(n)) if bits <= 128 => {
let mask = u128::MAX.checked_shl(128 - bits).unwrap_or(0);
u128::from(a) & mask == u128::from(n) & mask
}
_ => false,
}
}
#[cfg(test)]
pub(crate) mod tests {
#[test]
fn sha256_matches_only_the_true_digest() {
let bytes = b"csvlens release bytes";
let decoy = "8b0fa3ee6b2b3d3b0a0a4f3f6d2d7d5f1a4f0d6b3d5b1f0e3a4b7c2d9e8f1a0b";
assert!(!sha256_matches(
bytes,
"0000000000000000000000000000000000000000000000000000000000000000"
));
assert!(!sha256_matches(bytes, ""));
let real = {
use sha2::Digest;
format!("{:x}", sha2::Sha256::digest(bytes))
};
assert_ne!(real, decoy, "the decoy is not this input's digest");
assert!(sha256_matches(bytes, &real), "the true digest is accepted");
assert!(
sha256_matches(bytes, &real.to_uppercase()),
"case does not matter"
);
}
use super::*;
use std::io::{Read, Write};
use std::path::Path;
fn test_cert() -> Vec<CertificateDer<'static>> {
use rustls::pki_types::pem::PemObject;
let pem = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/web/testdata/cert.pem");
CertificateDer::pem_file_iter(pem)
.unwrap()
.map(Result::unwrap)
.collect()
}
pub(crate) fn https_server() -> String {
let here = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/web/testdata");
let config = crate::web::tls::load(&here.join("cert.pem"), &here.join("key.pem")).unwrap();
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
std::thread::spawn(move || {
for tcp in listener.incoming().flatten() {
let Ok(mut plain) = crate::web::tls::terminate(tcp, Arc::clone(&config)) else {
continue;
};
std::thread::spawn(move || {
let mut head = Vec::new();
let mut b = [0u8; 1];
while !head.ends_with(b"\r\n\r\n") && plain.read(&mut b).unwrap_or(0) == 1 {
head.push(b[0]);
}
let reply =
"HTTP/1.1 200 OK\r\ncontent-length: 2\r\nconnection: close\r\n\r\nok";
let _ = plain.write_all(reply.as_bytes());
});
}
});
format!("https://127.0.0.1:{port}/")
}
#[test]
fn a_ca_from_the_platform_store_is_trusted_alongside_the_mozilla_roots() {
let url = https_server();
let with_platform = ureq::AgentBuilder::new().tls_config(client_config(test_cert()));
let body = with_platform
.build()
.get(&url)
.call()
.unwrap()
.into_string();
assert_eq!(body.unwrap(), "ok");
let without = ureq::AgentBuilder::new().tls_config(client_config(Vec::new()));
let err = without.build().get(&url).call().unwrap_err();
let why = describe(&err);
assert!(why.contains("UnknownIssuer"), "{why}");
assert!(why.contains("SSL_CERT_FILE"), "{why}");
assert!(!why.contains("127.0.0.1"), "no URL in the reason: {why}");
}
fn testdata(name: &str) -> Vec<CertificateDer<'static>> {
use rustls::pki_types::pem::PemObject;
let pem = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("src/net/testdata")
.join(name);
CertificateDer::pem_file_iter(pem)
.unwrap()
.map(Result::unwrap)
.collect()
}
fn verify(platform: Vec<CertificateDer<'static>>, host: &str) -> Result<(), rustls::Error> {
use rustls::client::danger::ServerCertVerifier;
use rustls::pki_types::{ServerName, UnixTime};
let chain = testdata(&format!("{host}.pem"));
let provider = Arc::new(rustls::crypto::ring::default_provider());
let verifier = rustls::client::WebPkiServerVerifier::builder_with_provider(
Arc::new(root_store(platform)),
provider,
)
.build()
.unwrap();
let now = UnixTime::since_unix_epoch(std::time::Duration::from_secs(1_792_800_000));
let name = ServerName::try_from(host.to_string()).unwrap();
verifier
.verify_server_cert(&chain[0], &chain[1..], &name, &[], now)
.map(|_| ())
}
#[test]
fn a_compromised_emudhra_chain_is_refused_though_the_platform_trusts_its_root() {
for host in [
"dv-g3b-emudhra.we-have-a-problem.com",
"dv-g3b-aaa-emudhra.we-have-a-problem.com",
] {
let refused = verify(testdata("emudhra-roots.pem"), host);
assert!(
matches!(refused, Err(rustls::Error::InvalidCertificate(_))),
"{host}: {refused:?}"
);
}
verify(
testdata("emudhra-roots.pem"),
"emudhra.we-have-a-problem.com",
)
.unwrap();
}
#[test]
fn the_mozilla_roots_no_longer_carry_the_distrusted_emsign_roots() {
let subjects: Vec<String> = root_store(Vec::new())
.roots
.iter()
.map(|anchor| String::from_utf8_lossy(anchor.subject.as_ref()).into_owned())
.collect();
for gone in [
"emSign ECC Root CA - G3",
"emSign ECC Root CA - C3",
"emSign Root CA - C1",
] {
assert!(!subjects.iter().any(|s| s.contains(gone)), "{gone}");
}
assert!(subjects.iter().any(|s| s.contains("emSign Root CA - G1")));
}
#[test]
fn the_proxy_follows_the_scheme_and_no_proxy() {
let env = |pairs: &'static [(&'static str, &'static str)]| {
move |k: &str| pairs.iter().find(|p| p.0 == k).map(|p| p.1.to_string())
};
const NO_PROXY: &str = "internal.corp, .lan,*.svc.local,10.0.0.0/8,192.168.1.7,[fd00::1]";
let corp = env(&[
("HTTPS_PROXY", "http://gw:8080"),
("http_proxy", "http://plain:3128"),
("NO_PROXY", NO_PROXY),
]);
let proxy = |url: &str| proxy_for(url, &corp).unwrap_or_default();
assert_eq!(proxy("https://github.com/x"), "http://gw:8080");
assert_eq!(proxy("http://example.com/"), "http://plain:3128");
for exempt in [
"https://internal.corp/",
"https://git.internal.corp/",
"https://nas.lan/",
"https://api.svc.local/",
"https://10.20.30.40/",
"https://192.168.1.7:8443/",
"https://[fd00::1]/",
"http://localhost:3000/",
"http://127.0.0.1:8080/",
"http://[::1]/",
] {
assert_eq!(proxy(exempt), "", "{exempt}");
}
for outside in [
"https://notinternal.corp/",
"https://192.168.1.8/",
"https://11.0.0.1/",
] {
assert_eq!(proxy(outside), "http://gw:8080", "{outside}");
}
let all = env(&[("ALL_PROXY", "http://all:1")]);
assert_eq!(
proxy_for("https://a.b/", &all).as_deref(),
Some("http://all:1")
);
let star = env(&[("https_proxy", "http://gw:1"), ("no_proxy", "*")]);
assert_eq!(proxy_for("https://a.b/", &star), None);
assert_eq!(proxy_for("https://a.b/", &env(&[])), None);
}
#[test]
fn a_body_over_the_cap_is_refused_not_truncated() {
let at_cap = read_capped(&[7u8; 16][..], 16).unwrap();
assert_eq!(at_cap, vec![7u8; 16]);
assert_eq!(read_capped(&[][..], 16).unwrap(), Vec::<u8>::new());
let over = read_capped(&[7u8; 17][..], 16).unwrap_err();
assert_eq!(over.kind(), std::io::ErrorKind::FileTooLarge);
assert_eq!(
over.to_string(),
"the download is larger than its 16 bytes limit"
);
let mib = 1024 * 1024;
let over = read_capped(std::io::repeat(0).take(mib + 1), mib).unwrap_err();
assert_eq!(
over.to_string(),
"the download is larger than its 1 MiB limit"
);
}
}