Skip to main content

windows_headless/
ssh.rs

1use anyhow::Result;
2use std::sync::Arc;
3use std::time::Duration;
4use tokio::io::{AsyncBufReadExt, BufReader};
5use tokio::net::TcpStream;
6use tokio::time::{sleep, timeout};
7
8use crate::timeouts;
9
10/// Poll `host:port` until a real SSH server answers. A bare TCP connect is
11/// NOT enough: QEMU's user-mode NAT completes the host-side handshake while
12/// the guest is still in UEFI/Setup, so `connect()` succeeds minutes before
13/// any `sshd` exists (false "ready" + hung `ssh` client). We require the
14/// `SSH-2.0-...` banner, which only a live sshd sends.
15///
16/// Default budget is caller-chosen; poll interval [`crate::timeouts::SSH_POLL_INTERVAL`].
17/// On timeout the caller should `screendump` before failing (see canary test).
18pub async fn wait_for_ssh(host: &str, port: u16, timeout_: Duration) -> Result<()> {
19    let deadline = tokio::time::Instant::now() + timeout_;
20    let mut attempt = 0u32;
21    loop {
22        attempt += 1;
23        match TcpStream::connect((host, port)).await {
24            Ok(stream) => {
25                let mut reader = BufReader::new(stream);
26                let mut banner = String::new();
27                // Slirp may accept then stall; bound the banner wait so a
28                // half-open forward degrades to another poll, not a hang.
29                // Cap by the remaining budget so short timeouts stay short.
30                let now = tokio::time::Instant::now();
31                let budget = deadline
32                    .saturating_duration_since(now)
33                    .min(timeouts::SSH_BANNER_READ_BUDGET);
34                match timeout(budget, reader.read_line(&mut banner)).await {
35                    Ok(Ok(_)) if banner.starts_with("SSH-") => {
36                        tracing::info!("SSH banner after {attempt} polls: {}", banner.trim());
37                        return Ok(());
38                    }
39                    other => {
40                        tracing::debug!("poll {attempt}: no SSH banner yet ({other:?})");
41                    }
42                }
43            }
44            Err(e) => {
45                tracing::debug!("SSH poll {attempt} refused: {e:#}");
46            }
47        }
48        let now = tokio::time::Instant::now();
49        if now >= deadline {
50            anyhow::bail!(
51                "timed out waiting for SSH on {host}:{port} after {attempt} polls — likely stuck on a GUI prompt"
52            );
53        }
54        // Sleep the poll interval, capped at the remaining budget so short
55        // timeouts (and tests) don't overshoot by a full interval. The
56        // value is deliberately short (see `timeouts::SSH_POLL_INTERVAL`):
57        // polling is cheap (one TCP SYN per cycle); latency is what the
58        // user feels.
59        sleep(timeouts::SSH_POLL_INTERVAL.min(deadline.saturating_duration_since(now))).await;
60    }
61}
62
63/// Guest readiness probe as one `cmd` line: four `reg.exe` reads with
64/// marker-delimited sections. `&& echo YES || echo NO` keeps
65/// key-existence checks locale-independent; value parsing keys on the
66/// (never localized) `REG_DWORD` token.
67///
68/// Every query sends its stderr to `nul`: a missing value/key is a *verdict*
69/// here (OOBE not started, no servicing reboot pending), not a failure —
70/// letting it through logged "ERROR: The system was unable to find the
71/// specified registry key or value." twice on every healthy probe, which
72/// read like a broken install.
73fn reg_probe_command() -> String {
74    [
75        "echo [SETUP]",
76        "reg query \"HKLM\\SYSTEM\\Setup\" /v SetupType 2>nul",
77        "echo [OOBE]",
78        "reg query \"HKLM\\SYSTEM\\Setup\" /v OOBEInProgress 2>nul",
79        "echo [CBS]",
80        "reg query \"HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Component Based Servicing\\RebootPending\" 2>nul && echo YES || echo NO",
81        "echo [WU]",
82        "reg query \"HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\RebootRequired\" 2>nul && echo YES || echo NO",
83        "echo [END]",
84    ]
85    .join(" & ")
86}
87
88/// Split reg-probe output into its marker-delimited sections. Only the
89/// exact markers this probe emits are boundaries — anything else brackety
90/// in `reg` output is data, never structure.
91const KNOWN_MARKERS: &[&str] = &["SETUP", "OOBE", "CBS", "WU", "END"];
92
93fn probe_sections(text: &str) -> Option<std::collections::HashMap<&str, Vec<&str>>> {
94    let mut sections = std::collections::HashMap::new();
95    let mut current: Option<&str> = None;
96    let mut seen_marker = false;
97    for line in text.lines() {
98        let t = line.trim();
99        if t.starts_with('[') && t.ends_with(']') {
100            let name = &t[1..t.len() - 1];
101            if let Some(marker) = KNOWN_MARKERS.iter().find(|m| **m == name) {
102                current = Some(*marker);
103                if *marker != "END" {
104                    seen_marker = true;
105                }
106                sections.entry(*marker).or_insert_with(Vec::new);
107                continue;
108            }
109        }
110        if let Some(c) = current {
111            sections.entry(c).or_insert_with(Vec::new).push(t);
112        }
113    }
114    if seen_marker { Some(sections) } else { None }
115}
116
117/// DWORD value from a `reg query /v` section: `None` when the value (or
118/// key) is absent — absent OOBE counts as done, absent SetupType as busy.
119fn probe_dword(section: &[&str]) -> Option<u32> {
120    section
121        .iter()
122        .find(|l| l.contains("REG_DWORD"))
123        .and_then(|l| l.split_whitespace().last())
124        .and_then(|hex| {
125            let clean = hex
126                .strip_prefix("0x")
127                .or_else(|| hex.strip_prefix("0X"))
128                .unwrap_or(hex);
129            u32::from_str_radix(clean, 16).ok()
130        })
131}
132
133/// Password-authenticated session (host key accepted blind — see
134/// [`ssh_exec`]). Shared by exec, probe, and interactive shell.
135struct AcceptAny;
136
137impl russh::client::Handler for AcceptAny {
138    type Error = anyhow::Error;
139    async fn check_server_key(
140        &mut self,
141        _key: &russh::keys::PublicKeyOrCertificate,
142    ) -> Result<bool, Self::Error> {
143        // Loopback NAT to our own guest: TOFU is pointless, and the
144        // host key changes on every reinstall. Never prompt.
145        Ok(true)
146    }
147}
148
149async fn authed_session(
150    host: &str,
151    port: u16,
152    user: &str,
153    pass: &str,
154) -> Result<russh::client::Handle<AcceptAny>> {
155    let config = Arc::new(russh::client::Config::default());
156    let mut session = russh::client::connect(config, (host, port), AcceptAny).await?;
157    session.authenticate_password(user, pass).await?;
158    Ok(session)
159}
160
161/// Run one command over SSH (password auth), returning stdout.
162/// Host key is accepted blind (loopback NAT to our own guest; the key
163/// changes on every reinstall, so TOFU is pointless).
164///
165/// Stderr is not echoed unconditionally: healthy guests produce plenty of
166/// it (the readiness probe reads registry keys that legitimately don't
167/// exist yet), and printing every line made normal runs look broken. It is
168/// reported loudly only in the case that used to bite — empty stdout, where
169/// a broken command would otherwise masquerade as empty output — and
170/// otherwise at `tracing::debug!` (`RUST_LOG=debug`). The caller decides
171/// what stdout means.
172///
173/// NB: never log `cmd` itself — it may carry a password.
174pub async fn ssh_exec(host: &str, port: u16, user: &str, pass: &str, cmd: &str) -> Result<String> {
175    let session = authed_session(host, port, user, pass).await?;
176    let mut ch = session.channel_open_session().await?;
177    ch.exec(true, cmd).await?;
178    // Bounded channel drain: PowerShell cold-start on a fresh boot can
179    // stall tens of seconds, and a hung channel would otherwise burn the
180    // caller's whole budget silently. Hard cap, then loud timeout.
181    let (out, err) = tokio::time::timeout(timeouts::SSH_EXEC_DRAIN, async {
182        let mut out = Vec::new();
183        let mut err = Vec::new();
184        while let Some(msg) = ch.wait().await {
185            match msg {
186                russh::ChannelMsg::Data { data } => out.extend_from_slice(&data),
187                russh::ChannelMsg::ExtendedData { data, .. } => err.extend_from_slice(&data),
188                russh::ChannelMsg::ExitStatus { .. } => break,
189                _ => {}
190            }
191        }
192        Ok::<_, anyhow::Error>((out, err))
193    })
194    .await
195    .map_err(|_| {
196        anyhow::anyhow!(
197            "exec timed out after {} s (PowerShell cold-start or hung channel)",
198            timeouts::SSH_EXEC_DRAIN.as_secs()
199        )
200    })??;
201    match loud_stderr_message(&out, &err) {
202        Some(msg) => eprintln!("{msg}"),
203        None if !err.is_empty() => {
204            tracing::debug!("guest stderr: {}", String::from_utf8_lossy(&err).trim())
205        }
206        None => {}
207    }
208    Ok(String::from_utf8_lossy(&out).into_owned())
209}
210
211/// The one stderr report worth printing at the default level: `Some` only
212/// when stderr changes how the result reads (empty stdout = a broken
213/// command that would otherwise look like an empty answer). Routine stderr
214/// alongside real stdout is `None` here and goes to `RUST_LOG=debug`.
215fn loud_stderr_message(out: &[u8], err: &[u8]) -> Option<String> {
216    let text = String::from_utf8_lossy(err);
217    let text = text.trim();
218    if text.is_empty() || !out.iter().all(|b| b.is_ascii_whitespace()) {
219        return None;
220    }
221    Some(format!("guest command produced no stdout — stderr: {text}"))
222}
223
224/// One `bcdedit /enum` line check: `key ... want` (whitespace varies).
225fn bcdedit_value_verified(out: &str, key: &str, want: &str) -> bool {
226    out.lines().any(|l| {
227        let l = l.trim().to_ascii_lowercase();
228        l.starts_with(key) && l.ends_with(&want.to_ascii_lowercase())
229    })
230}
231
232/// Headless service diet + NLA profile, applied once over SSH after the
233/// guest reports Ready — deliberately NOT a specialize step: each list
234/// used to be its own synchronous PowerShell cold start serializing into
235/// Setup. One invocation here costs a single cold start off the critical
236/// path. Best-effort (warn, never fail): Setup is done, this is hygiene.
237/// Defender real-time monitoring is tamper-locked headless — not attempted.
238pub async fn apply_headless_diet(host: &str, port: u16, user: &str, pass: &str) -> Result<()> {
239    const SERVICES: &str = "'Spooler','WSearch','SysMain','DiagTrack','WerSvc','BITS','DoSvc','wisvc','RetailDemo','MapsBroker','Fax','WbioSrvc','PhoneSvc','RemoteRegistry','lfsvc','XblAuthManager','XblGameSave','dmwappushservice'";
240    let cmd = format!(
241        "powershell -NoProfile -Command \"Get-NetConnectionProfile | Set-NetConnectionProfile -NetworkCategory Private; {SERVICES}|%{{Set-Service -Name $_ -StartupType Disabled -EA SilentlyContinue}}\""
242    );
243    ssh_exec(host, port, user, pass, &cmd).await?;
244    Ok(())
245}
246
247/// Enable or disable Windows Automatic Repair ("Diagnosing your PC") on
248/// the guest. Disabled = boots fail fast instead of parking at recovery;
249/// snapshots are the safety net, not WinRE. Toggles BOTH BCD switches:
250/// `recoveryenabled` gates WinRE invocation, while the "Diagnosing your
251/// PC" screen itself is the boot-status policy (`bootstatuspolicy`) —
252/// IgnoreAllFailures makes winload skip it after an unclean stop.
253/// Verified by reading the entry back (`bcdedit /enum`) — same
254/// trust-nothing rule as `set_auto_updates`.
255pub async fn set_recovery_enabled(
256    host: &str,
257    port: u16,
258    user: &str,
259    pass: &str,
260    enabled: bool,
261) -> Result<()> {
262    let val = if enabled { "Yes" } else { "No" };
263    let policy = if enabled {
264        "DisplayAllFailures"
265    } else {
266        "IgnoreAllFailures"
267    };
268    ssh_exec(
269        host,
270        port,
271        user,
272        pass,
273        &format!("bcdedit /set {{current}} recoveryenabled {val}"),
274    )
275    .await?;
276    ssh_exec(
277        host,
278        port,
279        user,
280        pass,
281        &format!("bcdedit /set {{current}} bootstatuspolicy {policy}"),
282    )
283    .await?;
284    let en = ssh_exec(host, port, user, pass, "bcdedit /enum {current}").await?;
285    if !bcdedit_value_verified(&en, "recoveryenabled", val) {
286        anyhow::bail!("recoveryenabled {val} unverified (bcdedit /enum): {en:?}");
287    }
288    if !bcdedit_value_verified(&en, "bootstatuspolicy", policy) {
289        anyhow::bail!("bootstatuspolicy {policy} unverified (bcdedit /enum): {en:?}");
290    }
291    eprintln!(
292        "recovery {val} (Automatic Repair {}, boot status policy {policy}, verified)",
293        if enabled { "kept" } else { "disabled" }
294    );
295    Ok(())
296}
297
298/// Enable or disable Windows automatic updates (wuauserv) on the guest.
299/// `false` stops the service and sets it to manual-start: no download,
300/// no install, no surprise reboots. Manual updates over SSH still work.
301/// Verifies by reading the config back (`sc qc`) — a silent `sc` failure
302/// must never report success. Best-effort per command (warns, never fails)
303/// — callers decide.
304pub async fn set_auto_updates(
305    host: &str,
306    port: u16,
307    user: &str,
308    pass: &str,
309    enabled: bool,
310) -> Result<()> {
311    if enabled {
312        ssh_exec(
313            host,
314            port,
315            user,
316            pass,
317            "sc config wuauserv start= auto & sc start wuauserv",
318        )
319        .await?;
320        let qc = ssh_exec(host, port, user, pass, "sc qc wuauserv").await?;
321        if !qc.contains("AUTO_START") {
322            anyhow::bail!("wuauserv enable unverified (sc qc): {qc:?}");
323        }
324        eprintln!("automatic updates enabled (wuauserv, verified)");
325    } else {
326        ssh_exec(
327            host,
328            port,
329            user,
330            pass,
331            "sc config wuauserv start= disabled & sc stop wuauserv",
332        )
333        .await?;
334        let qc = ssh_exec(host, port, user, pass, "sc qc wuauserv").await?;
335        if !qc.contains("DISABLED") {
336            anyhow::bail!("wuauserv disable unverified (sc qc): {qc:?}");
337        }
338        eprintln!("automatic updates disabled (wuauserv, verified)");
339    }
340    Ok(())
341}
342
343/// Rotate the guest password via `net user` over the existing SSH session,
344/// then verify the new credential with a fresh login. Returns `Ok(())`
345/// only after the new password authenticates — callers can treat success
346/// as proof the rotation landed.
347/// After success the old password is dead: only `new_pass` authenticates.
348/// Never logs either password (see [`ssh_exec`]).
349pub async fn change_guest_password(
350    host: &str,
351    port: u16,
352    user: &str,
353    old_pass: &str,
354    new_pass: &str,
355) -> Result<()> {
356    // Hard budgets throughout: a stalled handshake must surface as an
357    // error, never hang the caller (same lesson as the install wait loop).
358    tokio::time::timeout(
359        timeouts::SSH_PASSWORD_ROTATION_BUDGET,
360        ssh_exec(
361            host,
362            port,
363            user,
364            old_pass,
365            &format!("net user {user} \"{new_pass}\""),
366        ),
367    )
368    .await
369    .map_err(|_| anyhow::anyhow!("password change timed out"))??;
370    let verified = tokio::time::timeout(
371        timeouts::SSH_PASSWORD_ROTATION_BUDGET,
372        probe_setup_done(host, port, user, new_pass),
373    )
374    .await
375    .map_err(|_| anyhow::anyhow!("rotated-password login timed out"))??;
376    if !verified.is_ready() {
377        anyhow::bail!("rotated password rejected by guest");
378    }
379    Ok(())
380}
381
382/// Terminal type requested for interactive shells (`DEFAULT_PTY_TERM`).
383/// Single source so the next person isn't grepping line 174 for it.
384pub const DEFAULT_PTY_TERM: &str = "xterm";
385
386/// Interactive shell over SSH: pty + local stdio, no host `ssh` binary.
387/// Cross-platform raw mode via crossterm (restored on exit via the guard);
388/// Ctrl-C inside goes to the guest, Ctrl-D / `exit` ends the session.
389pub async fn interactive_shell(host: &str, port: u16, user: &str, pass: &str) -> Result<()> {
390    use tokio::io::{AsyncReadExt, AsyncWriteExt};
391    let session = authed_session(host, port, user, pass).await?;
392    let mut ch = session.channel_open_session().await?;
393    // xterm, not dumb: fullscreen apps (editors, pagers) query the term
394    // type and emit garbage or refuse without one. Bytes pass through
395    // untouched, so capabilities only grow.
396    // Real terminal size (fixed 80x24 wraps into trash on bigger windows —
397    // observed live); the loop below keeps it live.
398    let mut term_size = crossterm::terminal::size().unwrap_or((80, 24));
399    ch.request_pty(
400        false,
401        DEFAULT_PTY_TERM,
402        term_size.0.into(),
403        term_size.1.into(),
404        0,
405        0,
406        &[],
407    )
408    .await?;
409    ch.request_shell(false).await?;
410    // Raw mode guard: console mode restored on drop, even on panic.
411    struct RawGuard;
412    impl Drop for RawGuard {
413        fn drop(&mut self) {
414            let _ = crossterm::terminal::disable_raw_mode();
415        }
416    }
417    crossterm::terminal::enable_raw_mode().map_err(|e| {
418        anyhow::anyhow!("raw mode needs a terminal ({e:#}); refusing shell on piped stdio")
419    })?;
420    let _guard = RawGuard;
421    eprintln!("shell open — Ctrl-D or `exit` to leave (Ctrl-C always goes to the guest)");
422    let mut stdin = tokio::io::stdin();
423    let mut stdout = tokio::io::stdout();
424    let mut inbuf = vec![0u8; 1024];
425    // No escape hatch, deliberately: every byte — including Ctrl-C, no
426    // matter how often — belongs to the guest. An earlier triple-ETX
427    // escape misfired on normal mashing and dropped users out of the
428    // shell into the kill prompt (observed live). Leave via Ctrl-D/exit.
429    // Resize ticker doubles as the loop's heartbeat: 500 ms lag max on
430    // window changes, and no signal/event plumbing (crossterm events would
431    // fight the raw stdin reader for the same fd).
432    let mut resize_tick = tokio::time::interval(std::time::Duration::from_millis(500));
433    loop {
434        tokio::select! {
435            _ = resize_tick.tick() => {
436                let cur = crossterm::terminal::size().unwrap_or(term_size);
437                if cur != term_size {
438                    term_size = cur;
439                    let _ = ch.window_change(cur.0.into(), cur.1.into(), 0, 0).await;
440                }
441            }
442            r = stdin.read(&mut inbuf) => {
443                let n = r?;
444                if n == 0 {
445                    break; // Ctrl-D
446                }
447                ch.data(&inbuf[..n]).await?;
448            }
449            msg = ch.wait() => {
450                match msg {
451                    Some(russh::ChannelMsg::Data { data }) => {
452                        stdout.write_all(&data).await?;
453                        stdout.flush().await?;
454                    }
455                    Some(russh::ChannelMsg::ExtendedData { data, .. }) => {
456                        stdout.write_all(&data).await?;
457                        stdout.flush().await?;
458                    }
459                    Some(russh::ChannelMsg::ExitStatus { .. }) | None => break,
460                    _ => {}
461                }
462            }
463        }
464    }
465    // Drain strays typed during the handoff (arrow keys, extra Ctrl-C):
466    // cooked mode is back, but bytes already in flight would echo as
467    // trash (observed live as ^[[A^C) into the next prompt.
468    while crossterm::event::poll(std::time::Duration::from_millis(50)).unwrap_or(false) {
469        let _ = crossterm::event::read();
470    }
471    Ok(())
472}
473
474/// Prove a usable interactive shell, not just an exec channel: open a
475/// real pty shell (the exact path a user login takes — profile, prompt,
476/// the lot), send a marker, and read it back. An exec `whoami` passing
477/// while interactive logon hangs is a real failure mode (profile load,
478/// shell startup); only a prompt answering proves the prompt exists.
479/// Bounded by [`timeouts::READINESS_PROBE_BUDGET`]: answers in milliseconds
480/// on a landed guest, loud error otherwise — never a hang.
481pub async fn prove_interactive_shell(host: &str, port: u16, user: &str, pass: &str) -> Result<()> {
482    const MARKER: &str = "GOLDEN_SHELL_PROBE_READY";
483    let session = authed_session(host, port, user, pass).await?;
484    let mut ch = session.channel_open_session().await?;
485    ch.request_pty(false, DEFAULT_PTY_TERM, 80, 24, 0, 0, &[])
486        .await?;
487    ch.request_shell(false).await?;
488    ch.data(format!("echo {MARKER}\r\n").as_bytes()).await?;
489    tokio::time::timeout(timeouts::READINESS_PROBE_BUDGET, async {
490        let mut seen = Vec::new();
491        loop {
492            match ch.wait().await {
493                Some(russh::ChannelMsg::Data { data })
494                | Some(russh::ChannelMsg::ExtendedData { data, .. }) => {
495                    seen.extend_from_slice(&data);
496                    if seen.windows(MARKER.len()).any(|w| w == MARKER.as_bytes()) {
497                        return Ok::<_, anyhow::Error>(());
498                    }
499                }
500                Some(russh::ChannelMsg::ExitStatus { .. }) | None => {
501                    anyhow::bail!("shell closed before answering");
502                }
503                _ => {}
504            }
505        }
506    })
507    .await
508    .map_err(|_| {
509        anyhow::anyhow!(
510            "no shell prompt within {} s — interactive logon is not usable",
511            timeouts::READINESS_PROBE_BUDGET.as_secs()
512        )
513    })??;
514    Ok(())
515}
516
517/// What the guest itself reports about Setup: finished, or still working —
518/// with a human-readable description of what is pending. Callers narrate
519/// that description only when it changes, so a long install logs a handful
520/// of progress lines instead of one per probe.
521#[derive(Debug, Clone, PartialEq, Eq)]
522pub enum GuestProgress {
523    Ready,
524    /// e.g. `Windows Setup in progress (SetupType=2), OOBE pending`.
525    Busy(String),
526}
527
528impl GuestProgress {
529    pub fn is_ready(&self) -> bool {
530        matches!(self, GuestProgress::Ready)
531    }
532}
533
534/// The guest's answer could not be interpreted: a defect in our probe
535/// command or in parsing its output — NOT a guest reboot. Typed so waiters
536/// report it as what it is instead of narrating a reboot that never happened.
537#[derive(Debug)]
538pub struct ProbeOutputBroken(pub String);
539
540impl std::fmt::Display for ProbeOutputBroken {
541    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
542        f.write_str(&self.0)
543    }
544}
545
546impl std::error::Error for ProbeOutputBroken {}
547
548/// Guest readiness probe over a real SSH login (password auth). Asks the
549/// guest itself whether Setup is finished instead of inferring it from
550/// banner timing: four registry reads through `cmd`+`reg.exe` (millisecond
551/// startup, no PowerShell cold start per probe).
552///
553/// Returns [`GuestProgress::Ready`] = finished, [`GuestProgress::Busy`] =
554/// still working (with what is pending), `Err` = SSH/login/exec failure
555/// (caller treats as "not yet" — sshd may be mid-restart during reboots).
556/// No marker lines at all means the probe command itself broke (quoting,
557/// channel) — a [`ProbeOutputBroken`] error, never a silent `Busy` limp.
558pub async fn probe_setup_done(
559    host: &str,
560    port: u16,
561    user: &str,
562    pass: &str,
563) -> Result<GuestProgress> {
564    let text = ssh_exec(host, port, user, pass, &reg_probe_command()).await?;
565    let sections = probe_sections(&text).ok_or_else(|| {
566        anyhow::Error::new(ProbeOutputBroken(format!(
567            "unparseable probe output: {text:?}"
568        )))
569    })?;
570    progress_from_sections(&sections)
571}
572
573/// Verdict from already-parsed probe sections (pure — unit-tested; the SSH
574/// transport lives in [`probe_setup_done`]).
575fn progress_from_sections(
576    sections: &std::collections::HashMap<&str, Vec<&str>>,
577) -> Result<GuestProgress> {
578    let get = |name: &str| sections.get(name).map(Vec::as_slice).unwrap_or(&[]);
579    // Absent key/value: OOBE counts as done (not started), everything
580    // else as busy — matching the old PowerShell probe's verdicts.
581    let setup = probe_dword(get("SETUP"));
582    let oobe = probe_dword(get("OOBE")).unwrap_or(0);
583    let cbs = get("CBS").contains(&"YES");
584    let wu = get("WU").contains(&"YES");
585    // CBS/WU sections must resolve to an explicit verdict; a section with
586    // neither YES nor NO means the chain broke mid-command.
587    for (name, lines) in [("CBS", get("CBS")), ("WU", get("WU"))] {
588        if !lines.iter().any(|l| *l == "YES" || *l == "NO") {
589            return Err(anyhow::Error::new(ProbeOutputBroken(format!(
590                "probe section {name} has no verdict: {lines:?}"
591            ))));
592        }
593    }
594    if setup == Some(0) && oobe == 0 && !cbs && !wu {
595        return Ok(GuestProgress::Ready);
596    }
597    // The raw tuple is diagnostic detail, not a progress report.
598    tracing::debug!("guest probe busy: setup={setup:?} oobe={oobe} cbs={cbs} wu={wu}");
599    Ok(GuestProgress::Busy(pending_description(
600        setup, oobe, cbs, wu,
601    )))
602}
603
604/// Phrasing for a not-ready verdict: exactly the four values the probe
605/// read, never a guess about what Windows is doing beyond them.
606fn pending_description(setup: Option<u32>, oobe: u32, cbs: bool, wu: bool) -> String {
607    let mut parts: Vec<String> = Vec::new();
608    match setup {
609        Some(0) => {}
610        Some(v) => parts.push(format!("Windows Setup in progress (SetupType={v})")),
611        None => parts.push("Setup state unreadable".into()),
612    }
613    if oobe != 0 {
614        parts.push("OOBE pending".into());
615    }
616    if cbs {
617        parts.push("component-servicing reboot pending".into());
618    }
619    if wu {
620        parts.push("Windows Update reboot pending".into());
621    }
622    if parts.is_empty() {
623        parts.push("finishing up".into());
624    }
625    parts.join(", ")
626}
627
628#[cfg(test)]
629mod tests {
630    use super::*;
631    use crate::unattend::{DEFAULT_PASSWORD, DEFAULT_USERNAME};
632
633    #[tokio::test]
634    async fn fast_fail_on_closed_port() {
635        let err = wait_for_ssh("127.0.0.1", 1, Duration::from_millis(100))
636            .await
637            .unwrap_err();
638        assert!(format!("{err:#}").contains("timed out"));
639    }
640
641    #[tokio::test]
642    async fn succeeds_on_ssh_banner() {
643        use tokio::io::AsyncWriteExt;
644        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
645        let port = listener.local_addr().unwrap().port();
646        tokio::spawn(async move {
647            let (mut sock, _) = listener.accept().await.unwrap();
648            sock.write_all(b"SSH-2.0-OpenSSH_for_Windows_9.5\r\n")
649                .await
650                .unwrap();
651            // Hold open briefly so the reader sees EOF only after the banner.
652            sleep(Duration::from_secs(5)).await;
653        });
654        wait_for_ssh("127.0.0.1", port, Duration::from_secs(30))
655            .await
656            .unwrap();
657    }
658
659    #[tokio::test]
660    async fn silent_accept_is_not_ready() {
661        // Regression: QEMU slirp completes TCP while the guest has no sshd.
662        // A listener that accepts but never sends a banner must NOT resolve.
663        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
664        let port = listener.local_addr().unwrap().port();
665        tokio::spawn(async move {
666            loop {
667                let _ = listener.accept().await;
668            }
669        });
670        let err = wait_for_ssh("127.0.0.1", port, Duration::from_secs(1))
671            .await
672            .unwrap_err();
673        assert!(format!("{err:#}").contains("timed out"));
674    }
675
676    /// Live guest probe: needs the proven VM up (`install` finished,
677    /// SSH on 2232 with default creds). Run explicitly:
678    /// `cargo test -- --ignored live_probe_reports_state`.
679    #[tokio::test]
680    #[ignore]
681    async fn live_probe_reports_state() {
682        let state = probe_setup_done("127.0.0.1", 2232, DEFAULT_USERNAME, DEFAULT_PASSWORD)
683            .await
684            .unwrap();
685        let _ = state;
686        eprintln!("guest setup state retrieved");
687    }
688
689    /// Live exec check (read-only): same transport the password rotation
690    /// uses. `cargo test -- --ignored live_exec_whoami`.
691    #[tokio::test]
692    #[ignore]
693    async fn live_exec_whoami() {
694        let out = ssh_exec(
695            "127.0.0.1",
696            2232,
697            DEFAULT_USERNAME,
698            DEFAULT_PASSWORD,
699            "whoami",
700        )
701        .await
702        .unwrap();
703        assert!(out.contains("adminuser"), "unexpected whoami output");
704    }
705
706    #[test]
707    fn reg_probe_parses_sample_output() {
708        // Shaped like real `reg.exe` output: value sections carry
709        // REG_DWORD lines, key-existence sections resolve via YES/NO.
710        let text = "[SETUP]\n    SetupType    REG_DWORD    0x0\n[OOBE]\nERROR: The system was unable to find the specified registry key or value.\n[CBS]\nERROR: The system was unable to find the specified registry key or value.\nNO\n[WU]\nHKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\RebootRequired\nYES\n[END]\n";
711        let sections = probe_sections(text).unwrap();
712        let get = |name: &str| sections.get(name).map(Vec::as_slice).unwrap_or(&[]);
713        assert_eq!(probe_dword(get("SETUP")), Some(0));
714        assert_eq!(probe_dword(get("OOBE")), None);
715        assert!(get("CBS").contains(&"NO"));
716        assert!(get("WU").contains(&"YES"));
717        // Busy SetupType parses as decimal from hex.
718        let busy = "[SETUP]\n    SetupType    REG_DWORD    0x2\n[OOBE]\n    OOBEInProgress    REG_DWORD    0x1\n[END]\n";
719        let s2 = probe_sections(busy).unwrap();
720        assert_eq!(
721            probe_dword(s2.get("SETUP").map(Vec::as_slice).unwrap_or(&[])),
722            Some(2)
723        );
724        // No markers at all: broken channel, not a verdict.
725        assert!(probe_sections("garbage\nmore garbage\n").is_none());
726        // The command itself is one &-chained line with all four queries.
727        let cmd = reg_probe_command();
728        assert!(!cmd.contains('\n'));
729        for marker in ["[SETUP]", "[OOBE]", "[CBS]", "[WU]", "[END]"] {
730            assert!(cmd.contains(marker), "missing {marker}");
731        }
732    }
733
734    #[test]
735    fn probe_verdicts_read_as_progress_not_failure() {
736        // Ready: everything quiet.
737        let ready = "[SETUP]\n    SetupType    REG_DWORD    0x0\n[OOBE]\n    OOBEInProgress    REG_DWORD    0x0\n[CBS]\nNO\n[WU]\nNO\n[END]\n";
738        let sections = probe_sections(ready).unwrap();
739        assert!(progress_from_sections(&sections).unwrap().is_ready());
740
741        // Typical mid-install: one calm line naming exactly what was read.
742        let mid = "[SETUP]\n    SetupType    REG_DWORD    0x2\n[OOBE]\n    OOBEInProgress    REG_DWORD    0x1\n[CBS]\nNO\n[WU]\nNO\n[END]\n";
743        let sections = probe_sections(mid).unwrap();
744        assert_eq!(
745            progress_from_sections(&sections).unwrap(),
746            GuestProgress::Busy("Windows Setup in progress (SetupType=2), OOBE pending".into())
747        );
748
749        // A section with no verdict means OUR probe broke: typed so waiters
750        // report a probe problem instead of narrating a guest reboot.
751        let broken = "[SETUP]\n    SetupType    REG_DWORD    0x0\n[OOBE]\n[CBS]\n[WU]\nNO\n[END]\n";
752        let sections = probe_sections(broken).unwrap();
753        let err = progress_from_sections(&sections).unwrap_err();
754        assert!(
755            err.downcast_ref::<ProbeOutputBroken>().is_some(),
756            "want ProbeOutputBroken, got {err:#}"
757        );
758    }
759
760    #[test]
761    fn probe_command_suppresses_expected_stderr() {
762        // A missing value/key is a *verdict* here (OOBE not started, no
763        // servicing reboot), not an error: every query must redirect stderr
764        // or a healthy install logs "ERROR: unable to find ..." twice per
765        // probe and reads like a broken one.
766        let cmd = reg_probe_command();
767        let queries = cmd.matches("reg query").count();
768        assert_eq!(queries, 4, "expected four reg queries: {cmd}");
769        assert_eq!(cmd.matches("2>nul").count(), queries, "unsilenced: {cmd}");
770    }
771
772    #[test]
773    fn stderr_is_loud_only_when_it_changes_the_reading() {
774        let err = b"ERROR: the key does not exist\r\n";
775        // No stdout: without the loud report a broken command would masquer
776        // as an empty-but-successful answer (observed live).
777        assert!(loud_stderr_message(b"", err).is_some());
778        // Routine stderr beside real stdout: that is progress, not an error.
779        assert!(loud_stderr_message(b"HKEY_LOCAL_MACHINE\\...\r\n", err).is_none());
780        assert!(loud_stderr_message(b"ok", b"").is_none());
781    }
782
783    #[test]
784    fn bcdedit_enum_lines_verify_both_switches() {
785        // Shaped like real `bcdedit /enum {current}` output: variable
786        // whitespace, mixed value widths.
787        let enum_out = "Windows Boot Manager\n---------------------\nidentifier              {bootmgr}\n\nWindows Boot Loader\n-------------------\nidentifier              {current}\npath                    \\Windows\\System32\\winload.efi\ndescription             Windows 11\nrecoveryenabled         No\nbootstatuspolicy        IgnoreAllFailures\n";
788        assert!(bcdedit_value_verified(enum_out, "recoveryenabled", "No"));
789        assert!(bcdedit_value_verified(
790            enum_out,
791            "bootstatuspolicy",
792            "IgnoreAllFailures"
793        ));
794        // Wrong policy (default DisplayAllFailures) must NOT verify.
795        assert!(!bcdedit_value_verified(
796            enum_out,
797            "bootstatuspolicy",
798            "DisplayAllFailures"
799        ));
800        // Keys must anchor at line start: "nrecoveryenabled" fails.
801        assert!(!bcdedit_value_verified(
802            "nrecoveryenabled  No\n",
803            "recoveryenabled",
804            "No"
805        ));
806        // Missing key entirely: verify-never-guess.
807        assert!(!bcdedit_value_verified(
808            "garbage\n",
809            "recoveryenabled",
810            "No"
811        ));
812    }
813}