// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! The fuzz targets' bodies (ROADMAP ยง5 layer 3), as plain functions: cargo-fuzz calls them //! from `fuzz/fuzz_targets/*` (libFuzzer), and `tests/regressions.rs` replays every saved input //! under `regressions//` in the ordinary `cargo test`, so a crash once found stays a //! test. A target must never panic on any input; where a property is cheap, it is asserted //! (a panic is how libFuzzer learns about it). //! //! Everything here is hostile input in production: route files (the routes repository), the //! header rules in them, share tokens and paths from visitors, CSRs and PEM files handed to the //! CA. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use std::path::PathBuf; use std::sync::OnceLock; use ianitor_core::compile::{self, CompileOptions}; use ianitor_core::edge_config::{EdgeConfig, EdgeTls}; use ianitor_core::share::{self, LinkSpec, Revocations, ShareId, ShareKey}; use ianitor_core::{SourceFile, load, pki, routes}; /// Every target, by the name its directories use. pub const TARGETS: &[(&str, fn(&[u8]))] = &[ ("routes", routes_toml), ("header_rules", header_rules), ("share_token", share_token), ("path_within", path_within), ("pki_pem", pki_pem), ]; fn text(data: &[u8]) -> String { String::from_utf8_lossy(data).into_owned() } /// The byte that splits one input into two (ASCII unit separator; not NUL, so seeds stay text /// files the pre-commit hook accepts). pub const SEP: u8 = 0x1f; /// Split at the first [`SEP`]: two independent inputs from one. fn split2(data: &[u8]) -> (&[u8], &[u8]) { match data.iter().position(|b| *b == SEP) { Some(i) => (&data[..i], &data[i + 1..]), None => (data, &[]), } } fn options() -> CompileOptions { CompileOptions { http_listen: "127.0.0.1:8080".parse().unwrap(), https_listen: "127.0.0.1:8443".parse().unwrap(), cert_dir: "/var/lib/ianitor/certs".into(), state_dir: "/var/lib/ianitor/state".into(), access_log: "/var/log/ianitor/access.log".into(), caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(), caddy_admin: None, caddy_admin_socket: Some("/run/caddy-fallback/admin.sock".into()), trusted_proxies: vec!["127.0.0.1".parse().unwrap()], proxy_socket: Some("/run/ianitor-proxy/edge.sock".into()), } } /// Load, then: both compilers succeed, are deterministic, and the edge config reads back. fn compile_checked(site: &str, hosts: &[(String, String)]) { let sources: Vec> = hosts .iter() .map(|(n, c)| SourceFile { name: n, contents: c, }) .collect(); let Ok(model) = load( &SourceFile { name: "ianitor.toml", contents: site, }, &sources, ) else { return; }; let o = options(); let edge = compile::edge(&model, &o).expect("a valid model compiles for edge"); let caddy = compile::caddy(&model, &o).expect("a valid model compiles for Caddy"); assert_eq!( edge, compile::edge(&model, &o).unwrap(), "edge output is deterministic" ); assert_eq!( caddy, compile::caddy(&model, &o).unwrap(), "Caddy output is deterministic" ); let cfg: EdgeConfig = serde_json::from_str(&edge).expect("edge reads what core writes"); let _: serde_json::Value = serde_json::from_str(&caddy).expect("the Caddy JSON is JSON"); build_edge_runtime(cfg); } /// The credentials directory the edge runtime reads secrets from (fixed test values). fn creds_dir() -> &'static PathBuf { static DIR: OnceLock = OnceLock::new(); DIR.get_or_init(|| { let d = std::env::temp_dir().join(format!("ianitor-fuzz-creds-{}", std::process::id())); std::fs::create_dir_all(&d).unwrap(); std::fs::write(d.join("api_key"), b"fuzz-secret-value\n").unwrap(); std::fs::write(d.join("ui-proof"), b"fuzz-proof-value\n").unwrap(); std::fs::write( d.join("share-link-key"), b"fuzz-share-link-key-0123456789abcdef0123456789", ) .unwrap(); d }) } /// Edge builds its runtime (header names and values, upstream addresses) from a compiled /// config. Files are kept out of it: no certificates to read, no access log to open, no device /// lists; what is left must build, since core validated it. fn build_edge_runtime(mut cfg: EdgeConfig) { cfg.device_certs = None; for h in &mut cfg.hosts { h.tls = EdgeTls::Acme; h.access_log = false; h.device_certs = false; } if let Err(e) = ianitor_edge::runtime::build(cfg, Some(creds_dir())) { panic!("edge refused a config core compiled: {e}"); } } /// Route files: a site file and one host file, split at the first SEP. Also the repository /// path check on the host file's first line. pub fn routes_toml(data: &[u8]) { let (site, host) = split2(data); let (site, host) = (text(site), text(host)); let path = host.lines().next().unwrap_or_default(); let _ = routes::check_path(path, routes::EntryKind::File); // Name the host file after the hostname it claims, so a valid file can get through. let name = host .lines() .find_map(|l| l.trim().strip_prefix("hostname")) .and_then(|r| r.split('"').nth(1)) .unwrap_or("x.test") .to_owned(); compile_checked(&site, &[(format!("hosts/{name}.toml"), host)]); } /// Header rules: the input is appended to a host file that is otherwise valid, so the fuzzer /// spends its time on `[[request_headers]]` / `[[response_headers]]` (names, values, secrets, /// the protected list), through both compilers and edge's runtime. pub fn header_rules(data: &[u8]) { let site = "secrets = [\"api_key\", \"ui-proof\"]\n"; let host = format!( "hostname = \"h.test\"\nupstreams = [\"http://127.0.0.1:9000\"]\ntls = \"domi\"\n{}", text(data) ); compile_checked(site, &[("hosts/h.test.toml".to_owned(), host)]); } fn key() -> &'static ShareKey { static KEY: OnceLock = OnceLock::new(); KEY.get_or_init(|| ShareKey::new(b"fuzz-share-link-key-0123456789abcdef0123456789").unwrap()) } /// Share tokens from visitors: a token and a password (split at SEP) checked as a link and as /// a session; then a link minted from the input's bytes verifies for its own host and password /// only. pub fn share_token(data: &[u8]) { let (token, password) = split2(data); let (token, password) = (text(token), text(password)); let revs = Revocations::default(); let _ = share::peek(&token); let pw = (!password.is_empty()).then_some(password.as_str()); let _ = share::verify_link(key(), "h.test", &token, pw, 1_000, &revs); let _ = share::verify_session(key(), "h.test", &token, 1_000, &revs); // Round trip with input-derived claims. let Ok(prefix) = share::check_prefix(&token) else { return; }; let mut id = [0u8; 16]; for (i, b) in data.iter().take(16).enumerate() { id[i] = *b; } let spec = LinkSpec { id: ShareId(id), epoch: u32::from(data.first().copied().unwrap_or(0)), expires_at: 2_000, prefix: &prefix, password: pw, }; let Ok(t) = share::mint(key(), "h.test", &spec) else { return; }; let c = share::verify_link(key(), "h.test", &t, pw, 1_000, &revs) .expect("a minted link verifies for its host"); assert_eq!(c.prefix, prefix); assert!( share::path_within(&prefix, &prefix), "a prefix covers itself" ); assert!( share::verify_link(key(), "other.test", &t, pw, 1_000, &revs).is_err(), "a link is bound to its host" ); if pw.is_some() { assert!( share::verify_link(key(), "h.test", &t, Some("not the password"), 1_000, &revs) .is_err() || password == "not the password", "a password link needs its password" ); } let s = share::session_value(key(), "h.test", &c); assert!(share::verify_session(key(), "h.test", &s, 1_000, &revs).is_ok()); assert!( share::verify_link(key(), "h.test", &t, pw, 2_000, &revs).is_err(), "expired" ); } /// Visitor paths against a share link's prefix: never a panic; a checked prefix covers itself; /// a dot segment never escapes it. pub fn path_within(data: &[u8]) { let (prefix, path) = split2(data); let (prefix, path) = (text(prefix), text(path)); let _ = share::path_within(&prefix, &path); if let Ok(p) = share::check_prefix(&prefix) { assert!(share::path_within(&p, &p)); let escape = format!("{}/../outside", p.trim_end_matches('/')); assert!(!share::path_within(&p, &escape), "{escape} escaped {p}"); } } /// The root the CA target signs with (made once; the fuzzer never sees its key). fn test_root() -> &'static (String, pki::KeyPair) { static ROOT: OnceLock<(String, pki::KeyPair)> = OnceLock::new(); ROOT.get_or_init(|| pki::create_root(1_700_000_000).unwrap()) } /// PEM and CSRs handed to the CA: parsers never panic, and a CSR the root signs gives an /// intermediate the root issued. pub fn pki_pem(data: &[u8]) { let (a, _) = split2(data); let pem = text(a); let _ = pki::inspect(&pem); let _ = pki::inspect_der(a); let _ = pki::chain_der(&pem); let _ = pki::first_pem(&pem); let _ = pki::public_key_der(&pem); let _ = pki::csr_der(&pem); let _ = pki::csr_public_key_der(&pem); let _ = pki::KeyPair::from_pem(&pem); let _ = pki::KeyPair::from_der(a); let (root_pem, root_key) = test_root(); let _ = pki::intermediate_problem(&pem, root_pem, 1_700_000_100); let _ = pki::issued_by(&pem, root_pem); if let Ok(cert) = pki::sign_intermediate(root_pem, root_key, &pem, 1_700_000_100) { assert_eq!(pki::issued_by(&cert, root_pem).ok(), Some(true)); } }