diff --git a/crates/core/src/connector/fuzz.rs b/crates/core/src/connector/fuzz.rs new file mode 100644 index 0000000..c924fab --- /dev/null +++ b/crates/core/src/connector/fuzz.rs @@ -0,0 +1,33 @@ +//! Fuzz of the port's request reader and answer (S037): no panic, a web page never gets a link in. + +use super::*; +use crate::fuzz::run; + +fn request(extra: &str, body: &str) -> Vec { + format!("POST / HTTP/1.1\r\nHost: 127.0.0.1:17616\r\nContent-Type: application/json\r\n{extra}Content-Length: {}\r\n\r\n{body}", body.len()).into_bytes() +} + +#[tokio::test] +async fn requests() { + let one = request("", r#"{"url":"https://h/a.zip","filename":"../.x","cookies":"k=v","headers":{"X-A":"1","Host":"evil"}}"#); + let list = request("", r#"[{"url":"ftp://h/b"},{"url":"javascript:alert(1)"},{"url":""},{}]"#); + let web = request("Origin: https://evil.test\r\n", r#"{"url":"https://h/a.zip"}"#); + let ping = b"GET / HTTP/1.1\r\nHost: localhost:17616\r\n\r\n".to_vec(); + let mut inputs = vec![]; + run(&[&one, &list, &web, &ping], |b| inputs.push(b.to_vec())); + for b in inputs { + let Ok(Ok(req)) = tokio::time::timeout(Duration::from_secs(1), wire::read(&mut &b[..])).await else { continue }; + let (code, _, entry) = answer(&req, 17616); + let from_web = req.header("origin").is_some() || req.header("sec-fetch-mode") == Some("cors"); + if from_web { + assert_ne!(code, 200, "{}", String::from_utf8_lossy(&b)); + } + if let Some((_, _, taken)) = entry { + for link in taken { + if let Some(name) = &link.name { + crate::fuzz::assert_safe_name(name); + } + } + } + } +} diff --git a/crates/core/src/connector/mod.rs b/crates/core/src/connector/mod.rs index 9f9014f..ef301a1 100644 --- a/crates/core/src/connector/mod.rs +++ b/crates/core/src/connector/mod.rs @@ -257,7 +257,11 @@ async fn serve(mut want: watch::Receiver<(bool, u16)>, shared: Arc, link tokio::select! { changed = want.changed() => if changed.is_err() { return } else { break }, accepted = listener.accept() => if let Ok((stream, peer)) = accepted { - let Ok(permit) = gate.connections.clone().try_acquire_owned() else { continue }; + let Ok(permit) = gate.connections.clone().try_acquire_owned() else { + // Full: say so at once instead of closing without a word (S037). + tokio::spawn(busy(stream)); + continue; + }; let (shared, links, gate) = (shared.clone(), links.clone(), gate.clone()); tokio::spawn(async move { handle(stream, peer, port, &shared, &links, &gate).await; @@ -284,6 +288,16 @@ async fn serve(mut want: watch::Receiver<(bool, u16)>, shared: Arc, link } } +/// Answer 429 to a connection over the limit, without reading it; the client sees "busy", not a reset. +async fn busy(mut stream: TcpStream) { + let answer = wire::answer(Refused::Busy.status(), &serde_json::json!({ "error": Refused::Busy.code() })); + let _ = tokio::time::timeout(Duration::from_secs(1), async { + let _ = stream.write_all(&answer).await; + let _ = stream.shutdown().await; + }) + .await; +} + struct Gate { connections: Arc, tokens: Mutex<(f64, Instant)>, @@ -396,3 +410,6 @@ fn guard(request: &wire::Request, port: u16) -> Result<(), Refused> { _ => Err(Refused::Method), } } + +#[cfg(test)] +mod fuzz; diff --git a/crates/core/src/fuzz.rs b/crates/core/src/fuzz.rs new file mode 100644 index 0000000..af17623 --- /dev/null +++ b/crates/core/src/fuzz.rs @@ -0,0 +1,113 @@ +//! Short fuzz runs of the parsers (S037): seeds mutated at random, no panic, and the safety rules hold. +//! Fixed seeds of the random source, so a failure repeats; `MEDLAR_FUZZ=n` runs more rounds. + +use crate::{batch::Batch, http::name, listing, metalink, redact}; + +pub(crate) fn rounds() -> usize { + std::env::var("MEDLAR_FUZZ").ok().and_then(|n| n.parse().ok()).unwrap_or(2000) +} + +const PIECES: &[&[u8]] = &[ + b"\0", b"\r\n", b"\n", b"/", b"\\", b"..", b"%2F", b"%00", b"\"", b"'", b";", b"=", b"*", b"<", b">", b"&", b"[", b"]", + b"{", b"}", b"-", b":", b"99999999999999999999", b"18446744073709551615", b"-1", b"0", b"\xff\xfe", b"\xe2\x80\xae", + b"\xc3", b"UTF-8''", b"", b"