use anyhow::Result;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::net::TcpStream;
use tokio::time::{sleep, timeout};
use crate::timeouts;
pub async fn wait_for_ssh(host: &str, port: u16, timeout_: Duration) -> Result<()> {
let deadline = tokio::time::Instant::now() + timeout_;
let mut attempt = 0u32;
loop {
attempt += 1;
match TcpStream::connect((host, port)).await {
Ok(stream) => {
let mut reader = BufReader::new(stream);
let mut banner = String::new();
let now = tokio::time::Instant::now();
let budget = deadline
.saturating_duration_since(now)
.min(timeouts::SSH_BANNER_READ_BUDGET);
match timeout(budget, reader.read_line(&mut banner)).await {
Ok(Ok(_)) if banner.starts_with("SSH-") => {
tracing::info!("SSH banner after {attempt} polls: {}", banner.trim());
return Ok(());
}
other => {
tracing::debug!("poll {attempt}: no SSH banner yet ({other:?})");
}
}
}
Err(e) => {
tracing::debug!("SSH poll {attempt} refused: {e:#}");
}
}
let now = tokio::time::Instant::now();
if now >= deadline {
anyhow::bail!(
"timed out waiting for SSH on {host}:{port} after {attempt} polls — likely stuck on a GUI prompt"
);
}
sleep(timeouts::SSH_POLL_INTERVAL.min(deadline.saturating_duration_since(now))).await;
}
}
fn reg_probe_command() -> String {
[
"echo [SETUP]",
"reg query \"HKLM\\SYSTEM\\Setup\" /v SetupType 2>nul",
"echo [OOBE]",
"reg query \"HKLM\\SYSTEM\\Setup\" /v OOBEInProgress 2>nul",
"echo [CBS]",
"reg query \"HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Component Based Servicing\\RebootPending\" 2>nul && echo YES || echo NO",
"echo [WU]",
"reg query \"HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\RebootRequired\" 2>nul && echo YES || echo NO",
"echo [END]",
]
.join(" & ")
}
const KNOWN_MARKERS: &[&str] = &["SETUP", "OOBE", "CBS", "WU", "END"];
fn probe_sections(text: &str) -> Option<std::collections::HashMap<&str, Vec<&str>>> {
let mut sections = std::collections::HashMap::new();
let mut current: Option<&str> = None;
let mut seen_marker = false;
for line in text.lines() {
let t = line.trim();
if t.starts_with('[') && t.ends_with(']') {
let name = &t[1..t.len() - 1];
if let Some(marker) = KNOWN_MARKERS.iter().find(|m| **m == name) {
current = Some(*marker);
if *marker != "END" {
seen_marker = true;
}
sections.entry(*marker).or_insert_with(Vec::new);
continue;
}
}
if let Some(c) = current {
sections.entry(c).or_insert_with(Vec::new).push(t);
}
}
if seen_marker { Some(sections) } else { None }
}
fn probe_dword(section: &[&str]) -> Option<u32> {
section
.iter()
.find(|l| l.contains("REG_DWORD"))
.and_then(|l| l.split_whitespace().last())
.and_then(|hex| {
let clean = hex
.strip_prefix("0x")
.or_else(|| hex.strip_prefix("0X"))
.unwrap_or(hex);
u32::from_str_radix(clean, 16).ok()
})
}
struct AcceptAny;
impl russh::client::Handler for AcceptAny {
type Error = anyhow::Error;
async fn check_server_key(
&mut self,
_key: &russh::keys::PublicKeyOrCertificate,
) -> Result<bool, Self::Error> {
Ok(true)
}
}
async fn authed_session(
host: &str,
port: u16,
user: &str,
pass: &str,
) -> Result<russh::client::Handle<AcceptAny>> {
let config = Arc::new(russh::client::Config::default());
let mut session = russh::client::connect(config, (host, port), AcceptAny).await?;
session.authenticate_password(user, pass).await?;
Ok(session)
}
pub async fn ssh_exec(host: &str, port: u16, user: &str, pass: &str, cmd: &str) -> Result<String> {
let session = authed_session(host, port, user, pass).await?;
let mut ch = session.channel_open_session().await?;
ch.exec(true, cmd).await?;
let (out, err) = tokio::time::timeout(timeouts::SSH_EXEC_DRAIN, async {
let mut out = Vec::new();
let mut err = Vec::new();
while let Some(msg) = ch.wait().await {
match msg {
russh::ChannelMsg::Data { data } => out.extend_from_slice(&data),
russh::ChannelMsg::ExtendedData { data, .. } => err.extend_from_slice(&data),
russh::ChannelMsg::ExitStatus { .. } => break,
_ => {}
}
}
Ok::<_, anyhow::Error>((out, err))
})
.await
.map_err(|_| {
anyhow::anyhow!(
"exec timed out after {} s (PowerShell cold-start or hung channel)",
timeouts::SSH_EXEC_DRAIN.as_secs()
)
})??;
match loud_stderr_message(&out, &err) {
Some(msg) => eprintln!("{msg}"),
None if !err.is_empty() => {
tracing::debug!("guest stderr: {}", String::from_utf8_lossy(&err).trim())
}
None => {}
}
Ok(String::from_utf8_lossy(&out).into_owned())
}
fn loud_stderr_message(out: &[u8], err: &[u8]) -> Option<String> {
let text = String::from_utf8_lossy(err);
let text = text.trim();
if text.is_empty() || !out.iter().all(|b| b.is_ascii_whitespace()) {
return None;
}
Some(format!("guest command produced no stdout — stderr: {text}"))
}
fn bcdedit_value_verified(out: &str, key: &str, want: &str) -> bool {
out.lines().any(|l| {
let l = l.trim().to_ascii_lowercase();
l.starts_with(key) && l.ends_with(&want.to_ascii_lowercase())
})
}
pub async fn apply_headless_diet(host: &str, port: u16, user: &str, pass: &str) -> Result<()> {
const SERVICES: &str = "'Spooler','WSearch','SysMain','DiagTrack','WerSvc','BITS','DoSvc','wisvc','RetailDemo','MapsBroker','Fax','WbioSrvc','PhoneSvc','RemoteRegistry','lfsvc','XblAuthManager','XblGameSave','dmwappushservice'";
let cmd = format!(
"powershell -NoProfile -Command \"Get-NetConnectionProfile | Set-NetConnectionProfile -NetworkCategory Private; {SERVICES}|%{{Set-Service -Name $_ -StartupType Disabled -EA SilentlyContinue}}\""
);
ssh_exec(host, port, user, pass, &cmd).await?;
Ok(())
}
pub async fn set_recovery_enabled(
host: &str,
port: u16,
user: &str,
pass: &str,
enabled: bool,
) -> Result<()> {
let val = if enabled { "Yes" } else { "No" };
let policy = if enabled {
"DisplayAllFailures"
} else {
"IgnoreAllFailures"
};
ssh_exec(
host,
port,
user,
pass,
&format!("bcdedit /set {{current}} recoveryenabled {val}"),
)
.await?;
ssh_exec(
host,
port,
user,
pass,
&format!("bcdedit /set {{current}} bootstatuspolicy {policy}"),
)
.await?;
let en = ssh_exec(host, port, user, pass, "bcdedit /enum {current}").await?;
if !bcdedit_value_verified(&en, "recoveryenabled", val) {
anyhow::bail!("recoveryenabled {val} unverified (bcdedit /enum): {en:?}");
}
if !bcdedit_value_verified(&en, "bootstatuspolicy", policy) {
anyhow::bail!("bootstatuspolicy {policy} unverified (bcdedit /enum): {en:?}");
}
eprintln!(
"recovery {val} (Automatic Repair {}, boot status policy {policy}, verified)",
if enabled { "kept" } else { "disabled" }
);
Ok(())
}
pub async fn set_auto_updates(
host: &str,
port: u16,
user: &str,
pass: &str,
enabled: bool,
) -> Result<()> {
if enabled {
ssh_exec(
host,
port,
user,
pass,
"sc config wuauserv start= auto & sc start wuauserv",
)
.await?;
let qc = ssh_exec(host, port, user, pass, "sc qc wuauserv").await?;
if !qc.contains("AUTO_START") {
anyhow::bail!("wuauserv enable unverified (sc qc): {qc:?}");
}
eprintln!("automatic updates enabled (wuauserv, verified)");
} else {
ssh_exec(
host,
port,
user,
pass,
"sc config wuauserv start= disabled & sc stop wuauserv",
)
.await?;
let qc = ssh_exec(host, port, user, pass, "sc qc wuauserv").await?;
if !qc.contains("DISABLED") {
anyhow::bail!("wuauserv disable unverified (sc qc): {qc:?}");
}
eprintln!("automatic updates disabled (wuauserv, verified)");
}
Ok(())
}
pub async fn change_guest_password(
host: &str,
port: u16,
user: &str,
old_pass: &str,
new_pass: &str,
) -> Result<()> {
tokio::time::timeout(
timeouts::SSH_PASSWORD_ROTATION_BUDGET,
ssh_exec(
host,
port,
user,
old_pass,
&format!("net user {user} \"{new_pass}\""),
),
)
.await
.map_err(|_| anyhow::anyhow!("password change timed out"))??;
let verified = tokio::time::timeout(
timeouts::SSH_PASSWORD_ROTATION_BUDGET,
probe_setup_done(host, port, user, new_pass),
)
.await
.map_err(|_| anyhow::anyhow!("rotated-password login timed out"))??;
if !verified.is_ready() {
anyhow::bail!("rotated password rejected by guest");
}
Ok(())
}
pub const DEFAULT_PTY_TERM: &str = "xterm";
pub async fn interactive_shell(host: &str, port: u16, user: &str, pass: &str) -> Result<()> {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let session = authed_session(host, port, user, pass).await?;
let mut ch = session.channel_open_session().await?;
let mut term_size = crossterm::terminal::size().unwrap_or((80, 24));
ch.request_pty(
false,
DEFAULT_PTY_TERM,
term_size.0.into(),
term_size.1.into(),
0,
0,
&[],
)
.await?;
ch.request_shell(false).await?;
struct RawGuard;
impl Drop for RawGuard {
fn drop(&mut self) {
let _ = crossterm::terminal::disable_raw_mode();
}
}
crossterm::terminal::enable_raw_mode().map_err(|e| {
anyhow::anyhow!("raw mode needs a terminal ({e:#}); refusing shell on piped stdio")
})?;
let _guard = RawGuard;
eprintln!("shell open — Ctrl-D or `exit` to leave (Ctrl-C always goes to the guest)");
let mut stdin = tokio::io::stdin();
let mut stdout = tokio::io::stdout();
let mut inbuf = vec![0u8; 1024];
let mut resize_tick = tokio::time::interval(std::time::Duration::from_millis(500));
loop {
tokio::select! {
_ = resize_tick.tick() => {
let cur = crossterm::terminal::size().unwrap_or(term_size);
if cur != term_size {
term_size = cur;
let _ = ch.window_change(cur.0.into(), cur.1.into(), 0, 0).await;
}
}
r = stdin.read(&mut inbuf) => {
let n = r?;
if n == 0 {
break; }
ch.data(&inbuf[..n]).await?;
}
msg = ch.wait() => {
match msg {
Some(russh::ChannelMsg::Data { data }) => {
stdout.write_all(&data).await?;
stdout.flush().await?;
}
Some(russh::ChannelMsg::ExtendedData { data, .. }) => {
stdout.write_all(&data).await?;
stdout.flush().await?;
}
Some(russh::ChannelMsg::ExitStatus { .. }) | None => break,
_ => {}
}
}
}
}
while crossterm::event::poll(std::time::Duration::from_millis(50)).unwrap_or(false) {
let _ = crossterm::event::read();
}
Ok(())
}
pub async fn prove_interactive_shell(host: &str, port: u16, user: &str, pass: &str) -> Result<()> {
const MARKER: &str = "GOLDEN_SHELL_PROBE_READY";
let session = authed_session(host, port, user, pass).await?;
let mut ch = session.channel_open_session().await?;
ch.request_pty(false, DEFAULT_PTY_TERM, 80, 24, 0, 0, &[])
.await?;
ch.request_shell(false).await?;
ch.data(format!("echo {MARKER}\r\n").as_bytes()).await?;
tokio::time::timeout(timeouts::READINESS_PROBE_BUDGET, async {
let mut seen = Vec::new();
loop {
match ch.wait().await {
Some(russh::ChannelMsg::Data { data })
| Some(russh::ChannelMsg::ExtendedData { data, .. }) => {
seen.extend_from_slice(&data);
if seen.windows(MARKER.len()).any(|w| w == MARKER.as_bytes()) {
return Ok::<_, anyhow::Error>(());
}
}
Some(russh::ChannelMsg::ExitStatus { .. }) | None => {
anyhow::bail!("shell closed before answering");
}
_ => {}
}
}
})
.await
.map_err(|_| {
anyhow::anyhow!(
"no shell prompt within {} s — interactive logon is not usable",
timeouts::READINESS_PROBE_BUDGET.as_secs()
)
})??;
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GuestProgress {
Ready,
Busy(String),
}
impl GuestProgress {
pub fn is_ready(&self) -> bool {
matches!(self, GuestProgress::Ready)
}
}
#[derive(Debug)]
pub struct ProbeOutputBroken(pub String);
impl std::fmt::Display for ProbeOutputBroken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for ProbeOutputBroken {}
pub async fn probe_setup_done(
host: &str,
port: u16,
user: &str,
pass: &str,
) -> Result<GuestProgress> {
let text = ssh_exec(host, port, user, pass, ®_probe_command()).await?;
let sections = probe_sections(&text).ok_or_else(|| {
anyhow::Error::new(ProbeOutputBroken(format!(
"unparseable probe output: {text:?}"
)))
})?;
progress_from_sections(§ions)
}
fn progress_from_sections(
sections: &std::collections::HashMap<&str, Vec<&str>>,
) -> Result<GuestProgress> {
let get = |name: &str| sections.get(name).map(Vec::as_slice).unwrap_or(&[]);
let setup = probe_dword(get("SETUP"));
let oobe = probe_dword(get("OOBE")).unwrap_or(0);
let cbs = get("CBS").contains(&"YES");
let wu = get("WU").contains(&"YES");
for (name, lines) in [("CBS", get("CBS")), ("WU", get("WU"))] {
if !lines.iter().any(|l| *l == "YES" || *l == "NO") {
return Err(anyhow::Error::new(ProbeOutputBroken(format!(
"probe section {name} has no verdict: {lines:?}"
))));
}
}
if setup == Some(0) && oobe == 0 && !cbs && !wu {
return Ok(GuestProgress::Ready);
}
tracing::debug!("guest probe busy: setup={setup:?} oobe={oobe} cbs={cbs} wu={wu}");
Ok(GuestProgress::Busy(pending_description(
setup, oobe, cbs, wu,
)))
}
fn pending_description(setup: Option<u32>, oobe: u32, cbs: bool, wu: bool) -> String {
let mut parts: Vec<String> = Vec::new();
match setup {
Some(0) => {}
Some(v) => parts.push(format!("Windows Setup in progress (SetupType={v})")),
None => parts.push("Setup state unreadable".into()),
}
if oobe != 0 {
parts.push("OOBE pending".into());
}
if cbs {
parts.push("component-servicing reboot pending".into());
}
if wu {
parts.push("Windows Update reboot pending".into());
}
if parts.is_empty() {
parts.push("finishing up".into());
}
parts.join(", ")
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn fast_fail_on_closed_port() {
let err = wait_for_ssh("127.0.0.1", 1, Duration::from_millis(100))
.await
.unwrap_err();
assert!(format!("{err:#}").contains("timed out"));
}
#[tokio::test]
async fn succeeds_on_ssh_banner() {
use tokio::io::AsyncWriteExt;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
let (mut sock, _) = listener.accept().await.unwrap();
sock.write_all(b"SSH-2.0-OpenSSH_for_Windows_9.5\r\n")
.await
.unwrap();
sleep(Duration::from_secs(5)).await;
});
wait_for_ssh("127.0.0.1", port, Duration::from_secs(30))
.await
.unwrap();
}
#[tokio::test]
async fn silent_accept_is_not_ready() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
loop {
let _ = listener.accept().await;
}
});
let err = wait_for_ssh("127.0.0.1", port, Duration::from_secs(1))
.await
.unwrap_err();
assert!(format!("{err:#}").contains("timed out"));
}
#[tokio::test]
#[ignore]
async fn live_probe_reports_state() {
let state = probe_setup_done("127.0.0.1", 2232, "AdminUser", "P@ssw0rd123!")
.await
.unwrap();
eprintln!("guest setup state: {state:?}");
}
#[tokio::test]
#[ignore]
async fn live_exec_whoami() {
let out = ssh_exec("127.0.0.1", 2232, "AdminUser", "P@ssw0rd123!", "whoami")
.await
.unwrap();
assert!(out.contains("adminuser"), "unexpected whoami: {out:?}");
}
#[test]
fn reg_probe_parses_sample_output() {
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";
let sections = probe_sections(text).unwrap();
let get = |name: &str| sections.get(name).map(Vec::as_slice).unwrap_or(&[]);
assert_eq!(probe_dword(get("SETUP")), Some(0));
assert_eq!(probe_dword(get("OOBE")), None);
assert!(get("CBS").contains(&"NO"));
assert!(get("WU").contains(&"YES"));
let busy = "[SETUP]\n SetupType REG_DWORD 0x2\n[OOBE]\n OOBEInProgress REG_DWORD 0x1\n[END]\n";
let s2 = probe_sections(busy).unwrap();
assert_eq!(
probe_dword(s2.get("SETUP").map(Vec::as_slice).unwrap_or(&[])),
Some(2)
);
assert!(probe_sections("garbage\nmore garbage\n").is_none());
let cmd = reg_probe_command();
assert!(!cmd.contains('\n'));
for marker in ["[SETUP]", "[OOBE]", "[CBS]", "[WU]", "[END]"] {
assert!(cmd.contains(marker), "missing {marker}");
}
}
#[test]
fn probe_verdicts_read_as_progress_not_failure() {
let ready = "[SETUP]\n SetupType REG_DWORD 0x0\n[OOBE]\n OOBEInProgress REG_DWORD 0x0\n[CBS]\nNO\n[WU]\nNO\n[END]\n";
let sections = probe_sections(ready).unwrap();
assert!(progress_from_sections(§ions).unwrap().is_ready());
let mid = "[SETUP]\n SetupType REG_DWORD 0x2\n[OOBE]\n OOBEInProgress REG_DWORD 0x1\n[CBS]\nNO\n[WU]\nNO\n[END]\n";
let sections = probe_sections(mid).unwrap();
assert_eq!(
progress_from_sections(§ions).unwrap(),
GuestProgress::Busy("Windows Setup in progress (SetupType=2), OOBE pending".into())
);
let broken = "[SETUP]\n SetupType REG_DWORD 0x0\n[OOBE]\n[CBS]\n[WU]\nNO\n[END]\n";
let sections = probe_sections(broken).unwrap();
let err = progress_from_sections(§ions).unwrap_err();
assert!(
err.downcast_ref::<ProbeOutputBroken>().is_some(),
"want ProbeOutputBroken, got {err:#}"
);
}
#[test]
fn probe_command_suppresses_expected_stderr() {
let cmd = reg_probe_command();
let queries = cmd.matches("reg query").count();
assert_eq!(queries, 4, "expected four reg queries: {cmd}");
assert_eq!(cmd.matches("2>nul").count(), queries, "unsilenced: {cmd}");
}
#[test]
fn stderr_is_loud_only_when_it_changes_the_reading() {
let err = b"ERROR: the key does not exist\r\n";
assert!(loud_stderr_message(b"", err).is_some());
assert!(loud_stderr_message(b"HKEY_LOCAL_MACHINE\\...\r\n", err).is_none());
assert!(loud_stderr_message(b"ok", b"").is_none());
}
#[test]
fn bcdedit_enum_lines_verify_both_switches() {
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";
assert!(bcdedit_value_verified(enum_out, "recoveryenabled", "No"));
assert!(bcdedit_value_verified(
enum_out,
"bootstatuspolicy",
"IgnoreAllFailures"
));
assert!(!bcdedit_value_verified(
enum_out,
"bootstatuspolicy",
"DisplayAllFailures"
));
assert!(!bcdedit_value_verified(
"nrecoveryenabled No\n",
"recoveryenabled",
"No"
));
assert!(!bcdedit_value_verified(
"garbage\n",
"recoveryenabled",
"No"
));
}
}