Skip to content

Security: ArthurJDurand/WinRE-Manager

SECURITY.md

Security Policy

Scope

WinRE Manager modifies partition tables, the WinRE registration, and the BitLocker state of the target recovery partition only — never the OS volume's. The v48 intervening-anchor path reads, but never modifies, the anchor partition's BitLocker state. WinRE Manager downloads code-adjacent artifacts (WIMs, driver packs) from the internet and injects them into the recovery image.

The script requires administrative privilege. The two supported execution modes are:

  • Elevated (single-machine repair). Run from an administrator PowerShell prompt under the current user's elevated token. This is the mode for one-off repairs.
  • NT AUTHORITY\SYSTEM (fleet deployment). Production can run under SYSTEM through a scheduled task or an organization's deployment tooling. The wrapper's built-in Maintain Windows RE task uses a startup trigger with a five-minute delay plus a recurring 30-day trigger at 03:00 local time. Custom fleet deployments may use a different schedule appropriate to the organization's maintenance policy. This is the recommended mode for a managed fleet; see docs/deployment.md for the deployment configuration and its security implications.

The security posture described below applies to both modes: the script always requires a privilege level capable of modifying partition tables and the WinRE registration. A compromise of the script or its sources is a compromise of whatever privilege level it is running under.

Where security sits in the design

docs/architecture.md states four design invariants — never break Windows RE, never leave a machine without a working recovery route, minimize the reagentc /disable → reagentc /enable window, and do no work unless needed; prepare everything before touching anything. Two of those invariants are the security posture's foundation.

Rule 4 — prepare everything before touching anything. Required image preparation and validation precede destructive partition work and the deployment registration switch. A rejected candidate stops deployment while retaining the existing recovery route. An anticipated refusal can return EXIT_WARNING; an exception such as an exhausted WIM-mount retry returns EXIT_FATAL. Either result can occur before destructive work. Preparation-before-destruction bounds when changes happen; it does not prove remote inputs authentic or benign. Operators who need control over artifact provenance should self-host the manifest, OEM maps and base WIM, and apply independent integrity and authenticity verification appropriate to their trust model.

Rule 1 — never break Windows RE. The pipeline gate (v44 patch 1) stops the run before deployment when injection fails, because a WIM that cannot see the OS disk is actively misleading. The gate rejects candidates whose required preparation fails. It does not establish that content passing the integrity, signing and applicability checks is benign.

Self-hosting (see docs/self-hosting.md) is the operator-facing response to the residual trust placed in the maintainer's gists under Rule 4. It exists because "prepare everything" is only as strong as the provenance of the artifacts being prepared.

Security-relevant areas:

  • Download integrity. Every OEM pack download is hash-verified when the map provides a hash. Lenovo SHA256 and Dell SHA256/MD5 are always verified. HP packs do not currently carry a hash in the HP map. On the HP path the script requires that the HTTP request completed cleanly and that the downloaded file is non-empty (an explicit zero-byte check was added in v44 patch 1); a truncated file that nonetheless reports a clean HTTP completion and a non-zero size would not be detected.

  • Base WIM source. The base WIM is sourced, in preference order, from (1) the currently-registered WinRE image, (2) the manager's last-known-good copy at C:\Recovery\WindowsRE\winre.wim, or (3) a GitHub repository over HTTPS, extracted with 7-Zip. Sources (1) and (2) are local files under the operator's own control; source (3) is a remote download. No signature verification is performed on the WIM itself in any of the three cases. The last-known-good source is trusted only when its SHA256 matches state.CurrentImageHash — a partial or stale file is not promoted to LKG, and a failed fallback copy in a prior run cannot silently promote a stale WIM. The registered image is preferred unless the LKG is provably newer by the image's DISM servicing metadata (Version + SPBuild, with SPLevel as a secondary tiebreak and Architecture required to match); the GitHub source is used only when neither local source is usable. As of v48 patch 1, the LKG-by-hash path scans every type-coded recovery partition on the OS disk for a matching winre.wim, in addition to the canonical C:\Recovery\WindowsRE\winre.wim path: provenance is content, not pathname. The discovery scan may assign temporary drive letters to recovery partitions; those letters are cleaned up at end of run.

  • Source-ownership classification (v49). Every candidate source WIM is classified into one of four ownership classes — Manager-Owned, Manager-Lineage, Foreign-No-Drivers, Foreign-With-Drivers — before the strip-and-reinject pipeline runs. A Foreign-With-Drivers source (a WIM with OEM or third-party drivers present that the manager did not inject) is preserved as-is: the manager will not strip and re-inject over a foreign WIM that a vendor populated with its own drivers. This is a deliberate narrowing of the v47 strip-everything-then-inject-the-recipe policy: the strip stage is now applied only when the source is a manager-owned image, a manager-lineage image, or an in-box WIM with no third-party drivers. The trust implication is that a WIM that an attacker (or a vendor) has populated with drivers at a location the manager classifies as Foreign-With-Drivers will not be normalized before use. In practice this is bounded by the base-WIM source rules above — sources (1) and (2) are local files under the operator's own control, and source (3) is a plain in-box image — but the policy is worth stating explicitly for operators who self-host a foreign WIM as their base. The v50 patch 1 revision extends the Manager-Owned classification across a version boundary: the classifier matches the staged source hash against the current state.CurrentImageHash or a historical CurrentImageHash read from a stale state file via the new Get-StaleWinREStateFields helper. The historical read is used only by the source-ownership classifier; it does not make the stale state operationally authoritative, does not enter any gate other than the ownership classification, and does not affect the fast path's DesiredStateId check. This bridge assumes that the state file and its ancestor directories are protected from untrusted modification. The legacy state readers do not enforce that ACL assumption; a forged current or historical hash can influence ownership classification. See the legacy state-file authenticity limitation below. A marker whose LineageId matches no known current or historical value is treated as absent, so a foreign image carrying a marker from another machine is preserved rather than stripped.

In patch 5, preservation and placement are assessed separately. A preserved image that needs dedicated relocation receives a read-only mount and storage-applicability check, followed by discard; the manager does not strip or export it. A foreign accepted hash never enters CurrentImageHash merely because it is relocated. An already adequate dedicated preserved route avoids unnecessary partition work.

  • Driver injection and normalization. v47 normalizes the mounted image to zero third-party drivers (Remove-WindowsDriver against the image's own filterless third-party inventory) before the current recipe is injected (Add-WindowsDriver), subject to the v49 source-ownership classification above. Driver-package signature validation is not exclusively a kernel-load-time check. DISM normally requires digitally signed driver packages when adding them to an x64 offline Windows image, and Add-WindowsDriver fails on an unsigned package unless it is invoked with -ForceUnsigned. The manager does not pass -ForceUnsigned, so DISM's signing enforcement is active at injection. Windows separately enforces the applicable driver-signing policies at driver-load time. Neither stage is a substitute for the storage-applicability and never-downgrade gates below: a validly signed driver that does not match the machine's controller is still refused. The strip stage is hard-gated: if enumeration, removal, or the final zero-driver verification fails at any point, the candidate is discarded before any partition work, reagentc call, or WIM deployment. For manager-owned, manager-lineage, and foreign-no-drivers sources, the deployed image is a deterministic function of the current recipe, not a lineage of prior injections.

  • Never-downgrade storage-driver check (v49). After injection completes and before ResetBase, the manager compares each storage-class driver in the final image against the pre-strip inventory, matched by INF basename. If any post-injection driver would be older than the source's version of the same basename, the entire candidate is discarded — the mounted image is dismounted with -Discard, the source is preserved, and the run exits EXIT_WARNING. This is the mechanism that resists a compromised, stale, or rolled-back manifest silently regressing the storage stack to an older driver. The check applies to all sources regardless of ownership class; the conservative response (whole-source preservation rather than partial normalize) is what makes the resistance structurally reliable.

  • Pre-deployment storage-driver applicability gate (v49). The gate runs inside Step 3, after injection is confirmed complete, before ResetBase and before the dismount. The manager verifies that every present SCSIAdapter-class device on the machine has at least one INF in the candidate image whose HardwareID or CompatibleID prefix-matches one of the device's IDs. A candidate that leaves any controller unmatched is refused, dismounted with -Discard, and deferred. The refusal exits EXIT_WARNING before any WIM is written to the active route — no Step 4, no partition work, no deployment. The machine defers until the manifest or the machine's controller set is updated. It was added after the ASUS-incident field case, in which the machine's controller (PCI\VEN_8086&DEV_7D0B) was not in the manifest's VMD patterns and the earlier pipeline would have deployed a candidate with no driver for it — a recovery environment that boots but cannot see the OS disk.

  • BitLocker interaction. The script decrypts the target recovery partition in place (manage-bde -off) if the Device Encryption service has claimed it, polling until manage-bde reports the volume is unmanaged or fully decrypted. The script does not modify the OS volume's BitLocker state, does not add or remove key protectors on C:, and defers without change if the OS-fallback route would require C: to be modified. As of v48 patch 1, the intervening-anchor path also reads (but never modifies) the BitLocker state of the anchor partition: it requires the anchor to be fully decrypted, or BitLocker-encrypted and currently unlocked, and defers if the state is locked or indeterminate.

  • Manager config trust gate (v50 patch 1; extended v50 patch 3). The single durable settings file at C:\ProgramData\OEM\WinRE-Manager\manager.json holds the backup-root catalogue and any future durable settings. Both the read path (Get-ManagerConfig) and the write path (Set-ManagerConfig) verify that the directory containing manager.json, its immediate parent, and the config file itself are trusted, via Test-PathTrustedForSystem, and fail closed on ambiguity. "Trusted" is defined as: the ACL owner is SYSTEM (S-1-5-18) or Administrators (S-1-5-32-544), and no Allow ACE grants a modify-capable right to a principal outside SYSTEM, Administrators, or TrustedInstaller (S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464). The v50 patch 1 form checked only the ACL owner on the two directories; ownership and effective write permissions are separate properties, and a directory owned by SYSTEM can still carry a permissive inherited ACE that lets a non-administrator modify its contents. The extended form additionally checks the config file itself, so a non-admin cannot pre-create manager.json inside a SYSTEM-owned directory and supply hostile content to the backup-root catalogue read by Cleanup-Backups.ps1. Two levels of directory are checked, not one: an attacker who owns the parent can delete-and-recreate the child directory to steal ownership of that child between runs. The write path additionally checks the ancestors before creating the directory, so a pre-created attacker-owned parent is caught before the manager adds a child to it. An untrusted or unparseable config is treated as absent: the caller gets the empty default, and an attacker who swapped the directory cannot inject backup roots for a later restore or cleanup to use. Writes are atomic via the existing Write-FileAtomically. The v50 generation also introduces a destination-volume free-space preflight on backup (100 MiB margin) and resolves a mapped drive-letter backup path to its UNC form via Get-PSDrive.DisplayRoot before storing it, so a later run that maps the same letter to a different share does not silently redirect the catalogue entry.

  • Trust-check InheritOnly skip and three-copy invariant (v50 patch 4). Test-PathTrustedForSystem skips InheritOnly ACEs. Those apply only to children, not to the object being checked; treating them as effective on the object itself is a false-positive source on the stock C:\ProgramData ACL, which carries an inherited CREATOR OWNER ACE with (OI)(CI)(IO)(F). Without the skip, the stock ACL fails the effective-permission check and the trust gate refuses to read or write manager.json on a machine whose program-data directory has the stock ACL — a false positive that would disable the backup catalogue entirely. The fix skips ACEs that do not apply. CREATOR OWNER (S-1-3-0) and CREATOR GROUP (S-1-3-1) are deliberately not added to the trusted SID list; the correct response is to skip ACEs whose scope is the children, not to trust their principals generally. The identical logic exists in three copies: WinRE.ps1's Test-PathTrustedForSystem, Cleanup-Backups.ps1's local copy (the script runs standalone and cannot dot-source WinRE.ps1), and the shared _T helper in WinRE-Manager.cmd's elevated payload. Any future change to the helper — owner SIDs, trusted ACE SIDs, the per-Kind modify-capable mask, the InheritOnly skip, or the fail-closed behaviour on unresolvable SIDs — must land in all three copies in the same PR. A change to one without the others is a defect: the three implementations together gate manager.json reads and writes, the backup-catalogue read, the resume-script staging, and the wrapper's Restore picker and permanent maintenance-task install, and splitting the logic would let one call site accept a path another refuses. The three-copy invariant is restated as a maintenance commitment in CONTRIBUTING.md. The WinRE.ps1 copy is field-exercised on the project's ASUS test machine (2026-10-19); the Cleanup-Backups.ps1 and WinRE-Manager.cmd copies are byte-verified only.

  • Backup and restore actions (v49). WinRE.ps1 -Action Backup -BackupPath <dir> captures a byte-for-byte copy of the currently registered WinRE WIM and writes a sidecar backup.json recording the source hash, size, and DISM servicing metadata. The operation is non-destructive with respect to the machine — it does not rebuild, replace, or reconfigure the active WinRE route — but it consumes an operator-supplied destination path as an input and writes to it. The script may temporarily assign a drive letter in order to access a WIM registered through a GLOBALROOT/volume path; that letter is cleaned up under the existing temporary-drive-letter machinery. WinRE.ps1 -Action Restore -BackupPath <dir> writes a previously captured WIM back to the currently registered route transactionally: it validates the backup, resolves the current registered route, handles dedicated and OS-fallback targets, uses the existing deployment machinery, re-registers WinRE, and re-enables it. Restore does not create a new partition or invent a replacement route — a usable current WinRE route must already exist — but it replaces the WIM on the active route with bytes from the operator-supplied backup directory. Operators must treat the backup directory as a trust boundary. The restore operation verifies the backup WIM's SHA256 against the value recorded in the same-directory backup.json; this detects accidental corruption and mismatches between the WIM and its sidecar, but a coordinated tamperer who can modify the WIM can also modify the sidecar. If protection against deliberate tampering is required, preserve the expected hash in a trusted, separate location or use a digitally signed manifest whose signature is verified against a trusted key. The backup's provenance remains the operator's responsibility.

  • Elevated or SYSTEM privilege. Both execution modes run with enough privilege to modify partition tables, the WinRE registration, and the BitLocker state of the target recovery partition. A compromise of the script or its sources is a compromise of every machine it runs on at that privilege level. The fleet-deployment mode (SYSTEM, scheduled task) is the higher-impact case because it runs automatically and unattended on many machines.

  • Fail-fast elevation guard (v48 patch 2). An unelevated launch of WinRE.ps1 is refused in milliseconds with FATAL: WinRE Manager requires an elevated (Administrator) PowerShell session. and exit code 3, before the program lock, before hardware probes, and before any network fetch. On refusal the guard creates the log directory itself so its FATAL message has somewhere to be written. The refusal happens before any hardware probe, network call, partition query, or workspace allocation; the only file-system operation on the refusal path is the creation of the log directory that the FATAL line is written into.

  • Guarded cleanup (v50 patch 5). RestoreWork cleanup accepts only the expected rollback WIM and checks before deleting individual files. Backup deletion validates the selected direct child of the discovered backup root, refuses reparse points in its ancestry or children, and accepts only winre.wim and optional backup.json. Unexpected content causes refusal before deletion. The final directory removal is nonrecursive; a new child prevents removal rather than authorizing recursion. These snapshot checks reduce replacement races but are not an atomic filesystem transaction. WIM-only backups and optional malformed metadata remain accepted by cleanup; this is a deletion allowlist, not validation of a restorable backup.

  • Pending-deployment state (v50 patch 5). A trusted %ProgramData%\OEM\WinRE-Manager\pending-deployment.json binds the chosen candidate hash to the protected %ProgramData%\OEM\WinRE-Manager\PendingDeployment\pending.wim and deployment disposition. An existing unreadable, untrusted or malformed record is a refusal condition. The candidate directory uses an explicit SYSTEM/Administrators DACL; the candidate path/file and parents are checked, and a read handle held during deployment denies writes and deletion. The independently verified pending.wim is retained across interruption and DSI changes until the final registered route and persisted state are verified. Foreign acceptance never becomes manager ownership merely through relocation. Hashes establish consistency with the accepted bytes; they do not certify the image's origin or prove it will boot. See state and idempotency.

  • Architecture gate (v48 patch 1). The manager refuses to run on any OS architecture other than x64 — ARM64, x86, and any architecture whose token cannot be resolved exit with EXIT_WARNING before any state mutation. The refusal is a stable deferral, not a crash: no partition is touched, no WIM is deployed, and no state file is written. The gate exists because the pipeline has not been validated on non-x64 targets; ARM64 support would be a separate, tested change.

  • Native-boot VHDX fail-closed gate (v49). Default Repair refuses a File Backed Virtual OS disk when another disk has a nonvirtual bus type, or when topology cannot be resolved safely. This conservative check protects against native boot exposing the backing disk's recovery partitions; it does not establish native-boot WinRE support or a limitation of the partition APIs. Ordinary Hyper-V and VirtualBox guest disks are not refused merely because their host storage is a virtual-disk file. The gate returns EXIT_WARNING before Repair changes partitions or WinRE registration. Logs and resume staging can already have been written. Backup and Restore dispatch before this gate, so it is not a safety boundary for those actions.

  • Non-OS sweep suppression boundary (v50 patch 2). The non-OS-disk recovery-partition sweep in Remove-StrayRecoveryPartitions can delete type-coded recovery partitions up to 2 GiB on eligible internal disks other than the OS disk. Detected or indeterminate guests suppress the sweep; mounted file-backed virtual disks and unsupported bus types, including USB, are preserved. Under a VM guest with a host physical disk attached via passthrough (Hyper-V) or raw disk access (VirtualBox), that sweep could reach the host's own recovery partition — Get-Disk's BusType cannot distinguish a host disk presented by a hypervisor's virtual controller from a genuine secondary internal disk. The sweep is now suppressed entirely when the running OS is detected inside a known hypervisor (matched against Win32_ComputerSystem Manufacturer and Model strings via Test-RunningInVirtualMachine), and it fails closed — suppresses — when the query returns no usable data. Any non-OS disk reported as File Backed Virtual (a mounted VHD/VHDX) is preserved individually, regardless of the hypervisor detection result. The OS-disk repair path is unaffected by either suppression: it operates only on the OS disk, which is the guest's own. Detection is a heuristic, not a security boundary: a hypervisor configured to spoof its manufacturer/model strings, or an unusual platform not covered by the signature list, may not match. The File Backed Virtual protection is independent. A false guest detection can leave stray partitions behind; a missed guest signature can expose attached host disks that otherwise pass the sweep filters.

  • Temporary crash-recovery scheduled task (v49). Live Repair and Restore attempt to register a scheduled task named WinRE Manager - Resume when a script path is available and staging checks pass that fires at boot+1m and as a one-shot at T+1h. The task invokes the production script's default Repair action, is deleted on clean completion, and is preserved on interruption. Two independent persist signals are merged by finally: $Script:ResumeTaskShouldPersist retains pending deployments and covered failure/cleanup cases, including Restore and the outer catch; [WinRECancelKeyProbe]::ShouldPersist records Ctrl+C through a compiled delegate. Patch 5 arms persistence while inspecting or executing pending work and clears it after verified completion. See the current persist contract. If the compiled-delegate registration fails — an Add-Type failure or a runtime exception during Register() — the pipeline logs a WARN and continues; the Ctrl+C signal is unavailable. Ctrl+C alone cannot retain the task in that case; other persist conditions still apply. Two further interruption classes leave the task registered without setting either signal, because the finally block never runs to consult them: a hard process kill (e.g. taskkill /F) and a reboot mid-run (the OS terminates PowerShell). See troubleshooting.md. The task runs as SYSTEM at the highest run level, with the same privilege envelope as the primary scheduled task described in deployment.md. This is a new privileged-execution surface introduced in v49: an interruption of a repair or restore leaves a SYSTEM-level task registered on the machine that will re-invoke the production script on the next boot or within the hour. The task is deleted on clean completion, but if a machine is abandoned mid-run the task will persist until either the next successful run removes it or an operator removes it manually. The task's $PSCommandPath guard means the task is not registered when the script is invoked via Invoke-RestMethod | Invoke-Expression (gist bootstrap) or by pasting the script text directly into a console — those invocation modes have no $PSCommandPath, so the resume task is unavailable and the run logs at INFO. The task's registered command invokes the same script that registered it; a compromise of the script file at that path is a compromise of the resume task's execution, at SYSTEM privilege, on the next boot. The v50 patch 1 release added a protected-path guard on top of the $PSCommandPath guard; the v50 patch 3 release replaces that guard with a staging design. The resume task now executes a staged copy of the running script placed at C:\Recovery\OEM\Resume\WinRE.ps1 under an explicit DACL (SYSTEM and Administrators FullControl, inheritance disabled). The staged copy is byte-verified against the source and re-verified with Test-PathTrustedForSystem (owner in {SYSTEM, Administrators}, no Allow ACE granting a modify-capable right to a principal outside SYSTEM, Administrators, or TrustedInstaller) before the task is registered; the staging directory is removed on clean terminal exit at the same point the task is unregistered. A v50 patch 3 first revision that refused registration whenever the running script's own path, its directory, or the directory's parent failed Test-PathTrustedForSystem shipped a false positive on every development checkout — any script running from a non-SYSTEM-owned path was refused — so the resume-task registration was disabled on every dev machine. The v50 patch 1 form checked only a four-SID deny-list against the script directory, and did not check the script file's own ACL or the directory's parent; a specific user SID, a domain group, or a locally-created group could hold write access without matching the deny-list, and a script file pre-created by a non-admin inside a SYSTEM-owned directory would bypass a directory-only check. The WriteData and AppendData exclusion on directories is deliberate: on a directory those rights mean only create-new-file and create-new-subdirectory, not modify-existing-file, and including them would false-positive on the stock C:\ProgramData ACL that grants BUILTIN\Users a container-inherited (I)(CI)(WD,AD,WEA,WA) ACE. On files, both rights are included, because on a file they permit modifying the file's content; the file-level owner check closes the pre-creation attack by refusing a file the attacker owns. The v50 patch 4 release hardens the staging lifecycle in three ways. First, Initialize-ResumeScriptStaging and Remove-ResumeScriptStaging now use Remove-StagingDirectorySafely, which refuses reparse points, subdirectories, unexpected content, or a non-directory path; enumerates the expected children; and deletes them individually rather than calling Remove-Item -Recurse on the tree. This avoids relying on recursive deletion of an unexpected directory tree. The isolated Windows PowerShell 5.1 junction probes preserved their target files; they did not establish the proposed target-deletion exploit or prove every runtime safe. Second, a warn-only parent-chain trust check logs a WARN when C:\Recovery\OEM or C:\Recovery fails Test-PathTrustedForSystem but does not refuse registration; a strict check would disable self-healing on machines where the parent ACL is imperfect. The residual risk — a local user with Modify on the parent chain can replace the staged directory between task registration and task execution — is documented and accepted, not closed; see Known limitations below. Third, two script-scope flags track staging safety: $Script:ResumeStagingTaskInvalid (set at entry to the staging touch-region, cleared only on a verified success return) and $Script:ResumeTaskCompromiseUnresolved (set only when $Script:ResumeStagingTaskInvalid is set and the existing task's removal cannot be positively confirmed via Get-ScheduledTask enumeration). When $Script:ResumeTaskCompromiseUnresolved = $true, Main exits $EXIT_FATAL before any destructive repair work. Registration failure on an otherwise-safe staging path preserves the verified staged copy so a prior task is not orphaned. Registration refusal is non-fatal: the repair pipeline proceeds without the self-healing hook, and the guard is fail-closed on unreadable ACL.

  • Stable install location for the permanent maintenance task (v49; hardened v50 patch 5). The wrapper installs WinRE.ps1 at C:\ProgramData\OEM\WinRE-Manager\WinRE.ps1 and registers Maintain Windows RE against that persistent SYSTEM-level artifact. Hash equality establishes copy integrity; permissions must also prevent a local user from replacing the script after installation. Patch 5 rejects reparse points in the destination ancestry and rejects existing untrusted directories or files using the shared trust policy. The volume-root check permits TrustedInstaller ownership in addition to SYSTEM/Administrators, but still refuses untrusted modify/delete permissions. Missing directories and a newly created staging file receive protected SYSTEM/Administrators permissions. Staging is verified before publication; the final file is verified under a read handle that denies writes and deletion through task registration. Existing untrusted ACLs are not rewritten, and failure before publication preserves an earlier installed copy. A failed publication retains the verified staging file where available and reports its path; Windows ReplaceFile failure outcomes do not guarantee that the old destination name survives every error. The installer therefore makes no blanket rollback claim after publication starts. These checks do not constrain another administrator or SYSTEM. The separate accepted warn-only policy for the temporary resume task's C:\Recovery parents does not apply to this permanent install. Removing the maintenance task leaves the installed copy; remove it separately when decommissioning the machine, preserving manager.json if its backup catalogue is still needed.

  • Wrapper helper scripts (v49 patch 2; update checker revised v50 patch 1). Two helper scripts ship alongside the wrapper. Check-Update.ps1 reads the local WinRE.ps1 version ($ScriptVersion / $ScriptPatchLevel) and compares it against the latest remote release. The primary source is the GitHub Releases API (api.github.com/repos/.../releases/latest); the CHANGELOG.md on main is a fallback for when the API is unreachable or the release tag format is unrecognised. Each source URL is bounded by a 5-second timeout. The script is read-only, requires no elevation, and never modifies the machine. The v49 patch 2 implementation cached the remote version string at %TEMP%\WinRE-Manager-remote-version.txt; the v50 patch 1 revision removes that cache entirely, eliminating a per-user-writable local-tampering surface and the stale-cache reporting window. The wrapper's session-level memoisation (UPDATE_STATUS_SET) still limits the network call to at most once per wrapper session. When the check fails — network unavailable, remote format unrecognised, local script not found — it returns an ERROR| protocol line and the wrapper hides the corresponding menu entry. Cleanup-Backups.ps1 is launched elevated by the wrapper's [C] menu option and deletes timestamped backup directories under an operator-supplied or manager-config-registered path. It enumerates subdirectories containing a winre.wim (a WIM-only backup, one whose backup.json sidecar is missing or unparseable, is listed with a [WIM-ONLY, no sidecar] tag rather than being ignored); requires the operator to type DELETE at a confirmation prompt before any deletion; uses the guarded, nonrecursive deletion helper and confirms the selected directory is absent before counting success; returns exit code 1 when any deletion failed so the wrapper can surface the outcome; and restricts its empty-directory cleanup of the default hierarchy (C:\Backup\WindowsRE, C:\Backup) to the requested scope, so an explicit -BackupPath E:\MyBackups does not prune empty directories under C:\Backup. Its v50 root-discovery path from the manager config carries the same Test-PathTrustedForSystem check described under "Manager config trust gate (v50)" below; when the config is untrusted, unreadable, or unparseable, the helper falls back to the default root alone. The v50 patch 3 release additionally rejects reparse-point candidates (junctions, symlinks) during discovery and re-stats each target immediately before deletion, and patch 5 replaces recursive backup deletion with the expected-child allowlist described above. It is read-only with respect to WinRE, partitions, BitLocker, the state file, the checkpoint, the deferral marker, and every path outside the selected backup directories.

  • Map-builder scripts (v47 patch 3; Lenovo helper resolution refined v50 patch 3). Three maintainer-side scripts - Build-DellWinPEMap.ps1, Build-HPWinPEMap.ps1, and Build-LenovoWinPEMap.ps1 - regenerate the JSON maps the runtime consumes as its OEM driver-pack catalogue. They are not invoked by the production script, are not shipped as part of a machine's deployment, and do not run on managed machines; they run in a developer environment, and their intended output is a data file the runtime reads as a lookup table. They also create and clean scratch files; the Lenovo builder executes its downloaded HTTP helper.

    Trust surfaces, by vendor:

    • Build-DellWinPEMap.ps1 downloads the Dell catalog CAB from downloads.dell.com over HTTPS. No hash is verified on the CAB. Trust argument: the URL resolves to Dell's own CDN, and the extracted XML is parsed by name-value lookups that do not execute anything.
    • Build-HPWinPEMap.ps1 fetches the HP WinPE driver-packs HTML page from ftp.ext.hp.com over HTTPS and parses a table. Same trust argument.
    • Build-LenovoWinPEMap.ps1 fetches RecipeCard.json from download.lenovo.com, then scrapes per-DS-ID support pages. The Lenovo site's anti-bot measures require a browser-impersonating HTTP client; the script fetches curl-impersonate from the lexiforest/curl-impersonate GitHub repository and executes it locally to perform those fetches.

    The v50 patch 3 change and the deliberate choice not to pin a version. Prior to v50 patch 3 the Lenovo builder downloaded curl-impersonate from a hard-coded asset path. It now resolves an asset through the GitHub Releases API and validates the resolved download host against an allowlist (github.com, objects.githubusercontent.com, codeload.github.com). The accepted policy does not pin a release or independently verify a publisher signature or maintainer-selected SHA256. HTTPS and the host allowlist protect transport and destination checks; they do not prove that an upstream executable is trustworthy or establish the upstream account's two-factor-authentication settings. A compromised binary runs with the builder's privileges and can affect its environment, credentials and generated map; its intended role as an HTTPS fetcher does not restrict malicious code. The runtime consumes the generated JSON and does not execute curl-impersonate, but compromised map output can still affect later downloads. Build in an isolated environment with appropriate credentials, review the output, and apply independent artifact verification where the deployment trust model requires it.

    Empty-map refusal. All three builders refuse to publish an empty map: Build-DellWinPEMap.ps1 and Build-HPWinPEMap.ps1 gained the check in v50 patch 3; Build-LenovoWinPEMap.ps1 has carried it since v47 patch 3. The guard exists because a catalog or page shape change could otherwise produce an empty map that a publish step would silently upload, and the runtime would then return no-entry for every machine of that vendor - a configuration failure masquerading as a legitimate "no pack available" answer.

  • Fail-closed safety-check integrity (v49 patch 2). Four internal safety checks were corrected from fail-open to fail-closed: the native-boot VHDX disk enumeration, the post-deletion partition verification (both call sites in Ensure-AdequateRecoveryPartition and Remove-OrphanPartition), the WinRE status determination (both call sites in Ensure-AdequateRecoveryPartition and Invoke-RestoreAction), and the storage-controller enumeration. Each previously permitted a failing query — an enumeration error, a suppressed exception, an unrecognized status, or a pipeline-enumeration collapse of an empty array — to be interpreted as a result that would authorize destructive work. The corrections make each guard positively confirm the safe state or refuse. From a security standpoint these are integrity fixes rather than new features: they raise the reliability of the existing gates under transient failure conditions. The principle is stated in the production script's .NOTES block as the "Fail-closed principle", so future safety checks are written against it from the start.

Reporting a vulnerability

Do not open a public issue.

Report vulnerabilities privately through one of these channels:

  1. GitHub Security Advisories (preferred) — open a private advisory at https://github.com/ArthurJDurand/WinRE-Manager/security/advisories/new.
  2. If you cannot use GitHub Security Advisories, open a blank issue at https://github.com/ArthurJDurand/WinRE-Manager/issues/new with only the word security-contact in the title and no body. A maintainer will reach out to you by reply.

Include:

  • Affected version.
  • Reproduction steps.
  • Impact assessment.
  • Whether the vulnerability is reachable without elevation.

You will receive a response within 72 hours. This is a best-effort project; the maintainer is a single individual, and coordinated disclosure timelines will be negotiated in good faith.

Known limitations and accepted risks

These entries describe current behavior and residual trust assumptions, including the impact of writable local paths and unverified build executables.

  • Invoke-WebRequest in scripts/WinRE.ps1 uses -UseBasicParsing and a static User-Agent. This is intentional — the script does not need a full browser engine, and the User-Agent is used to bypass CDN blocks on some vendor sites.

  • The fallback copy to C:\Recovery\WindowsRE\winre.wim is attempted even if the primary deployment succeeded. An ACL denial is logged, sets the run's non-fatal-warning flag, and causes the run to exit EXIT_WARNING rather than EXIT_SUCCESS. This surfaces a degraded LKG copy to the operator instead of hiding it. (Behaviour change introduced in v48 patch 1.)

  • Driver packs are downloaded from the OEM's own CDN. The project does not redistribute them.

  • The GitHub-hosted driver manifest and OEM maps are community-maintained. Do not trust them for anything beyond this project's scope. Under the fourth design invariant ("prepare everything before touching anything"), the manifest and maps are prepared before the destructive sequence begins; a compromise of either affects the deployed recovery image but cannot affect a machine that the script defers on. If your trust model does not extend to third-party content hosted outside your perimeter, self-hosting is the response — see docs/self-hosting.md for the trust model and the exact variables to change.

  • The offline fallback trust model — v44 patch 5 through v47 patch 3, narrowed by v48 patch 1. When the driver manifest fetch fails after its retry budget — typically a DNS failure, a proxy block, or a total network outage — the script reads C:\Recovery\OEM\winre_state.json and treats its stored DesiredStateId as ground truth, then takes the fast path if the local safety checks also pass. In the current patch 5 workflow, the relevant checks include:

    • WinRE is Enabled.
    • The state file's stored DesiredStateId matches — used directly; the DSI is not recomputed offline.
    • The drift detector reports no change: the currently-registered WinRE image's DISM servicing metadata (Version + SPBuild) matches the state file's DeployedWinREMetadata anchor, and no force-upgrade, driver-version change, or missing-anchor condition applies.
    • The state file's stored LocalInputsId matches the current locally-computable inputs (v48 patch 1). A stored value of $null (a state file predating v48 patch 1) skips the check with a WARN.
    • The current layout gate confirms an adequately sized, unencrypted, type-coded dedicated recovery partition on the OS disk. In patch 5 an OS-fallback flag in state does not make the OS route a healthy fast-path endpoint.

    The v46-and-earlier deployed-WIM-hash-vs-CurrentImageHash comparison is no longer a fast-path gate. The WIM hash remains in use for LKG validation, copy verification, deployment verification, and the pre-/disable race detector, but it does not gate the offline fast path.

    Under v44 patch 5 through v47 patch 3, the residual risk was that a machine whose hardware changed while offline could take the fast path with a stale DSI, because recomputing the DSI would require the OEM pack version from the OEM map — another gist on the same unavailable network.

    v48 patch 1 closes the hardware-drift residual with the LocalInputsId field. The state file now records a hash over the three deployment inputs observable without a network fetch (hardware identity, OS build, CPU vendor/generation). On the offline fallback path, the run recomputes that hash from the current machine and defers with EXIT_WARNING when the stored and current values disagree, rather than trusting a DesiredStateId that describes a machine whose hardware or OS has since changed. VMD presence is deliberately excluded because it depends on the manifest's requiredDevices patterns, which is the input the offline fallback does not have. See CHANGELOG.md for the v48 patch 1 details.

    This offline behavior is a correctness limitation only within a deployment that protects the state file and its full parent chain. Those permissions are not enforced by the legacy state readers or writer. If an unprivileged user can modify or replace the state, its ownership and maintenance fields can influence a later privileged run; that is a security concern, including when a scheduled task supplies the privileged invocation. The design also deliberately makes the state file human-editable: the loop-breaker recovery procedure instructs the operator to delete it to reset the enable-failure counter. See docs/architecture.md — Rule 4 — for the four-rule framing of the offline behavior.

  • Legacy state-file authenticity. Read-WinREState, Get-StaleWinREStateFields and Write-WinREState do not enforce an ACL or reparse-point trust gate on C:\Recovery\OEM\winre_state.json. The current and historical CurrentImageHash, lineage and other state fields are authoritative inputs, not authenticated evidence. A user who can alter the file, pre-create it, or replace it through a writable parent can influence ownership classification and maintenance decisions when a privileged run later reads it; the user need not launch that run personally. Protect the file and its full directory chain. The pending-deployment store's stronger ACL checks do not authenticate this legacy state file. Strict refusal or state relocation would change the existing permissive-parent policy and must be decided before partition work, rather than failing state persistence after mutation.

  • Working-directory trust. Workspace selection checks the scratch directory and its parent for reparse points, but it does not enforce an ACL boundary or inspect every descendant before all artifact cleanup. Recursive cleanup remains in production, some harness tests, and the Dell/Lenovo builders. Scratch content must therefore be protected from other users while a privileged process consumes it. The harness requires no elevation but can still be launched elevated; the builders do not enforce non-elevated execution. Isolated junction probes on Windows PowerShell 5.1.26100.9711 preserved the target files, so the proposed junction-deletion exploit is not established by those probes. They do not prove every supported filesystem or runtime safe.

  • The C:\Recovery\OEM parent-chain residual — v50 patch 4, accepted, not closed. The resume-script staging places a copy of the running script at C:\Recovery\OEM\Resume\WinRE.ps1 under an explicit SYSTEM/Administrators-only DACL, and the temporary resume task executes that copy at SYSTEM privilege on the next boot or within the hour. The staging directory's own DACL is strict. The parent chain (C:\Recovery\OEM and C:\Recovery) is only checked warn-only: a machine whose parent ACL grants Modify to a non-admin principal is left in that state so self-healing remains available, and the run logs a WARN naming the directory. The accepted residual is that a local user with Modify on the parent chain can replace the staged directory between task registration and task execution and thereby execute arbitrary code at SYSTEM privilege. Closing this class unconditionally would require either a hardened parent-chain policy on every managed machine — a deployment-time concern, not a script-time one — or a different staging mechanism (e.g. a signed script + SYSTEM-only loader), both of which are out of scope for v50 patch 4. Operators whose threat model includes a non-admin user with Modify on C:\Recovery or C:\Recovery\OEM should treat this as their own hardening obligation. On the project's ASUS desktop test machine (2026-10-19), C:\Recovery\OEM was user-owned and the warning fired as designed; the task registered and cleaned up correctly.

Hardening guidance

If you deploy this at scale, four changes reduce the trust surface:

  1. Fork the driver manifest and the three OEM maps to your own repository and point $DriverManifestUrl, $DellWinPEMapUrl, $HPWinPEMapUrl, $LenovoWinPEMapUrl at your fork. This is the strongest single mitigation and directly answers the "is the maintainer's gist untrusted?" question that the fourth design invariant raises.
  2. Mirror the base WIM to your own HTTPS endpoint and point $BaseWinRERepoApi at your mirror.
  3. Maintain a signed manifest containing the expected base-WIM SHA256 and verify the manifest's signature against a trusted key, then verify the WIM's SHA256 against the manifest before servicing the image.
  4. Restrict who can modify the script, its inputs and scheduled tasks, and who can launch elevated or SYSTEM processes through deployment tooling. SYSTEM is a service identity, not an account-membership group. A separate launcher can bypass a task's per-task IgnoreNew setting, but an unchanged WinRE.ps1 still takes the same program lock. Privilege and deployment-tool access remain Windows security configuration responsibilities.

Steps 1 through 3 change URLs and add verification to the production script; the full procedure — including the trust model, the exact variables to change in both WinRE.ps1 and Test-WinRE.ps1, the map-builder scripts, and the air-gapped deployment workflow — is documented in docs/self-hosting.md. Step 4 is a Windows security configuration and is outside the scope of the self-hosting doc.

Related documents

  • docs/architecture.md — the four design invariants (particularly Rule 1 and Rule 4), the pipeline, and the control-flow invariants that this document's hardening guidance is designed to preserve.
  • docs/self-hosting.md — the trust model for the external artifacts, the map-builder scripts, and the air-gapped deployment workflow.
  • docs/deployment.md — the operator-facing deployment story, including the four-rule translation into fleet-operator guidance.
  • docs/driver-injection.md — the driver package sources and the injection success gate.
  • CONTRIBUTING.md — the four-bullet requirement for PRs that touch the destructive sequence.

There aren't any published security advisories