diff --git a/Plans/05 Connector/S023-port-server.md b/Plans/05 Connector/S023-port-server.md index ad2a8f4..042afcc 100644 --- a/Plans/05 Connector/S023-port-server.md +++ b/Plans/05 Connector/S023-port-server.md @@ -12,15 +12,15 @@ A browser hands links to 127.0.0.1:17616; nothing else can abuse it. FEATURES 4. - CLAUDE.md §4 ## Steps -- [ ] Server on loopback only, changeable port, on and off live, port-in-use state that names the fix -- [ ] `GET /` ping with name and version; `POST /` with one link or a list, unknown fields ignored, size and rate limits, answers 2xx quickly -- [ ] Refuses foreign `Host` (DNS rebinding), any web `Origin`, form content types and preflights; no CORS headers -- [ ] Checks links (http, https, ftp, ftps, sftp, stream schemes only), names and headers; hop-by-hop and injection headers dropped -- [ ] Cookies, referrer and user agent used for the download and kept through the keyring module -- [ ] Sender log: when, what, accepted or why not; sender process name from /proc/net/tcp where possible -- [ ] docs/CONNECTOR.md: format, examples with curl, security notes -- [ ] Test file `docs/tests/S023-port-server.md`, with the checks below -- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S023: …`, push +- [x] Server on loopback only, changeable port, on and off live, port-in-use state that names the fix +- [x] `GET /` ping with name and version; `POST /` with one link or a list, unknown fields ignored, size and rate limits, answers 2xx quickly +- [x] Refuses foreign `Host` (DNS rebinding), any web `Origin`, form content types and preflights; no CORS headers +- [x] Checks links (http, https, ftp, ftps, sftp, stream schemes only), names and headers; hop-by-hop and injection headers dropped +- [x] Cookies, referrer and user agent used for the download and kept through the keyring module +- [x] Sender log: when, what, accepted or why not; sender process name from /proc/net/tcp where possible +- [x] docs/CONNECTOR.md: format, examples with curl, security notes +- [x] Test file `docs/tests/S023-port-server.md`, with the checks below +- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S023: …`, push ## End criteria `nice cargo check -q -j 2 -p medlar` clean diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 78b5e4e..1240d58 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -39,7 +39,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H ## 05 Connector -- [ ] [S023](05%20Connector/S023-port-server.md) The port and its protection +- [x] [S023](05%20Connector/S023-port-server.md) The port and its protection - [ ] [S024](05%20Connector/S024-handoff-flow.md) Hand-off flow and Nacre test ## 06 Media diff --git a/crates/core/lang/en.json b/crates/core/lang/en.json index a8f0e07..e96e891 100644 --- a/crates/core/lang/en.json +++ b/crates/core/lang/en.json @@ -330,6 +330,23 @@ "error.login.proxy": "The proxy for {server} wants a user name and password, or the ones it got are wrong.", "secret.memory": "No keyring answered, so logins are only remembered until Medlar closes.", "secret.label": "Medlar login for {host}", + "connector.taken": "Port {port} for the browser is used by another program. Pick another port under Settings, Browser, and give the browser the same one.", + "connector.taken_by": "Port {port} for the browser is used by {by}. Close {by} or pick another port under Settings, Browser, and give the browser the same one.", + "connector.failed": "Port {port} for the browser could not be opened: {why}", + "connector.refused.host": "Refused: it named another computer, as a web page does when it pretends to be this one.", + "connector.refused.origin": "Refused: it came from a web page.", + "connector.refused.preflight": "Refused: a web page asked whether it may send links.", + "connector.refused.type": "Refused: not sent as JSON, as a web form would send it.", + "connector.refused.method": "Refused: not a request for this port.", + "connector.refused.malformed": "Refused: the request was broken.", + "connector.refused.large": "Refused: too large.", + "connector.refused.slow": "Refused: the request did not arrive in time.", + "connector.refused.busy": "Refused: too many requests at once.", + "connector.refused.body": "Refused: it held no link in a known format.", + "connector.refused.no_links": "Refused: none of its links can be downloaded.", + "connector.bad.missing": "There is no link.", + "connector.bad.invalid": "This is not a valid link.", + "connector.bad.scheme": "Medlar can't download this kind of link.", "error.rejected": "Request rejected", "error.rejected.plain": "{server} did not accept the request.", "error.rejected.why": "{server} did not accept the request (status {code}).", diff --git a/crates/core/src/connector/link.rs b/crates/core/src/connector/link.rs new file mode 100644 index 0000000..65fa9fe --- /dev/null +++ b/crates/core/src/connector/link.rs @@ -0,0 +1,209 @@ +//! The links in a hand-over body: Nacre's `custom_body` (D-003, D-010), one object or a list of them. Unknown fields +//! are ignored. Each link is checked alone: a bad one is refused, the others still come in. + +use super::wire::{is_plain, is_token}; +use crate::auth::take_login; +use crate::model::Task; +use crate::redact; +use crate::secret::{self, Kept, Secret, Secrets}; +use serde::Deserialize; +use serde_json::Value; +use std::fmt; +use url::Url; + +pub(super) const LINKS_MAX: usize = 1000; +const URL_MAX: usize = 8 * 1024; +const VALUE_MAX: usize = 8 * 1024; +const COOKIES_MAX: usize = 32 * 1024; +const HEADERS_MAX: usize = 32; + +/// What the engine can fetch: HTTP, FTP, SFTP and the stream schemes the recorder knows. +const SCHEMES: &[&str] = &["http", "https", "ftp", "ftps", "ftpes", "sftp", "rtsp", "mms", "mmsh", "mmst"]; + +/// Never taken from a sender: they belong to the connection, would break ranges or resuming, or are set here. +const DROPPED: &[&str] = &[ + "connection", "keep-alive", "te", "trailer", "transfer-encoding", "upgrade", "host", "content-length", "content-type", + "content-encoding", "accept-encoding", "expect", "range", "origin", +]; +const DROPPED_STARTS: &[&str] = &["proxy-", "if-", "sec-", "access-control-"]; + +#[derive(Deserialize)] +#[serde(untagged)] +pub(super) enum Body { + Many(Vec), + One(Raw), +} + +impl Body { + pub fn links(self) -> Vec { + match self { + Body::Many(links) => links, + Body::One(link) => vec![link], + } + } +} + +#[derive(Deserialize, Default)] +#[serde(default)] +pub(super) struct Raw { + url: Option, + filename: Option, + referrer: Option, + cookies: Option, + user_agent: Option, + headers: Option>, + size: Option, + mime: Option, +} + +/// Why a link was not taken. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Bad { + Missing, + /// Not a link, too long, or with line breaks in it. + Invalid, + Scheme, +} + +impl Bad { + pub fn code(self) -> &'static str { + match self { + Bad::Missing => "missing", + Bad::Invalid => "invalid", + Bad::Scheme => "scheme", + } + } + + pub fn words(self) -> String { + match self { + Bad::Missing => crate::tr!("connector.bad.missing"), + Bad::Invalid => crate::tr!("connector.bad.invalid"), + Bad::Scheme => crate::tr!("connector.bad.scheme"), + } + } +} + +/// A link from the browser, checked. +#[derive(Clone, PartialEq, Eq)] +pub struct Incoming { + /// Without a login: that is in `secret`. + pub url: String, + /// Made safe; None to let the server name it. + pub name: Option, + /// The page it was on, without a login. Sent as Referer and kept to find a new link. + pub page: Option, + pub user_agent: Option, + /// Headers that carry no secret, User-Agent and Referer not among them. + pub headers: Vec<(String, String)>, + /// Cookies, a login and secret headers, for the keyring. + pub secret: Option, + pub size: Option, + pub mime: Option, + /// Names of the headers that were not taken, for the log. + pub dropped: Vec, +} + +impl fmt::Debug for Incoming { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Incoming").field("url", &redact::url(&self.url)).field("name", &self.name).finish_non_exhaustive() + } +} + +fn text(value: Option, max: usize) -> Option { + let Some(Value::String(text)) = value else { return None }; + let text = text.trim(); + (!text.is_empty() && text.len() <= max && is_plain(text)).then(|| text.to_string()) +} + +/// A web page's address without its login, or None. +fn page(text: &str) -> Option { + let mut url = Url::parse(text).ok().filter(|u| matches!(u.scheme(), "http" | "https"))?; + url.set_username("").ok()?; + url.set_password(None).ok()?; + Some(url.into()) +} + +impl Raw { + pub fn check(self) -> Result { + let Some(Value::String(url)) = self.url else { return Err(Bad::Missing) }; + let url = url.trim(); + if url.is_empty() { + return Err(Bad::Missing); + } + if url.len() > URL_MAX || url.chars().any(|c| c.is_control() || c.is_whitespace()) { + return Err(Bad::Invalid); + } + let parsed = Url::parse(url).map_err(|_| Bad::Invalid)?; + if !SCHEMES.contains(&parsed.scheme()) { + return Err(Bad::Scheme); + } + if parsed.host_str().is_none_or(str::is_empty) { + return Err(Bad::Invalid); + } + let (url, login) = take_login(parsed.as_str()); + let name = text(self.filename, VALUE_MAX).and_then(|n| crate::http::name::safe(&n)); + let mut page = text(self.referrer, URL_MAX).and_then(|p| page(&p)); + let mut user_agent = text(self.user_agent, VALUE_MAX); + let mut cookies = text(self.cookies, COOKIES_MAX); + let (mut headers, mut hidden, mut dropped) = (vec![], vec![], vec![]); + for (name, value) in self.headers.unwrap_or_default() { + let lower = name.to_ascii_lowercase(); + let max = if lower == "cookie" { COOKIES_MAX } else { VALUE_MAX }; + let Some(value) = text(Some(value), max).filter(|_| is_token(&name) && name.len() <= 64) else { + dropped.push(if is_token(&name) && name.len() <= 64 { name } else { "?".into() }); + continue; + }; + match lower.as_str() { + "cookie" => { + cookies.get_or_insert(value); + } + "user-agent" => { + user_agent.get_or_insert(value); + } + "referer" => { + if page.is_none() { + page = super::link::page(&value); + } + } + l if DROPPED.contains(&l) || DROPPED_STARTS.iter().any(|s| l.starts_with(s)) => dropped.push(name), + _ if headers.len() + hidden.len() == HEADERS_MAX => dropped.push(name), + l if redact::is_secret_header(l) => hidden.push((name, value)), + _ => headers.push((name, value)), + } + } + let secret = (login.is_some() || cookies.is_some() || !hidden.is_empty()) + .then(|| Secret { home: Some(url.clone()), login, cookies, headers: hidden }); + let size = self.size.and_then(|s| s.as_u64()); + let mime = text(self.mime, 256).filter(|m| m.contains('/')); + Ok(Incoming { url, name, page, user_agent, headers, secret, size, mime, dropped }) + } +} + +impl Incoming { + /// The headers the download is fetched with: the sender's, its User-Agent and the page as Referer. + pub fn task_headers(&self) -> Vec<(String, String)> { + let mut all = self.headers.clone(); + all.extend(self.user_agent.iter().map(|ua| ("User-Agent".to_string(), ua.clone()))); + all.extend(self.page.iter().map(|p| ("Referer".to_string(), p.clone()))); + all + } + + /// A task for it, on top of `common` (folder, queue and so on). Size and type are the sender's guess and are left + /// out: the server tells. Its secret goes to the keyring first, under a new name the task carries; `Kept::Memory` + /// says that it lasts only until Medlar closes. + pub async fn task(&self, secrets: &Secrets, common: Task) -> (Task, Option) { + let mut task = Task { + url: self.url.clone(), + name: self.name.clone().unwrap_or_default(), + source_page: self.page.clone(), + headers: self.task_headers(), + ..common + }; + let Some(secret) = &self.secret else { return (task, None) }; + let name = secret::task_name(); + let host = Url::parse(&self.url).ok().and_then(|u| u.host_str().map(String::from)).unwrap_or_default(); + let kept = secrets.save(&name, &host, secret).await; + task.secret = Some(name); + (task, Some(kept)) + } +} diff --git a/crates/core/src/connector/mod.rs b/crates/core/src/connector/mod.rs new file mode 100644 index 0000000..9f9014f --- /dev/null +++ b/crates/core/src/connector/mod.rs @@ -0,0 +1,398 @@ +//! The local port that takes links from the browser (FEATURES 4.1–4.3, 4.5; format in docs/CONNECTOR.md). +//! +//! Any web page can reach 127.0.0.1, so a request is refused unless it plainly comes from a program on this PC: a +//! `Host` naming loopback and this port (no DNS rebinding), no `Origin` and no cross-site `Sec-Fetch-Site` (no page's +//! fetch or form), `application/json` only (a form can't send it without a preflight, and preflights are refused), no +//! CORS headers in any answer. Bound to 127.0.0.1 only, never 0.0.0.0. + +mod link; +mod peer; +mod wire; + +pub use link::{Bad, Incoming}; + +use crate::model::{Time, now}; +use crate::{VERSION, redact, tr}; +use serde_json::json; +use std::collections::VecDeque; +use std::io; +use std::net::{Ipv4Addr, SocketAddr}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; +use tokio::io::AsyncWriteExt; +use tokio::net::{TcpListener, TcpStream}; +use tokio::sync::{Semaphore, mpsc, watch}; + +/// For the whole request to come in. +const READ: Duration = Duration::from_secs(5); +/// Before a port that was taken is tried again. +const RETRY: Duration = Duration::from_secs(5); +const CONNECTIONS: usize = 16; +/// Requests at once, and per second after that. +const BURST: f64 = 30.0; +const PER_SECOND: f64 = 5.0; +const LOG_MAX: usize = 500; + +/// Whether the port is open. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Status { + Off, + On(u16), + /// Another program has the port; `by` is its name when it can be seen. Tried again every few seconds. + Taken { port: u16, by: Option }, + Failed { port: u16, why: String }, +} + +impl Status { + /// What is wrong and how to fix it, or None when nothing is. + pub fn words(&self) -> Option { + match self { + Status::Off | Status::On(_) => None, + Status::Taken { port, by: Some(by) } => Some(tr!("connector.taken_by", port = port, by = by)), + Status::Taken { port, by: None } => Some(tr!("connector.taken", port = port)), + Status::Failed { port, why } => Some(tr!("connector.failed", port = port, why = why)), + } + } +} + +/// Why a request was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Refused { + /// `Host` is not this PC and port: a web page through DNS rebinding. + Host, + /// Sent by a web page. + Origin, + Preflight, + /// Not `application/json`, as a web form would send. + Type, + Method, + Path, + Malformed, + TooLarge, + /// Chunked or without a length. + Length, + Slow, + Busy, + /// Not the JSON of a link or a list of them. + Body, + /// None of its links could be taken. + NoLinks, + TooMany, +} + +impl Refused { + fn status(self) -> u16 { + match self { + Refused::Host | Refused::Origin => 403, + Refused::Preflight | Refused::Method => 405, + Refused::Type => 415, + Refused::Path => 404, + Refused::Malformed | Refused::Body => 400, + Refused::TooLarge | Refused::TooMany => 413, + Refused::Length => 411, + Refused::Slow => 408, + Refused::Busy => 429, + Refused::NoLinks => 422, + } + } + + /// For the sender: stable, in English. + pub fn code(self) -> &'static str { + match self { + Refused::Host => "host", + Refused::Origin => "origin", + Refused::Preflight => "preflight", + Refused::Type => "content-type", + Refused::Method => "method", + Refused::Path => "path", + Refused::Malformed => "malformed", + Refused::TooLarge => "too-large", + Refused::Length => "length", + Refused::Slow => "slow", + Refused::Busy => "busy", + Refused::Body => "body", + Refused::NoLinks => "no-links", + Refused::TooMany => "too-many", + } + } + + pub fn words(self) -> String { + match self { + Refused::Host => tr!("connector.refused.host"), + Refused::Origin => tr!("connector.refused.origin"), + Refused::Preflight => tr!("connector.refused.preflight"), + Refused::Type => tr!("connector.refused.type"), + Refused::Method | Refused::Path => tr!("connector.refused.method"), + Refused::Malformed | Refused::Length => tr!("connector.refused.malformed"), + Refused::TooLarge | Refused::TooMany => tr!("connector.refused.large"), + Refused::Slow => tr!("connector.refused.slow"), + Refused::Busy => tr!("connector.refused.busy"), + Refused::Body => tr!("connector.refused.body"), + Refused::NoLinks => tr!("connector.refused.no_links"), + } + } +} + +/// Who sent it. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Sender { + /// The program's name, when it is the user's own and could be seen. + pub process: Option, + /// Its port. + pub port: u16, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Outcome { + Accepted { links: usize, refused: usize }, + Refused(Refused), +} + +/// One line of the sender log. `what` has no secrets: links without login or query string. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Entry { + pub at: Time, + pub from: Sender, + pub what: String, + pub outcome: Outcome, +} + +/// Links that came in together. The incoming-link event for the UI. +#[derive(Debug, Clone)] +pub struct Arrival { + pub links: Vec, + pub from: Sender, + pub at: Time, +} + +#[derive(Default)] +struct Shared { + status: Mutex>, + log: Mutex>, + wake: Mutex>>, +} + +impl Shared { + fn set(&self, status: Status) { + *self.status.lock().unwrap() = Some(status); + self.wake(); + } + + fn note(&self, entry: Entry) { + match &entry.outcome { + Outcome::Refused(why) => log::info!("connector: refused {} from {:?}: {}", entry.what, entry.from.process, why.code()), + Outcome::Accepted { links, .. } => log::info!("connector: {links} links from {:?}", entry.from.process), + } + let mut list = self.log.lock().unwrap(); + if list.len() == LOG_MAX { + list.pop_front(); + } + list.push_back(entry); + drop(list); + self.wake(); + } + + fn wake(&self) { + if let Some(call) = &*self.wake.lock().unwrap() { + call(); + } + } +} + +/// The port, on its own thread. Dropping it closes the port. +pub struct Connector { + want: watch::Sender<(bool, u16)>, + shared: Arc, +} + +impl Connector { + /// Port 0 takes any free one (for tests); `status` tells which. + pub fn start(on: bool, port: u16) -> io::Result<(Connector, mpsc::UnboundedReceiver)> { + let (want, wanted) = watch::channel((on, port)); + let (links, arrivals) = mpsc::unbounded_channel(); + let shared = Arc::new(Shared::default()); + let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?; + let inner = shared.clone(); + std::thread::Builder::new().name("connector".into()).spawn(move || runtime.block_on(serve(wanted, inner, links)))?; + Ok((Connector { want, shared }, arrivals)) + } + + /// On or off and the port, live. + pub fn set(&self, on: bool, port: u16) { + self.want.send_if_modified(|w| std::mem::replace(w, (on, port)) != (on, port)); + } + + /// None until the first try is done. + pub fn status(&self) -> Option { + self.shared.status.lock().unwrap().clone() + } + + /// Oldest first. + pub fn log(&self) -> Vec { + self.shared.log.lock().unwrap().iter().cloned().collect() + } + + /// Called from the connector's thread when the status or the log changes. + pub fn on_change(&self, call: impl Fn() + Send + 'static) { + *self.shared.wake.lock().unwrap() = Some(Box::new(call)); + } +} + +async fn serve(mut want: watch::Receiver<(bool, u16)>, shared: Arc, links: mpsc::UnboundedSender) { + loop { + let (on, port) = *want.borrow_and_update(); + if !on { + shared.set(Status::Off); + if want.changed().await.is_err() { + return; + } + continue; + } + match TcpListener::bind((Ipv4Addr::LOCALHOST, port)).await { + Ok(listener) => { + let port = listener.local_addr().map_or(port, |a| a.port()); + shared.set(Status::On(port)); + let gate = Arc::new(Gate::new()); + loop { + 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 (shared, links, gate) = (shared.clone(), links.clone(), gate.clone()); + tokio::spawn(async move { + handle(stream, peer, port, &shared, &links, &gate).await; + drop(permit); + }); + }, + } + } + } + Err(e) => { + let status = if e.kind() == io::ErrorKind::AddrInUse { + let by = tokio::task::spawn_blocking(move || peer::listener(port)).await.ok().flatten(); + Status::Taken { port, by } + } else { + Status::Failed { port, why: e.to_string() } + }; + shared.set(status); + tokio::select! { + changed = want.changed() => if changed.is_err() { return }, + _ = tokio::time::sleep(RETRY) => {}, + } + } + } + } +} + +struct Gate { + connections: Arc, + tokens: Mutex<(f64, Instant)>, +} + +impl Gate { + fn new() -> Gate { + Gate { connections: Arc::new(Semaphore::new(CONNECTIONS)), tokens: Mutex::new((BURST, Instant::now())) } + } + + fn take(&self) -> bool { + let mut tokens = self.tokens.lock().unwrap(); + let (left, since) = *tokens; + let left = (left + since.elapsed().as_secs_f64() * PER_SECOND).min(BURST); + let taken = left >= 1.0; + *tokens = (if taken { left - 1.0 } else { left }, Instant::now()); + taken + } +} + +async fn handle(mut stream: TcpStream, peer: SocketAddr, port: u16, shared: &Shared, links: &mpsc::UnboundedSender, gate: &Gate) { + let other = peer.port(); + let who = tokio::task::spawn_blocking(move || peer::process(port, other)); + let (code, body, entry) = if gate.take() { + match tokio::time::timeout(READ, wire::read(&mut stream)).await { + Err(_) => refuse(Refused::Slow, "?".into()), + Ok(Err(why)) => refuse(why, "?".into()), + Ok(Ok(request)) => answer(&request, port), + } + } else { + refuse(Refused::Busy, "?".into()) + }; + let from = Sender { process: who.await.ok().flatten(), port: other }; + let _ = stream.write_all(&wire::answer(code, &body)).await; + let _ = stream.shutdown().await; + let Some((what, outcome, taken)) = entry else { return }; + if !taken.is_empty() { + let _ = links.send(Arrival { links: taken, from: from.clone(), at: now() }); + } + shared.note(Entry { at: now(), from, what, outcome }); +} + +/// Status, body, and what goes in the log (None for a ping). +type Answer = (u16, serde_json::Value, Option<(String, Outcome, Vec)>); + +fn refuse(why: Refused, what: String) -> Answer { + (why.status(), json!({ "error": why.code() }), Some((what, Outcome::Refused(why), vec![]))) +} + +fn answer(request: &wire::Request, port: u16) -> Answer { + // The path only: a query string may hold anything. + let path: String = request.target.split(['?', '#']).next().unwrap_or("").chars().take(100).collect(); + let what = format!("{} {path}", request.method); + if let Err(why) = guard(request, port) { + return refuse(why, what); + } + if request.method == "GET" { + return (200, json!({ "name": "Medlar", "version": VERSION }), None); + } + let Ok(body) = serde_json::from_slice::(&request.body) else { return refuse(Refused::Body, what) }; + let raw = body.links(); + if raw.len() > link::LINKS_MAX { + return refuse(Refused::TooMany, what); + } + let (mut taken, mut refused) = (vec![], vec![]); + for (index, link) in raw.into_iter().enumerate() { + match link.check() { + Ok(link) => taken.push(link), + Err(bad) => refused.push(json!({ "index": index, "why": bad.code() })), + } + } + let what = match taken.first() { + Some(first) => format!("{} ({})", redact::url(&first.url), taken.len()), + None => what, + }; + if taken.is_empty() { + let (code, _, entry) = refuse(Refused::NoLinks, what); + return (code, json!({ "error": Refused::NoLinks.code(), "refused": refused }), entry); + } + let outcome = Outcome::Accepted { links: taken.len(), refused: refused.len() }; + (200, json!({ "accepted": taken.len(), "refused": refused }), Some((what, outcome, taken))) +} + +/// Everything that tells a program on this PC from a web page. +fn guard(request: &wire::Request, port: u16) -> Result<(), Refused> { + let host = request.header("host").unwrap_or("").to_ascii_lowercase(); + let own = [format!("127.0.0.1:{port}"), format!("localhost:{port}")]; + if request.count("host") != 1 || !own.contains(&host) { + return Err(Refused::Host); + } + let fetch_site = request.header("sec-fetch-site"); + if request.header("origin").is_some() || fetch_site.is_some_and(|s| s != "none") || request.header("sec-fetch-mode").is_some_and(|m| m == "cors") { + return Err(Refused::Origin); + } + if request.method == "OPTIONS" || request.header("access-control-request-method").is_some() { + return Err(Refused::Preflight); + } + if request.target != "/" { + return Err(Refused::Path); + } + match request.method.as_str() { + "GET" => Ok(()), + "POST" => { + let kind = request.header("content-type").unwrap_or("").to_ascii_lowercase(); + let mut parts = kind.split(';').map(str::trim); + let json = parts.next() == Some("application/json"); + let utf8 = parts.all(|p| p.is_empty() || matches!(p, "charset=utf-8" | "charset=\"utf-8\"")); + if json && utf8 && request.count("content-type") == 1 { Ok(()) } else { Err(Refused::Type) } + } + _ => Err(Refused::Method), + } +} diff --git a/crates/core/src/connector/peer.rs b/crates/core/src/connector/peer.rs new file mode 100644 index 0000000..93cea1a --- /dev/null +++ b/crates/core/src/connector/peer.rs @@ -0,0 +1,44 @@ +//! Which program is at the other end of a connection on this PC: `/proc/net/tcp` gives the socket's inode, a process's +//! `fd` folder has a link to it. Only the user's own processes can be seen; others stay unnamed. + +use std::fs; + +/// The program whose socket has port `own` here and `other` at its other end, both on 127.0.0.1. +pub(super) fn process(own: u16, other: u16) -> Option { + inode(|local, remote, _| local == own && remote == other).and_then(owner) +} + +/// The program that listens on `port`. +pub(super) fn listener(port: u16) -> Option { + inode(|local, _, state| local == port && state == "0A").and_then(owner) +} + +fn port(address: &str) -> Option { + u16::from_str_radix(address.rsplit(':').next()?, 16).ok() +} + +fn inode(want: impl Fn(u16, u16, &str) -> bool) -> Option { + ["/proc/net/tcp", "/proc/net/tcp6"].iter().find_map(|file| { + let table = fs::read_to_string(file).ok()?; + table.lines().skip(1).find_map(|line| { + let f: Vec<&str> = line.split_whitespace().collect(); + let (local, remote) = (port(f.get(1)?)?, port(f.get(2)?)?); + let inode: u64 = f.get(9)?.parse().ok()?; + (inode != 0 && want(local, remote, f.get(3)?)).then_some(inode) + }) + }) +} + +fn owner(inode: u64) -> Option { + let link = format!("socket:[{inode}]"); + for process in fs::read_dir("/proc").ok()?.flatten() { + let pid = process.file_name(); + let Some(pid) = pid.to_str().filter(|p| p.bytes().all(|b| b.is_ascii_digit())) else { continue }; + let Ok(fds) = fs::read_dir(format!("/proc/{pid}/fd")) else { continue }; + if fds.flatten().any(|fd| fs::read_link(fd.path()).is_ok_and(|l| l.as_os_str() == link.as_str())) { + let name = fs::read_to_string(format!("/proc/{pid}/comm")).ok()?; + return Some(name.trim().chars().filter(|c| !c.is_control()).collect()); + } + } + None +} diff --git a/crates/core/src/connector/wire.rs b/crates/core/src/connector/wire.rs new file mode 100644 index 0000000..a0fe0df --- /dev/null +++ b/crates/core/src/connector/wire.rs @@ -0,0 +1,135 @@ +//! One HTTP/1.1 request, read strictly, and its answer: only what a browser's hand-over needs. One request per +//! connection, a body only with Content-Length. + +use super::Refused; +use tokio::io::{AsyncRead, AsyncReadExt}; + +pub(super) const HEAD_MAX: usize = 16 * 1024; +pub(super) const BODY_MAX: usize = 1024 * 1024; +const HEADERS_MAX: usize = 64; + +pub(super) struct Request { + pub method: String, + pub target: String, + /// Names in lower case. + pub headers: Vec<(String, String)>, + pub body: Vec, +} + +impl Request { + pub fn header(&self, name: &str) -> Option<&str> { + self.headers.iter().find(|(n, _)| n == name).map(|(_, v)| v.as_str()) + } + + pub fn count(&self, name: &str) -> usize { + self.headers.iter().filter(|(n, _)| n == name).count() + } +} + +/// A token in the sense of RFC 9110: what header names and methods are made of. +pub(super) fn is_token(text: &str) -> bool { + !text.is_empty() && text.bytes().all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)) +} + +/// Visible text, spaces and tabs: no line breaks or other control characters. +pub(super) fn is_plain(text: &str) -> bool { + text.chars().all(|c| c == '\t' || !c.is_control()) +} + +pub(super) async fn read(stream: &mut (impl AsyncRead + Unpin)) -> Result { + let mut buffer = Vec::with_capacity(2048); + let end = loop { + if let Some(at) = buffer.windows(4).position(|w| w == b"\r\n\r\n") { + break at; + } + if buffer.len() > HEAD_MAX { + return Err(Refused::TooLarge); + } + let mut chunk = [0u8; 4096]; + let n = stream.read(&mut chunk).await.map_err(|_| Refused::Malformed)?; + if n == 0 { + return Err(Refused::Malformed); + } + buffer.extend_from_slice(&chunk[..n]); + }; + if end > HEAD_MAX { + return Err(Refused::TooLarge); + } + let head = std::str::from_utf8(&buffer[..end]).map_err(|_| Refused::Malformed)?; + let mut lines = head.split("\r\n"); + let mut first = lines.next().unwrap_or("").split(' '); + let (Some(method), Some(target), Some(version), None) = (first.next(), first.next(), first.next(), first.next()) else { + return Err(Refused::Malformed); + }; + if !is_token(method) || target.is_empty() || !is_plain(target) || !matches!(version, "HTTP/1.1" | "HTTP/1.0") { + return Err(Refused::Malformed); + } + let mut headers = vec![]; + for line in lines { + // No folded lines, no names with spaces before the colon. + let Some((name, value)) = line.split_once(':') else { return Err(Refused::Malformed) }; + if !is_token(name) || !is_plain(value) || headers.len() == HEADERS_MAX { + return Err(Refused::Malformed); + } + headers.push((name.to_ascii_lowercase(), value.trim_matches([' ', '\t']).to_string())); + } + let mut request = Request { method: method.into(), target: target.into(), headers, body: vec![] }; + if request.header("transfer-encoding").is_some() { + return Err(Refused::Length); + } + let lengths: Vec<&str> = request.headers.iter().filter(|(n, _)| n == "content-length").map(|(_, v)| v.as_str()).collect(); + let length = match lengths[..] { + [] => 0, + [one] if !one.is_empty() && one.bytes().all(|b| b.is_ascii_digit()) => one.parse::().map_err(|_| Refused::TooLarge)?, + _ => return Err(Refused::Malformed), + }; + if length > BODY_MAX { + return Err(Refused::TooLarge); + } + let mut body = buffer.split_off(end + 4); + if body.len() > length { + // A second request on the same connection: not taken. + return Err(Refused::Malformed); + } + body.reserve_exact(length - body.len()); + while body.len() < length { + let mut chunk = vec![0u8; (length - body.len()).min(64 * 1024)]; + let n = stream.read(&mut chunk).await.map_err(|_| Refused::Malformed)?; + if n == 0 { + return Err(Refused::Malformed); + } + body.extend_from_slice(&chunk[..n]); + } + request.body = body; + Ok(request) +} + +/// The whole answer. No CORS headers, ever: a web page must not read it. +pub(super) fn answer(code: u16, body: &serde_json::Value) -> Vec { + let reason = match code { + 200 => "OK", + 400 => "Bad Request", + 403 => "Forbidden", + 404 => "Not Found", + 405 => "Method Not Allowed", + 408 => "Request Timeout", + 411 => "Length Required", + 413 => "Content Too Large", + 415 => "Unsupported Media Type", + 422 => "Unprocessable Content", + 429 => "Too Many Requests", + _ => "Error", + }; + let body = body.to_string(); + let mut out = format!( + "HTTP/1.1 {code} {reason}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\ + Cache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n", + body.len() + ); + if code == 405 { + out.push_str("Allow: GET, POST\r\n"); + } + out.push_str("\r\n"); + out.push_str(&body); + out.into_bytes() +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index fffa6b7..8e75f34 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -4,6 +4,7 @@ pub mod adapt; pub mod adopt; pub mod auth; pub mod batch; +pub mod connector; pub mod cookie; pub mod disk; pub mod duplicate; diff --git a/crates/core/tests/connector_nacre.json b/crates/core/tests/connector_nacre.json new file mode 100644 index 0000000..7d68c3b --- /dev/null +++ b/crates/core/tests/connector_nacre.json @@ -0,0 +1 @@ +{"cookies":"k=v","filename":"a.zip","headers":{"Cookie":"k=v","Referer":"https://example.com/","User-Agent":"UA"},"mime":null,"referrer":"https://example.com/","size":null,"url":"https://example.com/a.zip","user_agent":"UA"} diff --git a/docs/CONNECTOR.md b/docs/CONNECTOR.md new file mode 100644 index 0000000..dcb20ea --- /dev/null +++ b/docs/CONNECTOR.md @@ -0,0 +1,63 @@ +# The browser port + +Medlar listens on `127.0.0.1:17616` (D-006; changeable under Settings, Browser; on and off live). Only programs on this +PC can reach it. Code: `crates/core/src/connector/`. + +## Format + +`GET /` answers `{"name": "Medlar", "version": "0.1.0"}`: a ping. + +`POST /` with `Content-Type: application/json` and a body of one link or a list of them. This is Nacre's +`custom_body` as it is (D-003, D-010); unknown fields are ignored. + +| Field | | | +|---|---|---| +| `url` | required | http, https, ftp, ftps, ftpes, sftp, rtsp, mms, mmsh, mmst | +| `filename` | | made safe: path parts, control characters and leading dots go | +| `referrer` | | the page; sent as `Referer`, kept to find a new link later | +| `cookies` | | as in a `Cookie` header; kept in the keyring only | +| `user_agent` | | sent with the download | +| `headers` | | object of name to value; `Cookie`, `User-Agent`, `Referer` fill the fields above when those are empty | +| `size`, `mime` | | the sender's guess, shown only | + +Answer `200 {"accepted": n, "refused": [{"index": i, "why": "scheme"}]}` when one or more links came in, else an error +with `{"error": ""}`: + +| Status | `error` | Why | +|---|---|---| +| 403 | `host` | `Host` is not `127.0.0.1:` or `localhost:` (DNS rebinding) | +| 403 | `origin` | an `Origin` header, `Sec-Fetch-Site` other than `none`, or `Sec-Fetch-Mode: cors` | +| 405 | `preflight`, `method` | `OPTIONS`, `Access-Control-Request-Method`, or anything but GET and POST | +| 415 | `content-type` | not `application/json` (form types, `text/plain`) | +| 404 | `path` | anything but `/` | +| 400 | `malformed`, `body` | broken HTTP, or JSON that is no link or list | +| 411 | `length` | chunked body | +| 413 | `too-large`, `too-many` | head over 16 KiB, body over 1 MiB, list over 1000 links | +| 408 | `slow` | request not in within 5 s | +| 429 | `busy` | over 30 at once or 5 a second | +| 422 | `no-links` | no link in it could be taken (`why`: `missing`, `invalid`, `scheme`) | + +## Examples + +```sh +curl -s http://127.0.0.1:17616/ +curl -s -H 'Content-Type: application/json' -d '{"url": "https://example.com/a.zip"}' http://127.0.0.1:17616/ +curl -s -H 'Content-Type: application/json' \ + -d '[{"url": "https://example.com/a.zip", "filename": "a.zip", "referrer": "https://example.com/", + "cookies": "k=v", "user_agent": "UA", "headers": {"X-Kind": "one"}}, {"url": "ftp://example.com/b.iso"}]' \ + http://127.0.0.1:17616/ +``` + +## Security + +- Bound to 127.0.0.1 only, never 0.0.0.0. Port 15151 belongs to AB Download Manager and is not used. +- No CORS headers in any answer, so a web page can't read one; JSON only, so a page can't post without a preflight, + and preflights are refused. `Host` is checked against loopback and the port, so a rebound name is refused. +- One request per connection, 5 s to send it, 16 connections at once, a token bucket against floods. +- Headers in values with line breaks or control characters are dropped, and so are hop-by-hop and controlled ones + (`Connection`, `Host`, `Range`, `Accept-Encoding`, `Transfer-Encoding`, `Content-*`, `If-*`, `Proxy-*`, `Sec-*` …), + at most 32 kept. Cookies, a login in the link and secret headers go to the keyring (`secret::Secrets`), never to + the store or the log. +- Sender log (`Connector::log`): when, what (link without login or query string), accepted or why not, and the + sending program's name from `/proc/net/tcp` when it is the user's own. +- Links arrive on the channel from `Connector::start` as `Arrival`; `Incoming::task` makes a task and keeps its secret. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index e4987ac..5654460 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -208,3 +208,8 @@ Seen: boxes were ticked together after the tests, against rule 3. ## S022 — Control screens (compiled, not tested, no screenshots) - Toolbar mode switch (`views/modes.rs`, snail included) opens one sheet (`views/control.rs`): Speed dial (log scale, KB/s|MB/s, typing), Queues (`queues.rs` cards, live totals, reorder by handle or buttons, "move selected here", editor with week grid), Week (`Settings.mode_grid` → `limits_at`, applied by `bridge.apply`, rechecked each hour), When done (`schedule.rs`: Watcher countdown dialog, Logind, `run::run`, Inhibitor while running). Priority share text in details. - Not done: dragging tasks onto queue cards (used a button), start-time grid, priority share preview in list rows, core `Grid` unused (own grid instead). Limit changes save through the settings debounce, not on release. + +## S023 — Browser port (compiled, not tested) +- `connector::Connector::start(on, port) -> (Connector, UnboundedReceiver)`: the incoming-link event for the UI. `set(on, port)` live, `status()` (`Taken{by}` names the fix via `words()`), `log()` sender log, `on_change`. `Incoming::task(&Secrets, common)` makes the task and keeps cookies/login in the keyring. +- Guards: loopback only, Host = 127.0.0.1|localhost:port, no Origin / cross-site Sec-Fetch, JSON only, preflights refused, no CORS; header and link checks. Format: `docs/CONNECTOR.md`. Tests: `docs/tests/S023-port-server.md`. +- Not done: no app wiring (S024), no automatic tests yet; own small HTTP/1.1 reader instead of hyper's server. diff --git a/docs/tests/S023-port-server.md b/docs/tests/S023-port-server.md new file mode 100644 index 0000000..08e2e40 --- /dev/null +++ b/docs/tests/S023-port-server.md @@ -0,0 +1,45 @@ +# S023 — The port and its protection: test file + +Written by the worker that built it, run by the test phase. Nothing here has been tested until its Result says so. + +## Built +- `crates/core/src/connector/mod.rs` · `Connector::start(on, port) -> (Connector, Receiver)`, `set(on, port)` live, `status()`, `log()`, `on_change`; `guard` (Host, Origin, preflight, type), `Gate` (16 connections, bucket 30 + 5/s). +- `connector/wire.rs` · strict HTTP/1.1 read (head 16 KiB, body 1 MiB, Content-Length only), `answer` (no CORS). +- `connector/link.rs` · `Body` (object or list), `Raw::check` -> `Incoming`, `Incoming::task(&Secrets, common)`. +- `connector/peer.rs` · sender / listener program name from `/proc/net/tcp` and `/proc/*/fd`. +- `crates/core/tests/connector_nacre.json` · Nacre's `custom_body` output, as a fixture. `docs/CONNECTOR.md` · format. +Nothing is wired into the app yet (S024). Reach it from a test: `Connector::start(true, 0)`, read the port from `status()`. + +## Checks +| # | Risk | Do this | Expect | How | Result | +|---|---|---|---|---|---| +| 1 | HIGH | Start on port 0; `ss -ltn` / `status()` | `On(p)`, bound on 127.0.0.1 only, nothing on 0.0.0.0 or :: | integration | — | +| 2 | HIGH | curl POST the fixture with `Content-Type: application/json` | 200 `{"accepted":1,"refused":[]}`; one `Arrival`: url, name `a.zip`, page `https://example.com/`, user agent `UA`, secret cookies `k=v`, `task_headers()` has User-Agent and Referer, no Cookie | integration | — | +| 3 | HIGH | `Host: evil.example:p`, `Host: 127.0.0.1:1`, two Host headers, no Host | 403 `host`, no Arrival, log entry Refused(Host) | integration | — | +| 4 | HIGH | Add `Origin: https://evil.example`, `Origin: null`, `Sec-Fetch-Site: cross-site`, `Sec-Fetch-Mode: cors` (each alone) | 403 `origin` | integration | — | +| 5 | HIGH | POST with `application/x-www-form-urlencoded`, `multipart/form-data`, `text/plain`, `application/json; charset=latin1` | 415 `content-type` | integration | — | +| 6 | HIGH | `OPTIONS /` with `Access-Control-Request-Method: POST`; also POST with that header | 405 `preflight`; no `Access-Control-*` header in any answer of checks 2–9 | integration | — | +| 7 | HIGH | Link headers `{"X-A":"1\r\nX-B: 2","Connection":"close","Range":"bytes=5-","Accept-Encoding":"gzip","If-None-Match":"x","Authorization":"Bearer t"}` | X-A, Connection, Range, Accept-Encoding, If-None-Match dropped (in `dropped`); Authorization only in `secret.headers`; user agent with `\n` dropped | unit | — | +| 8 | HIGH | Links `javascript:alert(1)`, `file:///etc/passwd`, `data:,x`, `http://`, a 9 KiB URL, `https://u:p@h/f` | first five refused (`scheme`/`invalid`), last accepted as `https://h/f` with the login in `secret` | unit | — | +| 9 | HIGH | Filename `../../.bashrc`, `a\u0000b`, 400 chars | made safe by `http::name::safe` (no slashes, no leading dot, capped) | unit | — | +| 10 | HIGH | `Incoming::task` with `Secrets::new(Bus::Off)` | task.secret is a `task:` name; `secrets.load` gives the cookies; task headers carry no secret (store accepts it) | unit | — | +| 11 | HIGH | Log after checks 2–8 | entries with time, what, outcome; no cookie value, login or query string appears in any `what` | integration | — | +| 12 | MED | GET `/` | 200 `{"name":"Medlar","version":...}`, not logged | integration | — | +| 13 | MED | List of 3 links, one bad; then a list of 1001; then `{}`; then `[]`; then `not json` | 200 accepted 2 refused index 1; 413 `too-many`; 422 `no-links`; 422; 400 `body` | integration | — | +| 14 | MED | Body 1 MiB + 1; `Transfer-Encoding: chunked`; head of 20 KiB; open and send nothing for 6 s | 413; 411; 413; 408 or closed | integration | — | +| 15 | MED | 40 requests at once from one loop | the first ≈30 answered normally, later ones 429 `busy` | integration | — | +| 16 | MED | Hold the port with another listener, start on it | `Taken { by: Some(test binary name) }`, `words()` names the port and the fix; free it: `On` within ~5 s | integration | — | +| 17 | MED | `set(false, p)`, then `set(true, q)` | port closed (connect refused), then open on q; status follows | integration | — | +| 18 | LOW | Sender of check 2 | `from.process` is `curl` (a process of this user) | integration | — | + +## Needs +Loopback only, ports chosen free (port 0) — never 15151 or 38151 or 17616 while the user's Medlar runs. curl for check 2. No network. + +## Doubts +- Never compiled beyond `cargo check`; never run. The hand-written HTTP reader is the main risk: partial reads, a request split over several packets, HTTP/1.0 clients. +- Nacre's request (ureq): check it sends `Host: 127.0.0.1:`, no `Origin`, no chunked body — else check 2 passes with curl but Nacre fails. +- `Sec-Fetch-Site: none` is let through (typed in the address bar: GET only, harmless). +- Rate limit is per listener and global, so a flood also delays the real browser for a few seconds. +- `peer::process` scans every `/proc/*/fd`: may be slow with many processes; it runs beside the read. +- `Body` is untagged: a known field of the wrong JSON type (for example `"headers": []`) refuses the whole body with `body`. +- The UI is not wired: S024 must call `Connector::start`/`set` from settings and show `status().words()`.