1use quick_xml::escape::escape;
2use std::env::consts;
3
4const PUBLIC_KEY_TOKEN: &str = "31bf3856ad364e35";
6
7pub const DEFAULT_USERNAME: &str = "AdminUser";
11
12pub const DEFAULT_PASSWORD: &str = "P@ssw0rd123!";
21
22#[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 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 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 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 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#[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 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
142pub fn kvm_available() -> bool {
148 std::fs::OpenOptions::new()
149 .read(true)
150 .write(true)
151 .open("/dev/kvm")
152 .is_ok()
153}
154
155pub 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
189pub 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 "<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 "-Profile Any",
278 "GPSvcGroup",
281 "AuthenticationCapabilities",
282 "bootstatuspolicy IgnoreAllFailures",
286 "recoveryenabled No",
287 "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 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 assert!(!xml.contains("<AutoLogon>"));
309 }
310
311 #[test]
312 fn run_synchronous_orders_are_consecutive_from_one() {
313 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(§ion)
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 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(§ion)
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 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 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 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 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<b"));
484 assert!(xml.contains("P@ss<>&""));
485 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}