diff --git a/.gitattributes b/.gitattributes index 5cb58f7..5c52bbb 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,4 @@ # Line endings: shell scripts must stay LF (bash in WSL/Linux), cmd scripts CRLF. *.sh text eol=lf *.cmd text eol=crlf +*.efi binary diff --git a/NOTICE b/NOTICE index ff423ec..fe6d9b3 100644 --- a/NOTICE +++ b/NOTICE @@ -7,3 +7,6 @@ It bundles iPXE (https://ipxe.org/), in mgmt/ipxe/ipxe-src/, which is licensed u the GNU General Public License, version 2 (with the iPXE UBDL exception). iPXE's source and license are kept in that directory; the compiled snponly.efi embedded in the binary is built from it. iPXE is not covered by the Apache License above. + +mgmt/ipxe/signed/ holds unmodified official iPXE release binaries (Secure Boot builds): snponly.efi, signed by the +iPXE Secure Boot CA (UBDL), and the iPXE shim (https://github.com/ipxe/shim, BSD-2-Clause) signed by Microsoft. diff --git a/README.md b/README.md index 25c4cd7..edd72f1 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,16 @@ Then open `http:///`: **Client machines:** UEFI, Secure Boot **off**, **PXE first** in the boot order (required for the reset-on-boot). +**Secure Boot (test):** tick **Secure Boot clients** on the Network page. Clients then get the official iPXE signed +by the iPXE project (`mgmt/ipxe/signed/`, via its Microsoft-signed shim) instead of broom's own build, and the Ubuntu +kernels boot through Ubuntu's Microsoft-signed shim (`apt install shim-signed` on the server). The Windows stage runs +the server's own kernel, which must be ≥ 6.x: shim rejects the 5.15 kernel ("Relocation section is invalid"), so on +Ubuntu 22.04 install `linux-generic-hwe-22.04`, reboot, then publish again. On the clients: enable +Secure Boot and the "Microsoft 3rd-party UEFI CA" (often off on Secured-core PCs). The menu footer (Host / IP / MAC) +then shows as lines under the images. Untick to go back to broom's own iPXE. TPM 2.0, VBS / Memory integrity (HVCI) +and IOMMU work on the clients too — broom-prep-win turns on VBS + HVCI in the golden (runs where the client has VT-x); +drivers in the golden must be HVCI-compatible (e.g. the VMware `e1000` NIC driver is blocked — use `e1000e`). + ## Adding a golden Build the golden in a VM, power it off, then upload the whole VM folder (only `.vmx` / `.vmdk` are @@ -63,6 +73,15 @@ sent, in parallel 8 MB chunks with retry) — or a single `.vmdk` / `.img` / `.z ``` The VM syspreps and powers off by itself → upload (OS = Windows). +## Versions, export + +- **Versions** (Images → Versions): snapshot / rollback the golden (deduplicated 4 MB chunks). **→ New image** turns a + version into a separate image on the list (only its manifest is copied — no extra disk space) and publishes it. +- **Export** (per image, or per version): builds a VMware VM (`.vmx` + `.vmdk`) to edit the golden again — + download both into one folder, open the `.vmx`, edit, run broom-prep again, upload. Needs free space on the server + ≈ the golden size. Windows: works for images uploaded with this version or later (publish trims the boot partitions + from the golden; they are now kept aside for the export). + ## Data & configuration Everything lives next to the binary: diff --git a/mgmt/Cargo.lock b/mgmt/Cargo.lock index 9c1b74f..c2ceab1 100644 --- a/mgmt/Cargo.lock +++ b/mgmt/Cargo.lock @@ -132,7 +132,7 @@ dependencies = [ [[package]] name = "bootrom-mgmt" -version = "0.4.0" +version = "0.5.0" dependencies = [ "argon2", "axum", diff --git a/mgmt/Cargo.toml b/mgmt/Cargo.toml index b74faae..45fed5c 100644 --- a/mgmt/Cargo.toml +++ b/mgmt/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "bootrom-mgmt" -version = "0.4.0" +version = "0.5.0" edition = "2024" description = "Management app for the diskless bootrom system (M5–M8 + preflight)" diff --git a/mgmt/ipxe/fetch-signed.sh b/mgmt/ipxe/fetch-signed.sh new file mode 100644 index 0000000..73ac46e --- /dev/null +++ b/mgmt/ipxe/fetch-signed.sh @@ -0,0 +1,21 @@ +#!/bin/bash +# fetch-signed.sh — official Secure Boot iPXE (signed by the iPXE project) → mgmt/ipxe/signed/, embedded in the +# mgmt binary next to our own build (boot.rs). Used when "Secure Boot clients" is on (Network page): +# snponly-shim.efi = the iPXE shim (signed by Microsoft UEFI CA 2011, trusts only the iPXE Secure Boot CA); +# it loads snponly.efi from the same TFTP directory by name +# snponly.efi = iPXE snponly signed by the iPXE Secure Boot CA +# Our own ipxe-src build can't be signed (Secure Boot exists to stop that), hence the official binaries. +# Pinned release + sha256: rerun with another VERSION/SHA256 to upgrade. UBDL allows redistributing them unmodified. +set -euo pipefail +VERSION=v2.0.0 +SHA256=01a526d4cc791fc30362259c609d6c506cc64a7bdff51b9a5eb788354e17eee1 +here=$(cd "$(dirname "$0")" && pwd) +tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT +curl -fsSL -o "$tmp/ipxeboot.tar.gz" "https://github.com/ipxe/ipxe/releases/download/$VERSION/ipxeboot.tar.gz" +echo "$SHA256 $tmp/ipxeboot.tar.gz" | sha256sum -c - +tar -xzf "$tmp/ipxeboot.tar.gz" -C "$tmp" ipxeboot/x86_64-sb/shimx64.efi ipxeboot/x86_64-sb/snponly.efi +mkdir -p "$here/signed" +cp "$tmp/ipxeboot/x86_64-sb/shimx64.efi" "$here/signed/snponly-shim.efi" +cp "$tmp/ipxeboot/x86_64-sb/snponly.efi" "$here/signed/snponly.efi" +( cd "$here/signed" && { echo "iPXE $VERSION ipxeboot.tar.gz x86_64-sb (sha256 $SHA256)"; sha256sum snponly-shim.efi snponly.efi; } > VERSION ) +cat "$here/signed/VERSION" diff --git a/mgmt/ipxe/signed/VERSION b/mgmt/ipxe/signed/VERSION new file mode 100644 index 0000000..792d7f6 --- /dev/null +++ b/mgmt/ipxe/signed/VERSION @@ -0,0 +1,3 @@ +iPXE v2.0.0 ipxeboot.tar.gz x86_64-sb (sha256 01a526d4cc791fc30362259c609d6c506cc64a7bdff51b9a5eb788354e17eee1) +83ad71c7d4f2cf328b75b653d09bf3bea5f29bee2e67ca058f37d83c07133885 snponly-shim.efi +b1e67c3e4a1e8708ddfd0079ad4505e3a02245acb55ee9a95437ab3c507be82a snponly.efi diff --git a/mgmt/ipxe/signed/snponly-shim.efi b/mgmt/ipxe/signed/snponly-shim.efi new file mode 100644 index 0000000..67a86d2 Binary files /dev/null and b/mgmt/ipxe/signed/snponly-shim.efi differ diff --git a/mgmt/ipxe/signed/snponly.efi b/mgmt/ipxe/signed/snponly.efi new file mode 100644 index 0000000..1da3923 Binary files /dev/null and b/mgmt/ipxe/signed/snponly.efi differ diff --git a/mgmt/src/boot.rs b/mgmt/src/boot.rs index 240ba2e..962d8b2 100644 --- a/mgmt/src/boot.rs +++ b/mgmt/src/boot.rs @@ -17,6 +17,10 @@ use crate::SharedState; /// iPXE built by mgmt/ipxe/build.sh from mgmt/ipxe/ipxe-src (upgrading the mgmt binary = upgrading iPXE too). pub(crate) const SNPONLY_EFI: &[u8] = include_bytes!("../ipxe/snponly.efi"); +/// Official Secure Boot iPXE (mgmt/ipxe/fetch-signed.sh), served under `sb/` when "Secure Boot clients" is on: +/// the iPXE shim (signed by Microsoft) loads `sb/snponly.efi` (signed by the iPXE CA) by name from the same directory. +pub(crate) const SB_SHIM_EFI: &[u8] = include_bytes!("../ipxe/signed/snponly-shim.efi"); +pub(crate) const SB_IPXE_EFI: &[u8] = include_bytes!("../ipxe/signed/snponly.efi"); type Q = Query>; @@ -45,7 +49,26 @@ pub async fn render(State(st): State, Query(q): Q) -> impl IntoResp // Clamp: menu_script does timeout_s * 1000 (would overflow / panic on a huge stored value). let timeout_s: u64 = st.db.get_config("boot_timeout", "10").parse().unwrap_or(10).min(3600); let images = menu_images(st.db.images().unwrap_or_default(), m.as_ref().and_then(|m| m.image_id)); - script(menu_script(&images, timeout_s, host.as_deref(), lic)) + script(menu_script(&images, timeout_s, host.as_deref(), lic, secure_boot(&st))) +} + +/// "Secure Boot clients" switch (Network page): clients run the official signed iPXE. +fn secure_boot(st: &SharedState) -> bool { + st.db.get_config("ipxe_signed", "0") == "1" +} + +/// Under Secure Boot, iPXE boots the Canonical-signed Ubuntu kernel (Windows stage or Linux golden) through Ubuntu's +/// Microsoft-signed shim (publish::refresh_shim → tftp/shim/). None when the switch is off or no shim was collected +/// yet (Publish once with shim-signed installed). +fn shim_line(st: &SharedState, img: &crate::db::Image) -> Option { + if !secure_boot(st) { + return None; + } + if !crate::tftp_dir().join("shim/shimx64.efi").is_file() { + warn!("image {}: no shim/shimx64.efi — install shim-signed and Publish again so Secure Boot clients can boot", img.name); + return None; + } + Some(format!("shim http://{}/tftp/shim/shimx64.efi\n", st.db.get_config("dhcp_server_ip", ""))) } /// Menu entries; the machine's own image (Devices page) is its default when it still exists, else the global one. @@ -69,7 +92,7 @@ pub async fn start(State(st): State, Query(q): Q) -> impl IntoRespo script(match (&img, boot) { (Some(i), Some(bs)) => { info!("client {who} started - mac {mac} - ip {ip} - hostname {h} - image {name} ({})", i.os); - format!("#!ipxe\n{bs}\n") + format!("#!ipxe\n{}{bs}\n", shim_line(&st, i).unwrap_or_default()) } _ => { warn!("client {who} chose image {name:?} - mac {mac} - ip {ip}: not published, back to the menu"); @@ -90,7 +113,9 @@ struct MenuImage { /// Layout (ipxe-src/src/hci/tui/menu_ui.c): title left + `menu-hint` + countdown right, horizontal line, /// list `[1] NAME`, horizontal line, `menu-footer` "left|center|right". White text on dark, selected black/white. /// ESC → shell (technical). -fn menu_script(images: &[MenuImage], timeout_s: u64, host: Option<&str>, lic: Option) -> String { +/// `sb` = clients run the official signed iPXE (Secure Boot): it has no menu-hint/menu-footer, so the same info is +/// shown as non-selectable `item --gap` lines above the images instead (the cursor still starts on an image). +fn menu_script(images: &[MenuImage], timeout_s: u64, host: Option<&str>, lic: Option, sb: bool) -> String { let mut items = String::new(); let mut targets = String::new(); let mut default = None; @@ -129,6 +154,15 @@ fn menu_script(images: &[MenuImage], timeout_s: u64, host: Option<&str>, lic: Op set_host.push_str(&format!("set broom-lic {g}\n")); } let host = if host.is_empty() { "not registered".into() } else { host }; + // One short line per field: the menu box is as wide as its longest line, so this fits any console width. + let header = if sb { + format!( + "item --gap Host : {host}\nitem --gap IP : ${{net0/ip}}\nitem --gap MAC : ${{net0/mac}}\n\ + item --gap\nitem --gap Arrows/number to select, Enter to boot\nitem --gap\n" + ) + } else { + String::new() + }; format!( "#!ipxe\n\ @@ -141,7 +175,7 @@ fn menu_script(images: &[MenuImage], timeout_s: u64, host: Option<&str>, lic: Op {set_host}\ :start\n\ menu Select operating system to boot\n\ - {items}\ + {header}{items}\ choose {choose} sel || goto shell\n\ goto ${{sel}}\n\n\ {targets}\ @@ -169,7 +203,7 @@ mod tests { #[test] fn menu_default_keys_ascii() { - let s = menu_script(&[img("win-11", true), img("ubuntu", false)], 5, Some("FPS-43 $x|"), Some(3)); + let s = menu_script(&[img("win-11", true), img("ubuntu", false)], 5, Some("FPS-43 $x|"), Some(3), false); assert!(s.starts_with("#!ipxe\n")); assert!(s.is_ascii(), "the iPXE font is ASCII only"); assert!(s.contains("item --key 1 img_win_11 [1] win-11\n")); @@ -211,11 +245,23 @@ mod tests { #[test] fn menu_no_default_no_timeout() { - let s = menu_script(&[img("a", false)], 10, None, None); + let s = menu_script(&[img("a", false)], 10, None, None, false); assert!(s.contains("choose sel || goto shell")); assert!(s.contains("Host: not registered|")); assert!(!s.contains("broom-host") && !s.contains("broom-lic")); - let s = menu_script(&[], 10, None, None); + let s = menu_script(&[], 10, None, None, false); assert!(s.contains("item --key s shell [S] iPXE shell (no image yet")); } + + /// Official signed iPXE (Secure Boot) has no menu-hint/footer → the same info as `item --gap` lines, after the + /// images (so number keys still map to images), still ASCII. + #[test] + fn menu_secure_boot_footer_as_gap_lines() { + let s = menu_script(&[img("win-11", true)], 5, Some("PC05"), None, true); + assert!(s.is_ascii()); + let item = s.find("item --key 1 img_win_11").unwrap(); + let head = s.find("item --gap Host : PC05\nitem --gap IP : ${net0/ip}\nitem --gap MAC : ${net0/mac}\n").unwrap(); + assert!(head < item && s.contains("item --gap Arrows/number to select, Enter to boot\n")); + assert!(!menu_script(&[img("a", false)], 5, None, None, false).contains("item --gap")); + } } diff --git a/mgmt/src/dhcp.rs b/mgmt/src/dhcp.rs index fe1c46b..7566cf1 100644 --- a/mgmt/src/dhcp.rs +++ b/mgmt/src/dhcp.rs @@ -127,6 +127,8 @@ pub struct Cfg { pub gateway: Option, pub dns: Vec, pub lease_s: u32, + /// "Secure Boot clients" (Network page): hand UEFI PXE the official signed iPXE (sb/…) instead of our own build. + pub sb: bool, } /// "12h" / "30m" / "1d" / "3600" → seconds (default 12h). @@ -159,6 +161,7 @@ impl Cfg { gateway: ip("dhcp_gateway"), dns: g("dhcp_dns", "").split([',', ' ']).filter_map(|s| s.trim().parse().ok()).collect(), lease_s: lease_secs(&g("dhcp_lease", "12h")), + sb: g("ipxe_signed", "0") == "1", }) } } @@ -259,7 +262,8 @@ fn kind(req: &Packet) -> Kind { fn boot_file(k: Kind, cfg: &Cfg) -> Option { match k { Kind::Ipxe => Some(format!("http://{}/boot.ipxe?mac=${{net0/mac}}&ip=${{net0/ip}}", cfg.server)), - Kind::PxeEfi => Some("snponly.efi".into()), + // Secure Boot: the iPXE shim (Microsoft-signed) then loads sb/snponly.efi (iPXE-signed) by name itself. + Kind::PxeEfi => Some(if cfg.sb { "sb/snponly-shim.efi" } else { "snponly.efi" }.into()), _ => None, } } @@ -578,6 +582,7 @@ mod tests { gateway: Some(Ipv4Addr::new(10, 0, 0, 1)), dns: vec![Ipv4Addr::new(1, 1, 1, 1)], lease_s: 3600, + sb: false, } } @@ -639,6 +644,16 @@ mod tests { assert!(matches!(out.lease, LeaseOp::Set { expires: 1060, source: "full", .. })); } + #[test] + fn secure_boot_switch_picks_signed_ipxe() { + let sb = Cfg { sb: true, ..cfg() }; + let (p, _) = handle(&req(DISCOVER, &[]), FROM, 67, &sb, &store()).reply.unwrap(); + assert_eq!(p.file, "sb/snponly-shim.efi", "UEFI PXE → Microsoft-signed iPXE shim"); + // iPXE itself (option 175) still gets the menu URL, whichever iPXE it is. + let (p, _) = handle(&req(DISCOVER, &[(175, &[1])]), FROM, 67, &sb, &store()).reply.unwrap(); + assert!(p.file.starts_with("http://10.0.0.12/boot.ipxe")); + } + #[test] fn ipxe_gets_menu_url() { let out = handle(&req(DISCOVER, &[(175, &[1])]), FROM, 67, &cfg(), &store()); diff --git a/mgmt/src/export.rs b/mgmt/src/export.rs new file mode 100644 index 0000000..c879021 --- /dev/null +++ b/mgmt/src/export.rs @@ -0,0 +1,255 @@ +// export.rs — an image (current golden or a saved version) → a VMware VM: .vmx + .vmdk, to edit the +// golden again (Windows: boots through the broom unattend, edit, broom-prep-win, upload). +// Windows publish trims image.img in place (winstage::build_golden: holes outside the Windows partition + a +// one-partition GPT) → keep_boot_regions first saves what the trim destroys (the partition table, ESP/MSR/Recovery +// or System Reserved) to images//orig/, and the export stitches it back around the Windows partition. +// Linux goldens are never modified → converted as they are. +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; + +use crate::winstage::run; +use crate::SharedState; + +const ESP: &str = "C12A7328-F81F-11D2-BA4B-00A0C93EC93B"; + +/// What the upload had outside the Windows partition: head.raw = [0, start), tail.raw = [start+size, total). +#[derive(Serialize, Deserialize, Debug, PartialEq)] +struct Orig { + start: u64, + size: u64, + total: u64, + firmware: String, +} + +fn orig_dir(name: &str) -> PathBuf { + crate::images_dir().join(name).join("orig") +} + +/// work/export//: .vmx, .vmdk, `version` (what was exported). +pub(crate) fn export_dir(name: &str) -> PathBuf { + crate::work_dir().join("export").join(name) +} + +/// sfdisk -J → (already trimmed by publish = GPT with exactly one partition, firmware the disk boots with). +fn layout(sfdisk_json: &str) -> Result<(bool, &'static str), String> { + let v: serde_json::Value = serde_json::from_str(sfdisk_json).map_err(|e| format!("partition table: {e}"))?; + let t = &v["partitiontable"]; + let parts = t["partitions"].as_array().map(|a| a.as_slice()).unwrap_or(&[]); + let gpt = t["label"] == "gpt"; + // ESP: GPT type GUID, or MBR type ef. + let esp = parts.iter().any(|p| p["type"].as_str().is_some_and(|ty| ty.eq_ignore_ascii_case(ESP) || ty == "ef")); + Ok((gpt && parts.len() == 1, if esp { "efi" } else { "bios" })) +} + +/// The single partition (start, size) in bytes of a trimmed golden, None if it has not exactly one. +fn single_part(sfdisk_json: &str) -> Option<(u64, u64)> { + let v: serde_json::Value = serde_json::from_str(sfdisk_json).ok()?; + let t = &v["partitiontable"]; + let ss = t["sectorsize"].as_u64().unwrap_or(512); + match t["partitions"].as_array()?.as_slice() { + [p] => Some((p["start"].as_u64()? * ss, p["size"].as_u64()? * ss)), + _ => None, + } +} + +/// Copy [off, off+len) of `src` into a new sparse file `dst` (all-zero MB blocks stay holes). +fn copy_region(src: &Path, off: u64, len: u64, dst: &Path) -> Result<(), String> { + use std::os::unix::fs::FileExt; + let f = std::fs::File::open(src).map_err(|e| format!("{}: {e}", src.display()))?; + let out = std::fs::File::create(dst).map_err(|e| format!("{}: {e}", dst.display()))?; + out.set_len(len).map_err(|e| e.to_string())?; + let mut buf = vec![0u8; 1 << 20]; + let mut done = 0; + while done < len { + let n = (len - done).min(buf.len() as u64) as usize; + f.read_exact_at(&mut buf[..n], off + done).map_err(|e| format!("read {}: {e}", src.display()))?; + if buf[..n].iter().any(|&b| b != 0) { + out.write_all_at(&buf[..n], done).map_err(|e| format!("write {}: {e}", dst.display()))?; + } + done += n as u64; + } + Ok(()) +} + +/// Called by winstage::build_golden right BEFORE it trims image.img: keep the partition table + every partition +/// but Windows (start, size). An already-trimmed image.img (published before) keeps the orig/ of its upload. +pub(crate) fn keep_boot_regions(raw: &Path, name: &str, (start, size): (u64, u64)) -> Result<(), String> { + let (trimmed, firmware) = layout(&run("sfdisk", &["-J", &raw.to_string_lossy()])?)?; + if trimmed { + return Ok(()); + } + let d = orig_dir(name); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).map_err(|e| format!("{}: {e}", d.display()))?; + let total = std::fs::metadata(raw).map_err(|e| e.to_string())?.len(); + copy_region(raw, 0, start, &d.join("head.raw"))?; + copy_region(raw, start + size, total.saturating_sub(start + size), &d.join("tail.raw"))?; + // orig.json last: its presence = the set is complete. + let o = Orig { start, size, total, firmware: firmware.into() }; + std::fs::write(d.join("orig.json"), serde_json::to_vec(&o).unwrap_or_default()).map_err(|e| e.to_string()) +} + +/// Free bytes on the filesystem holding `p`. +fn free_bytes(p: &Path) -> Option { + use std::os::unix::ffi::OsStrExt; + let c = std::ffi::CString::new(p.as_os_str().as_bytes()).ok()?; + // SAFETY: valid NUL-terminated path + a zeroed out-struct that statvfs fills. + let mut s: libc::statvfs = unsafe { std::mem::zeroed() }; + (unsafe { libc::statvfs(c.as_ptr(), &mut s) } == 0).then(|| s.f_bavail as u64 * s.f_frsize as u64) +} + +/// Build work/export// from the current golden (version None) or a saved version. Blocking (job). +pub fn run_export(st: &SharedState, name: &str, os: &str, version: Option<&str>, steps: &mut crate::publish::Steps) -> Result { + let out = export_dir(name); + let _ = std::fs::remove_dir_all(&out); + std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?; + let r = build(st, name, os, version, &out, steps); + let _ = std::fs::remove_file(out.join("src.raw")); + if r.is_err() { + let _ = std::fs::remove_dir_all(&out); + } + r +} + +fn build(st: &SharedState, name: &str, os: &str, version: Option<&str>, out: &Path, steps: &mut crate::publish::Steps) -> Result { + use std::os::unix::fs::MetadataExt; + let img = crate::images_dir().join(name).join("image.img"); + // The vmdk holds about the data of the golden (+ a restored version needs its own copy first). + let used = std::fs::metadata(&img).map_err(|_| format!("image {name} has no golden yet"))?.blocks() * 512; + let copies = if version.is_some() { 2 } else { 1 }; + let need = used * copies + (1 << 30); + if let Some(free) = free_bytes(out).filter(|&f| f < need) { + return Err(format!("export needs ~{:.0} GB free in {}, only {:.0} GB", need as f64 / 1e9, out.display(), free as f64 / 1e9)); + } + let src = match version { + None => img, + Some(v) => { + steps.go(&format!("restore {v}")); + let p = out.join("src.raw"); + let _g = st.versions_lock.lock().unwrap_or_else(|p| p.into_inner()); + crate::versions::rehydrate_to(name, v, &p)?; + p + } + }; + let s = src.to_string_lossy(); + let json = run("sfdisk", &["-J", &s])?; + let vmdk = out.join(format!("{name}.vmdk")); + let v = vmdk.to_string_lossy(); + steps.go("convert → vmdk"); + let firmware = if os == "windows" { + let d = orig_dir(name); + let o: Orig = std::fs::read(d.join("orig.json")) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .ok_or("this Windows image was published before export existed (its boot partitions are gone) — upload the VM again, then export")?; + let total = std::fs::metadata(&src).map_err(|e| e.to_string())?.len(); + if single_part(&json) != Some((o.start, o.size)) || total != o.total { + return Err("this version comes from another upload (different disk layout) — its boot partitions were not kept".into()); + } + // qemu-img concatenates its sources: head + the Windows partition of the golden + tail, in one pass. + fn q(p: &Path) -> String { + p.to_string_lossy().replace(',', ",,") // option-string escaping + } + let mut srcs = vec![ + format!("driver=raw,file.filename={}", q(&d.join("head.raw"))), + format!("driver=raw,offset={},size={},file.filename={}", o.start, o.size, q(&src)), + ]; + if o.total > o.start + o.size { + srcs.push(format!("driver=raw,file.filename={}", q(&d.join("tail.raw")))); + } + let mut args = vec!["convert", "-m", "16", "-O", "vmdk", "-o", "subformat=monolithicSparse", "--image-opts"]; + args.extend(srcs.iter().map(String::as_str)); + args.push(&*v); + run("qemu-img", &args)?; + o.firmware + } else { + run("qemu-img", &["convert", "-m", "16", "-f", "raw", "-O", "vmdk", "-o", "subformat=monolithicSparse", &s, &v])?; + layout(&json)?.1.to_string() + }; + std::fs::write(out.join(format!("{name}.vmx")), vmx(name, os, &firmware)).map_err(|e| e.to_string())?; + std::fs::write(out.join("version"), version.unwrap_or("current")).map_err(|e| e.to_string())?; + let size = std::fs::metadata(&vmdk).map(|m| m.len()).unwrap_or(0); + Ok(format!( + "exported {} ({:.1} GB, {firmware}) — download {name}.vmx + {name}.vmdk on the Images page into ONE folder, open the .vmx", + version.unwrap_or("current golden"), + size as f64 / 1e9 + )) +} + +/// Export on the Images page: {version, size, created} or null. +pub(crate) fn export_info(name: &str) -> serde_json::Value { + let d = export_dir(name); + let (Ok(m), Ok(ver)) = (std::fs::metadata(d.join(format!("{name}.vmdk"))), std::fs::read_to_string(d.join("version"))) else { + return serde_json::Value::Null; + }; + let created = m.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs()); + serde_json::json!({"version": ver, "size": m.len(), "created": created}) +} + +/// Plain VMware Workstation VM around the exported disk. SATA boots under BIOS and EFI alike (publish enabled +/// storahci as boot-start); guestOS windows9-64 = "Windows 10 and later" — windows11-64 insists on a TPM. +fn vmx(name: &str, os: &str, firmware: &str) -> String { + let guest = if os == "windows" { "windows9-64" } else { "ubuntu-64" }; + let fw = if firmware == "efi" { "firmware = \"efi\"\n" } else { "" }; + let bridges: String = (4..8) + .map(|i| format!("pciBridge{i}.present = \"TRUE\"\npciBridge{i}.virtualDev = \"pcieRootPort\"\npciBridge{i}.functions = \"8\"\n")) + .collect(); + format!( + ".encoding = \"UTF-8\"\nconfig.version = \"8\"\nvirtualHW.version = \"19\"\ndisplayName = \"{name}\"\nguestOS = \"{guest}\"\n{fw}\ + memsize = \"8192\"\nnumvcpus = \"4\"\ncpuid.coresPerSocket = \"2\"\npciBridge0.present = \"TRUE\"\n{bridges}\ + sata0.present = \"TRUE\"\nsata0:0.present = \"TRUE\"\nsata0:0.fileName = \"{name}.vmdk\"\n\ + ethernet0.present = \"TRUE\"\nethernet0.virtualDev = \"e1000e\"\nethernet0.connectionType = \"nat\"\nethernet0.addressType = \"generated\"\n\ + usb.present = \"TRUE\"\nehci.present = \"TRUE\"\nusb_xhci.present = \"TRUE\"\nsvga.present = \"TRUE\"\n" + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn layout_and_single_partition() { + let gpt = |parts: &str| format!(r#"{{"partitiontable":{{"label":"gpt","sectorsize":512,"partitions":[{parts}]}}}}"#); + let esp = r#"{"start":2048,"size":204800,"type":"C12A7328-F81F-11D2-BA4B-00A0C93EC93B"}"#; + let win = r#"{"start":239616,"size":1000000,"type":"EBD0A0A2-B9E5-4433-87C0-68B6B72699C7"}"#; + // Fresh UEFI upload: several partitions with an ESP → not trimmed, efi. + assert_eq!(layout(&gpt(&format!("{esp},{win}"))).unwrap(), (false, "efi")); + // After publish: one GPT partition → trimmed. + assert_eq!(layout(&gpt(win)).unwrap().0, true); + assert_eq!(single_part(&gpt(win)), Some((239616 * 512, 1000000 * 512))); + assert_eq!(single_part(&gpt(&format!("{esp},{win}"))), None); + // Legacy BIOS (MBR, System Reserved + Windows): not trimmed even with one partition, bios. + let dos = r#"{"partitiontable":{"label":"dos","partitions":[{"start":2048,"size":100,"type":"7"}]}}"#; + assert_eq!(layout(dos).unwrap(), (false, "bios")); + } + + #[test] + fn region_copy_keeps_bytes_and_holes() { + use std::os::unix::fs::{FileExt, MetadataExt}; + let d = std::env::temp_dir().join("broom_t_export"); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + let src = d.join("src"); + let f = std::fs::File::create(&src).unwrap(); + f.set_len(8 << 20).unwrap(); + f.write_all_at(b"head", 100).unwrap(); + f.write_all_at(b"tail", (7 << 20) + 5).unwrap(); + let dst = d.join("dst"); + copy_region(&src, 50, (8 << 20) - 50, &dst).unwrap(); + let got = std::fs::read(&dst).unwrap(); + assert_eq!(got.len(), (8 << 20) - 50); + assert_eq!(&got[50..54], b"head"); + assert_eq!(&got[(7 << 20) + 5 - 50..(7 << 20) + 9 - 50], b"tail"); + // 2 data MB written, the 6 zero MB between stay holes. + assert!(std::fs::metadata(&dst).unwrap().blocks() * 512 <= 3 << 20); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn vmx_firmware_and_disk() { + let w = vmx("win", "windows", "efi"); + assert!(w.contains("firmware = \"efi\"") && w.contains("sata0:0.fileName = \"win.vmdk\"") && w.contains("windows9-64")); + let l = vmx("ubnt", "linux", "bios"); + assert!(!l.contains("firmware") && l.contains("ubuntu-64") && l.contains("ethernet0.virtualDev = \"e1000e\"")); + } +} diff --git a/mgmt/src/images.rs b/mgmt/src/images.rs index d55b3dc..426f52c 100644 --- a/mgmt/src/images.rs +++ b/mgmt/src/images.rs @@ -32,6 +32,9 @@ pub fn routes() -> Router { .route("/api/images/snapshots", get(snapshots)) .route("/api/images/rollback", post(rollback)) .route("/api/images/version-delete", post(version_delete)) + .route("/api/images/export", post(export)) + .route("/api/images/from-version", post(from_version)) + .route("/api/images/export-file", get(export_file)) } pub(crate) type ApiError = (StatusCode, String); @@ -54,6 +57,7 @@ async fn list(State(st): State) -> Result, Json(b): Json) -> Ok(Json(serde_json::json!({"ok": true, "async": true}))) } +#[derive(Deserialize)] +struct FromVersionBody { + id: i64, + version: String, + name: String, +} + +/// A saved version → a NEW image on the list (same OS + cache mode): its manifest becomes the new image's v1 (chunks +/// shared, nothing copied), restored to its image.img, then published. Background job on the new image. +async fn from_version(State(st): State, Json(b): Json) -> Result, ApiError> { + let src = st.db.image(b.id).map_err(ise)?.ok_or((StatusCode::NOT_FOUND, format!("image {} not found", b.id)))?; + if !valid_name(&b.name) { + return Err((StatusCode::BAD_REQUEST, "name may only contain letters/digits/_/-".into())); + } + let id = st + .db + .add_image(&NewImageRow { name: &b.name, os: &src.os, boot_script: None, cache_mode: &src.cache_mode }) + .map_err(|e| (StatusCode::BAD_REQUEST, e))?; + std::fs::create_dir_all(crate::images_dir().join(&b.name)).map_err(|e| ise(e.to_string()))?; + tracing::info!("image {} created from {} {}", b.name, src.name, b.version); + let version = b.version; + spawn_job(&st, b.name, "from-version", move |st, name, steps| { + steps.go(&format!("restore {} {version}", src.name)); + { + let _g = st.versions_lock.lock().unwrap_or_else(|p| p.into_inner()); + crate::versions::clone_to(&src.name, &version, name, &format!("from {} {version}", src.name))?; + crate::versions::rehydrate(name, "v1")?; + } + // Windows: the boot partitions kept at upload go along (Export needs them). + let orig = crate::images_dir().join(&src.name).join("orig"); + if orig.exists() { + let dst = crate::images_dir().join(name).join("orig"); + crate::winstage::run("cp", &["-r", "--sparse=always", &orig.to_string_lossy(), &dst.to_string_lossy()])?; + } + st.db.set_active_version(id, Some("v1"))?; + crate::publish::run_publish(st, name, steps) + })?; + Ok(Json(serde_json::json!({"ok": true, "async": true, "id": id}))) +} + +#[derive(Deserialize)] +struct ExportBody { + id: i64, + /// None = the current golden (image.img). + version: Option, +} + +/// Export an image (or one of its versions) as a VMware VM → work/export// (export.rs). Background job. +async fn export(State(st): State, Json(b): Json) -> Result, ApiError> { + let img = st.db.image(b.id).map_err(ise)?.ok_or((StatusCode::NOT_FOUND, format!("image {} not found", b.id)))?; + spawn_job(&st, img.name, "export", move |st, name, steps| crate::export::run_export(st, name, &img.os, b.version.as_deref(), steps))?; + Ok(Json(serde_json::json!({"ok": true, "async": true}))) +} + +/// GET /api/images/export-file?id=&f=vmx|vmdk — the exported files; Range supported (a 30 GB download can resume). +async fn export_file(State(st): State, Query(q): Query>, req: axum::extract::Request) -> Result { + let id: i64 = q.get("id").and_then(|s| s.parse().ok()).ok_or((StatusCode::BAD_REQUEST, "missing ?id=".to_string()))?; + let f = q.get("f").map(String::as_str).filter(|f| matches!(*f, "vmx" | "vmdk")).ok_or((StatusCode::BAD_REQUEST, "f must be vmx or vmdk".to_string()))?; + let name = name_of(&st, id)?; + let file = format!("{name}.{f}"); // name is [A-Za-z0-9_-] (valid_name) → safe in the path + header + let p = crate::export::export_dir(&name).join(&file); + if !p.exists() { + return Err((StatusCode::NOT_FOUND, "no export yet — press Export first".into())); + } + let mut res = tower_http::services::ServeFile::new(p).try_call(req).await.map_err(|e| ise(e.to_string()))?.map(Body::new); + if let Ok(v) = header::HeaderValue::from_str(&format!("attachment; filename=\"{file}\"")) { + res.headers_mut().insert(header::CONTENT_DISPOSITION, v); + } + Ok(res) +} + /// Versions of an image, newest first. GET /api/images/snapshots?id= async fn snapshots(State(st): State, Query(q): Query>) -> Result, ApiError> { let id: i64 = q.get("id").and_then(|s| s.parse().ok()).ok_or((StatusCode::BAD_REQUEST, "missing ?id=".to_string()))?; let img = st.db.image(id).map_err(ise)?.ok_or((StatusCode::NOT_FOUND, format!("image {id} not found")))?; let active = img.active_version.clone(); - let versions = tokio::task::spawn_blocking(move || crate::versions::list(&img.name, img.active_version.as_deref())) + let versions = tokio::task::spawn_blocking(move || crate::versions::list_vs_current(&img.name, img.active_version.as_deref())) .await .map_err(|e| ise(e.to_string()))?; Ok(Json(serde_json::json!({"active": active, "versions": versions}))) diff --git a/mgmt/src/machines.rs b/mgmt/src/machines.rs index e4baa97..c511a21 100644 --- a/mgmt/src/machines.rs +++ b/mgmt/src/machines.rs @@ -16,6 +16,7 @@ pub fn routes() -> Router { Router::new() .route("/api/machines", get(list).post(add)) .route("/api/machines/assign", post(assign)) + .route("/api/config", get(get_config)) .route("/api/config/timeout", post(set_timeout)) .route("/api/config/zram-reserve", post(set_zram_reserve)) .route("/api/dhcp", get(get_dhcp).post(set_dhcp)) @@ -357,6 +358,14 @@ async fn assign( Ok(ok()) } +/// System page values (same defaults as their readers: boot.rs, publish.rs). +async fn get_config(State(st): State) -> Json { + Json(serde_json::json!({ + "boot_timeout": st.db.get_config("boot_timeout", "10").parse::().unwrap_or(10), + "zram_reserve_mb": st.db.get_config("zram_reserve_mb", "2048").parse::().unwrap_or(2048), + })) +} + #[derive(Deserialize)] struct Timeout { seconds: u64, @@ -402,6 +411,7 @@ async fn get_dhcp(State(st): State) -> Json { "gateway": g("dhcp_gateway", ""), "dns": g("dhcp_dns", ""), "lease": g("dhcp_lease", "12h"), + "ipxe_signed": g("ipxe_signed", "0") == "1", })) } @@ -417,6 +427,8 @@ struct DhcpBody { gateway: Option, dns: Option, lease: Option, + /// "Secure Boot clients": "1" = official signed iPXE for UEFI PXE, "0" = our own build. + ipxe_signed: Option, } /// Validate one DHCP field. IPv4 fields must parse; a stored server IP / gateway / DNS flows into scripts + boot @@ -430,6 +442,7 @@ fn dhcp_field_ok(key: &str, v: &str) -> Result<(), String> { "dhcp_server_ip" | "dhcp_subnet" | "dhcp_netmask" | "dhcp_range_start" | "dhcp_range_end" => ipv4(v), "dhcp_gateway" | "dhcp_dns" => v.is_empty() || v.split(',').all(|p| ipv4(p.trim())), "dhcp_lease" => v.parse::().is_ok() || matches!(v.chars().last(), Some('h' | 'm' | 's')), + "ipxe_signed" => v == "0" || v == "1", _ => true, }; if ok { Ok(()) } else { Err(format!("{}: invalid value {v:?}", key.trim_start_matches("dhcp_"))) } @@ -452,6 +465,7 @@ async fn set_dhcp( ("dhcp_gateway", &b.gateway), ("dhcp_dns", &b.dns), ("dhcp_lease", &b.lease), + ("ipxe_signed", &b.ipxe_signed), ]; for (k, v) in &fields { if let Some(val) = v { diff --git a/mgmt/src/main.rs b/mgmt/src/main.rs index 28aed2b..0229015 100644 --- a/mgmt/src/main.rs +++ b/mgmt/src/main.rs @@ -6,6 +6,7 @@ mod db; mod devices; mod dhcp; mod drivers; +mod export; mod images; mod iscsi; mod linuxfs; @@ -249,6 +250,8 @@ async fn main() { Ok(s) => info!("{s}"), Err(e) => error!("DHCP/TFTP not started: {e} (fix it on the Network page → Apply)"), } + // Ubuntu shim for Secure Boot clients (official iPXE) → tftp/shim/, so the switch works without a Publish. + publish::refresh_shim(); // configfs targets + zram are lost on server reboot → re-export / rebuild (background, zram is slow). let st = state.clone(); tokio::task::spawn_blocking(move || publish::restore_targets(&st)); diff --git a/mgmt/src/overlay.rs b/mgmt/src/overlay.rs index 6e08e59..ce140a1 100644 --- a/mgmt/src/overlay.rs +++ b/mgmt/src/overlay.rs @@ -397,7 +397,8 @@ mod tests { #[test] fn hook_syntax() { for s in [super::BROOM_ISCSI, super::CACHE_SCRIPT, super::PREP_SCRIPT] { - let ok = std::process::Command::new("sh").args(["-n", "-c", s]).status().unwrap(); + // Wrapped in a never-called function: parsed only, even by a shell that ignores -n (busybox 1.30). + let ok = std::process::Command::new("sh").args(["-n", "-c", &format!("broom_syntax_check(){{\n{s}\n}}")]).status().unwrap(); assert!(ok.success()); } } diff --git a/mgmt/src/publish.rs b/mgmt/src/publish.rs index 9165b30..f66ad50 100644 --- a/mgmt/src/publish.rs +++ b/mgmt/src/publish.rs @@ -366,7 +366,8 @@ fn vmx_disks(vmx: &str) -> Vec { .collect() } -/// The first disk the VM uses according to the .vmx (used by tests + the single-disk path). +/// The first disk the .vmx names (tests; golden_from uses vmx_disks to refuse multi-disk VMs). +#[cfg(test)] fn vmx_disk(vmx: &str) -> Option { vmx_disks(vmx).into_iter().next() } @@ -452,8 +453,24 @@ fn run(bin: &str, args: &[&str]) -> Result<(), String> { } /// Publish an image according to its os. Blocking (called from spawn_blocking). +/// Secure Boot clients (official signed iPXE, Network page) boot the Canonical-signed Ubuntu kernels — the Windows +/// stage and Linux goldens alike — through Ubuntu's Microsoft-signed shim (package shim-signed): any Ubuntu shim +/// verifies any Canonical-signed kernel. Copied to tftp/shim/shimx64.efi at every publish (cheap); boot.rs adds the +/// `shim` line. Missing → only Secure Boot clients are affected (warning). +pub(crate) fn refresh_shim() { + let src = ["/usr/lib/shim/shimx64.efi.signed.latest", "/usr/lib/shim/shimx64.efi.signed"].into_iter().find(|p| Path::new(p).is_file()); + let Some(src) = src else { + return tracing::warn!("no Ubuntu shim (apt install shim-signed): Secure Boot clients cannot boot the kernels"); + }; + let dir = crate::tftp_dir().join("shim"); + if let Err(e) = std::fs::create_dir_all(&dir).and_then(|_| std::fs::copy(src, dir.join("shimx64.efi"))) { + tracing::warn!("copy {src} → {}: {e}", dir.display()); + } +} + pub fn run_publish(st: &SharedState, name: &str, steps: &mut Steps) -> Result { let img = st.db.image_by_name(name)?.ok_or(format!("image '{name}' not found in DB"))?; + refresh_shim(); let (id, os) = (img.id, img.os); match os.as_str() { "linux" => { diff --git a/mgmt/src/tftp.rs b/mgmt/src/tftp.rs index 183f2be..8ec5809 100644 --- a/mgmt/src/tftp.rs +++ b/mgmt/src/tftp.rs @@ -54,16 +54,17 @@ fn parse_rrq(b: &[u8]) -> Option<(String, Vec<(String, String)>)> { Some((name, opts)) } -/// TFTP serves ONLY the embedded iPXE (`snponly.efi`), from memory. Firmware fetches just that over TFTP; iPXE then -/// pulls kernel/initrd/golden over HTTP (`/tftp/...` ServeDir). Refusing everything else stops a spoofed UDP packet -/// from making the server read a multi-GB golden into RAM (no handshake on UDP → an amplification/OOM vector). +/// TFTP serves ONLY the embedded iPXE binaries, from memory: our own `snponly.efi`, and the official Secure Boot pair +/// `sb/snponly-shim.efi` + `sb/snponly.efi`. Firmware fetches just those over TFTP; iPXE then pulls kernel/initrd/golden +/// over HTTP (`/tftp/...` ServeDir). Refusing everything else stops a spoofed UDP packet from making the server read a +/// multi-GB golden into RAM (no handshake on UDP → an amplification/OOM vector). fn load(name: &str) -> Result<&'static [u8], String> { let name = name.replace('\\', "/"); - let name = name.trim_start_matches('/'); - if name == "snponly.efi" { - Ok(crate::boot::SNPONLY_EFI) - } else { - Err(format!("TFTP serves only snponly.efi (asked {name:?}); other files go over HTTP")) + match name.trim_start_matches('/') { + "snponly.efi" => Ok(crate::boot::SNPONLY_EFI), + "sb/snponly-shim.efi" => Ok(crate::boot::SB_SHIM_EFI), + "sb/snponly.efi" => Ok(crate::boot::SB_IPXE_EFI), + other => Err(format!("TFTP serves only the iPXE binaries (asked {other:?}); other files go over HTTP")), } } @@ -231,8 +232,15 @@ mod tests { let (oack, tid) = recv(&c).await; assert_eq!(oack, format!("\0\x06tsize\0{}\0", crate::boot::SNPONLY_EFI.len()).into_bytes()); c.send_to(b"\0\x05\0\x08abort\0", tid).await.unwrap(); - // Anything but snponly.efi (including a traversal attempt) → "file not found" ERROR, never a disk read. - for req in [rrq("../etc/passwd", &[]), rrq("broom-win/x/golden.vhdx", &[]), rrq("nope.bin", &[])] { + // The official Secure Boot pair under sb/ (shim → loads sb/snponly.efi by name). + for (name, want) in [("sb/snponly-shim.efi", crate::boot::SB_SHIM_EFI), ("sb/snponly.efi", crate::boot::SB_IPXE_EFI)] { + c.send_to(&rrq(name, &[("tsize", "0")]), srv).await.unwrap(); + let (oack, tid) = recv(&c).await; + assert_eq!(oack, format!("\0\x06tsize\0{}\0", want.len()).into_bytes(), "{name}"); + c.send_to(b"\0\x05\0\x08abort\0", tid).await.unwrap(); + } + // Anything else (including a traversal attempt) → "file not found" ERROR, never a disk read. + for req in [rrq("../etc/passwd", &[]), rrq("broom-win/x/golden.vhdx", &[]), rrq("nope.bin", &[]), rrq("sb/../x", &[])] { c.send_to(&req, srv).await.unwrap(); assert_eq!(op(&recv(&c).await.0), ERROR); } diff --git a/mgmt/src/versions.rs b/mgmt/src/versions.rs index 6260abd..7911485 100644 --- a/mgmt/src/versions.rs +++ b/mgmt/src/versions.rs @@ -77,7 +77,46 @@ pub fn list(name: &str, active: Option<&str>) -> Vec { list_at(&storage(), name, active) } -fn list_at(root: &Path, name: &str, active: Option<&str>) -> Vec { +/// Versions of an image, newest first, each `diff` = bytes that differ from image.img AS IT IS NOW (the golden on +/// the image list), not from another version. `active` only saves the hashing when image.img is still that version. +pub fn list_vs_current(name: &str, active: Option<&str>) -> Vec { + let root = storage(); + let cur = current_at(&root, &image_path(name), &crate::images_dir().join(name).join("current.chunks"), name, active); + let mut v = manifests(&root, name); + for m in &mut v { + m.diff = cur.as_ref().map(|c| diff_bytes(c, m)); + m.chunks.clear(); + } + v +} + +/// Chunk list of image.img now. Free when it is untouched since the active version was saved; otherwise hashed once +/// (a 30 GB golden ≈ a minute) and cached in `cache`, keyed by size + mtime. +fn current_at(root: &Path, img: &Path, cache: &Path, name: &str, active: Option<&str>) -> Option { + let meta = std::fs::metadata(img).ok()?; + let mtime = meta.modified().ok()?.duration_since(std::time::UNIX_EPOCH).ok()?; + if let Some(m) = active.and_then(|a| load(root, name, a).ok()).filter(|m| m.size == meta.len() && mtime.as_secs() <= m.created) { + return Some(m); + } + let size = meta.len(); + let stamp = format!("{size} {}", mtime.as_nanos()); + let cur = |chunks| Manifest { version: "current".into(), label: String::new(), created: 0, size, chunk_size: CHUNK, chunks, diff: None }; + if let Some((head, rest)) = std::fs::read_to_string(cache).ok().as_deref().and_then(|s| s.split_once('\n')) { + if head == stamp { + return Some(cur(rest.lines().map(String::from).collect())); + } + } + let f = File::open(img).ok()?; + let (mut chunks, mut buf) = (Vec::new(), Vec::new()); + for i in 0..size.div_ceil(CHUNK) { + chunks.push(read_chunk(&f, i, size, &mut buf).ok()?.unwrap_or_else(|| ZERO.to_string())); + } + let _ = std::fs::write(cache, format!("{stamp}\n{}", chunks.join("\n"))); + Some(cur(chunks)) +} + +/// Every manifest of an image (with chunks), newest first. +fn manifests(root: &Path, name: &str) -> Vec { let mut v: Vec = std::fs::read_dir(manifest_dir(root, name)) .into_iter() .flatten() @@ -85,6 +124,11 @@ fn list_at(root: &Path, name: &str, active: Option<&str>) -> Vec { .filter_map(|d| serde_json::from_slice::(&std::fs::read(d.path()).ok()?).ok()) .collect(); v.sort_by_key(|m| std::cmp::Reverse(m.version[1..].parse::().unwrap_or(0))); + v +} + +fn list_at(root: &Path, name: &str, active: Option<&str>) -> Vec { + let mut v = manifests(root, name); let base = active.and_then(|a| v.iter().find(|m| m.version == a)).cloned(); for m in &mut v { m.diff = base.as_ref().map(|b| diff_bytes(b, m)); @@ -155,6 +199,28 @@ pub fn rehydrate(name: &str, version: &str) -> Result { rehydrate_at(&storage(), &image_path(name), name, version) } +/// `version` of image `from` → v1 of the new image `to`: only the manifest is copied, the chunks are shared (dedup; +/// gc keeps a chunk while any manifest of any image names it). +pub fn clone_to(from: &str, version: &str, to: &str, label: &str) -> Result<(), String> { + clone_at(&storage(), from, version, to, label) +} + +fn clone_at(root: &Path, from: &str, version: &str, to: &str, label: &str) -> Result<(), String> { + let m = load(root, from, version)?; + let dir = manifest_dir(root, to); + if std::fs::read_dir(&dir).is_ok_and(|mut d| d.next().is_some()) { + return Err(format!("image {to} already has versions")); + } + std::fs::create_dir_all(&dir).map_err(e("mkdir manifests"))?; + let m = Manifest { version: "v1".into(), label: label.to_string(), ..m }; + std::fs::write(dir.join("v1.json"), serde_json::to_vec(&m).unwrap()).map_err(e("write manifest")) +} + +/// `version` → a new file `dst` (export), image.img untouched. +pub fn rehydrate_to(name: &str, version: &str, dst: &Path) -> Result { + rehydrate_at(&storage(), dst, name, version) +} + fn rehydrate_at(root: &Path, img: &Path, name: &str, version: &str) -> Result { let m = load(root, name, version)?; let f = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(img) @@ -272,6 +338,13 @@ mod tests { assert_eq!(changed, 2); // chunk 0 (data) + chunk 1 (→ hole); chunk 4 dropped by truncation assert_eq!(hash_file(&img), v1_hash); assert!(is_hole(&File::open(&img).unwrap(), CHUNK, CHUNK)); + // Diff vs image.img as it is now (= v1 content, no active version given): hashed once, then cached. + let cache = d.join("current.chunks"); + let cur = current_at(&root, &img, &cache, "img", None).unwrap(); + assert_eq!(cur.chunks, load(&root, "img", "v1").unwrap().chunks); + assert!(cache.exists()); + assert_eq!(current_at(&root, &img, &cache, "img", None).unwrap().chunks, cur.chunks); + assert_eq!(diff_bytes(&cur, &load(&root, "img", "v3").unwrap()), 4 * CHUNK); assert_eq!(list_at(&root, "img", None).iter().map(|m| m.version.as_str()).collect::>(), ["v3", "v2", "v1"]); // Diff vs active v1: v2 same content → 0; v3 differs at chunks 0, 1, 3 and the new chunk 4 (size grew). let diffs = |active| list_at(&root, "img", active).iter().map(|m| m.diff).collect::>(); @@ -291,6 +364,19 @@ mod tests { assert_eq!(delete_at(&root, "img", "v3").unwrap(), 3); assert_eq!(count(&root), 3); assert!(load(&root, "img", "../x").is_err()); + + // v1 → new image "copy": manifest only (no new chunks), restores to the same bytes in a new file, and its + // chunks survive when the source image's versions are all deleted. + clone_at(&root, "img", "v1", "copy", "from img v1").unwrap(); + assert!(clone_at(&root, "img", "v1", "copy", "").is_err(), "target already has versions"); + assert_eq!(count(&root), 3); + let img2 = d.join("copy.img"); + rehydrate_at(&root, &img2, "copy", "v1").unwrap(); + assert_eq!(hash_file(&img2), v1_hash); + assert_eq!(delete_at(&root, "img", "v1").unwrap(), 0); + let _ = std::fs::remove_file(&img2); + rehydrate_at(&root, &img2, "copy", "v1").unwrap(); + assert_eq!(hash_file(&img2), v1_hash); let _ = std::fs::remove_dir_all(&d); } diff --git a/mgmt/src/winstage.rs b/mgmt/src/winstage.rs index ddcde64..c71ae59 100644 --- a/mgmt/src/winstage.rs +++ b/mgmt/src/winstage.rs @@ -23,7 +23,7 @@ fn stage_dir() -> String { crate::tftp_dir().join("broom-stage").to_string_lossy().into_owned() } -fn run(bin: &str, args: &[&str]) -> Result { +pub(crate) fn run(bin: &str, args: &[&str]) -> Result { tracing::debug!("exec: {bin} {}", args.join(" ")); let o = Command::new(bin).args(args).output().map_err(|e| format!("{bin}: {e}"))?; if o.status.success() { @@ -70,6 +70,13 @@ restart(){ log "$*"; sleep 2; reboot -f 2>/dev/null || echo b > /proc/sysrq-trig # (delta Range requests + driver list need them) and must never be picked instead. if [ -x /broom/bin/wget ]; then wget(){ /broom/bin/wget "$@"; } else log "WARNING: no GNU wget in the stage (publish again) -> delta updates + drivers fall back / skip"; fi +# Whole-file download showing ONLY a progress bar (file name, %, bytes, speed, ETA) — no URL / connecting / headers / +# "saved" text. GNU wget: -q hides everything, --show-progress brings the bar back; bar:force because the initramfs +# console is not always seen as a tty; noscroll keeps the name still. Busybox wget: already just its own bar. +getfile(){ + if [ -x /broom/bin/wget ]; then /broom/bin/wget -q --show-progress --progress=bar:force:noscroll "$@" + else wget "$@"; fi +} NAME=""; HASH=""; SRV=""; HOST=""; LIC=""; MAC="" for a in $(cat /proc/cmdline); do case "$a" in broom.name=*) NAME=${a#*=};; broom.hash=*) HASH=${a#*=};; broom.srv=*) SRV=${a#*=};; @@ -151,7 +158,14 @@ delta(){ else if (h in at) print "c", i, h, at[h], nc++ else print "d", i, h }' $om $nm > $P || return 1 s=$(grep -c '^s ' $P); c=$(grep -c '^c ' $P); d=$(grep -c '^d ' $P); z=$(grep -c '^z ' $P) - avail=$(df -k $W | tail -1 | awk '{print $4}') + # Mostly new (a re-installed golden, not an update) → one plain whole-file stream beats thousands of 4 MB requests + # (and the server compressing them). Checked before anything is written → the old copy is untouched. + all=$((s + c + d + z)) + if [ $all -gt 0 ] && [ $((d * 2)) -gt $all ]; then + log "delta: $((d * 100 / all))% changed -> whole file instead"; rm -f $P; return 1 + fi + # -P: one line per filesystem (busybox df wraps long device names like /dev/mapper/... otherwise). + avail=$(df -Pk $W | tail -1 | awk '{print $4}') [ "$avail" -gt $((c * 4096 + 65536)) ] 2>/dev/null || { log "delta: not enough space to keep $c moved chunks"; return 1; } rm -rf $SP; mkdir -p $SP out=$old @@ -169,6 +183,8 @@ delta(){ try=$((try + 1)) done; rm -f $T.z; log "delta: chunk $1 failed 3 times"; return 1; } put(){ dd if=$T of=$out bs=4M seek=$1 conv=notrunc 2>/dev/null; } + # Chunk $1 already right in place (a run interrupted by a power cut wrote it) → no download (4 MB read < network). + have(){ dd if=$out of=$T bs=4M skip=$1 count=1 2>/dev/null && ok $2; } zero(){ dd if=/dev/zero of=$out bs=4M seek=$1 count=1 conv=notrunc 2>/dev/null; } # One worker: plan lines NR % DW == $1, phase $2. A failure leaves $F (a background job can't return into delta). work(){ @@ -183,7 +199,7 @@ delta(){ case "$a" in s) continue;; c) if [ -f $SP/$k ]; then T=$SP/$k; else dl $i $h || { touch $F; break; }; fi; put $i;; - d) dl $i $h || { touch $F; break; }; put $i;; + d) have $i $h || { dl $i $h || { touch $F; break; }; put $i; };; z) zero $i;; esac fi @@ -248,8 +264,8 @@ if [ "$(cat $B/golden.sha256 2>/dev/null)" != "$HASH" ]; then rm -f $B/golden.sha256 $B/base.vhdx $B/base.ok $B/first.pending $B/child.vhdx $B/child-local.vhdx mkdir -p $D U=http://$SRV/tftp/broom-win/$NAME - # Delta: only the chunks the old copy lacks cross the network (see delta()). No old copy / no manifest / - # any failure → drop the old golden + partial file and download the whole golden below. + # Delta: only the chunks the old copy lacks cross the network (see delta()). No old copy / no manifest / mostly + # changed / any failure → drop the old golden + partial file and download the whole golden below. if [ ! -f $D/golden.vhdx.ok ]; then if wget -q -O $D/golden.chunks $U/golden.chunks && [ -f $B/golden.vhdx ] && [ -f $B/golden.chunks ] \ && delta $B/golden.vhdx $B/golden.chunks $D/golden.chunks $D/golden.vhdx "http://$SRV/api/golden-chunk?name=$NAME"; then @@ -261,20 +277,35 @@ if [ "$(cat $B/golden.sha256 2>/dev/null)" != "$HASH" ]; then # $f.ok = file fully downloaded (power loss midway → next boot skips finished files, resumes the partial one). # Only -c -O: works with both busybox and GNU wget. -c failing (e.g. 416 when the file is complete but not yet .ok) # → download again from scratch. NO $((...)) on external data: an ash arithmetic error exits the whole script. + n=0 for f in golden.vhdx base-template.vhdx child-template.vhdx child-template.off efi.tar.gz; do + n=$((n + 1)) [ -f $D/$f.ok ] && continue - log "downloading $f" + # Size of the golden from the manifest (awk formats it: no shell arithmetic on server data). + sz="" + [ "$f" = golden.vhdx ] && sz=$(sed -n '1s/^size //p' $D/golden.chunks 2>/dev/null | awk '{ printf ", %.1f GB", $1 / 1073741824 }') + log "downloading $f ($n/5$sz)" U=http://$SRV/tftp/broom-win/$NAME/$f - wget -c -O $D/$f $U || { rm -f $D/$f; wget -O $D/$f $U; } || die "download $f" + # Fresh golden: sha256 WHILE downloading (tee) → no re-read of the whole file afterwards. Cut midway → the file + # stays; -c below resumes it and the full check runs at the end as before. + if [ "$f" = golden.vhdx ] && [ ! -s $D/$f ]; then + h=$( (cd $D && getfile -O - $U) | tee $D/$f | sha256sum | cut -c1-64 ) + [ "$h" = "$HASH" ] && touch $D/golden.hashed + fi + # cd + relative -O: the bar shows the file name ("golden.vhdx"), not the long dl- path cut short. + if [ "$f" != golden.vhdx ] || [ ! -f $D/golden.hashed ]; then + ( cd $D && getfile -c -O $f $U ) || { rm -f $D/$f; ( cd $D && getfile -O $f $U ); } || die "download $f" + fi touch $D/$f.ok done [ "$(srv_hash)" = "$HASH" ] || { rm -rf $D; restart "image $NAME changed on the server during the download -> reboot to get the new version"; } - # Delta: every chunk was checked against the manifest → no second full read. Full download → whole-file sha256. - if [ ! -f $D/golden.delta ]; then + # Delta: every chunk was checked against the manifest; fresh download: hashed while downloading → no second full + # read. Otherwise (resumed download) → whole-file sha256. + if [ ! -f $D/golden.delta ] && [ ! -f $D/golden.hashed ]; then log "checking golden sha256 - rereads the whole file, may take a few minutes, DO NOT power off..." [ "$(sha256sum $D/golden.vhdx | cut -d' ' -f1)" = "$HASH" ] || { rm -rf $D; die "golden sha256 mismatch"; } fi - rm -f $D/*.ok $D/golden.delta + rm -f $D/*.ok $D/golden.delta $D/golden.hashed # golden.chunks (if fetched) moves along → the manifest of the copy we now have = next delta's source. mv $D/* $B/ && rmdir $D && sync && echo "$HASH" > $B/golden.sha256 && sync fi @@ -564,7 +595,16 @@ fn with_part( let r = run("mount", &["-t", "ntfs-3g", "-o", opt, &dev, mnt]) .or_else(|_| run("mount", &["-t", "ntfs3", "-o", opt, &dev, mnt])) .and_then(|_| { - let r = f(mnt); + // ntfs-3g silently falls back to read-only when Windows didn't shut down cleanly → say so up front. + let probe = format!("{mnt}/.broom-rw"); + let r = if !ro && std::fs::write(&probe, b"").is_err() { + Err("Windows partition mounted read-only: Windows was not shut down cleanly (hibernated, Fast Startup or \ + forced power-off) — boot the VM, run broom-prep-win again and let it power off by itself, then upload" + .into()) + } else { + let _ = std::fs::remove_file(&probe); + f(mnt) + }; let _ = run("umount", &[mnt]); r }); @@ -683,6 +723,10 @@ fn build_golden(raw: &str, out: &str, name: &str, steps: &mut crate::publish::St // MSR/Recovery don't go into the golden) + GPT with a single partition (standard native VHD boot), KEEP start → // NTFS "hidden sectors" still match. Re-running gives the same result (re-publishing is safe). steps.go("trim disk"); + // Export (export.rs) rebuilds the VM disk from what the trim below destroys → keep it first. Never blocks publish. + if let Err(e) = crate::export::keep_boot_regions(Path::new(raw), name, (start, size)) { + tracing::warn!("image {name}: boot partitions not kept, export won't work for this upload: {e}"); + } const MB: u64 = 1024 * 1024; let total = std::fs::metadata(raw).map_err(|e| e.to_string())?.len(); let end = start + size; @@ -842,12 +886,26 @@ if (-not ([Security.Principal.WindowsPrincipal]$id).IsInRole('Administrators')) # 1. Native VHD boot: do NOT expand the VHDX to full size; no automatic device encryption. reg add HKLM\SYSTEM\CurrentControlSet\Services\FsDepends\Parameters /v VirtualDiskExpandOnMount /t REG_DWORD /d 4 /f | Out-Null reg add HKLM\SYSTEM\CurrentControlSet\Control\BitLocker /v PreventDeviceEncryption /t REG_DWORD /d 1 /f | Out-Null +# VBS + Memory integrity (HVCI), needs only Secure Boot: runs on clients with VT-x, ignored elsewhere. +# Drivers that aren't HVCI-compatible get blocked (e.g. VMware e1000 NIC → use e1000e). +$dg = 'HKLM\SYSTEM\CurrentControlSet\Control\DeviceGuard' +reg add $dg /v EnableVirtualizationBasedSecurity /t REG_DWORD /d 1 /f | Out-Null +reg add $dg /v RequirePlatformSecurityFeatures /t REG_DWORD /d 1 /f | Out-Null +reg add "$dg\Scenarios\HypervisorEnforcedCodeIntegrity" /v Enabled /t REG_DWORD /d 1 /f | Out-Null +# The web shows ON/OFF by ICMP ping (monitor.rs) — Windows Firewall drops echo requests by default. +netsh advfirewall firewall delete rule name="Broom ping" | Out-Null +netsh advfirewall firewall add rule name="Broom ping" protocol=icmpv4:8,any dir=in action=allow profile=any | Out-Null # 2. Reset every boot → turn off pointless writes. powercfg /h off Disable-ComputerRestore -Drive "$env:SystemDrive\" -ErrorAction SilentlyContinue Disable-ScheduledTask -TaskPath '\Microsoft\Windows\Defrag\' -TaskName ScheduledDefrag -ErrorAction SilentlyContinue | Out-Null Set-Service WSearch -StartupType Disabled -ErrorAction SilentlyContinue reg add HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU /v NoAutoUpdate /t REG_DWORD /d 1 /f | Out-Null +# Reserved storage (space kept for updates): a pending update holding it fails sysprep with 0x800F0975. +dism.exe /Online /Set-ReservedStorageState /State:Disabled /Quiet | Out-Null +$rm = 'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ReserveManager' +reg add $rm /v ShippedWithReserves /t REG_DWORD /d 0 /f | Out-Null +reg add $rm /v ActiveScenario /t REG_DWORD /d 0 /f | Out-Null $cs = Get-CimInstance Win32_ComputerSystem if ($cs.AutomaticManagedPagefile -or (Get-CimInstance Win32_PageFileSetting)) { Set-CimInstance $cs -Property @{AutomaticManagedPagefile = $false} @@ -860,8 +918,12 @@ if (Get-CimInstance Win32_PageFileUsage) { # 3. EFI bundle: temporary ESP (FAT32 vdisk) → bcdboot → BCD points to vhd=[locate]\broom\child.vhdx. $B = "$env:SystemDrive\broom" +# Rebuilt from scratch, except the admin's base-hook.ps1 (broom-done runs it while base is built). +$hookf = "$B\base-hook.ps1" +$hook = if (Test-Path $hookf) { [IO.File]::ReadAllBytes($hookf) } Remove-Item $B -Recurse -Force -ErrorAction SilentlyContinue New-Item -ItemType Directory "$B\efi" | Out-Null +if ($hook) { [IO.File]::WriteAllBytes($hookf, $hook); Write-Host '>>> keeping C:\broom\base-hook.ps1' -ForegroundColor Green } $vd = "$env:TEMP\broom-esp.vhdx" Remove-Item $vd -ErrorAction SilentlyContinue $L = (69..90 | ForEach-Object { [char]$_ } | Where-Object { -not (Test-Path "${_}:\") } | Select-Object -Last 1) @@ -962,12 +1024,21 @@ Write-Host '>>> Sysprep... the VM will POWER OFF. Then upload the .vmdk file on & "$env:SystemRoot\System32\Sysprep\sysprep.exe" /generalize /oobe /shutdown /unattend:"$B\unattend.xml" "#; -/// First logon (when base.vhdx is created on each machine): write base.ok to BROOMWIN then reboot → the stage -/// commits base. BROOMWIN has no drive letter (GPT bit 63, set by the stage) → write directly via the volume path -/// `\\?\Volume{..}\`; reboot only once written. ASCII only (Set-Content -Encoding ascii). +/// First logon (when base.vhdx is created on each machine): write base.ok to BROOMWIN, then BASE MODE — a popup tells +/// the technician to set up apps (FACEIT AC...) and restart; that restart → the stage commits base. BROOMWIN has no +/// drive letter (GPT bit 63, set by the stage) → write directly via the volume path `\\?\Volume{..}\`. ASCII only +/// (Set-Content -Encoding ascii). const BROOM_DONE: &str = r#"$v = Get-Volume -FileSystemLabel BROOMWIN -ErrorAction SilentlyContinue if (-not $v) { exit } +# Progress: on this console (FirstLogonCommands window) + broom\done.log on BROOMWIN (kept, readable later). +$lf = $v.Path + 'broom\done.log' +function step($m) { + Write-Host ('[broom {0:HH:mm:ss}] {1}' -f (Get-Date), $m) -ForegroundColor Cyan + try { [IO.File]::AppendAllText($lf, ('{0:yyyy-MM-dd HH:mm:ss} {1}' -f (Get-Date), $m) + "`r`n") } catch { } +} +step 'building base for this machine (once) - wait for the BASE MODE message' # SYSTEM task (stored in base.vhdx -> present every boot): keep Windows AFTER PXE in BootOrder, PXE first. +step 'boot order task (PXE first)' $s = "$env:SystemRoot\Setup\Scripts\broom-bootorder.ps1" $a = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-NoProfile -ExecutionPolicy Bypass -File $s" $t1 = New-ScheduledTaskTrigger -AtStartup @@ -986,14 +1057,15 @@ if ([IO.Directory]::Exists($dd)) { [IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($t)) | Out-Null [IO.File]::Copy($f, $t, $true) } + step 'installing driver packages from the server' if (Test-Path $tmp) { & pnputil /add-driver "$tmp\*.inf" /subdirs /install | Out-Null } Remove-Item $tmp -Recurse -Force -ErrorAction SilentlyContinue } -# Machine name from the server (stage writes broom\host.txt): rename -> takes effect after the reboot below, stored in base. +# Machine name from the server (stage writes broom\host.txt): rename -> takes effect after the restart that saves base. $h = $v.Path + 'broom\host.txt' if ([IO.File]::Exists($h)) { $n = [IO.File]::ReadAllText($h).Trim() - if ($n -and ($n -ne $env:COMPUTERNAME)) { Rename-Computer -NewName $n -Force -ErrorAction SilentlyContinue } + if ($n -and ($n -ne $env:COMPUTERNAME)) { step "machine name -> $n"; Rename-Computer -NewName $n -Force -ErrorAction SilentlyContinue } } # License key (Machines page): the server picks it by this machine's IP and hands it out once (403 = none). # slmgr /cpky afterwards: the key is not left readable in the registry. Never blocks building base. @@ -1003,6 +1075,7 @@ if ([IO.File]::Exists($sf)) { $k = '' try { $k = (Invoke-WebRequest -UseBasicParsing -TimeoutSec 15 -Method Post -Uri "http://$srv/api/license").Content.Trim() } catch { } if ($k) { + step 'activating the license key' $slmgr = "$env:SystemRoot\System32\slmgr.vbs" $r = (& cscript //nologo $slmgr /ipk $k | Out-String) + (& cscript //nologo $slmgr /ato | Out-String) & cscript //nologo $slmgr /cpky | Out-Null @@ -1010,12 +1083,33 @@ if ([IO.File]::Exists($sf)) { try { Invoke-WebRequest -UseBasicParsing -TimeoutSec 15 -Method Post -Body $r -Uri "http://$srv/api/license/result" | Out-Null } catch { } } } +# Golden hook C:\broom\base-hook.ps1 (optional, put there by the admin before prep): runs ONCE per machine while base +# is built, before the reboot that commits base -> what it does is kept every boot (e.g. an anti-cheat's first-run +# setup that wants one restart). Same console (its output shows), max 10 minutes, its errors never block base. +$hook = "$env:SystemDrive\broom\base-hook.ps1" +if ([IO.File]::Exists($hook)) { + step 'running C:\broom\base-hook.ps1' + try { + $p = Start-Process powershell.exe -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$hook`"" -NoNewWindow -PassThru + if ($p.WaitForExit(600000)) { step 'hook done' } else { $p.Kill(); step 'hook still running after 10 minutes -> stopped' } + } catch { step "hook failed: $_" } +} # Write base.ok DIRECTLY via the volume path (\\?\Volume{..}\broom\base.ok): no drive letter/mountvol needed # (the old version picked a letter via Test-Path -> clashed with an empty CD drive -> write failed -> OOBE loop every boot). $f = $v.Path + 'broom\base.ok' try { [IO.File]::WriteAllText($f, 'ok') } catch { } -# Reboot only if it WAS written: otherwise stay at the desktop (instead of an endless OOBE loop). -if ([IO.File]::Exists($f)) { shutdown /r /t 5 }"#; +# BASE MODE: base.ok is written, nothing restarts by itself. The technician sets up what must survive the reset on +# THIS machine (e.g. FACEIT AC: open it, it wants one restart through its own RESTART button), then restarts -> that +# restart commits base. Nobody there -> the next restart / power-off commits it. +if (-not [IO.File]::Exists($f)) { step 'could not write base.ok on BROOMWIN -> base is rebuilt next boot'; exit } +step 'BASE MODE: set up apps now (e.g. open FACEIT AC), then RESTART - that restart saves base for every boot' +$msg = "BASE MODE - this machine is building its base.`n`n" + + "Everything done now is KEPT on this machine after every reset.`n`n" + + "1. Open FACEIT AC (or other apps) and set them up.`n" + + "2. Restart (FACEIT's RESTART button, or Start > Restart).`n`n" + + "That restart saves the base. Afterwards every boot resets to it." +# 0x40 information icon + 0x1000 system modal (stays on top of the desktop). +try { (New-Object -ComObject WScript.Shell).Popup($msg, 0, 'Broom - BASE MODE', 0x1040) | Out-Null } catch { }"#; /// BroomBootOrder task (SYSTEM, at startup + every 5 minutes): Windows pulls "Windows Boot Manager" /// to the top of BootOrder every boot → the next power-on skips PXE (no reset). Restores the order the stage @@ -1102,6 +1196,11 @@ fn write_broom_done(mnt: &str) -> Result { for (f, body) in [("broom-done.ps1", BROOM_DONE), ("broom-bootorder.ps1", BROOM_BOOTORDER)] { std::fs::write(format!("{dir}/{f}"), body.replace('\n', "\r\n")).map_err(|e| format!("write {f}: {e}"))?; } + // The default hook an earlier prep wrote (open FACEIT, kill it after 120 s) — broom-done handles FACEIT itself now. + let hook = format!("{mnt}/broom/base-hook.ps1"); + if std::fs::read_to_string(&hook).is_ok_and(|s| s.contains("[hook] FACEIT AC")) { + let _ = std::fs::remove_file(&hook); + } Ok(true) } @@ -1120,11 +1219,26 @@ mod tests { } } + /// Shell functions are global: a helper defined inside another function (e.g. delta's chunk `dl`) silently + /// replaces a top-level one of the same name → every `name(){` in the stage must be unique. + #[test] + fn stage_function_names_unique() { + let mut seen = std::collections::HashSet::new(); + for l in super::STAGE_SCRIPT.lines() { + let t = l.trim_start(); + if let Some(name) = t.split_once("(){").map(|(n, _)| n).filter(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')) { + assert!(seen.insert(name.to_string()), "stage function {name}() defined twice"); + } + } + } + /// The stage script runs inside the initramfs — a syntax error = client stuck in a shell. #[test] fn stage_syntax() { for s in [super::STAGE_SCRIPT, super::STAGE_HOOK] { - let ok = stage_sh().args(["-n", "-c", s]).status().unwrap(); + // Busybox 1.30 (Ubuntu 22.04) ignores -n with -c and RUNS the script (partitions /dev/sda, reboots) → + // wrap it in a function that is never called: the whole body is parsed, nothing executes. + let ok = stage_sh().args(["-n", "-c", &format!("broom_syntax_check(){{\n{s}\n}}")]).status().unwrap(); assert!(ok.success()); } } @@ -1345,6 +1459,11 @@ mod tests { let a = file(&[chunk(1), chunk(2), chunk(9), chunk(4), chunk(5), vec![8; 1000]]); let (ok, same, dls, log) = run(&a, &a, None, false); assert!(ok && same && dls == 2 && log.contains("0 moved"), "{log}"); + // A2: a delta cut by a power loss already wrote the new chunk 2 (here 0xEE) in place → only the tail is + // downloaded; the plan still says "download" for chunk 2 but the bytes on disk already match. + let a2 = file(&[chunk(1), chunk(2), vec![0xEE; C], chunk(4), chunk(5), vec![8; 1000]]); + let (ok, same, dls, log) = run(&a2, &a2, Some(2), false); + assert!(ok && same && dls == 1, "{log}"); // B: a new chunk early → every later chunk shifts → 5 moved (saved first, then written), 1 download. let b = file(&[chunk(1), chunk(7), chunk(2), chunk(3), chunk(4), chunk(5), vec![6; 1000]]); let (ok, same, dls, log) = run(&b, &b, None, false); @@ -1368,6 +1487,11 @@ mod tests { // → no delta (the caller downloads everything). let (ok, _, dls, log) = run(&b, &b, None, true); assert!(!ok && dls == 0 && log.contains("half-patched"), "{log}"); + // G: a re-installed golden (5 of 6 chunks new) → no delta at all, the caller streams the whole file. + let g = file(&[chunk(40), chunk(41), chunk(42), chunk(43), chunk(44), vec![6; 1000]]); + let (ok, _, dls, log) = run(&g, &g, None, false); + assert!(!ok && dls == 0 && log.contains("83% changed -> whole file instead"), "{log}"); + assert_eq!(std::fs::read(d.join("o/golden.vhdx")).unwrap(), old, "old copy untouched"); let _ = std::fs::remove_dir_all(&d); } diff --git a/mgmt/static/index.html b/mgmt/static/index.html index 896a904..3bbda51 100644 --- a/mgmt/static/index.html +++ b/mgmt/static/index.html @@ -365,7 +365,7 @@ const gbs=b=>b>=1e9?(b/1e9).toFixed(1)+' GB':(b/1e6).toFixed(0)+' MB'; async function loadImages(){ const rows=await j('/api/images'); document.querySelector('#images tbody').innerHTML=rows.map(i=> - `${esc(i.name)}${esc(i.os)} + `${esc(i.name)}${i.export?`
⬇ .vmx · .vmdk ${gbs(i.export.size)} (${esc(i.export.version)})
`:''}${esc(i.os)} ${esc(i.cache_mode||'disk')} ${i.is_default?'✓':''} ${i.boot_script?'✓':'no'} @@ -376,6 +376,7 @@ async function loadImages(){ + `).join('') || 'no images yet'; @@ -402,12 +403,16 @@ function watchJob(name,el,done){ // ---- image versions (versions.rs: dedup 4 MB chunks; snapshot/rollback run as jobs) ---- let verImg=null; async function showVersions(id,name,os){verImg={id,name,os}; - const r=await j('/api/images/snapshots?id='+id), el=document.getElementById('img_versions'); + const el=document.getElementById('img_versions'); + el.innerHTML=`

Versions — ${esc(name)}

⏳ comparing with the current golden (the first time after a change reads the whole golden)...

`; + const r=await j('/api/images/snapshots?id='+id); el.innerHTML=`

Versions — ${esc(name)}

-
${ +
VersionLabelCreatedvs active
${ r.versions.map(v=>` - + `).join('') || ''}
VersionLabelCreatedvs current golden
${esc(v.version)} ${v.version===r.active?'active':''}${esc(v.label)}${new Date(v.created*1000).toLocaleString()}${v.version===r.active?'—':v.diff==null?'?':v.diff?'Δ '+gbs(v.diff):'same'}${esc(v.label)}${new Date(v.created*1000).toLocaleString()}${v.diff==null?'?':v.diff?'Δ '+gbs(v.diff):'same'} + +
no versions yet — Snapshot now saves the current golden
`;} async function snapshotImage(){const label=prompt('Label for this version (optional):','');if(label===null)return; @@ -420,6 +425,15 @@ async function rollbackImage(version){ async function deleteVersion(version){if(!confirm('Delete version '+version+' of '+verImg.name+'?'))return; try{await j('/api/images/version-delete',mk({id:verImg.id,version}));}catch(e){toast(e.message,true);} showVersions(verImg.id,verImg.name,verImg.os);} +async function exportImage(id,name,version){ + if(!confirm('Export '+name+(version?' '+version:' (current golden)')+' as a VMware VM (.vmx + .vmdk)?\nNeeds free disk space on the server ≈ the golden size; replaces the previous export of this image.'))return; + const el=document.getElementById('img_status'); + try{await j('/api/images/export',mk({id,version}));watchJob(name,el);}catch(e){el.textContent=' ✗ '+e.message;}} +async function versionToImage(version){ + const name=prompt('New image name for '+verImg.name+' '+version+' (letters, digits, _ -):',verImg.name+'-'+version); + if(!name)return; + const el=document.getElementById('img_status'); + try{await j('/api/images/from-version',mk({id:verImg.id,version,name}));loadImages();watchJob(name,el);}catch(e){el.textContent=' ✗ '+e.message;}} async function republish(id,name){const el=document.getElementById('img_status'); try{await j('/api/images/publish',mk({id}));watchJob(name,el);}catch(e){el.textContent=' ✗ '+e.message;}} async function editBoot(id,cur){const s=prompt('iPXE boot script:',cur||'');if(s===null)return; @@ -494,14 +508,19 @@ async function delDriver(id,name){if(!confirm('Delete driver package "'+name+'"? // ---- network ---- async function loadDhcp(){const c=await j('/api/dhcp'); ['mode','iface','server_ip','subnet','range_start','range_end','gateway','dns'].forEach(k=>{const e=document.getElementById('dhcp_'+k);if(e)e.value=c[k]||'';}); + const sb=document.getElementById('dhcp_ipxe_signed');if(sb)sb.checked=!!c.ipxe_signed; const dm=document.getElementById('dhcp_mode');if(dm)dm.onchange=toggleFull;toggleFull();} function toggleFull(){const fo=document.getElementById('full_only'),dm=document.getElementById('dhcp_mode');if(fo&&dm)fo.style.display=dm.value==='full'?'':'none';} async function applyDhcp(){const b={};['mode','iface','server_ip','subnet','range_start','range_end','gateway','dns'].forEach(k=>b[k]=document.getElementById('dhcp_'+k).value); + const sb=document.getElementById('dhcp_ipxe_signed');if(sb)b.ipxe_signed=sb.checked?'1':'0'; const m=document.getElementById('dhcp_msg'); try{const r=await j('/api/dhcp',mk(b));m.textContent=' ✓ '+(r.status||'applied');}catch(e){m.textContent=' ✗ '+e.message;}} // ---- system ---- -async function loadCafe(){const c=await j('/api/cafe-user'); +async function loadCafe(){ + j('/api/config').then(c=>{const t=document.getElementById('timeout'),z=document.getElementById('zram_reserve'); + if(t)t.value=c.boot_timeout;if(z)z.value=c.zram_reserve_mb;}).catch(()=>{}); + const c=await j('/api/cafe-user'); const u=document.getElementById('cafe_user');if(u)u.value=c.user||''; const p=document.getElementById('cafe_password');if(p)p.placeholder=c.password_set?'(unchanged)':'set a password';} async function saveCafe(){const m=document.getElementById('cafe_msg'); diff --git a/mgmt/static/page-network.html b/mgmt/static/page-network.html index 3a538bc..04855dc 100644 --- a/mgmt/static/page-network.html +++ b/mgmt/static/page-network.html @@ -13,6 +13,8 @@
+
+

DHCP + TFTP are built into bootrom-mgmt. On: this server hands out IPs + PXE boot info (turn off any other DHCP server on the LAN). Off: another DHCP server owns the LAN — broom serves no DHCP/TFTP.

diff --git a/mgmt/static/page-system.html b/mgmt/static/page-system.html index effc204..2142806 100644 --- a/mgmt/static/page-system.html +++ b/mgmt/static/page-system.html @@ -12,12 +12,12 @@

Countdown boot menu

-
seconds +
seconds

zram — RAM reserved for the server

-
MB +
MB

Loading a golden into zram (compressed RAM cache) is refused if img + reserve > available RAM → avoids RAM overflow/OOM. Reserve = RAM kept for the OS + iSCSI serving. Not enough → the image falls back to disk by itself.