// (Shared with relay/, which uses the parts the app doesn't.) #![allow(dead_code)] // A very small HTTP/1.1 server (one thread per connection), shared by the phone page on this // computer and by the relay (the thin backend). The relay's answers close the connection; the // phone page's keep it a while (`serve_kept`), so a phone doesn't open TCP and TLS anew each time. use std::collections::HashMap; use std::io::{Read, Write}; use std::net::{TcpListener, TcpStream}; use std::sync::{Arc, Mutex}; use std::time::Duration; /// Answer a WebSocket upgrade: "101 Switching Protocols" (or 400/403). True when the /// connection is now a WebSocket. Browser connections carry an `Origin` header, which must /// match `Host` so another site (or a sandboxed page with `Origin: null`) cannot open a socket. pub fn accept_websocket(req: &Req, c: &mut TcpStream) -> bool { let origin = req.header("origin"); if !origin.is_empty() { let o_host = origin.strip_prefix("https://").or_else(|| origin.strip_prefix("http://")).unwrap_or(""); let host = req.header("host"); if o_host.is_empty() || host.is_empty() || !o_host.eq_ignore_ascii_case(host) { write_response(c, &Resp::error(403, "forbidden origin")); return false; } } let key = req.header("sec-websocket-key"); if key.is_empty() { write_response(c, &Resp::error(400, "bad request")); return false; } let accept = tungstenite::handshake::derive_accept_key(key.as_bytes()); let ok = c.write_all(format!("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: {accept}\r\n\r\n").as_bytes()).is_ok(); let _ = c.set_nodelay(true); ok } /// Percent-encode a query value or form field (RFC 3986: letters, digits and -_.~ stay). pub fn url_encode(s: &str) -> String { s.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect() } /// Largest request body accepted (a phone photo fits); encrypted backups have their own ceiling. pub const MAX_BODY: usize = 30 * 1024 * 1024; pub const MAX_BACKUP_BODY: usize = 200 * 1024 * 1024; const MAX_CONNS: usize = 512; /// How long a request's first lines may take to arrive. const HEAD_WAIT: Duration = Duration::from_secs(15); /// Lasting connections (WebSockets: every AnyBot keeps one) have their own, larger room, so /// they don't use up the requests' (a few hundred people online used to fill all 512). const MAX_SOCKETS: usize = 8192; /// One address's connections at once, when it comes straight from the internet (behind a /// proxy, or on a private network, every request shares the proxy's address: no cap there). const MAX_CONNS_PER_ADDR: usize = 48; /// A request that shows no login may carry this much (signing in, pairing, a code). const MAX_BODY_NO_LOGIN: usize = 256 * 1024; /// Bodies being received at once, all connections together: past this, new ones wait their /// turn (503) instead of the server running out of memory. const MAX_BODIES_BYTES: usize = 512 * 1024 * 1024; /// The bytes of bodies now being received (see MAX_BODIES_BYTES). static BODIES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); /// Room for a body of `n` bytes while it is received (given back when dropped). struct BodyRoom(usize); impl BodyRoom { fn take(n: usize) -> Option { use std::sync::atomic::Ordering; if BODIES.fetch_add(n, Ordering::SeqCst) + n > MAX_BODIES_BYTES { BODIES.fetch_sub(n, Ordering::SeqCst); return None; } Some(BodyRoom(n)) } fn grow(&mut self, more: usize) -> bool { use std::sync::atomic::Ordering; if BODIES.fetch_add(more, Ordering::SeqCst) + more > MAX_BODIES_BYTES { BODIES.fetch_sub(more, Ordering::SeqCst); return false; } self.0 += more; true } } impl Drop for BodyRoom { fn drop(&mut self) { BODIES.fetch_sub(self.0, std::sync::atomic::Ordering::SeqCst); } } /// Password hashing is memory-hard (19 MiB each): a few at a time, the rest wait. (Hundreds /// of sign-in tries at once were hundreds of 19 MiB blocks.) fn hashing_turn() -> impl Drop { use std::sync::{Condvar, Mutex}; static BUSY: (Mutex, Condvar) = (Mutex::new(0), Condvar::new()); struct Turn; impl Drop for Turn { fn drop(&mut self) { *BUSY.0.lock().unwrap() -= 1; BUSY.1.notify_one(); } } let mut n = BUSY.0.lock().unwrap(); while *n >= 4 { n = BUSY.1.wait(n).unwrap(); } *n += 1; Turn } /// Browser state-changing requests carry `Origin` (or `Sec-Fetch-Site`), which must match `Host` /// so another page or a sandboxed `/s/…` site cannot trigger login lockouts or actions. pub fn same_origin(req: &Req) -> bool { let origin = req.header("origin"); if !origin.is_empty() { let o_host = origin.strip_prefix("https://").or_else(|| origin.strip_prefix("http://")).unwrap_or(""); let host = req.header("host"); if o_host.is_empty() || host.is_empty() || !o_host.eq_ignore_ascii_case(host) { return false; } } if req.header("sec-fetch-site").eq_ignore_ascii_case("cross-site") { return false; } true } #[derive(Clone, Debug, Default)] pub struct Req { pub method: String, pub path: String, pub query: HashMap, /// Header names in lower case. pub headers: HashMap, pub body: Vec, pub peer: String, } impl Req { pub fn header(&self, name: &str) -> &str { self.headers.get(&name.to_ascii_lowercase()).map(|s| s.as_str()).unwrap_or("") } pub fn bearer(&self) -> String { let a = self.header("authorization"); if let Some(t) = a.strip_prefix("Bearer ") { return t.trim().to_string(); } // EventSource / can't send headers: a token in the query works too. self.query.get("t").cloned().unwrap_or_default() } pub fn json(&self) -> serde_json::Value { serde_json::from_slice(&self.body).unwrap_or(serde_json::Value::Null) } /// Path segments, e.g. "/api/bots/3/send" → ["api", "bots", "3", "send"]. pub fn parts(&self) -> Vec<&str> { self.path.split('/').filter(|s| !s.is_empty()).collect() } } #[derive(Clone, Debug)] pub struct Resp { pub status: u16, pub ctype: String, pub body: Vec, pub headers: Vec<(String, String)>, } impl Resp { pub fn json(v: &serde_json::Value) -> Resp { Resp { status: 200, ctype: "application/json; charset=utf-8".into(), body: v.to_string().into_bytes(), headers: vec![] } } pub fn bytes(ctype: &str, body: Vec) -> Resp { Resp { status: 200, ctype: ctype.into(), body, headers: vec![] } } pub fn error(status: u16, msg: &str) -> Resp { Resp { status, ..Resp::json(&serde_json::json!({ "error": msg })) } } pub fn empty(status: u16) -> Resp { Resp { status, ctype: "text/plain".into(), body: vec![], headers: vec![] } } pub fn with_header(mut self, k: &str, v: &str) -> Resp { self.headers.push((k.into(), v.into())); self } } /// The browser asking reads gzip. pub fn reads_gzip(req: &Req) -> bool { req.header("accept-encoding").split(',').any(|e| e.trim().split(';').next() == Some("gzip")) } /// An answer gzipped when the asker reads that (`gz`) and it is words worth it: the page, the /// state, a chat (a JPEG or a zip is packed already; a part of a file stays as asked). pub fn squeeze(r: Resp, gz: bool) -> Resp { let t = r.ctype.split(';').next().unwrap_or("").trim().to_ascii_lowercase(); let words = t.starts_with("text/") || matches!(t.as_str(), "application/json" | "application/manifest+json" | "image/svg+xml"); if !gz || !words || r.status == 206 || r.body.len() < 1024 || r.headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("content-encoding")) { return r; } let mut e = flate2::write::GzEncoder::new(Vec::with_capacity(r.body.len() / 4), flate2::Compression::default()); if e.write_all(&r.body).is_err() { return r; } match e.finish() { Ok(body) => Resp { body, ..r }.with_header("Content-Encoding", "gzip").with_header("Vary", "Accept-Encoding"), Err(_) => r, } } fn reason(status: u16) -> &'static str { match status { 200 => "OK", 204 => "No Content", 304 => "Not Modified", 400 => "Bad Request", 401 => "Unauthorized", 403 => "Forbidden", 404 => "Not Found", 409 => "Conflict", 413 => "Payload Too Large", 429 => "Too Many Requests", 502 => "Bad Gateway", 503 => "Service Unavailable", 504 => "Gateway Timeout", _ => "OK", } } fn decode(s: &str) -> String { // Work on bytes only: slicing the &str at byte offsets can land inside a multi-byte // character and panic (an unauthenticated request like "/%)…" used to kill its thread). let b = s.as_bytes(); let mut out = Vec::with_capacity(b.len()); let hex = |c: u8| -> Option { match c { b'0'..=b'9' => Some(c - b'0'), b'a'..=b'f' => Some(c - b'a' + 10), b'A'..=b'F' => Some(c - b'A' + 10), _ => None, } }; let mut i = 0; while i < b.len() { match b[i] { b'+' => { out.push(b' '); i += 1; } b'%' if i + 2 < b.len() && hex(b[i + 1]).is_some() && hex(b[i + 2]).is_some() => { out.push(hex(b[i + 1]).unwrap() * 16 + hex(b[i + 2]).unwrap()); i += 3; } c => { out.push(c); i += 1; } } } String::from_utf8_lossy(&out).to_string() } pub fn parse_query(q: &str) -> HashMap { q.split('&').filter(|p| !p.is_empty()).map(|p| { let (k, v) = p.split_once('=').unwrap_or((p, "")); (decode(k), decode(v)) }).collect() } /// Read one request (head, then Content-Length or chunked body). pub fn read_request(c: &mut TcpStream) -> Result { let started = std::time::Instant::now(); let mut deadline = Duration::from_secs(90); let step_read = |c: &mut TcpStream, buf: &mut [u8], deadline: Duration| -> Result { let elapsed = started.elapsed(); if elapsed >= deadline { return Err(408); } let wait = Duration::from_secs(30).min(deadline - elapsed).max(Duration::from_millis(50)); c.set_read_timeout(Some(wait)).ok(); c.read(buf).map_err(|_| 400u16) }; let mut got: Vec = vec![]; let mut buf = [0u8; 16384]; let head_end = loop { if let Some(p) = got.windows(4).position(|w| w == b"\r\n\r\n") { break p; } if got.len() > 64 * 1024 { return Err(400); } // (The head is a packet or two: one that dribbles in, or never comes, gives its place // back in seconds — a body may take the long deadline.) let n = step_read(c, &mut buf, HEAD_WAIT)?; if n == 0 { return Err(400); } got.extend_from_slice(&buf[..n]); }; let head = String::from_utf8_lossy(&got[..head_end]).to_string(); let mut lines = head.split("\r\n"); let first = lines.next().unwrap_or(""); let mut fp = first.split_whitespace(); let method = fp.next().unwrap_or("").to_string(); let target = fp.next().unwrap_or("/").to_string(); let headers: HashMap = lines.filter_map(|l| l.split_once(':')).map(|(k, v)| (k.trim().to_ascii_lowercase(), v.trim().to_string())).collect(); if headers.contains_key("transfer-encoding") && headers.contains_key("content-length") { return Err(400); } let raw_path = target.split_once('?').map(|(p, _)| p).unwrap_or(&target); // (A request with no login at all — no bearer, no `t=` — is signing in or pairing: small.) let shows_login = headers.get("authorization").is_some_and(|a| a.len() > 16) || target.contains("t="); let max_body = if !shows_login { MAX_BODY_NO_LOGIN } else if method == "PUT" && raw_path == "/relay/backup" { deadline = Duration::from_secs(240); MAX_BACKUP_BODY } else { MAX_BODY }; let mut room = BodyRoom::take(0).ok_or(503u16)?; let chunked = match headers.get("transfer-encoding") { Some(te) => { if !te.trim().eq_ignore_ascii_case("chunked") { return Err(400); } true } None => false, }; let mut body = got[head_end + 4..].to_vec(); if chunked { // Some phone browsers send POST bodies in chunks (no Content-Length): read chunks // until the zero-size terminator, reassembling the body. let mut out: Vec = vec![]; let mut pos = 0usize; loop { if pos > 65536 { body.drain(..pos); pos = 0; } let size_end = loop { if let Some(p) = body[pos..].windows(2).position(|w| w == b"\r\n") { break pos + p; } if body.len().saturating_sub(pos) > 8 * 1024 { return Err(400); } let n = step_read(c, &mut buf, deadline)?; if n == 0 { return Err(400); } body.extend_from_slice(&buf[..n]); }; let hex = String::from_utf8_lossy(&body[pos..size_end]).split(';').next().unwrap_or("").trim().to_string(); if hex.is_empty() || hex.len() > 16 { return Err(400); } let size = usize::from_str_radix(&hex, 16).map_err(|_| 400u16)?; let data_start = size_end.checked_add(2).ok_or(400u16)?; if size == 0 { // Zero-size chunk is followed by \r\n (or optional trailer headers + \r\n\r\n). loop { if body.len() >= data_start + 2 && &body[data_start..data_start + 2] == b"\r\n" { break; } if body.len() >= data_start + 4 && body[data_start..].windows(4).any(|w| w == b"\r\n\r\n") { break; } if body.len().saturating_sub(data_start) > 16 * 1024 { return Err(400); } let n = step_read(c, &mut buf, deadline)?; if n == 0 { return Err(400); } body.extend_from_slice(&buf[..n]); } break; } if out.len().checked_add(size).is_none_or(|total| total > max_body) || !room.grow(size) { return Err(413); } let end = data_start.checked_add(size).ok_or(413u16)?; let next_pos = end.checked_add(2).ok_or(413u16)?; while body.len() < next_pos { let n = step_read(c, &mut buf, deadline)?; if n == 0 { return Err(400); } body.extend_from_slice(&buf[..n]); } if &body[end..next_pos] != b"\r\n" { return Err(400); } out.extend_from_slice(&body[data_start..end]); pos = next_pos; } body = out; } else { let len: usize = match headers.get("content-length") { Some(v) => v.parse().map_err(|_| 400u16)?, None => 0, }; if len > max_body { return Err(413); } if !room.grow(len) { return Err(503); } while body.len() < len { let n = step_read(c, &mut buf, deadline)?; // The connection ended before the whole body came: not a request. (Half a body // used to be handed on as the request: half an upload, saved over the whole one.) if n == 0 { return Err(400); } body.extend_from_slice(&buf[..n]); } body.truncate(len); } let (path, q) = target.split_once('?').unwrap_or((&target, "")); Ok(Req { method, path: decode(path), query: parse_query(q), headers, body, peer: peer_of(c) }) } fn clean_header_val(s: &str) -> String { s.chars().filter(|&c| c != '\r' && c != '\n' && c != '\0').collect() } fn clean_header_name(s: &str) -> String { s.chars().filter(|&c| c.is_ascii_graphic() && c != ':').collect() } pub fn write_response(c: &mut TcpStream, r: &Resp) { write_kept(c, r, false); } /// How long a kept connection waits for its next request. const KEEP_IDLE: Duration = Duration::from_secs(30); /// Write the answer, saying whether the connection stays open for another request (`keep`). /// False when it couldn't be written whole (the connection is shut then). fn write_kept(c: &mut TcpStream, r: &Resp, keep: bool) -> bool { let ctype = clean_header_val(&r.ctype); // (Told a little less than KEEP_IDLE, so a browser doesn't send on a connection being closed.) let connection = if keep { format!("keep-alive\r\nKeep-Alive: timeout={}", KEEP_IDLE.as_secs() - 5) } else { "close".to_string() }; let own_cache = r.headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("cache-control")); let mut head = format!( "HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: {connection}\r\n{}X-Content-Type-Options: nosniff\r\nReferrer-Policy: no-referrer\r\n", r.status, reason(r.status), if ctype.is_empty() { "application/octet-stream" } else { &ctype }, r.body.len(), if own_cache { "" } else { "Cache-Control: no-store\r\n" }, ); for (k, v) in &r.headers { let k = clean_header_name(k); if !k.is_empty() { head.push_str(&format!("{k}: {}\r\n", clean_header_val(v))); } } head.push_str("\r\n"); // The whole answer has a deadline (30 s, plus time for its size at a slow 50 KB/s). A // timeout per write alone let a client that takes a few bytes a minute keep its connection, // its thread and the body for ever — a few hundred of them were every connection there is. let deadline = std::time::Instant::now() + Duration::from_secs(30 + (r.body.len() / 50_000) as u64); let mut send = |bytes: &[u8]| -> bool { for chunk in bytes.chunks(64 * 1024) { let left = deadline.saturating_duration_since(std::time::Instant::now()); if left.is_zero() { return false; } let _ = c.set_write_timeout(Some(left.min(Duration::from_secs(30)))); if c.write_all(chunk).is_err() { return false; } } true }; if send(head.as_bytes()) && send(&r.body) { c.flush().is_ok() } else { let _ = c.shutdown(std::net::Shutdown::Both); false } } /// A kept connection: true once the next request starts coming, false when it stays quiet past /// KEEP_IDLE, ends, or the server is told to stop (`alive`) meanwhile. fn next_request_comes(c: &TcpStream, alive: &(dyn Fn() -> bool + Send + Sync)) -> bool { let until = std::time::Instant::now() + KEEP_IDLE; let _ = c.set_read_timeout(Some(Duration::from_secs(1))); let mut b = [0u8; 1]; while std::time::Instant::now() < until { if !alive() { return false; } match c.peek(&mut b) { Ok(n) => return n > 0, Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {} Err(_) => return false, } } false } /// A quoted tag for a body that only changes with a new build (the phone page), for If-None-Match. pub fn etag_of(body: &[u8]) -> String { let d = ring::digest::digest(&ring::digest::SHA256, body); format!("\"{}\"", hex_of(&d.as_ref()[..12])) } /// The browser already holds the body tagged `etag`. pub fn holds(req: &Req, etag: &str) -> bool { req.header("if-none-match").split(',').any(|t| t.trim().trim_start_matches("W/") == etag) } pub type Handler = Arc Resp + Send + Sync>; /// Takes over a connection that asked to become a WebSocket (it answers the handshake itself). pub type Upgrade = Arc; /// Who really asked, for connections a front on this machine carries here (區網 HTTPS, see /// lantls): the front's own port on this side → the address it took the connection from. pub fn carried() -> &'static Mutex> { static C: std::sync::OnceLock>> = std::sync::OnceLock::new(); C.get_or_init(Default::default) } fn peer_of(c: &TcpStream) -> String { match c.peer_addr() { Ok(a) if a.ip().is_loopback() => carried().lock().unwrap().get(&a.port()).map(|ip| ip.to_string()).unwrap_or_else(|| a.ip().to_string()), Ok(a) => a.ip().to_string(), Err(_) => String::new(), } } /// Answer every connection on this listener with `handler` (each on its own thread). pub fn serve(listener: TcpListener, handler: Handler, alive: Arc bool + Send + Sync>) { serve_upgrade(listener, handler, None, alive) } /// Like `serve`, and connections asking for a WebSocket go to `upgrade`. pub fn serve_upgrade(listener: TcpListener, handler: Handler, upgrade: Option, alive: Arc bool + Send + Sync>) { serve_with(listener, handler, upgrade, alive, false) } /// Like `serve_upgrade`, and a connection stays open for the next request (KEEP_IDLE). pub fn serve_kept(listener: TcpListener, handler: Handler, upgrade: Option, alive: Arc bool + Send + Sync>) { serve_with(listener, handler, upgrade, alive, true) } fn serve_with(listener: TcpListener, handler: Handler, upgrade: Option, alive: Arc bool + Send + Sync>, keep: bool) { use std::sync::atomic::{AtomicUsize, Ordering}; struct Slot(Arc); impl Drop for Slot { fn drop(&mut self) { self.0.fetch_sub(1, Ordering::SeqCst); } } listener.set_nonblocking(true).ok(); let active = Arc::new(AtomicUsize::new(0)); let sockets = Arc::new(AtomicUsize::new(0)); let per_addr: Arc>> = Arc::new(Mutex::new(HashMap::new())); struct AddrSlot(Arc>>, std::net::IpAddr); impl Drop for AddrSlot { fn drop(&mut self) { let mut m = self.0.lock().unwrap(); if let Some(n) = m.get_mut(&self.1) { *n -= 1; if *n == 0 { m.remove(&self.1); } } } } loop { if !alive() { return; } match listener.accept() { Ok((mut c, peer)) => { c.set_nonblocking(false).ok(); if active.load(Ordering::SeqCst) >= MAX_CONNS { write_response(&mut c, &Resp::error(503, "伺服器忙碌中,請稍後再試")); continue; } // One internet address can't hold all the room (a proxy's or a private // network's address stands for many people: not counted). let ip = peer.ip(); let direct = !(ip.is_loopback() || is_private_addr(&ip)); let addr_slot = if direct { let mut m = per_addr.lock().unwrap(); let n = m.entry(ip).or_insert(0); if *n >= MAX_CONNS_PER_ADDR { drop(m); write_response(&mut c, &Resp::error(429, "同一個位址的連線太多了,請稍後再試")); continue; } *n += 1; Some(AddrSlot(per_addr.clone(), ip)) } else { None }; active.fetch_add(1, Ordering::SeqCst); let slot = Slot(active.clone()); let h = handler.clone(); let up = upgrade.clone(); let socks = sockets.clone(); let alive = alive.clone(); if std::thread::Builder::new() .spawn(move || { let _addr = addr_slot; let slot = slot; let mut first = true; loop { if !first && !next_request_comes(&c, &*alive) { return; } first = false; match read_request(&mut c) { Ok(req) if req.header("upgrade").eq_ignore_ascii_case("websocket") && up.is_some() => { // A lasting connection leaves the requests' room for its own. if socks.load(Ordering::SeqCst) >= MAX_SOCKETS { write_response(&mut c, &Resp::error(503, "伺服器忙碌中,請稍後再試")); return; } socks.fetch_add(1, Ordering::SeqCst); let _sock = Slot(socks.clone()); drop(slot); if let Some(u) = up { u(req, c) } return; } Ok(req) if !matches!(req.method.as_str(), "GET" | "HEAD") && !same_origin(&req) => { write_response(&mut c, &Resp::error(403, "forbidden origin")); return; } Ok(req) => { let again = keep && !req.header("connection").eq_ignore_ascii_case("close"); let resp = h(req); if !write_kept(&mut c, &resp, again) || !again { return; } } Err(code) => { write_response(&mut c, &Resp::error(code, "bad request")); return; } } } }) .is_err() { // Slot drops immediately above on Err, decrementing `active`. } } Err(_) => std::thread::sleep(Duration::from_millis(50)), } } } /// 10.x, 172.16–31.x, 192.168.x, 100.64/10 (Tailscale), link-local, and IPv6's private ranges. fn is_private_addr(ip: &std::net::IpAddr) -> bool { match ip { std::net::IpAddr::V4(v) => { let o = v.octets(); v.is_private() || v.is_link_local() || (o[0] == 100 && (64..128).contains(&o[1])) } std::net::IpAddr::V6(v) => (v.segments()[0] & 0xfe00) == 0xfc00 || (v.segments()[0] & 0xffc0) == 0xfe80 || v.to_ipv4_mapped().is_some_and(|m| m.is_private() || m.is_loopback()), } } /// `script-src` for a page of ours: this address's own files and exactly the scripts written /// in the page (by their SHA-256), nothing else. With 'unsafe-inline' any text that ever slipped /// into the page unescaped could run as script and read the login kept in the browser; now it /// can't run at all. pub fn script_src(html: &str) -> String { use base64::Engine; let mut out = String::from("script-src 'self'"); let mut rest = html; while let Some(i) = rest.find("') else { break }; let body_start = open_end + 1; let Some(len) = after[body_start..].find("") else { break }; let body = &after[body_start..body_start + len]; if !body.trim().is_empty() { let d = ring::digest::digest(&ring::digest::SHA256, body.as_bytes()); out.push_str(&format!(" 'sha256-{}'", base64::engine::general_purpose::STANDARD.encode(d.as_ref()))); } rest = &after[body_start + len..]; } out } // ---------- secrets ---------- pub fn random_hex(bytes: usize) -> String { use ring::rand::SecureRandom; let mut b = vec![0u8; bytes]; ring::rand::SystemRandom::new().fill(&mut b).expect("random"); b.iter().map(|x| format!("{x:02x}")).collect() } pub fn sha256_hex(s: &str) -> String { ring::digest::digest(&ring::digest::SHA256, s.as_bytes()).as_ref().iter().map(|x| format!("{x:02x}")).collect() } const PBKDF2_ROUNDS: u32 = 120_000; /// A password stored as "salt$hash" (PBKDF2-HMAC-SHA256). /// Password hashes: argon2id (memory-hard, OWASP parameters) in the form /// `argon2id$$`. Old accounts keep their `salt$pbkdf2` string and are /// checked with it (check_password reads the format from the stored string). pub fn hash_password(pw: &str) -> String { let salt = random_bytes(16); let _turn = hashing_turn(); let out = argon2_hash(pw, &salt).expect("argon2"); format!("argon2id${}${}", hex_of(&salt), hex_of(&out)) } fn argon2_hash(pw: &str, salt: &[u8]) -> Option> { use argon2::{Algorithm, Argon2, Params, Version}; // m=19 MiB, t=2, p=1 (OWASP's argon2id recommendation); 32-byte tag. let params = Params::new(19_456, 2, 1, Some(32)).ok()?; let a = Argon2::new(Algorithm::Argon2id, Version::V0x13, params); let mut out = vec![0u8; 32]; a.hash_password_into(pw.as_bytes(), salt, &mut out).ok()?; Some(out) } pub fn random_bytes(n: usize) -> Vec { use ring::rand::SecureRandom; let mut b = vec![0u8; n]; ring::rand::SystemRandom::new().fill(&mut b).expect("random"); b } fn hex_of(b: &[u8]) -> String { b.iter().map(|x| format!("{x:02x}")).collect() } fn pbkdf2_hex(pw: &str, salt: &str) -> String { let mut out = [0u8; 32]; ring::pbkdf2::derive(ring::pbkdf2::PBKDF2_HMAC_SHA256, std::num::NonZeroU32::new(PBKDF2_ROUNDS).unwrap(), salt.as_bytes(), pw.as_bytes(), &mut out); out.iter().map(|x| format!("{x:02x}")).collect() } pub fn check_password(pw: &str, stored: &str) -> bool { if let Some(rest) = stored.strip_prefix("argon2id$") { let Some((salt, hash)) = rest.split_once('$') else { return false }; let salt_bytes = hex_bytes(salt); let _turn = hashing_turn(); let Some(raw) = argon2_hash(pw, &salt_bytes) else { return false }; let mine = hex_of(&raw); return constant_time_eq(&mine, hash); } let Some((salt, hash)) = stored.split_once('$') else { return false }; let mine = pbkdf2_hex(pw, salt); // Compare without stopping at the first difference. constant_time_eq(&mine, hash) } pub fn constant_time_eq(a: &str, b: &str) -> bool { a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 } /// Restrict an existing file to its owner (`0600` on Unix). pub fn tighten_permissions(path: &std::path::Path) { #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)); } #[cfg(not(unix))] let _ = path; } /// Restrict an existing directory to its owner (`0700` on Unix). pub fn tighten_dir_permissions(path: &std::path::Path) { #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)); } #[cfg(not(unix))] let _ = path; } /// Create a private directory (`0700` on Unix). pub fn ensure_private_dir(path: &std::path::Path) { let _ = std::fs::create_dir_all(path); tighten_dir_permissions(path); } /// Atomically write a private file (`0600` from creation on Unix, synced before rename, unique temp file). pub fn write_private(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> { if let Some(d) = path.parent() { if !d.as_os_str().is_empty() { let _ = std::fs::create_dir_all(d); } } let mut tmp_os = path.as_os_str().to_os_string(); tmp_os.push(format!(".tmp.{}.{}", std::process::id(), random_hex(6))); let tmp = std::path::PathBuf::from(tmp_os); let mut opts = std::fs::OpenOptions::new(); opts.write(true).create_new(true); #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; opts.mode(0o600); } let res = (|| -> std::io::Result<()> { let mut f = opts.open(&tmp)?; tighten_permissions(&tmp); f.write_all(bytes)?; f.sync_all()?; drop(f); std::fs::rename(&tmp, path) })(); if res.is_err() { let _ = std::fs::remove_file(&tmp); } res } fn hex_bytes(s: &str) -> Vec { let s = s.trim(); if !s.is_ascii() { return Vec::new(); } (0..s.len() / 2).map(|i| u8::from_str_radix(&s[i * 2..i * 2 + 2], 16).unwrap_or(0)).collect() } // ── TOTP (RFC 6238, SHA-1, 30 s, 6 digits): the codes authenticator apps show. ── const B32: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; pub fn base32_encode(b: &[u8]) -> String { let mut out = String::new(); let mut acc = 0u32; let mut bits = 0u32; for x in b { acc = (acc << 8) | *x as u32; bits += 8; while bits >= 5 { bits -= 5; out.push(B32[((acc >> bits) & 31) as usize] as char); } } if bits > 0 { out.push(B32[((acc << (5 - bits)) & 31) as usize] as char); } out } fn base32_decode(s: &str) -> Vec { let mut out = Vec::new(); let (mut acc, mut bits) = (0u32, 0u32); for c in s.to_uppercase().chars() { if c == '=' || c == ' ' { continue; } let Some(v) = B32.iter().position(|&x| x as char == c) else { continue }; acc = (acc << 5) | v as u32; bits += 5; if bits >= 8 { bits -= 8; out.push((acc >> bits) as u8); } } out } /// A fresh shared secret (20 random bytes, the size authenticator apps expect). pub fn totp_new_secret() -> String { base32_encode(&random_bytes(20)) } pub fn totp_uri(secret: &str, user: &str) -> String { format!("otpauth://totp/AnyBot:{user}?secret={secret}&issuer=AnyBot&period=30&digits=6") } pub fn totp_code(secret: &str, step: u64) -> String { use ring::hmac; let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, &base32_decode(secret)); let tag = hmac::sign(&key, &step.to_be_bytes()); let t = tag.as_ref(); let off = (t[t.len() - 1] & 0x0F) as usize; let n = (u32::from(t[off] & 0x7F) << 24) | (u32::from(t[off + 1]) << 16) | (u32::from(t[off + 2]) << 8) | u32::from(t[off + 3]); format!("{:06}", n % 1_000_000) } /// A code is good for its 30-second step and one step each way (clocks drift). pub fn totp_check(secret: &str, code: &str) -> bool { let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() / 30).unwrap_or(0); let code: String = code.chars().filter(|c| c.is_ascii_digit()).collect(); if code.len() != 6 { return false; } (now.saturating_sub(1)..=now + 1).any(|s| constant_time_eq(&totp_code(secret, s), &code)) } /// A 256-bit key from a password (for the encrypted backup kept by the relay). pub fn derive_key(pw: &str, user: &str) -> [u8; 32] { derive_key_with(pw, user, BACKUP_ROUNDS) } /// The key as it was derived before BACKUP_ROUNDS was raised: older backups open with it. pub fn derive_key_before(pw: &str, user: &str) -> [u8; 32] { derive_key_with(pw, user, PBKDF2_ROUNDS) } /// The backup holds the model keys and sits on the server: whoever gets a copy guesses the /// password offline, so each guess is made five times dearer than it was (OWASP's count for /// PBKDF2-SHA256). const BACKUP_ROUNDS: u32 = 600_000; fn derive_key_with(pw: &str, user: &str, rounds: u32) -> [u8; 32] { let mut out = [0u8; 32]; ring::pbkdf2::derive(ring::pbkdf2::PBKDF2_HMAC_SHA256, std::num::NonZeroU32::new(rounds).unwrap(), format!("anybot-backup:{user}").as_bytes(), pw.as_bytes(), &mut out); out } /// AES-256-GCM; the 12-byte nonce goes first. pub fn seal(key: &[u8; 32], plain: &[u8]) -> Vec { use ring::aead::*; use ring::rand::SecureRandom; let k = LessSafeKey::new(UnboundKey::new(&AES_256_GCM, key).expect("key")); let mut nonce = [0u8; 12]; ring::rand::SystemRandom::new().fill(&mut nonce).expect("random"); let mut data = plain.to_vec(); k.seal_in_place_append_tag(Nonce::assume_unique_for_key(nonce), Aad::empty(), &mut data).expect("seal"); let mut out = nonce.to_vec(); out.extend(data); out } pub fn open(key: &[u8; 32], sealed: &[u8]) -> Option> { use ring::aead::*; if sealed.len() < 12 + 16 { return None; } let k = LessSafeKey::new(UnboundKey::new(&AES_256_GCM, key).ok()?); let nonce = Nonce::try_assume_unique_for_key(&sealed[..12]).ok()?; let mut data = sealed[12..].to_vec(); let plain = k.open_in_place(nonce, Aad::empty(), &mut data).ok()?; Some(plain.to_vec()) } #[cfg(test)] mod tests { use super::*; #[test] fn totp_matches_the_rfc_6238_vectors() { // RFC 6238's SHA-1 test secret, 8-digit codes; the last six of each. let s = base32_encode(b"12345678901234567890"); assert_eq!(s, "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"); assert_eq!(&totp_code(&s, 59 / 30), "287082"); assert_eq!(&totp_code(&s, 1_111_111_109 / 30), "081804"); assert_eq!(&totp_code(&s, 1_111_111_111 / 30), "050471"); assert_eq!(&totp_code(&s, 1_234_567_890 / 30), "005924"); } #[test] fn password_hashes_are_argon2_and_old_ones_still_sign_in() { let h = hash_password(" hunter2 "); assert!(h.starts_with("argon2id$")); assert!(check_password(" hunter2 ", &h)); assert!(!check_password("hunter2", &h)); // A hash made with the old PBKDF2 format keeps working (no forced password reset). let old = format!("{}${}", "abcd", pbkdf2_hex("hunter2", "abcd")); assert!(check_password("hunter2", &old)); } #[test] fn passwords_and_sealing() { let h = hash_password("貓咪 123"); assert!(check_password("貓咪 123", &h) && !check_password("貓咪 124", &h)); let k = derive_key("pw", "daniel"); let s = seal(&k, "秘密".as_bytes()); assert_eq!(open(&k, &s).unwrap(), "秘密".as_bytes()); assert!(open(&derive_key("pw2", "daniel"), &s).is_none()); assert_eq!(parse_query("a=1&b=%E4%BD%A0+x")["b"], "你 x"); } /// A request that shows no login can't make the server hold a large body. #[test] fn a_body_without_a_login_is_small() { use std::io::Write; let l = TcpListener::bind("127.0.0.1:0").unwrap(); let port = l.local_addr().unwrap().port(); let t = std::thread::spawn(move || { let (mut c, _) = l.accept().unwrap(); read_request(&mut c).err() }); let mut c = TcpStream::connect(("127.0.0.1", port)).unwrap(); write!(c, "POST /api/login HTTP/1.1\r\nHost: x\r\nContent-Length: {}\r\n\r\n", MAX_BODY_NO_LOGIN + 1).unwrap(); assert_eq!(t.join().unwrap(), Some(413)); // Room for bodies is given back when a request is done with. let before = BODIES.load(std::sync::atomic::Ordering::SeqCst); { let mut r = BodyRoom::take(0).unwrap(); assert!(r.grow(1000) && !r.grow(MAX_BODIES_BYTES)); } assert_eq!(BODIES.load(std::sync::atomic::Ordering::SeqCst), before); assert!(is_private_addr(&"192.168.1.5".parse().unwrap()) && is_private_addr(&"100.100.1.1".parse().unwrap()) && !is_private_addr(&"8.8.8.8".parse().unwrap())); } #[test] fn a_page_allows_only_its_own_scripts() { // (The hash of 「alert(1)」, as browsers compute it for a script element's text.) let p = script_src("

x

"); assert!(p.starts_with("script-src 'self' 'sha256-bhHHL3z2vDgxUt0W3dWQOrprscmda2Y5pLsLg4GF+pI='"), "{p}"); assert_eq!(p.matches("'sha256-").count(), 2, "one per inline script, none for a file: {p}"); assert!(!p.contains("unsafe-inline")); } #[test] fn serves_a_request() { let l = TcpListener::bind("127.0.0.1:0").unwrap(); let port = l.local_addr().unwrap().port(); let h: Handler = Arc::new(|r: Req| Resp::json(&serde_json::json!({"p": r.path, "n": r.body.len(), "q": r.query.get("x")}))); std::thread::spawn(move || serve(l, h, Arc::new(|| true))); let body = vec![7u8; 100_000]; let mut resp = ureq::post(&format!("http://127.0.0.1:{port}/a/b?x=1")).send(&body[..]).unwrap(); let v: serde_json::Value = serde_json::from_str(&resp.body_mut().read_to_string().unwrap()).unwrap(); assert_eq!(v["n"], 100_000); assert_eq!(v["p"], "/a/b"); } /// The phone page's server keeps a connection for the next request (no new TCP and TLS each /// time); the relay's still closes it. An answer's own Cache-Control stands alone. #[test] fn a_kept_connection_carries_the_next_request() { use std::io::{BufRead, BufReader, Write}; let h: Handler = Arc::new(|r: Req| if r.path == "/c" { Resp::json(&serde_json::json!({})).with_header("Cache-Control", "no-cache") } else { Resp::json(&serde_json::json!({"p": r.path})) }); let answer = |rd: &mut BufReader| -> (String, String) { let mut head = String::new(); loop { let mut l = String::new(); if rd.read_line(&mut l).unwrap() == 0 || l == "\r\n" { break; } head.push_str(&l); } let n: usize = head.lines().find_map(|l| l.strip_prefix("Content-Length: ")).unwrap().trim().parse().unwrap(); let mut body = vec![0u8; n]; std::io::Read::read_exact(rd, &mut body).unwrap(); (head, String::from_utf8(body).unwrap()) }; let l = TcpListener::bind("127.0.0.1:0").unwrap(); let port = l.local_addr().unwrap().port(); let h2 = h.clone(); std::thread::spawn(move || serve_kept(l, h2, None, Arc::new(|| true))); let mut c = TcpStream::connect(("127.0.0.1", port)).unwrap(); let mut rd = BufReader::new(c.try_clone().unwrap()); c.write_all(b"GET /a HTTP/1.1\r\nHost: x\r\n\r\n").unwrap(); let (head, body) = answer(&mut rd); assert!(head.contains("Connection: keep-alive") && body.contains("/a"), "{head}"); c.write_all(b"GET /c HTTP/1.1\r\nHost: x\r\n\r\n").unwrap(); let (head, _) = answer(&mut rd); assert_eq!(head.matches("Cache-Control").count(), 1, "{head}"); assert!(head.contains("Cache-Control: no-cache"), "{head}"); c.write_all(b"GET /b HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n").unwrap(); let (head, body) = answer(&mut rd); assert!(head.contains("Connection: close") && body.contains("/b"), "{head}"); let mut rest = vec![]; assert_eq!(std::io::Read::read_to_end(&mut rd, &mut rest).unwrap(), 0, "closed after it"); let l = TcpListener::bind("127.0.0.1:0").unwrap(); let port = l.local_addr().unwrap().port(); std::thread::spawn(move || serve(l, h, Arc::new(|| true))); let mut c = TcpStream::connect(("127.0.0.1", port)).unwrap(); let mut rd = BufReader::new(c.try_clone().unwrap()); c.write_all(b"GET /a HTTP/1.1\r\nHost: x\r\n\r\n").unwrap(); let (head, _) = answer(&mut rd); assert!(head.contains("Connection: close") && head.contains("Cache-Control: no-store"), "{head}"); assert_eq!(std::io::Read::read_to_end(&mut rd, &mut rest).unwrap(), 0, "the relay's closes"); } /// An upload cut off on the way is no request (it used to be answered as a whole one). #[test] fn half_a_body_is_not_a_request() { use std::io::Write; let l = TcpListener::bind("127.0.0.1:0").unwrap(); let port = l.local_addr().unwrap().port(); let send = move |bytes: &'static [u8]| { std::thread::spawn(move || { let mut c = TcpStream::connect(("127.0.0.1", port)).unwrap(); c.write_all(bytes).unwrap(); // (Closed here, before the rest of the body.) }) }; let t = send(b"POST /backup HTTP/1.1\r\nContent-Length: 10\r\n\r\nabc"); let (mut c, _) = l.accept().unwrap(); assert_eq!(read_request(&mut c).err(), Some(400)); t.join().unwrap(); let t = send(b"POST /backup HTTP/1.1\r\nContent-Length: 10\r\n\r\n0123456789"); let (mut c, _) = l.accept().unwrap(); assert_eq!(read_request(&mut c).map(|r| r.body).ok(), Some(b"0123456789".to_vec())); t.join().unwrap(); } #[test] fn websocket_checks_origin_and_private_writes_are_owner_only() { let l = TcpListener::bind("127.0.0.1:0").unwrap(); let port = l.local_addr().unwrap().port(); let try_ws = |origin: &str| -> bool { let mut headers = HashMap::new(); headers.insert("host".into(), format!("127.0.0.1:{port}")); headers.insert("sec-websocket-key".into(), "dGhlIHNhbXBsZSBub25jZQ==".into()); if !origin.is_empty() { headers.insert("origin".into(), origin.into()); } let req = Req { headers, ..Default::default() }; let t = std::thread::spawn(move || TcpStream::connect(("127.0.0.1", port)).unwrap()); let (mut srv, _) = l.accept().unwrap(); let _cli = t.join().unwrap(); accept_websocket(&req, &mut srv) }; assert!(!try_ws("https://evil.example")); assert!(!try_ws("null")); assert!(try_ws(&format!("http://127.0.0.1:{port}"))); assert!(try_ws("")); let f = std::env::temp_dir().join(format!("anybot-priv-{}.secret", random_hex(6))); write_private(&f, b"top-secret").unwrap(); assert_eq!(std::fs::read(&f).unwrap(), b"top-secret"); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; assert_eq!(std::fs::metadata(&f).unwrap().permissions().mode() & 0o777, 0o600); } let _ = std::fs::remove_file(&f); // Non-ASCII stored password string must never panic on byte slicing. assert!(!check_password("pw", "argon2id$密碼$abcd")); } #[test] fn chunked_overflow_and_header_crlf_are_safe() { use std::io::Write; let l = TcpListener::bind("127.0.0.1:0").unwrap(); let port = l.local_addr().unwrap().port(); let send = move |bytes: &'static [u8]| { std::thread::spawn(move || { let mut c = TcpStream::connect(("127.0.0.1", port)).unwrap(); let _ = c.write_all(bytes); }) }; // Overflow chunk size must return 413 cleanly without panicking. let t = send(b"POST /x HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n1\r\na\r\nffffffffffffffff\r\nx"); let (mut c, _) = l.accept().unwrap(); assert_eq!(read_request(&mut c).err(), Some(413)); t.join().unwrap(); // Missing chunk CRLF must be rejected. let t = send(b"POST /x HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nabcXX0\r\n\r\n"); let (mut c, _) = l.accept().unwrap(); assert_eq!(read_request(&mut c).err(), Some(400)); t.join().unwrap(); // Both Transfer-Encoding and Content-Length must be rejected. let t = send(b"POST /x HTTP/1.1\r\nTransfer-Encoding: chunked\r\nContent-Length: 4\r\n\r\n0\r\n\r\n"); let (mut c, _) = l.accept().unwrap(); assert_eq!(read_request(&mut c).err(), Some(400)); t.join().unwrap(); // CRLF in response ctype / headers is stripped. let t = std::thread::spawn(move || { let mut cli = TcpStream::connect(("127.0.0.1", port)).unwrap(); let mut out = String::new(); let _ = cli.read_to_string(&mut out); out }); let (mut srv, _) = l.accept().unwrap(); let resp = Resp::bytes("text/plain\r\nSet-Cookie: bad=1", b"ok".to_vec()).with_header("X-Size", "10x20\r\nLocation: https://evil.example"); write_response(&mut srv, &resp); drop(srv); let raw = t.join().unwrap(); assert!(!raw.contains("\r\nSet-Cookie:") && !raw.contains("\r\nLocation:"), "{raw}"); } }