From 7e978450829488a4443d4486ab5918207d101a4f Mon Sep 17 00:00:00 2001 From: Derrors <33656531+Derrors@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:08:43 +0800 Subject: [PATCH 1/2] fix(viewer): request head checks, no body before the login, agent hardening From a full review of main after #195: - Request heads: the target must be a path (`GET @evil.example/` made the HTTPS redirect `https://host:port@evil.example/`), no control characters or lone CR/LF (a header line in `Location`), HTTP/1.0 or 1.1 only, one Host, one Content-Length of digits only, never a length and Transfer-Encoding together. Anything else gets 400. A chunked body outside /mcp gets 411 instead of being read as empty. - Nothing of a body is read before the login, and the connection counts against its machine's limit until then: a keep-alive request read its whole body first, so 64 bodies that never came, from one machine without a token, held every place. - Video acks past what was sent are taken as all of it (u64 underflow: a panic in debug, a frozen picture in release). - Origin without a port: the scheme's default (443/80). - AI task agents: the prompt goes last after `--` (claude's -p is a flag, so a prompt starting with `--permission-mode=...` was an option); the task's token reaches the MCP server through a 0600 file (`mcp --task-token-file`, hidden) instead of the command line every user can read; notification keys and the viewer login aren't passed to the agent; output lines that aren't UTF-8 are skipped instead of ending the run, and a run that ends early stops the agent's group. Co-authored-by: Claude Opus 5.5 --- CHANGELOG.md | 3 + CHANGELOG.zh-CN.md | 3 + apps/iphone-control/src/agent.rs | 121 ++++++++++++++++++---- apps/iphone-control/src/main.rs | 17 +++- apps/iphone-control/src/video/mod.rs | 17 +++- apps/iphone-control/src/viewer.rs | 140 +++++++++++++++++++++++--- apps/iphone-control/src/viewer/lan.rs | 13 ++- crates/ictl-mcp/src/server.rs | 13 ++- docs/dev/regression-cases.md | 4 + 9 files changed, 294 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 90ec4667..91715233 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,9 @@ What changed in each release, one line per change. Versions follow [Semantic Ver - Switching back to a phone made ready in the background takes effect at once even when the daemon was busy at that moment; it could wait 10 seconds. The daemon serves at most 256 clients at once; more wait their turn (#197). - AI tasks limited to some apps: an action is checked again once it has the phone, in case another app came to the front meanwhile, and `iphone_web_eval` is checked against the app that shows the page (#197). - `iphone_tap_element`'s scroll search and `iphone_wait_for` stop as soon as the task is paused or taken over or the caller goes away, instead of holding the phone until they time out; the daemon also limits a scroll search to 15 swipes (#197). +- The control page's server refuses malformed requests, so a crafted link can no longer send a browser from it to another site, and it no longer waits for request bodies from someone who isn't logged in (#196). +- AI tasks from the control page: a task whose text starts with `--` is no longer taken as an option by the agent, and the agent no longer gets the task's token on its command line or notification keys in its environment (#196). +- A malformed video report from a page no longer freezes its picture (#196). - iOS 17–18: the developer disk image is mounted the way these versions need, so WebDriverAgent starts on them again (#186). - Times in `status`, `doctor` and the event log are shown in local time with the time zone; they were UTC without saying so (#184). - Errors from `iphone-control update`, `service` and the update panel on the control page follow the chosen language; they were always in English (#184). diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 5ca29410..f18b6a10 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -21,6 +21,9 @@ - 切回一台在后台准备好的手机时,即使守护进程当时正忙也马上生效,之前可能要等 10 秒;守护进程同时最多服务 256 个客户端,更多的排队等候(#197)。 - 限定了 App 范围的 AI 任务:操作拿到手机后再查一次前台 App,以防期间换了别的 App;`iphone_web_eval` 按显示页面的 App 检查(#197)。 - `iphone_tap_element` 的边滑边找和 `iphone_wait_for` 在任务暂停、被接管或调用方离开时立刻停下,不再占着手机等到超时;守护进程也把边滑边找限制在 15 次以内(#197)。 +- 控制台服务拒绝格式不对的请求,精心构造的链接不能再把浏览器从控制台跳到别的网站;也不再为没登录的人等请求体(#196)。 +- 控制台上的 AI 任务:以 `--` 开头的任务描述不再被 agent 当成选项;agent 的命令行里不再有任务口令,环境里也没有通知密钥(#196)。 +- 页面发来格式不对的视频回执时,画面不再卡住(#196)。 - iOS 17–18:开发者镜像按这些版本需要的方式挂载,WebDriverAgent 又能在上面启动了(#186)。 - `status`、`doctor` 和事件日志里的时间改为本地时间并标明时区,之前显示的是 UTC 却没有说明(#184)。 - `iphone-control update`、`service` 和控制台更新面板里的报错跟随界面语言,之前总是英文(#184)。 diff --git a/apps/iphone-control/src/agent.rs b/apps/iphone-control/src/agent.rs index bbb63ac3..990501ef 100644 --- a/apps/iphone-control/src/agent.rs +++ b/apps/iphone-control/src/agent.rs @@ -80,17 +80,57 @@ pub struct Agents { running: std::sync::Mutex>, } -/// Takes an agent's process group off [`Agents::running`] when its run ends -struct Running<'a>(&'a Agents, Option); +/// Takes an agent's process group off [`Agents::running`] when its run ends. A run that ends before the agent was +/// waited for (an error reading its output) stops the group first, so nothing of it is left running; once it was +/// waited for (`waited`), the group isn't signalled any more: its id may be another process's by then +struct Running<'a> { + agents: &'a Agents, + pid: Option, + waited: bool, +} impl Drop for Running<'_> { fn drop(&mut self) { - if let Some(pid) = self.1 { - self.0.running.lock().unwrap_or_else(|p| p.into_inner()).remove(&pid); + if let Some(pid) = self.pid { + if !self.waited { + crate::procgroup::stop(pid); + } + self.agents.running.lock().unwrap_or_else(|p| p.into_inner()).remove(&pid); } } } +/// The task's token for the agent's MCP server, in a file of its own (0600, in the agent's private directory) instead +/// of the command line, which every user on the machine can read (`ps`). Removed when the run ends +struct TokenFile(PathBuf); + +impl TokenFile { + fn new(dir: &Path, token: &str) -> std::io::Result { + use std::io::Write; + use std::os::unix::fs::OpenOptionsExt; + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); + let path = dir.join(format!("task-{}-{nanos:x}.token", std::process::id())); + let mut f = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(&path)?; + f.write_all(token.as_bytes())?; + Ok(Self(path)) + } +} + +impl Drop for TokenFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +/// Variables of this program's settings that the agent has no use for and shouldn't see: notification keys, the +/// viewer's login (the agent's MCP server reads the settings file itself, so nothing it needs is lost) +const HIDDEN_FROM_AGENT: [&str; 4] = [ + ictl_daemon::protocol::env::TG_BOT_TOKEN, + ictl_daemon::protocol::env::BARK_KEY, + ictl_daemon::protocol::env::VIEWER_TOKEN, + ictl_daemon::protocol::env::TASK_TOKEN, +]; + /// The agent's working directory under `base`: this user's own (0700, not a link). The agent reads what is there /// (`CLAUDE.md`, `AGENTS.md`, `.claude/`), so in a shared directory such as `/tmp` a name made by someone else first /// isn't used: then one made just now, which nobody else can have @@ -239,9 +279,13 @@ impl Agents { prompt: &str, apps: &[String], ) -> anyhow::Result<()> { + let token_file = TokenFile::new(&self.workdir, token)?; let mut cmd = tokio::process::Command::new(program); - cmd.args(self.agent_args(backend, token, prompt, apps)) - .current_dir(&self.workdir) + cmd.args(self.agent_args(backend, &token_file.0, prompt, apps)); + for k in HIDDEN_FROM_AGENT { + cmd.env_remove(k); + } + cmd.current_dir(&self.workdir) .stdin(std::process::Stdio::null()) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) @@ -257,7 +301,7 @@ impl Agents { if let Some(pid) = pid { self.running.lock().unwrap_or_else(|p| p.into_inner()).insert(pid); } - let _running = Running(self, pid); + let mut running = Running { agents: self, pid, waited: false }; let stdout = child.stdout.take().ok_or_else(|| anyhow::anyhow!("no stdout"))?; let stderr = child.stderr.take().ok_or_else(|| anyhow::anyhow!("no stderr"))?; let errs = tokio::spawn(async move { @@ -273,12 +317,13 @@ impl Agents { }); let (mut summary, mut failure, mut last_text) = (None, None, None); let mut ended = false; - let mut lines = BufReader::new(stdout).lines(); + // by bytes: a line that isn't UTF-8 (an agent printing raw output) is skipped, not the end of reading + let mut lines = BufReader::new(stdout).split(b'\n'); loop { tokio::select! { - line = lines.next_line() => { + line = lines.next_segment() => { let Some(line) = line? else { break }; - let Ok(v) = serde_json::from_str::(&line) else { continue }; + let Ok(v) = serde_json::from_slice::(&line) else { continue }; match parse_line(backend, &v) { Some(Out::Thought(t)) => { last_text = Some(t.clone()); @@ -301,6 +346,7 @@ impl Agents { } } let status = child.wait().await?; + running.waited = true; let tail = errs.await.unwrap_or_default(); if ended { return Ok(()); @@ -323,21 +369,24 @@ impl Agents { Ok(()) } - fn agent_args(&self, backend: Backend, token: &str, prompt: &str, apps: &[String]) -> Vec { + /// The agent's command line. The task's token isn't on it (every user can read a command line): the MCP server + /// reads it from `token_file`. The prompt comes last, after `--`, so whatever it starts with is never taken for + /// an option (a prompt of `--permission-mode=bypassPermissions` would otherwise lift the agent's limits) + fn agent_args(&self, backend: Backend, token_file: &Path, prompt: &str, apps: &[String]) -> Vec { let guide = guidance(apps); let exe = self.exe.to_string_lossy().into_owned(); let socket = self.socket.to_string_lossy().into_owned(); + let token_file = token_file.to_string_lossy().into_owned(); let mut env = Map::new(); - env.insert(protocol::TASK_TOKEN_ENV.into(), token.into()); // the agent's tools answer in the task's language (this runs in its scope, see `start`) env.insert(ictl_daemon::protocol::env::LANG.into(), ictl_l10n::lang().code().into()); let s = |v: &str| v.to_owned(); match backend { Backend::Claude => { - let mcp = json!({"mcpServers": {"iphone": {"command": exe, "args": ["--socket", socket, "mcp"], "env": env}}}); + let args = ["--socket", &socket, "mcp", "--task-token-file", &token_file]; + let mcp = json!({"mcpServers": {"iphone": {"command": exe, "args": args, "env": env}}}); vec![ s("-p"), - s(prompt), s("--output-format"), s("stream-json"), s("--verbose"), @@ -354,6 +403,8 @@ impl Agents { s("--no-session-persistence"), s("--append-system-prompt"), guide.clone(), + s("--"), + s(prompt), ] } Backend::Codex => { @@ -373,7 +424,14 @@ impl Agents { s("-c"), format!("mcp_servers.iphone.command={}", q(&exe)), s("-c"), - format!("mcp_servers.iphone.args=[{},{},{}]", q("--socket"), q(&socket), q("mcp")), + format!( + "mcp_servers.iphone.args=[{},{},{},{},{}]", + q("--socket"), + q(&socket), + q("mcp"), + q("--task-token-file"), + q(&token_file) + ), s("-c"), format!("mcp_servers.iphone.env={{{env_toml}}}"), s("-c"), @@ -384,6 +442,7 @@ impl Agents { s("mcp_servers.iphone.default_tools_approval_mode=\"approve\""), s("-c"), s("suppress_unstable_features_warning=true"), + s("--"), format!("{guide}\n\n{}{prompt}", ictl_l10n::tr!("任务:", "Task: ")), ] } @@ -510,13 +569,41 @@ mod tests { let agents = Agents::new(Path::new("/nonexistent/ctl.sock")).unwrap(); let scoped = v(&["com.apple.Preferences", "com.apple.mobiletimer"]); for backend in Backend::ALL { - let plain = agents.agent_args(backend, "t", "看看设置", &[]).join("\n"); - let limited = agents.agent_args(backend, "t", "看看设置", &scoped).join("\n"); + let plain = agents.agent_args(backend, Path::new("/x/t.token"), "看看设置", &[]).join("\n"); + let limited = agents.agent_args(backend, Path::new("/x/t.token"), "看看设置", &scoped).join("\n"); assert!(!plain.contains("com.apple.Preferences"), "{backend:?}: no scope, nothing about one"); assert!(limited.contains("com.apple.Preferences、com.apple.mobiletimer"), "{backend:?}"); } } + /// Whatever a prompt starts with, it is the prompt: it comes last, after `--`. The task's token isn't on the + /// command line (every user on the machine can read it), only the file it is in + #[test] + fn a_prompt_is_never_an_option_and_the_token_never_on_the_command_line() { + let agents = Agents::new(Path::new("/nonexistent/ctl.sock")).unwrap(); + let hostile = "--permission-mode=bypassPermissions"; + for backend in Backend::ALL { + let args = agents.agent_args(backend, Path::new("/x/t.token"), hostile, &[]); + let dashes = args.iter().position(|a| a == "--").expect("an end of options"); + assert_eq!(dashes, args.len() - 2, "{backend:?}: the prompt alone follows it"); + assert!(args.last().unwrap().contains(hostile), "{backend:?}"); + assert!(!args[..dashes].iter().any(|a| a.contains(hostile)), "{backend:?}: not before it"); + let all = args.join(" "); + assert!(all.contains("--task-token-file") && all.contains("/x/t.token"), "{backend:?}"); + assert!(!all.contains(protocol::TASK_TOKEN_ENV), "{backend:?}: no token variable on the command line"); + } + let dir = std::env::temp_dir().join(format!("ictl-agent-token-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let f = TokenFile::new(&dir, "secret").unwrap(); + let path = f.0.clone(); + use std::os::unix::fs::MetadataExt; + assert_eq!(std::fs::metadata(&path).unwrap().mode() & 0o777, 0o600); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "secret"); + drop(f); + assert!(!path.exists(), "removed with the run"); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn the_agent_works_in_a_directory_of_its_own() { use std::os::unix::fs::{MetadataExt, PermissionsExt}; diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rs index 4f0eaadc..30fd3383 100644 --- a/apps/iphone-control/src/main.rs +++ b/apps/iphone-control/src/main.rs @@ -68,6 +68,10 @@ enum Command { url: Option, #[arg(long, value_name = "PEM", env = ictl_daemon::protocol::env::CA, help = ictl_l10n::tr!("--url 是本机生成的自签证书时,信任这张证书", "With --url and a self-signed certificate: trust it"))] ca: Option, + /// The task's token, from this file instead of IPHONE_CONTROL_TASK_TOKEN: the control page starts its agent's + /// MCP server this way, so the token isn't on a command line every user can read + #[arg(long, value_name = "FILE", hide = true)] + task_token_file: Option, }, #[command(about = ictl_l10n::tr!("打印把 MCP 注册到 Claude Code 的命令", "Print the command that registers the MCP server with Claude Code"))] McpConfig, @@ -347,9 +351,16 @@ async fn run() -> anyhow::Result<()> { cfg.socket = cli.socket; ictl_daemon::run(cfg).await } - Command::Mcp { url: Some(url), ca } => mcp_bridge::run(&url, ca.as_deref()).await, - Command::Mcp { url: None, .. } => { - ictl_mcp::serve_stdio(cli.socket, Some(ictl_daemon::maintenance::shared)).await + Command::Mcp { url: Some(url), ca, .. } => mcp_bridge::run(&url, ca.as_deref()).await, + Command::Mcp { url: None, task_token_file, .. } => { + let token = match task_token_file { + Some(f) => { + let t = std::fs::read_to_string(&f).map_err(|e| anyhow::anyhow!("{}: {e}", f.display()))?; + Some(t.trim().to_owned()).filter(|t| !t.is_empty()) + } + None => None, + }; + ictl_mcp::serve_stdio(cli.socket, Some(ictl_daemon::maintenance::shared), token).await } Command::McpConfig => { println!("{}", mcp_config(&cli.socket)?); diff --git a/apps/iphone-control/src/video/mod.rs b/apps/iphone-control/src/video/mod.rs index d687c4ea..51fe1ed3 100644 --- a/apps/iphone-control/src/video/mod.rs +++ b/apps/iphone-control/src/video/mod.rs @@ -133,6 +133,8 @@ impl Flow { } fn ack(&mut self, bytes: u64, now: Instant) { + // the page can't have read what wasn't sent; anything past it is a broken or hostile report + let bytes = bytes.min(self.sent); self.reports = true; self.heard = Some(now); if bytes > self.acked { @@ -188,7 +190,7 @@ impl Flow { return true; } let rate = self.rates.iter().map(|(_, r)| *r).fold(0.0, f64::max); - rate > 0.0 && (self.sent - self.acked) as f64 > rate * allowed.as_secs_f64() + rate > 0.0 && self.sent.saturating_sub(self.acked) as f64 > rate * allowed.as_secs_f64() } } @@ -503,6 +505,19 @@ mod tests { /// A page that confirms in time is never behind; one whose confirmations stop coming is, once the oldest /// unconfirmed message is older than the usual round trip plus the slack + /// A report of more than was sent (a broken or hostile page) counts as all of it, instead of wrapping the + /// bytes on the way around (a panic in a debug build, a frozen picture in a release one) + #[test] + fn a_report_beyond_what_was_sent_is_taken_as_all_of_it() { + let t0 = Instant::now(); + let mut f = Flow::default(); + f.sent(100, t0); + f.ack(u64::MAX, t0 + Duration::from_millis(10)); + assert_eq!(f.acked, 100); + f.sent(100, t0 + Duration::from_millis(20)); + assert!(!f.behind(t0 + Duration::from_millis(30))); + } + #[test] fn behind_means_late_beyond_the_usual_round_trip() { let t0 = Instant::now(); diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs index 22af89b8..d9724944 100644 --- a/apps/iphone-control/src/viewer.rs +++ b/apps/iphone-control/src/viewer.rs @@ -496,19 +496,16 @@ async fn serve( } } first = false; - let (head, mut body) = crate::read_head_from(c, std::mem::take(&mut carry)).await?; - drop(early.take()); + let (head, body) = crate::read_head_from(c, std::mem::take(&mut carry)).await?; let Some(req) = Head::parse(&head) else { return reply(c, 400, "text/plain", b"bad request").await; }; let keep = keepable(&req) && slots.is_none_or(|s| s.available_permits() >= KEEP_ROOM); - if keep { - // the whole body now, so the next request starts where it ends - carry = read_body(c, &mut body, req.content_length.unwrap_or(0)).await?; - } let lang = req.lang; + let next = &mut carry; + let early = &mut early; let run = KEEP_ALIVE.scope(std::cell::Cell::new(if keep { Keep::Allowed } else { Keep::No }), async { - handle(&mut slot, ctx, head, req, body).await?; + handle(&mut slot, ctx, head, req, body, early, next).await?; anyhow::Ok(KEEP_ALIVE.with(std::cell::Cell::get)) }); let kept = match lang { @@ -548,11 +545,27 @@ fn keepable(req: &Head) -> bool { short && !req.close && !req.chunked && req.content_length.unwrap_or(0) <= MAX_BODY } -async fn handle(slot: &mut Option, ctx: &Ctx, head: Vec, req: Head, mut body: Vec) -> anyhow::Result<()> { +/// One request. Until it has passed the login, its connection still counts against its machine's limit (`early`, +/// [`ARRIVING_PER_PEER`]) and nothing of its body is read beyond what came with the head: someone without a token +/// can't hold places with bodies that trickle in. A request that may keep its connection open reads its whole body +/// once logged in, and leaves what follows in `next` (the start of the next request) +async fn handle( + slot: &mut Option, + ctx: &Ctx, + head: Vec, + req: Head, + mut body: Vec, + early: &mut Option, + next: &mut Vec, +) -> anyhow::Result<()> { let Some(client) = slot.as_mut() else { return Ok(()) }; if !ctx.access.host_allowed(&head) || (req.path != "/" && !fetch_site_ok(&req)) { return reply(client, 403, "text/plain", b"forbidden").await; } + // a chunked body is read for `/mcp` only ([`read_chunked`]); elsewhere it would be taken for an empty one + if req.chunked && req.path != "/mcp" { + return reply(client, 411, "text/plain", b"length required").await; + } // HTTPS is on: from the network only HTTPS (plain HTTP stays for this machine) let local = client.tcp().peer_addr().is_ok_and(|a| a.ip().to_canonical().is_loopback()); if ctx.tls.is_some() && !client.is_tls() && !local { @@ -564,11 +577,18 @@ async fn handle(slot: &mut Option, ctx: &Ctx, head: Vec, req: Head, mu let Some(pass) = login_gate(client, ctx, &head, &req, &mut body).await? else { return Ok(()); }; - let _ = KEEP_ALIVE.try_with(|k| { - if k.get() == Keep::Allowed { + drop(early.take()); + let keep = KEEP_ALIVE.try_with(|k| { + let allowed = k.get() == Keep::Allowed; + if allowed { k.set(Keep::May); } + allowed }); + if keep == Ok(true) { + // the whole body now, so the next request starts where it ends + *next = read_body(client, &mut body, req.content_length.unwrap_or(0)).await?; + } if !pass.may(&req) { let m = ictl_l10n::tr!( "这是只读令牌:只能看画面、设备状态和任务,不能操作", @@ -1374,13 +1394,32 @@ struct Head { } impl Head { + /// `None` (answered 400) for what isn't a plain HTTP/1.x request: a target that isn't a path (it is put into the + /// HTTPS redirect's `Location`, [`https_location`]), control characters or a lone CR or LF anywhere (they would + /// end a header line we write), a second `Host` or `Content-Length`, or a body framed both ways (a request read + /// two ways is how requests are smuggled past proxies) fn parse(head: &[u8]) -> Option { + if !clean_head(head) { + return None; + } let text = std::str::from_utf8(head).ok()?; let mut lines = text.split("\r\n"); let mut first = lines.next()?.split(' '); let method = first.next()?.to_owned(); let target = first.next()?; - let close = first.next() == Some("HTTP/1.0"); + let close = match first.next()? { + "HTTP/1.1" => false, + "HTTP/1.0" => true, + _ => return None, + }; + if first.next().is_some() + || method.is_empty() + || !method.bytes().all(|b| b.is_ascii_uppercase()) + || !target.starts_with('/') + || target.starts_with("//") + { + return None; + } let (path, query) = target.split_once('?').unwrap_or((target, "")); let (path, query) = (path.to_owned(), query.to_owned()); let mut h = Self { @@ -1398,12 +1437,17 @@ impl Head { chunked: false, transfer_chunked_only: false, }; + let mut hosts = 0; for l in lines { let Some((k, v)) = l.split_once(':') else { continue }; let v = v.trim(); match k.trim().to_ascii_lowercase().as_str() { + "host" => hosts += 1, "origin" => h.origin = Some(v.to_owned()), "content-type" => h.content_type = Some(v.to_ascii_lowercase()), + // a second length is refused even when it is the same: proxies differ in which one they take + "content-length" if h.content_length.is_some() => return None, + "content-length" if v.is_empty() || !v.bytes().all(|b| b.is_ascii_digit()) => return None, "content-length" => h.content_length = Some(v.parse().ok()?), "sec-fetch-site" => h.fetch_site = Some(v.to_ascii_lowercase()), "x-ictl-lang" => h.lang = ictl_l10n::parse(v), @@ -1418,6 +1462,9 @@ impl Head { _ => {} } } + if hosts > 1 || (h.chunked && h.content_length.is_some()) { + return None; + } Some(h) } @@ -1430,6 +1477,21 @@ impl Head { } } +/// A request head with nothing but printable text, tabs and CRLF line ends: no other control character, no CR or LF +/// on its own +fn clean_head(head: &[u8]) -> bool { + let mut i = 0; + while i < head.len() { + match head[i] { + b'\r' if head.get(i + 1) == Some(&b'\n') => i += 2, + b'\t' => i += 1, + b if b < 0x20 || b == 0x7f => return false, + _ => i += 1, + } + } + true +} + fn percent_decode(s: &str) -> String { let b = s.as_bytes(); let mut out = Vec::with_capacity(b.len()); @@ -2012,6 +2074,58 @@ mod tests { assert_eq!(at(b"GET / HTTP/1.1\r\n\r\n"), None); } + /// The redirect's `Location` is built from the request target: only a path is a target, so it can't send a + /// browser to another host (`@evil.example/` would make `https://host:port@evil.example/`) nor add a header line + #[test] + fn only_a_plain_request_head_is_taken() { + let ok = |s: &str| Head::parse(s.as_bytes()).is_some(); + assert!(ok("GET /stream?x=1 HTTP/1.1\r\nHost: a\r\n")); + assert!(ok("POST /api/tap HTTP/1.0\r\nHost: a\r\nContent-Length: 2\r\nX-Pad:\tx\r\n")); + for bad in [ + "GET @evil.example/ HTTP/1.1\r\nHost: a\r\n", + "GET //evil.example/ HTTP/1.1\r\nHost: a\r\n", + "GET http://evil.example/ HTTP/1.1\r\nHost: a\r\n", + "GET /a\nLocation: x HTTP/1.1\r\nHost: a\r\n", + "GET /a HTTP/1.1\r\nHost: a\nSet-Cookie: x\r\n", + "GET /a HTTP/1.1\r\nHost: a\rX: y\r\n", + "GET /a HTTP/1.1\r\nHost: a\x00\r\n", + "GET /a HTTP/2\r\nHost: a\r\n", + "GET /a HTTP/1.1 extra\r\nHost: a\r\n", + "get /a HTTP/1.1\r\nHost: a\r\n", + "GET /a HTTP/1.1\r\nHost: a\r\nHost: b\r\n", + "POST /a HTTP/1.1\r\nContent-Length: 2\r\nContent-Length: 2\r\n", + "POST /a HTTP/1.1\r\nContent-Length: +2\r\n", + "POST /mcp HTTP/1.1\r\nTransfer-Encoding: chunked\r\nContent-Length: 2\r\n", + ] { + assert!(!ok(bad), "{bad:?}"); + } + } + + /// Without a login nothing of a body is waited for: a request that may keep its connection open used to read + /// its whole body before the login, so a body that never came held one of the places for the read timeout + #[tokio::test] + async fn a_body_is_not_waited_for_before_the_login() { + let temp = tempfile::tempdir_in("/tmp").unwrap(); + let mut ctx = test_ctx(temp.path(), &temp.path().join("none.sock")); + let entry = auth::Entry { name: "owner".into(), role: auth::Role::Operate, token: "t".repeat(64), created: 0 }; + ctx.auth = Some(auth::Auth::fixed(vec![entry], 8202)); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let server = async { + let (tcp, _) = listener.accept().await.unwrap(); + let _ = serve(Conn::Plain(tcp), &ctx, None, None).await; + }; + let client = async { + let mut s = tokio::net::TcpStream::connect(addr).await.unwrap(); + let req = "POST /api/tap HTTP/1.1\r\nHost: 127.0.0.1:8202\r\nConnection: keep-alive\r\n\ + Content-Type: application/json\r\nContent-Length: 4000\r\n\r\n{"; + s.write_all(req.as_bytes()).await.unwrap(); + let (h, _) = tokio::time::timeout(Duration::from_secs(2), answer(&mut s)).await.expect("answered at once"); + assert!(h.starts_with("HTTP/1.1 401"), "{h}"); + }; + tokio::join!(server, client); + } + #[tokio::test] async fn cancelled_picture_unregisters_its_feed() { let temp = tempfile::tempdir_in("/tmp").unwrap(); @@ -2025,7 +2139,9 @@ mod tests { let raw = b"GET /video?src=device&udid=TEST&feed=tab HTTP/1.1\r\nHost: localhost\r\n\r\n"; let (client, _) = accepted.unwrap(); let mut slot = Some(Conn::Plain(client)); - let mut request = Box::pin(handle(&mut slot, &ctx, raw.to_vec(), Head::parse(raw).unwrap(), vec![])); + let (mut early, mut next) = (None, Vec::new()); + let mut request = + Box::pin(handle(&mut slot, &ctx, raw.to_vec(), Head::parse(raw).unwrap(), vec![], &mut early, &mut next)); // The simulated daemon has accepted the request but has not supplied a stream. tokio::select! { result = &mut request => panic!("picture ended before cancellation: {result:?}"), diff --git a/apps/iphone-control/src/viewer/lan.rs b/apps/iphone-control/src/viewer/lan.rs index 909b7500..fdc26c76 100644 --- a/apps/iphone-control/src/viewer/lan.rs +++ b/apps/iphone-control/src/viewer/lan.rs @@ -95,8 +95,14 @@ impl Access { return false; }; let rest = rest.to_ascii_lowercase(); - let Some((name, p)) = rest.rsplit_once(':') else { return false }; - p.parse::().ok() == Some(port) && self.knows(name) + // a browser leaves the scheme's default port out + let default = if origin.starts_with("https://") { 443 } else { 80 }; + // `[::1]` has colons but no port: what follows the last one isn't a number there + let (name, p) = match rest.rsplit_once(':').and_then(|(n, p)| Some((n, p.parse::().ok()?))) { + Some(np) => np, + None => (rest.as_str(), default), + }; + p == port && self.knows(name) } } @@ -231,6 +237,9 @@ mod tests { assert!(!a.origin_allowed("http://192.168.10.100:3000", 8202), "another port"); assert!(!a.origin_allowed("http://evil.example:8202", 8202)); assert!(!a.origin_allowed("null", 8202)); + // the scheme's default port, which a browser leaves out + assert!(a.origin_allowed("https://nas.local", 443) && a.origin_allowed("http://nas.local", 80)); + assert!(!a.origin_allowed("https://nas.local", 8202) && !a.origin_allowed("http://nas.local", 443)); // what its certificate covers assert_eq!(a.names(), ["localhost", "127.0.0.1", "::1", "192.168.10.100", "nas.local", "nas"]); assert_eq!(Access::with_hosts(["[fd00::5]".into()]).names()[3], "fd00::5"); diff --git a/crates/ictl-mcp/src/server.rs b/crates/ictl-mcp/src/server.rs index aa30b96a..dfca144d 100644 --- a/crates/ictl-mcp/src/server.rs +++ b/crates/ictl-mcp/src/server.rs @@ -423,8 +423,17 @@ impl McpServer { /// 在 stdin/stdout 上运行 MCP 服务直到客户端断开 /// The MCP server on stdin/stdout. `lease` is taken for each tool call, not for the life of the process: agents keep /// this process running for hours, and an update has to wait only for calls under way -pub async fn serve_stdio(socket: PathBuf, lease: Option) -> anyhow::Result<()> { - let running = McpServer { socket, task: task::join_from_env(), lease }.serve(rmcp::transport::stdio()).await?; +/// `task_token`: the task to work for, given by the caller; without it the environment's +/// ([`crate::task::join_from_env`]) +pub async fn serve_stdio(socket: PathBuf, lease: Option, task_token: Option) -> anyhow::Result<()> { + let task = match task_token { + Some(t) => { + protocol::join_task(t.trim()); + true + } + None => task::join_from_env(), + }; + let running = McpServer { socket, task, lease }.serve(rmcp::transport::stdio()).await?; running.waiting().await?; Ok(()) } diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md index bb708c50..dcc40bfe 100644 --- a/docs/dev/regression-cases.md +++ b/docs/dev/regression-cases.md @@ -190,6 +190,10 @@ | 184 | 浏览器解不了 HEVC 时,每个看手机原生视频的控制台页面各起一个 ffmpeg 解 60 帧的 HEVC 再编 H.264,没有上限:开几个页面就能把主机 CPU 或显卡的编码会话占满 | 同时最多 4 个页面转码(`transcode::Slots`),再多的回 503(`Retry-After`),页面显示「画面断开 · 自动重试中」、等有页面关掉后接上;日志每分钟最多记一次 | 单测 `transcoding_pages_are_limited_and_their_places_come_back` + 真机 | | 185 | 控制台页面各自定时轮询:`/api/info` 每 2 秒、任务列表每 3 秒、设备面板每 10 秒三个请求(`/api/daemon`、`/api/devices` 读的是同一份快照),后台标签页也照常轮询;几个页面开着时守护进程的请求成倍增加 | 任务列表随 `/api/info?tasks=1` 一起取(只在页面要接任务时带上);`/api/daemon` 带上设备列表,一轮两个请求;页面在后台时 `/api/info`、设备面板、弹窗检查都不问,切回前台立刻补一次 | 页面测试 `a task list from the info poll is used as it is` 和原有的任务接续测试 + 真机 | | 186 | 守护进程开着 HID 会话就退出(看门狗判定卡死后 `exit(1)`、崩溃、kill -9):屏幕媒体流没停,手机一直显示「正在被查看」、一直不自动锁屏(iPhone 15 Pro Max iOS 27.2.1:kill -9 后 5 分钟仍是这样),直到下次有程序开了再正常关 HID。看门狗退出时拿不到设备锁,没法先收尾 | 开 HID 时写 `hid-open/`,正常关掉时删;启动时发现残留的,等那台手机就绪后开一下 HID 再正常关掉(最多试 3 次),事件日志记一笔 | 单测 `markers_outlive_the_process_until_cleared` + 真机(开着 HID 时 kill -9 守护进程,看灵动岛的图标) | +| 187 | 控制台不校验请求目标和请求头:`GET @evil.example/` 在局域网明文 HTTP 下被 307 到 `https://主机:端口@evil.example/`(浏览器去了外站),带裸 LF 的目标能往 `Location` 里加头;重复 `Content-Length` 取最后一个;长度和 chunked 同时出现也照收 | 目标必须以 `/` 开头(`//` 也不行),请求头只许可见字符、制表符和 CRLF,只认 HTTP/1.0、1.1,`Host`、`Content-Length` 各一个且长度只含数字,长度和 `Transfer-Encoding` 不能同时出现:否则 400;`/mcp` 以外的 chunked 回 411 | 单测 `only_a_plain_request_head_is_taken` + 真机主机(对部署的 viewer 发 `@evil.example/`、裸 LF、重复长度,都回 400;正常的 307 不变) | +| 188 | 能保持连接的请求在登录检查之前就把请求体读完(最长 60 秒),读完请求头就不再算进单个 IP 的 8 个未登录连接限额:局域网里一台没令牌的机器发 64 个不发完的请求体就占满控制台的连接 | 登录通过之前不读请求体,也一直算在那台机器的限额里;登录后再读整个请求体,后面的字节留给下一个请求 | 单测 `a_body_is_not_waited_for_before_the_login` + 真机主机(未登录、声明 4000 字节只发 1 字节:立刻 401;登录后同一连接上带请求体的请求和下一个请求都正常应答) | +| 189 | `/api/video/ack` 报告的字节数超过已发出的:`sent - acked` 下溢,debug 构建 panic,release 构建画面冻住(只读令牌也能发) | 回执按已发出的封顶,差值用饱和减法 | 单测 `a_report_beyond_what_was_sent_is_taken_as_all_of_it` | +| 190 | 控制台 AI 任务:claude 的 `-p` 是开关,prompt 以 `--permission-mode=…` 开头会被当成选项、去掉工具限制;任务口令写在 MCP 配置里出现在命令行(同机其他用户 `ps` 可见);agent 继承通知密钥和控制台令牌;agent 输出一行不是 UTF-8 就停止读取并留下进程组 | prompt 放最后、前面加 `--`;口令写进 agent 私有目录里的 0600 文件,MCP 服务用隐藏参数 `--task-token-file` 读,任务结束删掉;不给 agent 传 `TG_BOT_TOKEN`、`BARK_KEY`、`IPHONE_CONTROL_VIEWER_TOKEN`;按字节读行,没等到 agent 退出就结束时停掉它的进程组 | 单测 `a_prompt_is_never_an_option_and_the_token_never_on_the_command_line` + 真机(iPhone 15 Pro Max:控制台跑 claude 任务,prompt 以 `--permission-mode=bypassPermissions` 开头,照常当作任务文字完成;codex 任务完成;MCP 服务的命令行只有令牌文件路径,agent 环境里没有 `BARK_KEY`,结束后令牌文件已删) | | 191 | 原生控制(iOS 27)下,后台检查(控制台的弹窗、状态轮询)给操作让路时在无障碍请求中途被丢掉:DTX 会话的流停在半条消息上,下一个请求读到错位的应答;后台检查读不到应答时还会重启手机的 axauditd | 请求中途被丢掉时把会话标记为作废并停掉它的读循环(不再往那条流上回应答),下次重新打开;写入(包括读循环回应答)5 秒超时(算 I/O 超时,不触发重启 axauditd);连接关闭时结束等待;后台检查(`core::BACKGROUND`)不重启 axauditd | 单测 `a_cancelled_request_abandons_the_session`、`an_unanswered_request_keeps_the_session`、`a_closed_connection_ends_the_wait` + 真机(iPhone 15 Pro Max iOS 27.2.1:两个线程以 background 标记连续发弹窗检查和状态,同时做 24 个操作 ×2 轮:操作 0 失败,9000 多次后台检查都让路,日志里没有重连或重启 axauditd;操作停下 4 秒后后台检查照常应答) | | 192 | 任务暂停时排队的操作一直算在「等设备的操作」里:暂停多久,控制台的后台检查就让路多久 | 只在等设备锁时计数,等任务恢复时不算;Web 通道的锁不算 | 单测 `waiting_for_a_paused_task_doesnt_hold_off_the_checks` | | 193 | 守护进程主循环:要求的一轮巡检因设备忙没跑成时,只在循环下一次醒来时才发现,可能要等 10 秒的定时巡检;同时服务的连接数没有上限 | 直接等这一轮结束,没跑成就 200 毫秒后再要一轮;同时最多 256 个连接,更多的留在套接字队列里;先收割结束的连接再接受新的 | 真机(iPhone 和 iPad 之间来回切换:切回 iPhone 0.66 秒就绪,切到 iPad 2 秒就绪) | From 3e5011b3b5e41263b74f6e50986be6675943dee3 Mon Sep 17 00:00:00 2001 From: Derrors <33656531+Derrors@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:04:50 +0800 Subject: [PATCH 2/2] fix(viewer): review of #196 (token file fails closed, stricter heads, token dir, stderr) - mcp --task-token-file: an empty file, or one given with --url (also from IPHONE_CONTROL_URL), stops the server instead of running it outside the task; the viewer no longer passes IPHONE_CONTROL_URL/CA to its agents - request heads: the target is visible ASCII only; header names are tokens (`Content-Length : 1` and a name with blanks are 400); a line without a colon (folded or garbage) is 400 instead of skipped - token files live in the private directory's `tokens/`, beside the agent's `work/`, named with a counter, and removed if writing fails - the agent's stderr is read by bytes like its stdout - the login form is read within the head timeout (10 s), not the body's 60 s Co-Authored-By: Claude Opus 5.5 --- apps/iphone-control/src/agent.rs | 58 +++++++++++++++++++---- apps/iphone-control/src/main.rs | 46 ++++++++++++++---- apps/iphone-control/src/viewer.rs | 77 +++++++++++++++++++++++++++++-- docs/dev/regression-cases.md | 6 +-- 4 files changed, 162 insertions(+), 25 deletions(-) diff --git a/apps/iphone-control/src/agent.rs b/apps/iphone-control/src/agent.rs index 990501ef..b7257285 100644 --- a/apps/iphone-control/src/agent.rs +++ b/apps/iphone-control/src/agent.rs @@ -75,7 +75,10 @@ pub struct Agents { /// This program, for the agent's MCP server exe: PathBuf, socket: PathBuf, + /// Where the agent works workdir: PathBuf, + /// The tasks' token files ([`TokenFile`]), beside the working directory rather than in it + tokens: PathBuf, /// The process groups of the agents running now ([`Self::stop_all`]) running: std::sync::Mutex>, } @@ -105,14 +108,19 @@ impl Drop for Running<'_> { struct TokenFile(PathBuf); impl TokenFile { + /// In `dir` (the private directory's `tokens`, not the agent's working directory), under a name no other run of + /// this process has (a counter: clocks with microseconds only gave two runs the same name) fn new(dir: &Path, token: &str) -> std::io::Result { use std::io::Write; use std::os::unix::fs::OpenOptionsExt; - let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos()); - let path = dir.join(format!("task-{}-{nanos:x}.token", std::process::id())); + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let path = dir.join(format!("task-{}-{n}.token", std::process::id())); let mut f = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(&path)?; + // removed again if the write fails + let file = Self(path); f.write_all(token.as_bytes())?; - Ok(Self(path)) + Ok(file) } } @@ -124,11 +132,15 @@ impl Drop for TokenFile { /// Variables of this program's settings that the agent has no use for and shouldn't see: notification keys, the /// viewer's login (the agent's MCP server reads the settings file itself, so nothing it needs is lost) -const HIDDEN_FROM_AGENT: [&str; 4] = [ +const HIDDEN_FROM_AGENT: [&str; 6] = [ ictl_daemon::protocol::env::TG_BOT_TOKEN, ictl_daemon::protocol::env::BARK_KEY, ictl_daemon::protocol::env::VIEWER_TOKEN, ictl_daemon::protocol::env::TASK_TOKEN, + // the agent works on this machine's phone: its MCP server mustn't be sent to another viewer (with the token file + // it would refuse to start) + ictl_daemon::protocol::env::URL, + ictl_daemon::protocol::env::CA, ]; /// The agent's working directory under `base`: this user's own (0700, not a link). The agent reads what is there @@ -165,14 +177,30 @@ fn private_dir(base: &Path) -> std::io::Result { unreachable!("returns from the loop") } +/// A directory of our own inside the private one (which nobody else can write to): made 0700 if it isn't there +fn sub_dir(private: &Path, name: &str) -> std::io::Result { + use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; + let dir = private.join(name); + match std::fs::DirBuilder::new().mode(0o700).create(&dir) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && std::fs::symlink_metadata(&dir)?.is_dir() => { + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700))?; + } + Err(e) => return Err(e), + } + Ok(dir) +} + impl Agents { pub fn new(socket: &Path) -> anyhow::Result> { let base = std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).filter(|p| p.is_absolute()); - let workdir = private_dir(&base.unwrap_or_else(std::env::temp_dir))?; + let private = private_dir(&base.unwrap_or_else(std::env::temp_dir))?; + // the agent works in `work`; the tasks' tokens are kept beside it, not in what it works on Ok(Arc::new(Self { exe: std::env::current_exe()?, socket: socket.to_path_buf(), - workdir, + workdir: sub_dir(&private, "work")?, + tokens: sub_dir(&private, "tokens")?, running: Default::default(), })) } @@ -279,7 +307,7 @@ impl Agents { prompt: &str, apps: &[String], ) -> anyhow::Result<()> { - let token_file = TokenFile::new(&self.workdir, token)?; + let token_file = TokenFile::new(&self.tokens, token)?; let mut cmd = tokio::process::Command::new(program); cmd.args(self.agent_args(backend, &token_file.0, prompt, apps)); for k in HIDDEN_FROM_AGENT { @@ -306,9 +334,10 @@ impl Agents { let stderr = child.stderr.take().ok_or_else(|| anyhow::anyhow!("no stderr"))?; let errs = tokio::spawn(async move { let mut tail: Vec = Vec::new(); - let mut lines = BufReader::new(stderr).lines(); - while let Ok(Some(l)) = lines.next_line().await { - tail.push(l); + // by bytes like stdout: stopping at a line that isn't UTF-8 would leave the pipe full and the agent stuck + let mut lines = BufReader::new(stderr).split(b'\n'); + while let Ok(Some(l)) = lines.next_segment().await { + tail.push(String::from_utf8_lossy(&l).trim_end_matches('\r').to_owned()); if tail.len() > 20 { tail.remove(0); } @@ -601,7 +630,16 @@ mod tests { assert_eq!(std::fs::read_to_string(&path).unwrap(), "secret"); drop(f); assert!(!path.exists(), "removed with the run"); + // two at once never share a name + let (a, b) = (TokenFile::new(&dir, "a").unwrap(), TokenFile::new(&dir, "b").unwrap()); + assert_ne!(a.0, b.0); + drop((a, b)); std::fs::remove_dir_all(dir).unwrap(); + // kept beside the agent's working directory, not in what it works on; both its own + assert!(!agents.tokens.starts_with(&agents.workdir) && !agents.workdir.starts_with(&agents.tokens)); + for d in [&agents.tokens, &agents.workdir] { + assert_eq!(std::fs::metadata(d).unwrap().mode() & 0o777, 0o700, "{}", d.display()); + } } #[test] diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rs index 30fd3383..f4ebe0a5 100644 --- a/apps/iphone-control/src/main.rs +++ b/apps/iphone-control/src/main.rs @@ -70,7 +70,7 @@ enum Command { ca: Option, /// The task's token, from this file instead of IPHONE_CONTROL_TASK_TOKEN: the control page starts its agent's /// MCP server this way, so the token isn't on a command line every user can read - #[arg(long, value_name = "FILE", hide = true)] + #[arg(long, value_name = "FILE", hide = true, conflicts_with = "url")] task_token_file: Option, }, #[command(about = ictl_l10n::tr!("打印把 MCP 注册到 Claude Code 的命令", "Print the command that registers the MCP server with Claude Code"))] @@ -307,6 +307,20 @@ fn restore_sigpipe() { } } +/// The task's token from `mcp --task-token-file`. Given the file, there must be a token in it: without one the server +/// would run outside the task (no scope, no pause, no confirmation), so it doesn't start at all +fn read_task_token(f: &std::path::Path) -> anyhow::Result { + let t = std::fs::read_to_string(f).map_err(|e| anyhow::anyhow!("{}: {e}", f.display()))?; + let t = t.trim(); + anyhow::ensure!( + !t.is_empty(), + "{}: {}", + f.display(), + ictl_l10n::tr!("任务口令文件是空的", "the task token file is empty") + ); + Ok(t.to_owned()) +} + async fn run() -> anyhow::Result<()> { // 依赖树里 rustls 的 ring 和 aws-lc-rs 都开着,不装默认 provider 的话第一个 HTTPS 请求就 panic let _ = rustls::crypto::ring::default_provider().install_default(); @@ -353,13 +367,7 @@ async fn run() -> anyhow::Result<()> { } Command::Mcp { url: Some(url), ca, .. } => mcp_bridge::run(&url, ca.as_deref()).await, Command::Mcp { url: None, task_token_file, .. } => { - let token = match task_token_file { - Some(f) => { - let t = std::fs::read_to_string(&f).map_err(|e| anyhow::anyhow!("{}: {e}", f.display()))?; - Some(t.trim().to_owned()).filter(|t| !t.is_empty()) - } - None => None, - }; + let token = task_token_file.as_deref().map(read_task_token).transpose()?; ictl_mcp::serve_stdio(cli.socket, Some(ictl_daemon::maintenance::shared), token).await } Command::McpConfig => { @@ -1449,6 +1457,20 @@ mod tests { /// `IPHONE_CONTROL_VIEWER_LAN=1` turns `--lan` on. A plain flag only took true/false, so the service didn't start /// `--url` anywhere in `task …`, or from IPHONE_CONTROL_URL (which `task run --url` gives its command), and for /// `mcp` + /// Given a token file, the server works for that task or doesn't start: an empty one isn't "no task" + #[test] + fn an_empty_task_token_file_is_refused() { + let dir = std::env::temp_dir().join(format!("ictl-token-file-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let f = dir.join("t.token"); + for (content, ok) in [("", false), (" \n\t", false), ("abc\n", true)] { + std::fs::write(&f, content).unwrap(); + assert_eq!(super::read_task_token(&f).ok().as_deref(), ok.then_some("abc"), "{content:?}"); + } + assert!(super::read_task_token(&dir.join("missing")).is_err()); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn the_remote_viewer_from_a_flag_or_the_environment() { use clap::Parser; @@ -1467,7 +1489,15 @@ mod tests { assert_eq!(task(&["i", "task", "--url", "https://a:1", "pause", "abc"]).as_deref(), Some("https://a:1")); assert_eq!(task(&["i", "task", "approve", "abc", "--url", "https://a:1"]).as_deref(), Some("https://a:1")); assert_eq!(mcp(&["i", "mcp", "--url", "https://a:1"]).as_deref(), Some("https://a:1")); + // the token file is for the local server only: never silently dropped for a bridge + let both = ["i", "mcp", "--url", "https://a:1", "--task-token-file", "/x/t.token"]; + assert!(super::Cli::try_parse_from(both).is_err()); + assert!(super::Cli::try_parse_from(["i", "mcp", "--task-token-file", "/x/t.token"]).is_ok()); unsafe { std::env::set_var(ictl_daemon::protocol::env::URL, "https://b:2") }; + assert!( + super::Cli::try_parse_from(["i", "mcp", "--task-token-file", "/x/t.token"]).is_err(), + "nor for one from the environment" + ); assert_eq!(task(&["i", "task", "finish", "done"]).as_deref(), Some("https://b:2")); assert_eq!(mcp(&["i", "mcp"]).as_deref(), Some("https://b:2")); unsafe { std::env::remove_var(ictl_daemon::protocol::env::URL) }; diff --git a/apps/iphone-control/src/viewer.rs b/apps/iphone-control/src/viewer.rs index d9724944..5e398db6 100644 --- a/apps/iphone-control/src/viewer.rs +++ b/apps/iphone-control/src/viewer.rs @@ -1298,7 +1298,10 @@ async fn login_gate( reply(client, 413, "text/plain", b"too large").await?; return Ok(None); } - read_body(client, body, len).await?; + // a 4 KB form: no longer than a head may take ([`BODY_TIMEOUT`] is for large bodies) + tokio::time::timeout(crate::HEAD_TIMEOUT, read_body(client, body, len)) + .await + .map_err(|_| anyhow::anyhow!("login form took too long"))??; match auth::form_token(body).filter(|t| !t.trim().is_empty()).map(|t| a.try_token(&t)) { Some(Verdict::Ok(w)) => logged_in(client, a, &w.name, secure).await?, Some(v) => login_page(client, v).await?, @@ -1403,7 +1406,8 @@ impl Head { return None; } let text = std::str::from_utf8(head).ok()?; - let mut lines = text.split("\r\n"); + // the blank line that ends the head; any other empty line is a malformed one + let mut lines = text.trim_end_matches("\r\n").split("\r\n"); let mut first = lines.next()?.split(' '); let method = first.next()?.to_owned(); let target = first.next()?; @@ -1417,6 +1421,8 @@ impl Head { || !method.bytes().all(|b| b.is_ascii_uppercase()) || !target.starts_with('/') || target.starts_with("//") + // visible ASCII only: a tab or a byte past ASCII went into the redirect's `Location` as it was + || !target.bytes().all(|b| (0x21..=0x7e).contains(&b)) { return None; } @@ -1439,9 +1445,14 @@ impl Head { }; let mut hosts = 0; for l in lines { - let Some((k, v)) = l.split_once(':') else { continue }; + // a line without a colon (a folded continuation, garbage) or a name with blanks (`Content-Length : 1`, + // which some proxies read and others don't): 400, as RFC 9112 §5.1 asks + let (k, v) = l.split_once(':')?; + if k.is_empty() || !k.bytes().all(is_tchar) { + return None; + } let v = v.trim(); - match k.trim().to_ascii_lowercase().as_str() { + match k.to_ascii_lowercase().as_str() { "host" => hosts += 1, "origin" => h.origin = Some(v.to_owned()), "content-type" => h.content_type = Some(v.to_ascii_lowercase()), @@ -1477,6 +1488,11 @@ impl Head { } } +/// A character of a header name (RFC 9110 §5.6.2 `tchar`) +fn is_tchar(b: u8) -> bool { + b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b) +} + /// A request head with nothing but printable text, tabs and CRLF line ends: no other control character, no CR or LF /// on its own fn clean_head(head: &[u8]) -> bool { @@ -2096,9 +2112,62 @@ mod tests { "POST /a HTTP/1.1\r\nContent-Length: 2\r\nContent-Length: 2\r\n", "POST /a HTTP/1.1\r\nContent-Length: +2\r\n", "POST /mcp HTTP/1.1\r\nTransfer-Encoding: chunked\r\nContent-Length: 2\r\n", + // a tab or a byte past ASCII in the target (it goes into the redirect's `Location`) + "GET /\tfoo HTTP/1.1\r\nHost: a\r\n", + "GET /a\tHTTP/1.1 HTTP/1.1\r\nHost: a\r\n", + "GET /caf\u{e9} HTTP/1.1\r\nHost: a\r\n", + // blanks in a header's name, which proxies read differently + "POST /a HTTP/1.1\r\nContent-Length : 1\r\n", + "POST /mcp HTTP/1.1\r\nTransfer-Encoding : chunked\r\n", + "GET /a HTTP/1.1\r\n Host: a\r\n", + // a line without a colon: a folded continuation, or garbage + "GET /a HTTP/1.1\r\nHost: a\r\nX-A: 1\r\n folded\r\n", + "GET /a HTTP/1.1\r\nHost: a\r\nnocolon\r\n", + "GET /a HTTP/1.1\r\n\r\nHost: a\r\n", + "GET /a HTTP/1.1\r\n: empty name\r\n", ] { assert!(!ok(bad), "{bad:?}"); } + assert!(ok("GET /a HTTP/1.1\r\nHost: a\r\nX-Ok: v\r\n\r\n"), "the blank line that ends the head"); + } + + /// A connection counts against its machine's limit until the login passes, not only until its head is in; a + /// chunked body outside `/mcp` is refused (411) rather than taken for an empty one + #[tokio::test] + async fn the_place_is_kept_until_the_login_passes() { + let temp = tempfile::tempdir_in("/tmp").unwrap(); + let mut ctx = test_ctx(temp.path(), &temp.path().join("none.sock")); + let token = "t".repeat(64); + let entry = auth::Entry { name: "owner".into(), role: auth::Role::Operate, token: token.clone(), created: 0 }; + ctx.auth = Some(auth::Auth::fixed(vec![entry], 8202)); + let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); + let arriving = Arriving::default(); + let lan: std::net::IpAddr = "192.168.1.9".parse().unwrap(); + let run = async |raw: String, early: &mut Option| { + let (tab, accepted) = + tokio::join!(tokio::net::TcpStream::connect(listener.local_addr().unwrap()), listener.accept()); + let mut tab = tab.unwrap(); + let mut slot = Some(Conn::Plain(accepted.unwrap().0)); + let head = Head::parse(raw.as_bytes()).unwrap(); + let mut next = Vec::new(); + let _ = handle(&mut slot, &ctx, raw.clone().into_bytes(), head, vec![], early, &mut next).await; + drop(slot); + answer(&mut tab).await.0 + }; + let mut early = arriving.enter(lan); + let h = run("GET /api/daemon HTTP/1.1\r\nHost: 127.0.0.1:8202\r\n\r\n".into(), &mut early).await; + assert!(h.starts_with("HTTP/1.1 401"), "{h}"); + assert!(early.is_some(), "not logged in: still counted"); + let h = run( + "POST /api/tap HTTP/1.1\r\nHost: 127.0.0.1:8202\r\nTransfer-Encoding: chunked\r\n\r\n".into(), + &mut early, + ) + .await; + assert!(h.starts_with("HTTP/1.1 411"), "{h}"); + let logged = format!("GET / HTTP/1.1\r\nHost: 127.0.0.1:8202\r\nAuthorization: Bearer {token}\r\n\r\n"); + let h = run(logged, &mut early).await; + assert!(h.starts_with("HTTP/1.1 200"), "{h}"); + assert!(early.is_none(), "logged in: the place is let go"); } /// Without a login nothing of a body is waited for: a request that may keep its connection open used to read diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md index dcc40bfe..c3505718 100644 --- a/docs/dev/regression-cases.md +++ b/docs/dev/regression-cases.md @@ -190,10 +190,10 @@ | 184 | 浏览器解不了 HEVC 时,每个看手机原生视频的控制台页面各起一个 ffmpeg 解 60 帧的 HEVC 再编 H.264,没有上限:开几个页面就能把主机 CPU 或显卡的编码会话占满 | 同时最多 4 个页面转码(`transcode::Slots`),再多的回 503(`Retry-After`),页面显示「画面断开 · 自动重试中」、等有页面关掉后接上;日志每分钟最多记一次 | 单测 `transcoding_pages_are_limited_and_their_places_come_back` + 真机 | | 185 | 控制台页面各自定时轮询:`/api/info` 每 2 秒、任务列表每 3 秒、设备面板每 10 秒三个请求(`/api/daemon`、`/api/devices` 读的是同一份快照),后台标签页也照常轮询;几个页面开着时守护进程的请求成倍增加 | 任务列表随 `/api/info?tasks=1` 一起取(只在页面要接任务时带上);`/api/daemon` 带上设备列表,一轮两个请求;页面在后台时 `/api/info`、设备面板、弹窗检查都不问,切回前台立刻补一次 | 页面测试 `a task list from the info poll is used as it is` 和原有的任务接续测试 + 真机 | | 186 | 守护进程开着 HID 会话就退出(看门狗判定卡死后 `exit(1)`、崩溃、kill -9):屏幕媒体流没停,手机一直显示「正在被查看」、一直不自动锁屏(iPhone 15 Pro Max iOS 27.2.1:kill -9 后 5 分钟仍是这样),直到下次有程序开了再正常关 HID。看门狗退出时拿不到设备锁,没法先收尾 | 开 HID 时写 `hid-open/`,正常关掉时删;启动时发现残留的,等那台手机就绪后开一下 HID 再正常关掉(最多试 3 次),事件日志记一笔 | 单测 `markers_outlive_the_process_until_cleared` + 真机(开着 HID 时 kill -9 守护进程,看灵动岛的图标) | -| 187 | 控制台不校验请求目标和请求头:`GET @evil.example/` 在局域网明文 HTTP 下被 307 到 `https://主机:端口@evil.example/`(浏览器去了外站),带裸 LF 的目标能往 `Location` 里加头;重复 `Content-Length` 取最后一个;长度和 chunked 同时出现也照收 | 目标必须以 `/` 开头(`//` 也不行),请求头只许可见字符、制表符和 CRLF,只认 HTTP/1.0、1.1,`Host`、`Content-Length` 各一个且长度只含数字,长度和 `Transfer-Encoding` 不能同时出现:否则 400;`/mcp` 以外的 chunked 回 411 | 单测 `only_a_plain_request_head_is_taken` + 真机主机(对部署的 viewer 发 `@evil.example/`、裸 LF、重复长度,都回 400;正常的 307 不变) | -| 188 | 能保持连接的请求在登录检查之前就把请求体读完(最长 60 秒),读完请求头就不再算进单个 IP 的 8 个未登录连接限额:局域网里一台没令牌的机器发 64 个不发完的请求体就占满控制台的连接 | 登录通过之前不读请求体,也一直算在那台机器的限额里;登录后再读整个请求体,后面的字节留给下一个请求 | 单测 `a_body_is_not_waited_for_before_the_login` + 真机主机(未登录、声明 4000 字节只发 1 字节:立刻 401;登录后同一连接上带请求体的请求和下一个请求都正常应答) | +| 187 | 控制台不校验请求目标和请求头:`GET @evil.example/` 在局域网明文 HTTP 下被 307 到 `https://主机:端口@evil.example/`(浏览器去了外站),带裸 LF 的目标能往 `Location` 里加头;重复 `Content-Length` 取最后一个;长度和 chunked 同时出现也照收 | 目标必须以 `/` 开头(`//` 也不行)、只含可见 ASCII,请求头只许可见字符、制表符和 CRLF,头名只许 token 字符(`Content-Length : 1` 这种名字带空白的、没有冒号的行、折行都回 400),只认 HTTP/1.0、1.1,`Host`、`Content-Length` 各一个且长度只含数字,长度和 `Transfer-Encoding` 不能同时出现:否则 400;`/mcp` 以外的 chunked 回 411 | 单测 `only_a_plain_request_head_is_taken`、`the_place_is_kept_until_the_login_passes` + 真机主机(对部署的 viewer 发 `@evil.example/`、裸 LF、重复长度,都回 400;正常的 307 不变) | +| 188 | 能保持连接的请求在登录检查之前就把请求体读完(最长 60 秒),读完请求头就不再算进单个 IP 的 8 个未登录连接限额:局域网里一台没令牌的机器发 64 个不发完的请求体就占满控制台的连接 | 登录通过之前不读请求体,也一直算在那台机器的限额里;登录后再读整个请求体,后面的字节留给下一个请求;登录表单(最多 4 KB)的读取限时和请求头一样是 10 秒 | 单测 `a_body_is_not_waited_for_before_the_login` + 真机主机(未登录、声明 4000 字节只发 1 字节:立刻 401;登录后同一连接上带请求体的请求和下一个请求都正常应答) | | 189 | `/api/video/ack` 报告的字节数超过已发出的:`sent - acked` 下溢,debug 构建 panic,release 构建画面冻住(只读令牌也能发) | 回执按已发出的封顶,差值用饱和减法 | 单测 `a_report_beyond_what_was_sent_is_taken_as_all_of_it` | -| 190 | 控制台 AI 任务:claude 的 `-p` 是开关,prompt 以 `--permission-mode=…` 开头会被当成选项、去掉工具限制;任务口令写在 MCP 配置里出现在命令行(同机其他用户 `ps` 可见);agent 继承通知密钥和控制台令牌;agent 输出一行不是 UTF-8 就停止读取并留下进程组 | prompt 放最后、前面加 `--`;口令写进 agent 私有目录里的 0600 文件,MCP 服务用隐藏参数 `--task-token-file` 读,任务结束删掉;不给 agent 传 `TG_BOT_TOKEN`、`BARK_KEY`、`IPHONE_CONTROL_VIEWER_TOKEN`;按字节读行,没等到 agent 退出就结束时停掉它的进程组 | 单测 `a_prompt_is_never_an_option_and_the_token_never_on_the_command_line` + 真机(iPhone 15 Pro Max:控制台跑 claude 任务,prompt 以 `--permission-mode=bypassPermissions` 开头,照常当作任务文字完成;codex 任务完成;MCP 服务的命令行只有令牌文件路径,agent 环境里没有 `BARK_KEY`,结束后令牌文件已删) | +| 190 | 控制台 AI 任务:claude 的 `-p` 是开关,prompt 以 `--permission-mode=…` 开头会被当成选项、去掉工具限制;任务口令写在 MCP 配置里出现在命令行(同机其他用户 `ps` 可见);agent 继承通知密钥和控制台令牌;agent 输出一行不是 UTF-8 就停止读取并留下进程组 | prompt 放最后、前面加 `--`;口令写进私有目录 `tokens/` 里的 0600 文件(agent 在旁边的 `work/` 里工作,文件名带递增序号),MCP 服务用隐藏参数 `--task-token-file` 读,文件为空或同时给了 `--url` 就不启动(不会悄悄变成任务以外的普通 MCP),任务结束删掉;不给 agent 传 `TG_BOT_TOKEN`、`BARK_KEY`、`IPHONE_CONTROL_VIEWER_TOKEN`、`IPHONE_CONTROL_URL`、`IPHONE_CONTROL_CA`;stdout、stderr 都按字节读行,没等到 agent 退出就结束时停掉它的进程组 | 单测 `a_prompt_is_never_an_option_and_the_token_never_on_the_command_line`、`an_empty_task_token_file_is_refused`、`the_remote_viewer_from_a_flag_or_the_environment` + 真机(iPhone 15 Pro Max:控制台跑 claude 任务,prompt 以 `--permission-mode=bypassPermissions` 开头,照常当作任务文字完成;codex 任务完成;MCP 服务的命令行只有令牌文件路径,agent 环境里没有 `BARK_KEY`,结束后令牌文件已删) | | 191 | 原生控制(iOS 27)下,后台检查(控制台的弹窗、状态轮询)给操作让路时在无障碍请求中途被丢掉:DTX 会话的流停在半条消息上,下一个请求读到错位的应答;后台检查读不到应答时还会重启手机的 axauditd | 请求中途被丢掉时把会话标记为作废并停掉它的读循环(不再往那条流上回应答),下次重新打开;写入(包括读循环回应答)5 秒超时(算 I/O 超时,不触发重启 axauditd);连接关闭时结束等待;后台检查(`core::BACKGROUND`)不重启 axauditd | 单测 `a_cancelled_request_abandons_the_session`、`an_unanswered_request_keeps_the_session`、`a_closed_connection_ends_the_wait` + 真机(iPhone 15 Pro Max iOS 27.2.1:两个线程以 background 标记连续发弹窗检查和状态,同时做 24 个操作 ×2 轮:操作 0 失败,9000 多次后台检查都让路,日志里没有重连或重启 axauditd;操作停下 4 秒后后台检查照常应答) | | 192 | 任务暂停时排队的操作一直算在「等设备的操作」里:暂停多久,控制台的后台检查就让路多久 | 只在等设备锁时计数,等任务恢复时不算;Web 通道的锁不算 | 单测 `waiting_for_a_paused_task_doesnt_hold_off_the_checks` | | 193 | 守护进程主循环:要求的一轮巡检因设备忙没跑成时,只在循环下一次醒来时才发现,可能要等 10 秒的定时巡检;同时服务的连接数没有上限 | 直接等这一轮结束,没跑成就 200 毫秒后再要一轮;同时最多 256 个连接,更多的留在套接字队列里;先收割结束的连接再接受新的 | 真机(iPhone 和 iPad 之间来回切换:切回 iPhone 0.66 秒就绪,切到 iPad 2 秒就绪) |