Skip to main content

windows_headless/
unattend.rs

1use quick_xml::escape::escape;
2use std::env::consts;
3
4/// Microsoft's public key token, identical on every inbox component.
5const PUBLIC_KEY_TOKEN: &str = "31bf3856ad364e35";
6
7/// Default guest username. Single source of truth: `VmConfig::default`,
8/// the CLI `--username` defaults, and the sidecar fallback all reference
9/// this const directly (clap accepts const paths in `default_value`).
10pub const DEFAULT_USERNAME: &str = "AdminUser";
11
12/// Default guest password. Its only job is passing Windows'
13/// password-complexity filter unattended — Setup rejects weak passwords
14/// and fails the install, so the default must contain upper, lower,
15/// digit, and special by construction. It is neither secure nor memorable
16/// on purpose: nobody types it (copy-paste once from the ready line),
17/// the VM sits behind slirp NAT with no LAN exposure, and serious users
18/// override it via `--password`. Same single-source rule as
19/// [`DEFAULT_USERNAME`].
20pub const DEFAULT_PASSWORD: &str = "P@ssw0rd123!";
21
22/// CPU architecture targeted by the answer file and QEMU binary.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum Architecture {
25    Amd64,
26    Arm64,
27}
28
29impl Architecture {
30    pub fn as_xml_str(&self) -> &'static str {
31        match self {
32            Architecture::Amd64 => "amd64",
33            Architecture::Arm64 => "arm64",
34        }
35    }
36
37    pub fn qemu_binary(&self) -> &'static str {
38        match self {
39            Architecture::Amd64 => "qemu-system-x86_64",
40            Architecture::Arm64 => "qemu-system-aarch64",
41        }
42    }
43
44    /// UEFI firmware template names for this guest arch: read-only CODE
45    /// candidates plus writable VARS candidates, resolved under
46    /// `<qemu-dir>/share/qemu` (first hit wins).
47    pub fn firmware_names(&self) -> (&[&str], &[&str]) {
48        match self {
49            Architecture::Amd64 => (
50                &[
51                    "edk2-x86_64-secure-code.fd",
52                    "edk2-x86_64-code.fd",
53                    "OVMF_CODE.fd",
54                ],
55                &["edk2-i386-vars.fd", "OVMF_VARS.fd"],
56            ),
57            Architecture::Arm64 => (&["edk2-aarch64-code.fd"], &["edk2-arm-vars.fd"]),
58        }
59    }
60
61    /// Win32-OpenSSH release zip for this guest arch
62    /// (`OpenSSH-Win64.zip` vs `OpenSSH-ARM64.zip`; both extract to a
63    /// same-named subdir holding `install-sshd.ps1`).
64    pub fn openssh_zip_name(&self) -> &'static str {
65        match self {
66            Architecture::Amd64 => "OpenSSH-Win64.zip",
67            Architecture::Arm64 => "OpenSSH-ARM64.zip",
68        }
69    }
70
71    /// Expected SHA-256 of [`Self::openssh_zip_name`] at
72    /// [`crate::pins::OPENSSH_RELEASE_TAG`]. Strict per-arch mapping — no
73    /// fallback, no caller-side `if`: the wrong hash for the wrong arch is
74    /// a guaranteed mismatch, which is exactly what we want.
75    pub fn openssh_sha256(&self) -> &'static str {
76        match self {
77            Architecture::Amd64 => crate::pins::OPENSSH_SHA256_WIN64,
78            Architecture::Arm64 => crate::pins::OPENSSH_SHA256_ARM64,
79        }
80    }
81
82    pub fn openssh_extract_dir(&self) -> &'static str {
83        match self {
84            Architecture::Amd64 => "OpenSSH-Win64",
85            Architecture::Arm64 => "OpenSSH-ARM64",
86        }
87    }
88
89    /// NetKVM driver dir inside virtio-win.iso (`NetKVM/w11/<this>`).
90    /// Matched case-insensitively, so case is cosmetic; doubles as the
91    /// staged output dir (`drivers/NetKVM/w11/<this>/`).
92    pub fn netkvm_iso_dir(&self) -> &'static str {
93        match self {
94            Architecture::Amd64 => "amd64",
95            Architecture::Arm64 => "arm64",
96        }
97    }
98}
99
100impl std::str::FromStr for Architecture {
101    type Err = anyhow::Error;
102    fn from_str(s: &str) -> Result<Self, Self::Err> {
103        match s.to_ascii_lowercase().as_str() {
104            "amd64" | "x86_64" => Ok(Architecture::Amd64),
105            "arm64" | "aarch64" => Ok(Architecture::Arm64),
106            other => Err(anyhow::anyhow!(
107                "unknown arch '{other}' (want amd64|x86_64|arm64|aarch64)"
108            )),
109        }
110    }
111}
112
113/// User intent for the answer file; rendering is pure `format!` + XML escaping.
114/// Single-USB design: the install stick is always drive C: in WinPE, so no
115/// drive letter is configurable.
116#[derive(Debug, Clone)]
117pub struct VmConfig {
118    pub username: String,
119    pub password: String,
120    pub locale: String,
121    pub timezone: String,
122    pub arch: Architecture,
123    /// Single `LogonCount 1` auto-logon; default false. No desktop session
124    /// is needed (sshd runs headless); callers opt in explicitly.
125    pub auto_logon: bool,
126}
127
128impl Default for VmConfig {
129    fn default() -> Self {
130        let (arch, _) = auto_detect_platform();
131        Self {
132            username: DEFAULT_USERNAME.to_string(),
133            password: DEFAULT_PASSWORD.to_string(),
134            locale: "en-US".to_string(),
135            timezone: "Pacific Standard Time".to_string(),
136            arch,
137            auto_logon: false,
138        }
139    }
140}
141
142/// `/dev/kvm` present *and* openable for read/write. OrbStack (Apple
143/// Virtualization Framework) and plain containers expose no KVM node at
144/// all; rootless boxes may expose one owned by `kvm:root` that this user
145/// cannot open. Either case must fall back to TCG instead of passing
146/// `-accel kvm` and dying with "Could not access KVM kernel module".
147pub fn kvm_available() -> bool {
148    std::fs::OpenOptions::new()
149        .read(true)
150        .write(true)
151        .open("/dev/kvm")
152        .is_ok()
153}
154
155/// Resolve the accelerator: `$WINDOWS_HEADLESS_ACCEL` wins when set to
156/// `kvm|hvf|tcg`, else per-OS default with a Linux KVM probe. On Linux
157/// without usable KVM (OrbStack, docker, WSL1, unprivileged chroot) this
158/// returns `tcg` — slow (expect 5-15x on install) but bootable. Run on the
159/// macOS host (hvf) or bare-metal Linux (kvm) for full speed.
160pub fn resolve_accel() -> &'static str {
161    if let Ok(v) = std::env::var("WINDOWS_HEADLESS_ACCEL") {
162        match v.to_ascii_lowercase().as_str() {
163            "kvm" => return "kvm",
164            "hvf" => return "hvf",
165            "tcg" => return "tcg",
166            other => {
167                tracing::warn!(
168                    "ignoring unknown $WINDOWS_HEADLESS_ACCEL='{other}' (want kvm|hvf|tcg)"
169                );
170            }
171        }
172    }
173    match consts::OS {
174        "macos" => "hvf",
175        "linux" => {
176            if kvm_available() {
177                "kvm"
178            } else {
179                tracing::warn!(
180                    "no usable /dev/kvm — falling back to tcg (very slow; run on the macOS host with hvf or bare-metal Linux with KVM for full speed; override with $WINDOWS_HEADLESS_ACCEL)"
181                );
182                "tcg"
183            }
184        }
185        _ => "tcg",
186    }
187}
188
189/// Detect host arch/accel. Unknown arch falls back to Amd64 with a warning
190/// (caller may override); WHPX is intentionally not a v1 target.
191pub fn auto_detect_platform() -> (Architecture, &'static str) {
192    let arch = match consts::ARCH {
193        "x86_64" => Architecture::Amd64,
194        "aarch64" => Architecture::Arm64,
195        other => {
196            tracing::warn!(
197                "unknown host arch '{other}', defaulting to amd64 (override via VmConfig)"
198            );
199            Architecture::Amd64
200        }
201    };
202    (arch, resolve_accel())
203}
204
205impl VmConfig {
206    pub fn generate_unattend_xml(&self) -> String {
207        let arch = self.arch.as_xml_str();
208        let user = escape(&self.username);
209        let pass = escape(&self.password);
210        let locale = escape(&self.locale);
211        let tz = escape(&self.timezone);
212
213        let auto_logon_xml = if self.auto_logon {
214            format!(
215                r#"
216      <AutoLogon>
217        <Password><Value>{pass}</Value><PlainText>true</PlainText></Password>
218        <Username>{user}</Username>
219        <Enabled>true</Enabled>
220        <LogonCount>1</LogonCount>
221      </AutoLogon>"#
222            )
223        } else {
224            String::new()
225        };
226
227        let tpl = include_str!("../templates/autounattend.xml");
228        tpl.replace("{arch}", arch)
229            .replace("{sshzip}", self.arch.openssh_zip_name())
230            .replace("{sshdir}", self.arch.openssh_extract_dir())
231            .replace("{pkt}", PUBLIC_KEY_TOKEN)
232            .replace("{locale}", &locale)
233            .replace("{user}", &user)
234            .replace("{pass}", &pass)
235            .replace("{tz}", &tz)
236            .replace("{auto_logon_xml}", &auto_logon_xml)
237    }
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    #[test]
245    fn hardened_markers_present_amd64() {
246        let xml = VmConfig {
247            arch: Architecture::Amd64,
248            ..VmConfig::default()
249        }
250        .generate_unattend_xml();
251        for marker in [
252            "<InstallTo>",
253            "<DiskID>0</DiskID>",
254            "<MetaData",
255            "Windows 11 Pro",
256            // Single-partition media: Setup finds install.swm via
257            // MetaData media search (proven). No InstallFrom Path —
258            // USB letters are topology-dependent (a stale D: Path
259            // failed live with 0x80070490 ELEMENT_NOT_FOUND).
260            "<ProductKey>",
261            "<Key></Key>",
262            "diskpart /s",
263            "BypassTPMCheck",
264            "BypassSecureBootCheck",
265            "BypassRAMCheck",
266            "BypassCPUCheck",
267            "BypassStorageCheck",
268            "DisablePrivacyExperience",
269            "BypassNRO",
270            "HideOEMRegistrationScreen",
271            "install-sshd.ps1",
272            "OpenSSH-Win64",
273            "OpenSSH-Win64.zip",
274            "New-NetFirewallRule",
275            // SSH must be reachable regardless of NLA's profile verdict
276            // (the profile wait is EventLog's gpsvc stall).
277            "-Profile Any",
278            // gpsvc repair must ship: missing GPSvcGroup blocks EventLog
279            // 300 s on the IUserProfile2 endpoint resolution (5 min boots).
280            "GPSvcGroup",
281            "AuthenticationCapabilities",
282            // Recovery off from the first specialize boot: a hard stop
283            // (Ctrl-C) must never surface "Diagnosing your PC" — the
284            // post-install SSH step only applies once Setup hits Ready.
285            "bootstatuspolicy IgnoreAllFailures",
286            "recoveryenabled No",
287            // Headless diet lives post-READY (one SSH call), not here:
288            // firewall off only (slirp NAT gates inbound; the firewall sat
289            // on port 22 ~27s after sshd bound — measured).
290            "netsh advfirewall set allprofiles state off",
291            "NetworkLocation",
292            "TimeZone",
293        ] {
294            assert!(xml.contains(marker), "missing {marker}");
295        }
296        assert!(xml.contains(r#"processorArchitecture="amd64""#));
297        assert!(!xml.contains("<DiskConfiguration>"));
298        // No powershell in windowsPE (absent from WinPE); specialize may use it.
299        let pe = xml
300            .split("<settings pass=\"windowsPE\">")
301            .nth(1)
302            .unwrap()
303            .split("</settings>")
304            .next()
305            .unwrap();
306        assert!(!pe.contains("powershell.exe"));
307        // Headless default: no auto-logon; callers opt in explicitly.
308        assert!(!xml.contains("<AutoLogon>"));
309    }
310
311    #[test]
312    fn run_synchronous_orders_are_consecutive_from_one() {
313        // A gap (orders starting at 2) fails Setup with 0x800700D
314        // ERROR_INVALID_DATA (observed live). NB: DiskConfiguration
315        // partitions also use <Order>; only RunSynchronous counts here.
316        // Both command passes are checked: specialize carries the gpsvc
317        // repair, the SSH firewall commands, the recovery policy, and
318        // firewall-off (orders 1..=14; pre-SSH trim is 15..=17, the rest
319        // of the service diet moved post-READY).
320        for arch in [Architecture::Amd64, Architecture::Arm64] {
321            let xml = VmConfig {
322                arch,
323                ..VmConfig::default()
324            }
325            .generate_unattend_xml();
326            for pass in ["windowsPE", "specialize"] {
327                let section = format!("<settings pass=\"{pass}\">");
328                let rs = xml
329                    .split(&section)
330                    .nth(1)
331                    .unwrap()
332                    .split("</settings>")
333                    .next()
334                    .unwrap()
335                    .split("<RunSynchronous>")
336                    .nth(1)
337                    .unwrap()
338                    .split("</RunSynchronous>")
339                    .next()
340                    .unwrap();
341                let orders: Vec<u32> = rs
342                    .split("<Order>")
343                    .skip(1)
344                    .map(|s| s.split("</Order>").next().unwrap().parse().unwrap())
345                    .collect();
346                assert_eq!(
347                    orders,
348                    (1..=orders.len() as u32).collect::<Vec<_>>(),
349                    "gap in {arch:?} pass {pass}: {orders:?}"
350                );
351            }
352        }
353    }
354
355    #[test]
356    fn run_synchronous_paths_stay_short() {
357        // Setup validates every <Path> with WCM: a long value comes back
358        // as WCM_E_INVALIDVALUE 0x80220005 "Value is invalid", which fails
359        // the WHOLE answer file (windeploy 0x1f -> the "computer restarted
360        // unexpectedly" loop). Live 2026-10-04: an 854-char PowerShell Path
361        // was rejected while every command up to 243 chars passed, so keep
362        // the proven bound with margin: nothing over 256.
363        for arch in [Architecture::Amd64, Architecture::Arm64] {
364            let xml = VmConfig {
365                arch,
366                ..VmConfig::default()
367            }
368            .generate_unattend_xml();
369            for pass in ["windowsPE", "specialize"] {
370                let section = format!("<settings pass=\"{pass}\">");
371                let rs = xml
372                    .split(&section)
373                    .nth(1)
374                    .unwrap()
375                    .split("</settings>")
376                    .next()
377                    .unwrap()
378                    .split("<RunSynchronous>")
379                    .nth(1)
380                    .unwrap()
381                    .split("</RunSynchronous>")
382                    .next()
383                    .unwrap();
384                let mut paths = rs
385                    .split("<Path>")
386                    .skip(1)
387                    .map(|s| s.split("</Path>").next().unwrap());
388                for path in &mut paths {
389                    assert!(
390                        path.len() <= 256,
391                        "{arch:?} pass {pass}: Path is {} chars (limit 256): {path}",
392                        path.len()
393                    );
394                }
395            }
396        }
397    }
398
399    #[test]
400    fn arm64_and_drive_and_autologon() {
401        // NVMe topology: no third-party storage drivers in the file;
402        // part.txt selects Disk 0, InstallTo targets Disk 0.
403        let cfg = VmConfig {
404            arch: Architecture::Arm64,
405            auto_logon: true,
406            ..VmConfig::default()
407        };
408        let xml = cfg.generate_unattend_xml();
409        assert!(xml.contains(r#"processorArchitecture="arm64""#));
410        assert!(xml.contains("<DiskID>0</DiskID>"));
411        assert!(!xml.contains("viostor"));
412        assert!(!xml.contains("offlineServicing"));
413        assert!(xml.contains("<AutoLogon>"));
414        // Arch-parameterized inputs: no placeholders leak, names match arch.
415        assert!(xml.contains("OpenSSH-ARM64.zip"));
416        assert!(xml.contains(r#"OpenSSH\OpenSSH-ARM64"#));
417        assert!(!xml.contains("{sshzip}"));
418        assert!(!xml.contains("{sshdir}"));
419        assert!(!xml.contains("Win64"));
420    }
421
422    #[test]
423    fn openssh_names_follow_arch() {
424        for (arch, zip, dir) in [
425            (Architecture::Amd64, "OpenSSH-Win64.zip", "OpenSSH-Win64"),
426            (Architecture::Arm64, "OpenSSH-ARM64.zip", "OpenSSH-ARM64"),
427        ] {
428            let xml = VmConfig {
429                arch,
430                ..VmConfig::default()
431            }
432            .generate_unattend_xml();
433            assert!(xml.contains(zip), "missing {zip} for {arch:?}");
434            assert!(xml.contains(dir), "missing {dir} for {arch:?}");
435        }
436    }
437
438    #[test]
439    fn openssh_hashes_are_arch_strict() {
440        // Strict per-arch pins: distinct, 64 lowercase hex each, matching
441        // the constants in pins.rs (bump rule: tag change updates both).
442        let win64 = Architecture::Amd64.openssh_sha256();
443        let arm64 = Architecture::Arm64.openssh_sha256();
444        assert_eq!(win64, crate::pins::OPENSSH_SHA256_WIN64);
445        assert_eq!(arm64, crate::pins::OPENSSH_SHA256_ARM64);
446        assert_ne!(win64, arm64);
447        for h in [win64, arm64] {
448            assert_eq!(h.len(), 64, "not 64 hex chars: {h}");
449            assert!(h.chars().all(|c| c.is_ascii_hexdigit()), "not hex: {h}");
450        }
451    }
452
453    #[test]
454    fn no_double_hyphen_in_comments() {
455        // `--` inside <!-- --> is illegal XML: expat/MSXML reject the whole
456        // file while quick-xml tolerates it (this exact defect shipped in an
457        // answer file that Setup reset on). Check comment bodies strictly.
458        let xml = VmConfig::default().generate_unattend_xml();
459        let mut reader = quick_xml::Reader::from_str(&xml);
460        let mut buf = Vec::new();
461        loop {
462            match reader.read_event_into(&mut buf) {
463                Ok(quick_xml::events::Event::Comment(e)) => {
464                    let s: &str = e.as_ref();
465                    assert!(!s.contains("--"), "illegal -- in comment: {s}");
466                }
467                Ok(quick_xml::events::Event::Eof) => break,
468                Ok(_) => {}
469                Err(e) => panic!("malformed XML: {e}"),
470            }
471            buf.clear();
472        }
473    }
474
475    #[test]
476    fn escaping_round_trips() {
477        let cfg = VmConfig {
478            username: "a<b".to_string(),
479            password: "P@ss<>&\"".to_string(),
480            ..VmConfig::default()
481        };
482        let xml = cfg.generate_unattend_xml();
483        assert!(xml.contains("a&lt;b"));
484        assert!(xml.contains("P@ss&lt;&gt;&amp;&quot;"));
485        // Well-formedness spot check via quick-xml event reader.
486        let mut reader = quick_xml::Reader::from_str(&xml);
487        let mut buf = Vec::new();
488        let mut count = 0;
489        loop {
490            match reader.read_event_into(&mut buf) {
491                Ok(quick_xml::events::Event::Eof) => break,
492                Ok(_) => {
493                    count += 1;
494                    buf.clear();
495                }
496                Err(e) => panic!("malformed XML: {e}"),
497            }
498        }
499        assert!(count > 50);
500    }
501}