diff --git a/CHANGELOG.md b/CHANGELOG.md index 794df05..bff7de9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,16 @@ is on main, the release is published with that section as its notes (AGENTS.md, ### Installer and launcher +- On Linux, a start through palera1n or checkra1n begins only once the + computer has given your account access to the device, so the tool is no + longer refused it in its first moment. When a tool is refused the device + anyway, as it comes back on USB during the exploit, the start ends with + "USB permission: … was refused the device" and how to fix it (Orchard's + USB rule, or starting orchard with sudo), instead of "Pongo did not + appear on USB" or a timeout. The iOS 12 to 14 start with checkra1n + reports checkra1n's own failure about a minute after it gives up, instead + of "usbmuxd is not running" seven minutes later. + - Choosing Dopamine in the Options after a start with palera1n didn't work now switches to Dopamine: the installer finds the device again as it is, and Continue installs the helper app. Before, it kept sending the device diff --git a/crates/runtime/src/access_checkra1n.rs b/crates/runtime/src/access_checkra1n.rs index 53ca2ca..39c3718 100644 --- a/crates/runtime/src/access_checkra1n.rs +++ b/crates/runtime/src/access_checkra1n.rs @@ -41,6 +41,10 @@ const SSH_PORT: u16 = 44; const PASSWORD: &str = "alpine"; /// checkra1n's own run, then iOS's start until its SSH server answers. const BOOT: Duration = Duration::from_secs(120 + 300); +/// How long checkra1n may say nothing more after an error before the start +/// counts as failed: after "Timed out in state 1" it waits on with the +/// device in DFU mode and never tries again (orchard#416). +const SILENT_AFTER_ERROR: Duration = Duration::from_secs(60); fn fail(message: impl Into) -> Error { Error::new(Code::Refused, message.into()) @@ -105,6 +109,23 @@ fn spawn_error(error: std::io::Error) -> Error { error.into() } +/// checkra1n's last error, when it is its last word: "checkra1n: Timed out +/// in state 1, …", or a USB permission timeout when it was refused the +/// device (usb_node.rs). None while it carries on after its errors. +fn last_word(log: &str) -> Option { + let line = crate::chain::strip_ansi(log.lines().rev().find(|l| !l.trim().is_empty())?); + let message = line.split("").nth(1)?.trim_start_matches(':').trim(); + let failed = fail(format!("checkra1n: {message}")); + Some(if cfg!(target_os = "linux") && crate::usb_node::refused_in(log) { crate::usb_node::refused("checkra1n", &failed) } else { failed }) +} + +/// Why a start that ran out of time failed: checkra1n's own last error over +/// usbmuxd's absence (iOS never started, so nothing started usbmuxd), else +/// that, else that the SSH server did not come up. +fn timed_out(log: &str, usbmuxd_down: Option) -> Error { + last_word(log).or(usbmuxd_down).unwrap_or_else(|| fail("checkra1n's SSH server did not come up. Unlock the device; if it stays in iOS without the checkra1n app, start again")) +} + /// Runs checkra1n until the device's SSH server answers, and returns the /// device's UDID. fn start_ios(executor: &Executor) -> Result { @@ -119,6 +140,11 @@ fn start_ios(executor: &Executor) -> Result { // Resolved while the device is in DFU mode: its node goes away after. let reset_off = crate::flags::port_reset().is_some_and(|w| w.is_zero()); let in_dfu: Vec<_> = orchard_usb::list().map(|all| all.into_iter().filter(|d| d.mode == orchard_usb::Mode::Dfu).collect()).unwrap_or_default(); + // Linux: a device that has just entered DFU mode may not be open to this + // account yet; checkra1n 0.12.4 doesn't try again when refused. + if let [device] = in_dfu.as_slice() { + crate::usb_node::wait_accessible(&device.location)?; + } let replug = match in_dfu.as_slice() { [device] if !reset_off => crate::replug::port_control(&device.location, Path::new("/sys/bus/usb/devices")).map(|c| crate::replug::Watcher::start(log_path.clone(), c)), _ => None, @@ -139,6 +165,8 @@ fn start_ios(executor: &Executor) -> Result { } }; let until = Instant::now() + BOOT; + let read_log = || std::fs::read(&log_path).map(|t| String::from_utf8_lossy(&t).into_owned()).unwrap_or_default(); + let (mut seen, mut changed) = (0usize, Instant::now()); let outcome = loop { std::thread::sleep(Duration::from_secs(3)); let usbmuxd_down = match ssh_answers() { @@ -151,10 +179,17 @@ fn start_ios(executor: &Executor) -> Result { break Err(fail(format!("checkra1n failed ({status}); its log: {}", log_path.display()))); } } + let text = read_log(); + if text.len() != seen { + (seen, changed) = (text.len(), Instant::now()); + } + if changed.elapsed() >= SILENT_AFTER_ERROR { + if let Some(failed) = last_word(&text) { + break Err(failed); + } + } if Instant::now() > until { - break Err(usbmuxd_down.unwrap_or_else(|| { - fail("checkra1n's SSH server did not come up. Unlock the device; if it stays in iOS without the checkra1n app, start again") - })); + break Err(timed_out(&text, usbmuxd_down)); } }; let _ = child.kill(); @@ -562,6 +597,35 @@ mod tests { assert_eq!(on_host(failed(), "s5l8960x", false).hint, None); } + #[test] + fn a_failed_checkra1n_is_named_not_usbmuxd() { + // orchard#416, run 7: refused after the trigger, then timed out. + let refused = "14:24:05 : Right before trigger (this is the real bug setup)\n\ + 14:24:05 : Couldn't open USB interface due to EACCES. Run as root maybe? (error code: -75)\n\ + 14:24:30 : Timed out in state 1, assuming we are back to square one with this device. (error code: -31)\n"; + let usbmuxd = || Some(Error::new(Code::NotFound, "usbmuxd is not running (Connection refused (os error 111))")); + let error = timed_out(refused, usbmuxd()); + if cfg!(target_os = "linux") { + assert!(error.message.starts_with("USB permission: checkra1n was refused the device"), "{}", error.message); + assert!(error.to_string().contains("orchard setup usb")); + } else { + assert!(error.message.starts_with("checkra1n: Timed out in state 1")); + } + assert!(!error.message.contains("usbmuxd")); + // As root (no EACCES): checkra1n's own error. + let root = "14:43:17 : Right before trigger (this is the real bug setup)\n\ + 14:43:42 : Timed out in state 1, assuming we are back to square one with this device. (error code: -31)\n"; + assert_eq!( + timed_out(root, usbmuxd()).message, + "checkra1n: Timed out in state 1, assuming we are back to square one with this device. (error code: -31)" + ); + // checkra1n went on after an error: not its last word. + assert!(last_word(&format!("{root}14:43:45 : Exploiting\n")).is_none()); + // Nothing from checkra1n: usbmuxd, then the SSH server. + assert!(timed_out("14:43:01 : Booting...\n", usbmuxd()).message.starts_with("usbmuxd is not running")); + assert!(timed_out("", None).message.starts_with("checkra1n's SSH server did not come up")); + } + #[test] fn a_leftover_session_is_undone_with_its_own_helper() { let script = leftover(SESSION, APP); diff --git a/crates/runtime/src/chain.rs b/crates/runtime/src/chain.rs index 8d7de04..e47fab6 100644 --- a/crates/runtime/src/chain.rs +++ b/crates/runtime/src/chain.rs @@ -142,13 +142,13 @@ fn install_bundle(executor: &Executor, session: &Session, device: &Device) /// Runs palera1n on the device in DFU: checks it is the user's device /// first, resets its USB port on Linux if it doesn't come back after /// checkm8, and logs palera1n's output in the cache. -fn run_palera1n(executor: &Executor, session: &mut Session, args: &[std::ffi::OsString], seconds: u64) -> Result<()> { +fn run_palera1n(executor: &Executor, session: &mut Session, args: &[std::ffi::OsString], seconds: u64) -> Result { run_palera1n_from(executor, session, Mode::Dfu, args, seconds) } /// palera1n on the device in `from`: DFU (the exploit, with the port reset /// on Linux), or Pongo (palera1n carries on from there). -fn run_palera1n_from(executor: &Executor, session: &mut Session, from: Mode, args: &[std::ffi::OsString], seconds: u64) -> Result<()> { +fn run_palera1n_from(executor: &Executor, session: &mut Session, from: Mode, args: &[std::ffi::OsString], seconds: u64) -> Result { let (pin, release) = crate::flags::palera1n_pin().ok_or_else(|| fail("palera1n publishes no build for this computer"))?; let palera1n = executor.palera1n(pin, release)?; run_tool(executor, session, from, "palera1n", &labelled("palera1n", release), &palera1n, args, seconds) @@ -156,7 +156,7 @@ fn run_palera1n_from(executor: &Executor, session: &mut Session, from: Mod /// checkra1n's exploit and Pongo with `pongo_image`, /// with the arguments orchard's Python CLI runs it with. -fn run_checkra1n(executor: &Executor, session: &mut Session, pongo_image: &std::path::Path, seconds: u64) -> Result<()> { +fn run_checkra1n(executor: &Executor, session: &mut Session, pongo_image: &std::path::Path, seconds: u64) -> Result { let (pin, release) = crate::flags::checkra1n_pin().ok_or_else(|| fail("checkra1n publishes no build for this computer"))?; let checkra1n = executor.palera1n(pin, release)?; let args: Vec = ["-E", "-p", "-v", "-n", "-k"].iter().map(Into::into).chain([pongo_image.as_os_str().to_owned()]).collect(); @@ -487,12 +487,18 @@ fn step(text: &str) { } /// One run of the tool that takes the device on from `from`, its output in -/// a log of its own and followed while it runs. -fn run_tool(executor: &Executor, session: &mut Session, from: Mode, name: &str, label: &str, palera1n: &std::path::Path, args: &[std::ffi::OsString], seconds: u64) -> Result<()> { +/// a log of its own and followed while it runs; returns that log. A failure +/// whose log shows the tool was refused the device is a USB permission +/// timeout (usb_node.rs). +fn run_tool(executor: &Executor, session: &mut Session, from: Mode, name: &str, label: &str, palera1n: &std::path::Path, args: &[std::ffi::OsString], seconds: u64) -> Result { if !now_in(session, from)? { return Err(fail(if from == Mode::Dfu { "the device is no longer in DFU mode" } else { "the device is not in Pongo" })); } let location = session.device().location.clone(); + // Linux: the device has just shown up in this mode (a replug, Pongo + // after the exploit); the tool opens it once, and only after udev gave + // this account access. + crate::usb_node::wait_accessible(&location)?; if let Some(ecid) = &session.identity().ecid { orchard_cache::runlog::hide(ecid); } @@ -565,7 +571,7 @@ fn run_tool(executor: &Executor, session: &mut Session, from: Mode, name: step(&format!("{label} did not end within {seconds} s: ended by orchard")); let _ = child.kill(); let _ = child.wait(); - break Err(fail(format!("{name} did not finish"))); + break Err(crate::usb_node::explain(name, &log_path, fail(format!("{name} did not finish")))); } // From DFU mode, iOS on USB means the device restarted normally: // this start can't work any more, whatever palera1n still waits for. @@ -601,9 +607,10 @@ fn run_tool(executor: &Executor, session: &mut Session, from: Mode, name: } let status = status?; if !status.success() { - return Err(fail(last_error(&log_path).unwrap_or_else(|| format!("{name} failed ({status})")))); + let failed = fail(last_error(&log_path).unwrap_or_else(|| format!("{name} failed ({status})"))); + return Err(crate::usb_node::explain(name, &log_path, failed)); } - Ok(()) + Ok(log_path) } /// palera1n's last error line, without colors and timestamp: "palera1n: @@ -703,8 +710,9 @@ fn into_pongo(executor: &Executor, session: &mut Session, pongo_image: &st Tool::Checkra1n => run_checkra1n(executor, session, pongo_image, PALERA1N_SECONDS), Tool::Palera1n => run_palera1n(executor, session, &args, PALERA1N_SECONDS), }; + let name = if with == Tool::Checkra1n { "checkra1n" } else { "palera1n" }; let failed = match ran { - Ok(()) => { + Ok(log) => { let deadline = Instant::now() + Duration::from_secs(PONGO_SECONDS); loop { if now_in(session, Mode::Pongo)? { @@ -714,7 +722,9 @@ fn into_pongo(executor: &Executor, session: &mut Session, pongo_image: &st return Err(fail(format!("{RESTARTED} of starting Pongo"))); } if Instant::now() > deadline { - break fail("Pongo did not appear on USB"); + // The tool said it started Pongo: one refused open + // on the way is what went wrong. + break crate::usb_node::explain(name, &log, fail("Pongo did not appear on USB")); } std::thread::sleep(Duration::from_millis(250)); } @@ -857,7 +867,7 @@ pub fn boot_ipados_with(executor: &Executor, session: &mut Session, overla // palera1n goes on from its own Pongo start. into_pongo(executor, session, &ours, Tool::Palera1n)?; let second = vec![std::ffi::OsString::from("-l"), "-o".into(), overlay.as_os_str().to_owned(), "-k".into(), ours.into_os_string()]; - run_palera1n_from(executor, session, Mode::Pongo, &second, IPADOS_SECONDS) + run_palera1n_from(executor, session, Mode::Pongo, &second, IPADOS_SECONDS).map(|_| ()) } /// The launcher's loader, by the boot route: palera1n or checkra1n → Pongo → diff --git a/crates/runtime/src/lib.rs b/crates/runtime/src/lib.rs index d334871..974f19f 100644 --- a/crates/runtime/src/lib.rs +++ b/crates/runtime/src/lib.rs @@ -31,6 +31,7 @@ pub mod ready; pub mod records; pub mod recovery_mode; pub mod usb_access; +mod usb_node; pub mod helper_app; mod held; pub mod usbmux; diff --git a/crates/runtime/src/usb_node.rs b/crates/runtime/src/usb_node.rs new file mode 100644 index 0000000..d83bf02 --- /dev/null +++ b/crates/runtime/src/usb_node.rs @@ -0,0 +1,217 @@ +//! Linux: the device's USB node, as the exploit tools see it. Each new +//! stage (DFU after a replug, Pongo, the device back after checkm8) is a new +//! node, which appears a moment before udev applies Orchard's rule +//! (usb_access.rs) and gives this account access. orchard's own opens wait +//! for that (orchard_usb's `denied_a_while`); a tool orchard starts is +//! started only once the node opens, and a tool that was refused in that +//! moment anyway is named as such, with the fix, instead of what followed. +use orchard_cache::{Code, Error}; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +/// How long a new node may stay refused: udev takes milliseconds. +pub(crate) const ACCESS_WAIT: Duration = Duration::from_secs(5); + +/// What the account does about it: the rule, else the start as root. +pub(crate) const FIX: &str = "Install Orchard's USB rule with `orchard setup usb` and reconnect the device. If it is installed already, start orchard with sudo: the tool opened the device again before the rule applied."; + +/// The usbfs node of the device at sysfs `location` ("9-3"): +/// `/dev/bus/usb/009/086`. None when the device isn't there (any more). +fn node(location: &str, sysfs: &Path, dev: &Path) -> Option { + if location.is_empty() || location.contains('/') || location.starts_with("0x") { + return None; + } + let read = |name: &str| std::fs::read_to_string(sysfs.join(location).join(name)).ok()?.trim().parse::().ok(); + Some(dev.join(format!("{:03}", read("busnum")?)).join(format!("{:03}", read("devnum")?))) +} + +/// How the node opens for this account. +#[derive(Debug, PartialEq, Eq)] +enum Access { + Open, + Denied, + /// No node (yet): the device is between stages, or gone. + Absent, +} + +fn access(node: Option<&Path>) -> Access { + let Some(node) = node else { return Access::Absent }; + match std::fs::OpenOptions::new().read(true).write(true).open(node) { + Ok(_) => Access::Open, + Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => Access::Denied, + Err(_) => Access::Absent, + } +} + +/// Waits up to `wait` while the node at `location` is refused. Err only when +/// it was refused the whole time; a device that isn't there is the tool's +/// to find (or not). +fn wait_at(location: &str, sysfs: &Path, dev: &Path, wait: Duration) -> Result<(), Error> { + let until = Instant::now() + wait; + loop { + let path = node(location, sysfs, dev); + match access(path.as_deref()) { + Access::Denied if Instant::now() < until => std::thread::sleep(Duration::from_millis(100)), + Access::Denied => return Err(denied(&path.map(|p| p.display().to_string()).unwrap_or_else(|| location.to_owned()))), + Access::Open | Access::Absent => return Ok(()), + } + } +} + +/// Before a tool takes the device at `location`: waits the moment udev may +/// still need to give this account access. Linux only. +pub(crate) fn wait_accessible(location: &str) -> Result<(), Error> { + if !cfg!(target_os = "linux") { + return Ok(()); + } + wait_at(location, Path::new("/sys/bus/usb/devices"), Path::new("/dev/bus/usb"), ACCESS_WAIT) +} + +/// The node stayed refused. +fn denied(node: &str) -> Error { + Error::new(Code::Usb, format!("USB permission: this account may not open the device ({node}), and it got no access within {} s", ACCESS_WAIT.as_secs())) + .hint(FIX) +} + +/// What checkra1n and palera1n say when the device's node refused them +/// (libusb's EACCES). +const REFUSED: [&str; 3] = ["EACCES", "LIBUSB_ERROR_ACCESS", "insufficient permissions"]; + +/// What a tool says once it has the device again after a refused open: +/// checkra1n 0.1337.3 tries again by itself ("DFU mode device found", +/// "Checkmate!"), and the refusal was not what failed. +const RECOVERED: [&str; 3] = ["device found", "found device", "checkmate"]; + +/// Whether `tool`'s log says the device's node refused it, without the tool +/// getting the device again after that. +pub(crate) fn refused_in(log: &str) -> bool { + let Some(at) = REFUSED.iter().filter_map(|r| log.rfind(r)).max() else { return false }; + let after = log[at..].split_once('\n').map_or("", |(_, rest)| rest).to_ascii_lowercase(); + !RECOVERED.iter().any(|r| after.contains(r)) +} + +/// The failure of a start whose tool `name` was refused the device: +/// a USB permission timeout, with the fix, in place of what followed +/// (`then`: the tool timing out, Pongo not appearing, usbmuxd). +pub(crate) fn refused(name: &str, then: &Error) -> Error { + Error::new( + Code::Usb, + format!("USB permission: {name} was refused the device when it reconnected on USB, before the computer gave this account access to it, and timed out ({})", then.message), + ) + .hint(FIX) +} + +/// `failed` as the run's real failure: a USB permission timeout when the +/// tool's log at `log` shows it was refused the device. +pub(crate) fn explain(name: &str, log: &Path, failed: Error) -> Error { + let text = std::fs::read(log).map(|t| String::from_utf8_lossy(&t).into_owned()).unwrap_or_default(); + if cfg!(target_os = "linux") && refused_in(&text) && !failed.message.starts_with("USB permission") { + refused(name, &failed) + } else { + failed + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A sysfs and /dev of one device at 9-3, bus 9 device 86. + fn tree() -> (tempfile::TempDir, PathBuf, PathBuf, PathBuf) { + let dir = tempfile::tempdir().unwrap(); + let (sysfs, dev) = (dir.path().join("sys"), dir.path().join("dev")); + std::fs::create_dir_all(sysfs.join("9-3")).unwrap(); + std::fs::write(sysfs.join("9-3/busnum"), "9\n").unwrap(); + std::fs::write(sysfs.join("9-3/devnum"), "86\n").unwrap(); + std::fs::create_dir_all(dev.join("009")).unwrap(); + let node = dev.join("009/086"); + std::fs::write(&node, b"").unwrap(); + (dir, sysfs, dev, node) + } + + #[cfg(unix)] + fn mode(path: &Path, mode: u32) { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap(); + } + + #[test] + fn the_node_is_found_from_the_port() { + let (_dir, sysfs, dev, node) = tree(); + assert_eq!(node_at(&sysfs, &dev, "9-3"), Some(node)); + assert_eq!(node_at(&sysfs, &dev, "9-4"), None); + assert_eq!(node_at(&sysfs, &dev, "0x14100000"), None, "a macOS location"); + assert_eq!(node_at(&sysfs, &dev, "../9-3"), None); + } + + fn node_at(sysfs: &Path, dev: &Path, location: &str) -> Option { + node(location, sysfs, dev) + } + + #[cfg(unix)] + #[test] + fn a_tool_starts_once_udev_gave_access() { + // root opens everything: nothing to see there. + if unsafe { libc::geteuid() } == 0 { + return; + } + let (_dir, sysfs, dev, node) = tree(); + assert!(wait_at("9-3", &sysfs, &dev, Duration::ZERO).is_ok()); + // Refused, then opened by "udev" 300 ms later: waited for. + mode(&node, 0o400); + let later = node.clone(); + let udev = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(300)); + mode(&later, 0o600); + }); + let started = Instant::now(); + assert!(wait_at("9-3", &sysfs, &dev, Duration::from_secs(5)).is_ok()); + assert!(started.elapsed() >= Duration::from_millis(250)); + udev.join().unwrap(); + // Refused for good: a USB permission error with the fix. + mode(&node, 0o400); + let error = wait_at("9-3", &sysfs, &dev, Duration::from_millis(200)).unwrap_err(); + assert_eq!(error.code, Code::Usb); + assert!(error.message.starts_with("USB permission: this account may not open the device (")); + assert!(error.message.contains("009/086")); + assert_eq!(error.hint.as_deref(), Some(FIX)); + // Not there: the tool's to find. + assert!(wait_at("9-4", &sysfs, &dev, Duration::from_secs(5)).is_ok()); + } + + #[test] + fn a_tool_refused_the_device_is_named_with_the_fix() { + // orchard#416: checkra1n 0.12.4 right after the checkm8 trigger. + assert!(refused_in("[Error]: Couldn't open USB interface due to EACCES. Run as root maybe? (error code: -75)")); + assert!(refused_in("libusb: error [get_usbfs_fd] libusb couldn't open USB device /dev/bus/usb/009/086, errno=13 LIBUSB_ERROR_ACCESS")); + assert!(!refused_in(": Timed out in state 1, assuming we are back to square one with this device. (error code: -31)")); + // checkra1n 0.1337.3 opens it again by itself: not what failed. + assert!(!refused_in("Couldn't open USB interface due to EACCES. Run as root maybe?\nDFU mode device disconnected\nDFU mode device found\nCheckmate!\n")); + assert!(refused_in("Right before trigger\nCouldn't open USB interface due to EACCES. Run as root maybe?\nTimed out in state 1\n")); + let then = Error::new(Code::NotFound, "usbmuxd is not running (Connection refused (os error 111))"); + let error = refused("checkra1n", &then); + assert_eq!(error.code, Code::Usb); + assert!(error.message.starts_with("USB permission: checkra1n was refused the device")); + assert!(error.message.ends_with("timed out (usbmuxd is not running (Connection refused (os error 111)))")); + assert!(error.to_string().contains("orchard setup usb")); + } + + #[test] + fn only_a_refused_run_is_explained_as_a_permission_timeout() { + let dir = tempfile::tempdir().unwrap(); + let log = dir.path().join("palera1n.log"); + std::fs::write(&log, "Checkmate!\nCouldn't open USB interface due to EACCES. Run as root maybe?\nBooting PongoOS...\n").unwrap(); + let explained = explain("palera1n", &log, Error::new(Code::NotFound, "Pongo did not appear on USB")); + if cfg!(target_os = "linux") { + assert!(explained.message.starts_with("USB permission: palera1n was refused")); + assert!(explained.message.contains("(Pongo did not appear on USB)")); + // Once is enough. + let again = explain("palera1n", &log, explained.clone()); + assert_eq!(again.message, explained.message); + } else { + assert_eq!(explained.message, "Pongo did not appear on USB", "macOS has no udev"); + } + std::fs::write(&log, "Checkmate!\nBooting PongoOS...\n").unwrap(); + assert_eq!(explain("palera1n", &log, Error::new(Code::NotFound, "Pongo did not appear on USB")).message, "Pongo did not appear on USB"); + } +}