windows-headless 0.3.0-alpha

Minimal-dependency headless Windows 11 VM provisioning and automation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
use quick_xml::escape::escape;
use std::env::consts;

/// Microsoft's public key token, identical on every inbox component.
const PUBLIC_KEY_TOKEN: &str = "31bf3856ad364e35";

/// Default guest username. Single source of truth: `VmConfig::default`,
/// the CLI `--username` defaults, and the sidecar fallback all reference
/// this const directly (clap accepts const paths in `default_value`).
pub const DEFAULT_USERNAME: &str = "AdminUser";

/// Default guest password. Its only job is passing Windows'
/// password-complexity filter unattended — Setup rejects weak passwords
/// and fails the install, so the default must contain upper, lower,
/// digit, and special by construction. It is neither secure nor memorable
/// on purpose: nobody types it (copy-paste once from the ready line),
/// the VM sits behind slirp NAT with no LAN exposure, and serious users
/// override it via `--password`. Same single-source rule as
/// [`DEFAULT_USERNAME`].
pub const DEFAULT_PASSWORD: &str = "P@ssw0rd123!";

/// CPU architecture targeted by the answer file and QEMU binary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Architecture {
    Amd64,
    Arm64,
}

impl Architecture {
    pub fn as_xml_str(&self) -> &'static str {
        match self {
            Architecture::Amd64 => "amd64",
            Architecture::Arm64 => "arm64",
        }
    }

    pub fn qemu_binary(&self) -> &'static str {
        match self {
            Architecture::Amd64 => "qemu-system-x86_64",
            Architecture::Arm64 => "qemu-system-aarch64",
        }
    }

    /// UEFI firmware template names for this guest arch: read-only CODE
    /// candidates plus writable VARS candidates, resolved under
    /// `<qemu-dir>/share/qemu` (first hit wins).
    pub fn firmware_names(&self) -> (&[&str], &[&str]) {
        match self {
            Architecture::Amd64 => (
                &[
                    "edk2-x86_64-secure-code.fd",
                    "edk2-x86_64-code.fd",
                    "OVMF_CODE.fd",
                ],
                &["edk2-i386-vars.fd", "OVMF_VARS.fd"],
            ),
            Architecture::Arm64 => (&["edk2-aarch64-code.fd"], &["edk2-arm-vars.fd"]),
        }
    }

    /// Win32-OpenSSH release zip for this guest arch
    /// (`OpenSSH-Win64.zip` vs `OpenSSH-ARM64.zip`; both extract to a
    /// same-named subdir holding `install-sshd.ps1`).
    pub fn openssh_zip_name(&self) -> &'static str {
        match self {
            Architecture::Amd64 => "OpenSSH-Win64.zip",
            Architecture::Arm64 => "OpenSSH-ARM64.zip",
        }
    }

    /// Expected SHA-256 of [`Self::openssh_zip_name`] at
    /// [`crate::pins::OPENSSH_RELEASE_TAG`]. Strict per-arch mapping — no
    /// fallback, no caller-side `if`: the wrong hash for the wrong arch is
    /// a guaranteed mismatch, which is exactly what we want.
    pub fn openssh_sha256(&self) -> &'static str {
        match self {
            Architecture::Amd64 => crate::pins::OPENSSH_SHA256_WIN64,
            Architecture::Arm64 => crate::pins::OPENSSH_SHA256_ARM64,
        }
    }

    pub fn openssh_extract_dir(&self) -> &'static str {
        match self {
            Architecture::Amd64 => "OpenSSH-Win64",
            Architecture::Arm64 => "OpenSSH-ARM64",
        }
    }

    /// NetKVM driver dir inside virtio-win.iso (`NetKVM/w11/<this>`).
    /// Matched case-insensitively, so case is cosmetic; doubles as the
    /// staged output dir (`drivers/NetKVM/w11/<this>/`).
    pub fn netkvm_iso_dir(&self) -> &'static str {
        match self {
            Architecture::Amd64 => "amd64",
            Architecture::Arm64 => "arm64",
        }
    }
}

impl std::str::FromStr for Architecture {
    type Err = anyhow::Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_ascii_lowercase().as_str() {
            "amd64" | "x86_64" => Ok(Architecture::Amd64),
            "arm64" | "aarch64" => Ok(Architecture::Arm64),
            other => Err(anyhow::anyhow!(
                "unknown arch '{other}' (want amd64|x86_64|arm64|aarch64)"
            )),
        }
    }
}

/// User intent for the answer file; rendering is pure `format!` + XML escaping.
/// Single-USB design: the install stick is always drive C: in WinPE, so no
/// drive letter is configurable.
#[derive(Debug, Clone)]
pub struct VmConfig {
    pub username: String,
    pub password: String,
    pub locale: String,
    pub timezone: String,
    pub arch: Architecture,
    /// Single `LogonCount 1` auto-logon; default false. No desktop session
    /// is needed (sshd runs headless); callers opt in explicitly.
    pub auto_logon: bool,
}

impl Default for VmConfig {
    fn default() -> Self {
        let (arch, _) = auto_detect_platform();
        Self {
            username: DEFAULT_USERNAME.to_string(),
            password: DEFAULT_PASSWORD.to_string(),
            locale: "en-US".to_string(),
            timezone: "Pacific Standard Time".to_string(),
            arch,
            auto_logon: false,
        }
    }
}

/// `/dev/kvm` present *and* openable for read/write. OrbStack (Apple
/// Virtualization Framework) and plain containers expose no KVM node at
/// all; rootless boxes may expose one owned by `kvm:root` that this user
/// cannot open. Either case must fall back to TCG instead of passing
/// `-accel kvm` and dying with "Could not access KVM kernel module".
pub fn kvm_available() -> bool {
    std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .open("/dev/kvm")
        .is_ok()
}

/// Resolve the accelerator: `$WINDOWS_HEADLESS_ACCEL` wins when set to
/// `kvm|hvf|tcg`, else per-OS default with a Linux KVM probe. On Linux
/// without usable KVM (OrbStack, docker, WSL1, unprivileged chroot) this
/// returns `tcg` — slow (expect 5-15x on install) but bootable. Run on the
/// macOS host (hvf) or bare-metal Linux (kvm) for full speed.
pub fn resolve_accel() -> &'static str {
    if let Ok(v) = std::env::var("WINDOWS_HEADLESS_ACCEL") {
        match v.to_ascii_lowercase().as_str() {
            "kvm" => return "kvm",
            "hvf" => return "hvf",
            "tcg" => return "tcg",
            other => {
                tracing::warn!(
                    "ignoring unknown $WINDOWS_HEADLESS_ACCEL='{other}' (want kvm|hvf|tcg)"
                );
            }
        }
    }
    match consts::OS {
        "macos" => "hvf",
        "linux" => {
            if kvm_available() {
                "kvm"
            } else {
                tracing::warn!(
                    "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)"
                );
                "tcg"
            }
        }
        _ => "tcg",
    }
}

/// Detect host arch/accel. Unknown arch falls back to Amd64 with a warning
/// (caller may override); WHPX is intentionally not a v1 target.
pub fn auto_detect_platform() -> (Architecture, &'static str) {
    let arch = match consts::ARCH {
        "x86_64" => Architecture::Amd64,
        "aarch64" => Architecture::Arm64,
        other => {
            tracing::warn!(
                "unknown host arch '{other}', defaulting to amd64 (override via VmConfig)"
            );
            Architecture::Amd64
        }
    };
    (arch, resolve_accel())
}

impl VmConfig {
    pub fn generate_unattend_xml(&self) -> String {
        let arch = self.arch.as_xml_str();
        let user = escape(&self.username);
        let pass = escape(&self.password);
        let locale = escape(&self.locale);
        let tz = escape(&self.timezone);

        let auto_logon_xml = if self.auto_logon {
            format!(
                r#"
      <AutoLogon>
        <Password><Value>{pass}</Value><PlainText>true</PlainText></Password>
        <Username>{user}</Username>
        <Enabled>true</Enabled>
        <LogonCount>1</LogonCount>
      </AutoLogon>"#
            )
        } else {
            String::new()
        };

        let tpl = include_str!("../templates/autounattend.xml");
        tpl.replace("{arch}", arch)
            .replace("{sshzip}", self.arch.openssh_zip_name())
            .replace("{sshdir}", self.arch.openssh_extract_dir())
            .replace("{pkt}", PUBLIC_KEY_TOKEN)
            .replace("{locale}", &locale)
            .replace("{user}", &user)
            .replace("{pass}", &pass)
            .replace("{tz}", &tz)
            .replace("{auto_logon_xml}", &auto_logon_xml)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn hardened_markers_present_amd64() {
        let xml = VmConfig {
            arch: Architecture::Amd64,
            ..VmConfig::default()
        }
        .generate_unattend_xml();
        for marker in [
            "<InstallTo>",
            "<DiskID>0</DiskID>",
            "<MetaData",
            "Windows 11 Pro",
            // Single-partition media: Setup finds install.swm via
            // MetaData media search (proven). No InstallFrom Path —
            // USB letters are topology-dependent (a stale D: Path
            // failed live with 0x80070490 ELEMENT_NOT_FOUND).
            "<ProductKey>",
            "<Key></Key>",
            "diskpart /s",
            "BypassTPMCheck",
            "BypassSecureBootCheck",
            "BypassRAMCheck",
            "BypassCPUCheck",
            "BypassStorageCheck",
            "DisablePrivacyExperience",
            "BypassNRO",
            "HideOEMRegistrationScreen",
            "install-sshd.ps1",
            "OpenSSH-Win64",
            "OpenSSH-Win64.zip",
            "New-NetFirewallRule",
            // SSH must be reachable regardless of NLA's profile verdict
            // (the profile wait is EventLog's gpsvc stall).
            "-Profile Any",
            // gpsvc repair must ship: missing GPSvcGroup blocks EventLog
            // 300 s on the IUserProfile2 endpoint resolution (5 min boots).
            "GPSvcGroup",
            "AuthenticationCapabilities",
            // Recovery off from the first specialize boot: a hard stop
            // (Ctrl-C) must never surface "Diagnosing your PC" — the
            // post-install SSH step only applies once Setup hits Ready.
            "bootstatuspolicy IgnoreAllFailures",
            "recoveryenabled No",
            // Headless diet lives post-READY (one SSH call), not here:
            // firewall off only (slirp NAT gates inbound; the firewall sat
            // on port 22 ~27s after sshd bound — measured).
            "netsh advfirewall set allprofiles state off",
            "NetworkLocation",
            "TimeZone",
        ] {
            assert!(xml.contains(marker), "missing {marker}");
        }
        assert!(xml.contains(r#"processorArchitecture="amd64""#));
        assert!(!xml.contains("<DiskConfiguration>"));
        // No powershell in windowsPE (absent from WinPE); specialize may use it.
        let pe = xml
            .split("<settings pass=\"windowsPE\">")
            .nth(1)
            .unwrap()
            .split("</settings>")
            .next()
            .unwrap();
        assert!(!pe.contains("powershell.exe"));
        // Headless default: no auto-logon; callers opt in explicitly.
        assert!(!xml.contains("<AutoLogon>"));
    }

    #[test]
    fn run_synchronous_orders_are_consecutive_from_one() {
        // A gap (orders starting at 2) fails Setup with 0x800700D
        // ERROR_INVALID_DATA (observed live). NB: DiskConfiguration
        // partitions also use <Order>; only RunSynchronous counts here.
        // Both command passes are checked: specialize carries the gpsvc
        // repair, the SSH firewall commands, the recovery policy, and
        // firewall-off (orders 1..=14; pre-SSH trim is 15..=17, the rest
        // of the service diet moved post-READY).
        for arch in [Architecture::Amd64, Architecture::Arm64] {
            let xml = VmConfig {
                arch,
                ..VmConfig::default()
            }
            .generate_unattend_xml();
            for pass in ["windowsPE", "specialize"] {
                let section = format!("<settings pass=\"{pass}\">");
                let rs = xml
                    .split(&section)
                    .nth(1)
                    .unwrap()
                    .split("</settings>")
                    .next()
                    .unwrap()
                    .split("<RunSynchronous>")
                    .nth(1)
                    .unwrap()
                    .split("</RunSynchronous>")
                    .next()
                    .unwrap();
                let orders: Vec<u32> = rs
                    .split("<Order>")
                    .skip(1)
                    .map(|s| s.split("</Order>").next().unwrap().parse().unwrap())
                    .collect();
                assert_eq!(
                    orders,
                    (1..=orders.len() as u32).collect::<Vec<_>>(),
                    "gap in {arch:?} pass {pass}: {orders:?}"
                );
            }
        }
    }

    #[test]
    fn run_synchronous_paths_stay_short() {
        // Setup validates every <Path> with WCM: a long value comes back
        // as WCM_E_INVALIDVALUE 0x80220005 "Value is invalid", which fails
        // the WHOLE answer file (windeploy 0x1f -> the "computer restarted
        // unexpectedly" loop). Live 2026-10-04: an 854-char PowerShell Path
        // was rejected while every command up to 243 chars passed, so keep
        // the proven bound with margin: nothing over 256.
        for arch in [Architecture::Amd64, Architecture::Arm64] {
            let xml = VmConfig {
                arch,
                ..VmConfig::default()
            }
            .generate_unattend_xml();
            for pass in ["windowsPE", "specialize"] {
                let section = format!("<settings pass=\"{pass}\">");
                let rs = xml
                    .split(&section)
                    .nth(1)
                    .unwrap()
                    .split("</settings>")
                    .next()
                    .unwrap()
                    .split("<RunSynchronous>")
                    .nth(1)
                    .unwrap()
                    .split("</RunSynchronous>")
                    .next()
                    .unwrap();
                let mut paths = rs
                    .split("<Path>")
                    .skip(1)
                    .map(|s| s.split("</Path>").next().unwrap());
                for path in &mut paths {
                    assert!(
                        path.len() <= 256,
                        "{arch:?} pass {pass}: Path is {} chars (limit 256): {path}",
                        path.len()
                    );
                }
            }
        }
    }

    #[test]
    fn arm64_and_drive_and_autologon() {
        // NVMe topology: no third-party storage drivers in the file;
        // part.txt selects Disk 0, InstallTo targets Disk 0.
        let cfg = VmConfig {
            arch: Architecture::Arm64,
            auto_logon: true,
            ..VmConfig::default()
        };
        let xml = cfg.generate_unattend_xml();
        assert!(xml.contains(r#"processorArchitecture="arm64""#));
        assert!(xml.contains("<DiskID>0</DiskID>"));
        assert!(!xml.contains("viostor"));
        assert!(!xml.contains("offlineServicing"));
        assert!(xml.contains("<AutoLogon>"));
        // Arch-parameterized inputs: no placeholders leak, names match arch.
        assert!(xml.contains("OpenSSH-ARM64.zip"));
        assert!(xml.contains(r#"OpenSSH\OpenSSH-ARM64"#));
        assert!(!xml.contains("{sshzip}"));
        assert!(!xml.contains("{sshdir}"));
        assert!(!xml.contains("Win64"));
    }

    #[test]
    fn openssh_names_follow_arch() {
        for (arch, zip, dir) in [
            (Architecture::Amd64, "OpenSSH-Win64.zip", "OpenSSH-Win64"),
            (Architecture::Arm64, "OpenSSH-ARM64.zip", "OpenSSH-ARM64"),
        ] {
            let xml = VmConfig {
                arch,
                ..VmConfig::default()
            }
            .generate_unattend_xml();
            assert!(xml.contains(zip), "missing {zip} for {arch:?}");
            assert!(xml.contains(dir), "missing {dir} for {arch:?}");
        }
    }

    #[test]
    fn openssh_hashes_are_arch_strict() {
        // Strict per-arch pins: distinct, 64 lowercase hex each, matching
        // the constants in pins.rs (bump rule: tag change updates both).
        let win64 = Architecture::Amd64.openssh_sha256();
        let arm64 = Architecture::Arm64.openssh_sha256();
        assert_eq!(win64, crate::pins::OPENSSH_SHA256_WIN64);
        assert_eq!(arm64, crate::pins::OPENSSH_SHA256_ARM64);
        assert_ne!(win64, arm64);
        for h in [win64, arm64] {
            assert_eq!(h.len(), 64, "not 64 hex chars: {h}");
            assert!(h.chars().all(|c| c.is_ascii_hexdigit()), "not hex: {h}");
        }
    }

    #[test]
    fn no_double_hyphen_in_comments() {
        // `--` inside <!-- --> is illegal XML: expat/MSXML reject the whole
        // file while quick-xml tolerates it (this exact defect shipped in an
        // answer file that Setup reset on). Check comment bodies strictly.
        let xml = VmConfig::default().generate_unattend_xml();
        let mut reader = quick_xml::Reader::from_str(&xml);
        let mut buf = Vec::new();
        loop {
            match reader.read_event_into(&mut buf) {
                Ok(quick_xml::events::Event::Comment(e)) => {
                    let s: &str = e.as_ref();
                    assert!(!s.contains("--"), "illegal -- in comment: {s}");
                }
                Ok(quick_xml::events::Event::Eof) => break,
                Ok(_) => {}
                Err(e) => panic!("malformed XML: {e}"),
            }
            buf.clear();
        }
    }

    #[test]
    fn escaping_round_trips() {
        let cfg = VmConfig {
            username: "a<b".to_string(),
            password: "P@ss<>&\"".to_string(),
            ..VmConfig::default()
        };
        let xml = cfg.generate_unattend_xml();
        assert!(xml.contains("a&lt;b"));
        assert!(xml.contains("P@ss&lt;&gt;&amp;&quot;"));
        // Well-formedness spot check via quick-xml event reader.
        let mut reader = quick_xml::Reader::from_str(&xml);
        let mut buf = Vec::new();
        let mut count = 0;
        loop {
            match reader.read_event_into(&mut buf) {
                Ok(quick_xml::events::Event::Eof) => break,
                Ok(_) => {
                    count += 1;
                    buf.clear();
                }
                Err(e) => panic!("malformed XML: {e}"),
            }
        }
        assert!(count > 50);
    }
}