Improve backup validation (#849)

This commit is contained in:
Jeffrey
2026-10-21 22:47:01 +02:00
committed by GitHub
parent 97f3f805ef
commit 039ef80a8b
18 changed files with 1504 additions and 46 deletions
@@ -48,6 +48,7 @@ function Get-RegistryBackupCapturePlans {
Path = $entry.Path
IncludeSubKeys = [bool]$entry.IncludeSubKeys
CaptureAllValues = [bool]$entry.CaptureAllValues
AllowDeleteKey = [bool]$entry.AllowDeleteKey
ValueNames = @($entry.ValueNames)
}
}
@@ -66,6 +67,7 @@ function Add-RegistryPlanOperation {
Path = $Operation.KeyPath
IncludeSubKeys = $false
CaptureAllValues = $false
AllowDeleteKey = $false
ValueNames = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
}
}
@@ -75,6 +77,7 @@ function Add-RegistryPlanOperation {
'DeleteKey' {
$plan.IncludeSubKeys = $true
$plan.CaptureAllValues = $true
$plan.AllowDeleteKey = $true
}
'SetValue' {
if (-not $plan.CaptureAllValues) {
@@ -127,7 +130,7 @@ function Get-RegistrySnapshotsForBackup {
$snapshots = @()
foreach ($plan in $plans) {
$snapshots += Get-RegistryKeySnapshot -KeyPath $plan.Path -CaptureAllValues:$plan.CaptureAllValues -ValueNames @($plan.ValueNames) -IncludeSubKeys:$plan.IncludeSubKeys
$snapshots += Get-RegistryKeySnapshot -KeyPath $plan.Path -CaptureAllValues:$plan.CaptureAllValues -ValueNames @($plan.ValueNames) -IncludeSubKeys:$plan.IncludeSubKeys -AllowDeleteKey:([bool]$plan.AllowDeleteKey)
}
return @($snapshots)
@@ -163,7 +166,8 @@ function Get-RegistryKeySnapshot {
[string]$KeyPath,
[bool]$CaptureAllValues = $false,
[string[]]$ValueNames = @(),
[bool]$IncludeSubKeys = $false
[bool]$IncludeSubKeys = $false,
[bool]$AllowDeleteKey = $false
)
$registryParts = Split-RegistryPath -path $KeyPath
@@ -179,10 +183,19 @@ function Get-RegistryKeySnapshot {
$subKeyPath = $registryParts.SubKey
$key = $rootKey.OpenSubKey($subKeyPath, $false)
if ($null -eq $key) {
# Value-only plans restore missing values, never the absence of the whole key.
# Preserve absence separately so trusted validation can authorize empty-key cleanup.
return @{
Path = $KeyPath
Exists = $false
Values = @()
Exists = -not $AllowDeleteKey
OriginallyAbsent = $true
Values = @(
if (-not $AllowDeleteKey) {
foreach ($valueName in @($ValueNames | Sort-Object -Unique)) {
@{ Name = $valueName; Exists = $false; Kind = $null; Data = $null }
}
}
)
SubKeys = @()
}
}
+267 -23
View File
@@ -101,9 +101,9 @@ function Get-NormalizedSelectedUndoFeatureIdsFromBackup {
Normalizes a raw registry key snapshot into a consistent shape, recursing into sub-keys.
.DESCRIPTION
Fills in defaults for optional properties (Exists, Values, SubKeys) so downstream
Fills in defaults for optional properties (Values, SubKeys) so downstream
validation can read a predictable shape regardless of what the backup file omitted.
Throws if Path is missing, since every snapshot must be anchored to a real key.
Requires Path and a Boolean Exists to avoid interpreting missing data as deletion.
#>
function Normalize-RegistryKeySnapshot {
param(
@@ -115,9 +115,8 @@ function Normalize-RegistryKeySnapshot {
throw (Get-Translation -Key 'BackupSnapshotMissingPath')
}
$exists = $false
if ($Snapshot.PSObject.Properties['Exists']) {
$exists = [bool]$Snapshot.Exists
if (-not $Snapshot.PSObject.Properties['Exists'] -or $Snapshot.Exists -isnot [bool]) {
throw (Get-Translation -Key 'BackupSnapshotInvalidExists' -FormatArgs @($Snapshot.Path))
}
$values = @()
@@ -146,7 +145,8 @@ function Normalize-RegistryKeySnapshot {
return [PSCustomObject]@{
Path = [string]$Snapshot.Path
Exists = $exists
Exists = $Snapshot.Exists
OriginallyAbsent = ($Snapshot.OriginallyAbsent -is [bool] -and $Snapshot.OriginallyAbsent)
Values = @($values)
SubKeys = @($subKeys)
}
@@ -161,6 +161,7 @@ function Normalize-RegistryKeySnapshot {
Builds an allow-list from the capture plans of the selected features, then checks
every snapshot against it. Returns an array of translated error strings; an empty
array means the backup is valid.
#>
function Test-RegistryBackupMatchesSelectedFeatures {
param(
@@ -179,33 +180,220 @@ function Test-RegistryBackupMatchesSelectedFeatures {
$errors = New-Object System.Collections.Generic.List[string]
if (-not $script:Features -or $script:Features.Count -eq 0) {
$errors.Add((Get-Translation -Key 'BackupFeatureCatalogNotLoaded'))
$planMap = Get-RegistryBackupValidationPlanMap -SelectedFeatureIds $SelectedFeatureIds -SelectedUndoFeatureIds $SelectedUndoFeatureIds -Target $Target -Errors $errors
if ($errors.Count -gt 0) {
return $errors.ToArray()
}
$selectedRegistryFeatures = @(Get-SelectedRegistryFeaturesForBackupValidation -SelectedFeatureIds @($SelectedFeatureIds) -IsUndoFeature:$false -Errors $errors)
$undoRegistryFeatures = @(Get-SelectedRegistryFeaturesForBackupValidation -SelectedFeatureIds @($SelectedUndoFeatureIds) -IsUndoFeature:$true -Errors $errors)
$useSysprepRegFiles = ($Target -eq 'DefaultUserProfile') -or ($Target -like 'User:*')
return Test-RegistryBackupAgainstAllowList -RegistryKeys $RegistryKeys -PlanMap $planMap
}
$capturePlans = @()
if ($errors.Count -eq 0 -and ($selectedRegistryFeatures.Count -gt 0 -or $undoRegistryFeatures.Count -gt 0)) {
$capturePlans = @(Get-RegistryBackupCapturePlans -SelectedRegistryFeatures @($selectedRegistryFeatures) -UndoRegistryFeatures @($undoRegistryFeatures) -UseSysprepRegFiles:$useSysprepRegFiles)
}
<#
.SYNOPSIS
Validates registry snapshots against an already derived trusted allow-list.
$planMap = New-RegistryBackupAllowListPlanMap -CapturePlans @($capturePlans)
.DESCRIPTION
Internal helper shared by feature-based validation and the import workflow.
The plan map must come from Get-RegistryBackupValidationPlanMap, never backup data.
When ExecutableValueWarnings is supplied, executable content mismatches are collected
for confirmation instead of blocking import. All other validation errors remain blocking.
#>
function Test-RegistryBackupAgainstAllowList {
param(
[Parameter(Mandatory)]
[AllowEmptyCollection()]
[object[]]$RegistryKeys,
[Parameter(Mandatory)]
[hashtable]$PlanMap,
[AllowEmptyCollection()]
[System.Collections.Generic.List[object]]$ExecutableValueWarnings
)
if ($planMap.Count -eq 0 -and @($RegistryKeys).Count -gt 0) {
$errors = New-Object System.Collections.Generic.List[string]
if ($PlanMap.Count -eq 0 -and @($RegistryKeys).Count -gt 0) {
$errors.Add((Get-Translation -Key 'BackupNoAllowedRegistryPaths'))
}
foreach ($rootSnapshot in @($RegistryKeys)) {
Test-RegistrySnapshotAgainstAllowList -Snapshot $rootSnapshot -PlanMap $planMap -Errors $errors
Test-RegistrySnapshotAgainstAllowList -Snapshot $rootSnapshot -PlanMap $PlanMap -Errors $errors -ExecutableValueWarnings $ExecutableValueWarnings
}
return $errors.ToArray()
}
<#
.SYNOPSIS
Derives trusted registry permissions once for backup conversion and validation.
#>
function Get-RegistryBackupValidationPlanMap {
param(
[Parameter(Mandatory)]
[AllowEmptyCollection()]
[string[]]$SelectedFeatureIds,
[Parameter(Mandatory)]
[AllowEmptyCollection()]
[string[]]$SelectedUndoFeatureIds,
[Parameter(Mandatory)]
[string]$Target,
[Parameter(Mandatory)]
[AllowEmptyCollection()]
[System.Collections.Generic.List[string]]$Errors
)
if (-not $script:Features -or $script:Features.Count -eq 0) {
$Errors.Add((Get-Translation -Key 'BackupFeatureCatalogNotLoaded'))
return @{}
}
$selectedRegistryFeatures = @(Get-SelectedRegistryFeaturesForBackupValidation -SelectedFeatureIds @($SelectedFeatureIds) -IsUndoFeature:$false -Errors $Errors)
$undoRegistryFeatures = @(Get-SelectedRegistryFeaturesForBackupValidation -SelectedFeatureIds @($SelectedUndoFeatureIds) -IsUndoFeature:$true -Errors $Errors)
$useSysprepRegFiles = ($Target -eq 'DefaultUserProfile') -or ($Target -like 'User:*')
$capturePlans = @()
if ($Errors.Count -eq 0 -and ($selectedRegistryFeatures.Count -gt 0 -or $undoRegistryFeatures.Count -gt 0)) {
$capturePlans = @(Get-RegistryBackupCapturePlans -SelectedRegistryFeatures @($selectedRegistryFeatures) -UndoRegistryFeatures @($undoRegistryFeatures) -UseSysprepRegFiles:$useSysprepRegFiles)
}
$planMap = New-RegistryBackupAllowListPlanMap -CapturePlans @($capturePlans)
if ($planMap.Count -gt 0) {
# Catalog data supplies trusted content only; selected plans still authorize locations and operations.
$trustedValueMap = Get-RegistryBackupTrustedValueMap -Features @($script:Features.Values) -UseSysprepRegFiles:$useSysprepRegFiles
foreach ($plan in $planMap.Values) {
$plan | Add-Member -MemberType NoteProperty -Name TrustedValueMap -Value $trustedValueMap
}
}
return $planMap
}
<#
.SYNOPSIS
Reads trusted executable value data from both directions of catalog features.
.DESCRIPTION
This supplies data comparisons only; the selected operation's capture plan still
controls which paths and value names may be restored. Backup fields never supply trust.
#>
function Get-RegistryBackupTrustedValueMap {
param(
[object[]]$Features = @(),
[switch]$UseSysprepRegFiles
)
$trustedValueMap = @{}
$filePaths = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
foreach ($feature in $Features) {
if (-not [string]::IsNullOrWhiteSpace([string]$feature.RegistryKey)) {
$null = $filePaths.Add((Get-RegistryFilePathForFeature -RegistryKey $feature.RegistryKey -UseSysprepRegFiles:$UseSysprepRegFiles))
}
$undoPath = Resolve-RegistryBackupUndoFilePath -Feature $feature
if (-not [string]::IsNullOrWhiteSpace($undoPath)) { $null = $filePaths.Add($undoPath) }
}
foreach ($filePath in $filePaths) {
# A missing counterpart cannot authorize data; the active direction is checked by capture planning.
if (-not (Test-Path -LiteralPath $filePath)) { continue }
foreach ($operation in @(Get-RegFileOperations -regFilePath $filePath)) {
if ($operation.OperationType -ne 'SetValue' -or
-not (Test-RegistryValueMayExecuteCode -Path $operation.KeyPath -ValueName $operation.ValueName -KindName $operation.ValueType)) { continue }
$pathKey = Get-NormalizedRegistryPathKey -Path $operation.KeyPath
if (-not $trustedValueMap.ContainsKey($pathKey)) { $trustedValueMap[$pathKey] = @{} }
$name = [string]$operation.ValueName
$trustedValueMap[$pathKey][$name] = @($trustedValueMap[$pathKey][$name]) + @($operation)
}
}
return $trustedValueMap
}
<#
.SYNOPSIS
Identifies command lines, COM server registrations, and executable indirections.
#>
function Test-RegistryValueMayExecuteCode {
param([string]$Path, [AllowEmptyString()][string]$ValueName, [string]$KindName = 'String')
$parts = Split-RegistryPath -path $Path
if (-not $parts) { return $false }
return $parts.SubKey -match '(?i)(?:^|\\)(?:Run|RunOnce|RunOnceEx|InprocServer(?:32)?|InprocHandler(?:32)?|LocalServer(?:32)?|TreatAs|AutoTreatAs|AutoConvertTo|ScriptletURL)(?:\\|$)' -or
$parts.SubKey -match '(?i)\\shell\\[^\\]+\\(?:command|ddeexec)(?:\\|$)' -or
($ValueName -eq '' -and $parts.SubKey -match '(?i)\\shellex\\ContextMenuHandlers\\[^\\]+$') -or
# COM activation can use string indirections outside InprocServer32. Numeric settings are not server paths.
($KindName -notin @('DWord', 'QWord') -and $parts.SubKey -match '(?i)(?:^|\\)CLSID\\[^\\]+(?:\\|$)') -or
$ValueName -match '^(?i:DelegateExecute|ExplorerCommandHandler|ScriptletURL|DllSurrogate|DllSurrogateExecutable)$'
}
function Test-RegistryExecutableValueDataAllowed {
param($Snapshot, [string]$Path, [hashtable]$TrustedValueMap)
$kind = [System.Enum]::Parse([Microsoft.Win32.RegistryValueKind], [string]$Snapshot.Kind, $true)
if (-not (Test-RegistryValueMayExecuteCode -Path $Path -ValueName $Snapshot.Name -KindName $kind.ToString())) { return $true }
$stringKinds = @([Microsoft.Win32.RegistryValueKind]::String, [Microsoft.Win32.RegistryValueKind]::ExpandString)
if ($kind -notin ($stringKinds + @([Microsoft.Win32.RegistryValueKind]::DWord, [Microsoft.Win32.RegistryValueKind]::QWord))) { return $false }
# Empty executable registrations cannot supply a command or DLL path.
if ($kind -in $stringKinds -and ($null -eq $Snapshot.Data -or [string]$Snapshot.Data -ceq '')) { return $true }
$pathKey = Get-NormalizedRegistryPathKey -Path $Path
if ($null -eq $TrustedValueMap -or -not $TrustedValueMap.ContainsKey($pathKey)) { return $false }
foreach ($operation in @($TrustedValueMap[$pathKey][[string]$Snapshot.Name])) {
if ($null -eq $operation) { continue }
$trustedKind = if ($operation.ValueType -eq 'Hex2') { 'ExpandString' } else { $operation.ValueType }
if ($kind.ToString() -eq $trustedKind -and [string]$Snapshot.Data -ceq [string]$operation.ValueData) { return $true }
}
return $false
}
<#
.SYNOPSIS
Converts legacy absent value-only keys into scoped missing-value snapshots.
.DESCRIPTION
Uses only trusted feature plans. Empty absent-key snapshots at exact value-only
paths are converted in memory; authorized tree deletions and invalid snapshots
remain unchanged for subsequent validation. The input snapshots are not modified.
#>
function ConvertTo-CompatibleRegistryKeySnapshots {
param(
[Parameter(Mandatory)]
[AllowEmptyCollection()]
[object[]]$RegistryKeys,
[Parameter(Mandatory)]
[hashtable]$PlanMap
)
foreach ($snapshot in $RegistryKeys) {
$normalizedPath = Get-NormalizedRegistryPathKey -Path $snapshot.Path
$plan = if ($normalizedPath) { $PlanMap[$normalizedPath] } else { $null }
$convertAbsentKey = $snapshot.Exists -is [bool] -and -not $snapshot.Exists -and
@($snapshot.Values).Count -eq 0 -and @($snapshot.SubKeys).Count -eq 0 -and
$null -ne $plan -and -not $plan.CaptureAllValues -and -not $plan.IncludeSubKeys -and
$plan.ValueNames.Count -gt 0 -and
-not (Test-RegistryKeyDeletionAllowed -NormalizedPath $normalizedPath -PlanMap $PlanMap)
$originallyAbsent = $convertAbsentKey -or ($snapshot.OriginallyAbsent -is [bool] -and $snapshot.OriginallyAbsent)
# Absence is backup data; permission to clean up comes from an exact, nonrecursive plan.
# RemoveEmptyKey is derived here and is deliberately not read by normalization.
$removeEmptyKey = $originallyAbsent -and ($snapshot.Exists -or $convertAbsentKey) -and
$null -ne $plan -and -not $plan.CaptureAllValues -and -not $plan.IncludeSubKeys -and
@($snapshot.SubKeys).Count -eq 0 -and
@($snapshot.Values | Where-Object { [bool]$_.Exists }).Count -eq 0
[PSCustomObject]@{
Path = $snapshot.Path
Exists = if ($convertAbsentKey) { $true } else { $snapshot.Exists }
OriginallyAbsent = $originallyAbsent
RemoveEmptyKey = $removeEmptyKey
Values = @(
if ($convertAbsentKey) {
foreach ($valueName in @($plan.ValueNames | Sort-Object)) {
[PSCustomObject]@{ Name = $valueName; Exists = $false; Kind = $null; Data = $null }
}
} else { $snapshot.Values }
)
SubKeys = @(ConvertTo-CompatibleRegistryKeySnapshots -RegistryKeys @($snapshot.SubKeys) -PlanMap $PlanMap)
}
}
}
<#
.SYNOPSIS
Resolves selected feature IDs to their catalog entries, keeping only the ones with a
@@ -287,6 +475,7 @@ function New-RegistryBackupAllowListPlanMap {
NormalizedPath = $normalizedPath
IncludeSubKeys = [bool]$plan.IncludeSubKeys
CaptureAllValues = [bool]$plan.CaptureAllValues
AllowDeleteKey = [bool]$plan.AllowDeleteKey
ValueNames = ConvertTo-RegistryValueNameSet -ValueNames @($plan.ValueNames)
}
}
@@ -333,12 +522,14 @@ function Test-RegistrySnapshotAgainstAllowList {
[hashtable]$PlanMap,
[Parameter(Mandatory)]
[AllowEmptyCollection()]
[System.Collections.Generic.List[string]]$Errors
[System.Collections.Generic.List[string]]$Errors,
[AllowEmptyCollection()]
[System.Collections.Generic.List[object]]$ExecutableValueWarnings
)
$snapshotPath = [string]$Snapshot.Path
$normalizedPath = Get-NormalizedRegistryPathKey -Path $snapshotPath
if ([string]::IsNullOrWhiteSpace($normalizedPath)) {
if ([string]::IsNullOrWhiteSpace($normalizedPath) -or $snapshotPath.IndexOf([char]0) -ge 0) {
$Errors.Add((Get-Translation -Key 'BackupUnsupportedRegistryPath' -FormatArgs @($snapshotPath)))
return
}
@@ -349,11 +540,20 @@ function Test-RegistrySnapshotAgainstAllowList {
return
}
if (-not $Snapshot.PSObject.Properties['Exists'] -or $Snapshot.Exists -isnot [bool]) {
$Errors.Add((Get-Translation -Key 'BackupSnapshotInvalidExists' -FormatArgs @($snapshotPath)))
return
}
if (-not $Snapshot.Exists -and -not (Test-RegistryKeyDeletionAllowed -NormalizedPath $normalizedPath -PlanMap $PlanMap)) {
$Errors.Add((Get-Translation -Key 'BackupUnexpectedKeyDeletion' -FormatArgs @($snapshotPath)))
}
foreach ($valueSnapshot in @($Snapshot.Values)) {
$valueName = Get-NormalizedRegistryValueName -ValueName $valueSnapshot.Name
$valueExists = [bool]$valueSnapshot.Exists
if (-not (Test-RegistryValueAllowedByPlan -PlanMatch $planMatch -ValueName $valueName)) {
if ($valueName.IndexOf([char]0) -ge 0 -or -not (Test-RegistryValueAllowedByPlan -PlanMatch $planMatch -ValueName $valueName)) {
$Errors.Add((Get-Translation -Key 'BackupUnexpectedValue' -FormatArgs @($valueName, $snapshotPath)))
}
@@ -366,6 +566,19 @@ function Test-RegistrySnapshotAgainstAllowList {
elseif (-not (Test-RegistryValueDataMatchesKind -KindName $kindName -Data $valueSnapshot.Data)) {
$Errors.Add((Get-Translation -Key 'BackupInvalidValueData' -FormatArgs @($kindName, $valueReference)))
}
elseif (-not (Test-RegistryExecutableValueDataAllowed -Snapshot $valueSnapshot -Path $snapshotPath -TrustedValueMap $planMatch.TrustedValueMap)) {
if ($null -eq $ExecutableValueWarnings) {
$Errors.Add((Get-Translation -Key 'BackupUnsafeExecutableValue' -FormatArgs @($valueReference)))
}
else {
$ExecutableValueWarnings.Add([PSCustomObject]@{
Path = $snapshotPath
Name = $valueName
Kind = $kindName
Data = $valueSnapshot.Data
})
}
}
}
elseif (-not [string]::IsNullOrWhiteSpace($kindName)) {
$Errors.Add((Get-Translation -Key 'BackupValueMustNotDefineKind' -FormatArgs @($valueReference)))
@@ -373,7 +586,7 @@ function Test-RegistrySnapshotAgainstAllowList {
}
foreach ($subKeySnapshot in @($Snapshot.SubKeys)) {
Test-RegistrySnapshotAgainstAllowList -Snapshot $subKeySnapshot -PlanMap $PlanMap -Errors $Errors
Test-RegistrySnapshotAgainstAllowList -Snapshot $subKeySnapshot -PlanMap $PlanMap -Errors $Errors -ExecutableValueWarnings $ExecutableValueWarnings
}
}
@@ -487,6 +700,34 @@ function Get-NormalizedRegistryValueName {
return [string]$ValueName
}
<#
.SYNOPSIS
Checks whether selected feature operations authorize deletion of a key tree.
.DESCRIPTION
Only DeleteKey operations grant this permission. Checks all plans so an exact
value-only plan cannot hide a recursive deletion allowed by an ancestor.
#>
function Test-RegistryKeyDeletionAllowed {
param(
[Parameter(Mandatory)]
[string]$NormalizedPath,
[Parameter(Mandatory)]
[hashtable]$PlanMap
)
foreach ($plan in $PlanMap.Values) {
if (-not $plan.AllowDeleteKey) { continue }
if ($NormalizedPath.Equals($plan.NormalizedPath, [System.StringComparison]::OrdinalIgnoreCase) -or
($plan.IncludeSubKeys -and $NormalizedPath.StartsWith("$($plan.NormalizedPath)\", [System.StringComparison]::OrdinalIgnoreCase))) {
return $true
}
}
return $false
}
function Find-RegistryAllowListPlanMatch {
param(
[Parameter(Mandatory)]
@@ -501,6 +742,7 @@ function Find-RegistryAllowListPlanMatch {
IsDescendant = $false
CaptureAllValues = [bool]$plan.CaptureAllValues
ValueNames = $plan.ValueNames
TrustedValueMap = $plan.TrustedValueMap
}
}
@@ -515,6 +757,7 @@ function Find-RegistryAllowListPlanMatch {
IsDescendant = $true
CaptureAllValues = $true
ValueNames = $plan.ValueNames
TrustedValueMap = $plan.TrustedValueMap
}
}
}
@@ -571,7 +814,8 @@ function Test-RegistryValueKindNameSupported {
try {
$kind = [System.Enum]::Parse([Microsoft.Win32.RegistryValueKind], $KindName, $true)
return $kind -notin @([Microsoft.Win32.RegistryValueKind]::Unknown, [Microsoft.Win32.RegistryValueKind]::None)
return [System.Enum]::IsDefined([Microsoft.Win32.RegistryValueKind], $kind) -and
$kind -notin @([Microsoft.Win32.RegistryValueKind]::Unknown, [Microsoft.Win32.RegistryValueKind]::None)
}
catch {
return $false
@@ -101,6 +101,27 @@ function Test-RegistryKeySnapshotCanBeRestored {
}
}
<#
.SYNOPSIS
Preflights every root snapshot before any registry changes or hive loading.
#>
function Test-RegistryBackupSnapshotsCanBeRestored {
param([Parameter(Mandatory)][AllowEmptyCollection()][object[]]$RegistryKeys)
$rootPaths = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
foreach ($snapshot in $RegistryKeys) {
$parts = Split-RegistryPath -path $snapshot.Path
if (-not $parts -or [string]::IsNullOrWhiteSpace($parts.SubKey) -or
$parts.Hive -notin @('HKEY_CURRENT_USER', 'HKEY_LOCAL_MACHINE', 'HKEY_CLASSES_ROOT', 'HKEY_USERS', 'HKEY_CURRENT_CONFIG')) {
throw "Unsupported registry path in backup: $($snapshot.Path)"
}
if (-not $rootPaths.Add("$($parts.Hive)\$($parts.SubKey)")) {
throw "Backup contains duplicate registry root path: $($snapshot.Path)"
}
Test-RegistryKeySnapshotCanBeRestored -Snapshot $snapshot
}
}
<#
.SYNOPSIS
Returns a snapshot child's name only when it is directly below its parent.
@@ -145,6 +166,8 @@ function Get-DirectRegistrySnapshotChildName {
.DESCRIPTION
Writes only values and descendants represented by the backup. Existing keys are
retained so their security descriptors and unrelated data are not destroyed.
A key recorded as originally absent is removed only if trusted validation
authorized cleanup and no values or subkeys remain.
#>
function Restore-RegistryKeySnapshotAtPath {
param(
@@ -161,20 +184,37 @@ function Restore-RegistryKeySnapshotAtPath {
return
}
$key = $RootKey.CreateSubKey($SubKeyPath)
$onlyDeletesValues = @($Snapshot.SubKeys).Count -eq 0 -and
@($Snapshot.Values | Where-Object { [bool]$_.Exists }).Count -eq 0
if ($onlyDeletesValues -and (@($Snapshot.Values).Count -gt 0 -or $Snapshot.RemoveEmptyKey)) {
# An absent value-only key already has the requested state.
$key = $RootKey.OpenSubKey($SubKeyPath, $true)
if ($null -eq $key) { return }
}
else {
$key = $RootKey.CreateSubKey($SubKeyPath)
}
if ($null -eq $key) {
throw "Unable to create or open registry key '$($Snapshot.Path)'"
}
$removeEmptyKey = $false
try {
foreach ($valueSnapshot in @($Snapshot.Values)) {
Restore-RegistryValueSnapshot -RegistryKey $key -Snapshot $valueSnapshot
}
if ($Snapshot.RemoveEmptyKey -and $onlyDeletesValues) {
$removeEmptyKey = @($key.GetValueNames()).Count -eq 0 -and @($key.GetSubKeyNames()).Count -eq 0
}
}
finally {
$key.Close()
}
if ($removeEmptyKey) {
Remove-RegistryEmptyKeyIfExists -RootKey $RootKey -SubKeyPath $SubKeyPath
}
foreach ($subKeySnapshot in @($Snapshot.SubKeys)) {
$childName = Get-DirectRegistrySnapshotChildName -ParentPath $Snapshot.Path -ChildPath $subKeySnapshot.Path
@@ -244,7 +284,12 @@ function Convert-RegistryValueKindFromBackup {
}
try {
return [System.Enum]::Parse([Microsoft.Win32.RegistryValueKind], $KindName, $true)
$kind = [System.Enum]::Parse([Microsoft.Win32.RegistryValueKind], $KindName, $true)
if (-not [System.Enum]::IsDefined([Microsoft.Win32.RegistryValueKind], $kind) -or
$kind -in @([Microsoft.Win32.RegistryValueKind]::Unknown, [Microsoft.Win32.RegistryValueKind]::None)) {
throw "Unsupported registry value kind in backup: $KindName"
}
return $kind
}
catch {
throw "Unsupported registry value kind in backup: $KindName"
+47 -4
View File
@@ -40,8 +40,9 @@ function Import-RegistryBackup {
.DESCRIPTION
Validates the structure and content of the supplied backup and converts
it into a normalized representation that can be safely consumed by the
restore workflow. Throws if validation fails.
it into a normalized representation for the restore workflow. Executable
content mismatches are returned in ExecutableValueWarnings for confirmation;
structural and authorization failures throw.
.PARAMETER Backup
The raw backup object (typically parsed from JSON) to normalize.
@@ -59,6 +60,7 @@ function ConvertTo-NormalizedRegistryBackup {
)
$errors = New-Object System.Collections.Generic.List[string]
$executableValueWarnings = New-Object 'System.Collections.Generic.List[object]'
if (-not $Backup.PSObject.Properties['Version']) {
$errors.Add((Get-Translation -Key 'BackupMissingProperty' -FormatArgs @('Version')))
@@ -137,7 +139,22 @@ function ConvertTo-NormalizedRegistryBackup {
}
else {
try {
$allowListValidationErrors = @(Test-RegistryBackupMatchesSelectedFeatures -SelectedFeatureIds @($selectedFeatures) -SelectedUndoFeatureIds @($selectedUndoFeatures) -Target $normalizedTarget -RegistryKeys @($normalizedKeys))
$planErrors = New-Object System.Collections.Generic.List[string]
$planMap = Get-RegistryBackupValidationPlanMap -SelectedFeatureIds @($selectedFeatures) -SelectedUndoFeatureIds @($selectedUndoFeatures) -Target $normalizedTarget -Errors $planErrors
foreach ($planError in $planErrors) {
$errors.Add($planError)
}
if ($planErrors.Count -eq 0) {
$normalizedKeys = @(ConvertTo-CompatibleRegistryKeySnapshots -RegistryKeys @($normalizedKeys) -PlanMap $planMap)
$allowListValidationErrors = @(Test-RegistryBackupAgainstAllowList -RegistryKeys @($normalizedKeys) -PlanMap $planMap -ExecutableValueWarnings $executableValueWarnings)
if ($allowListValidationErrors.Count -eq 0) {
Test-RegistryBackupSnapshotsCanBeRestored -RegistryKeys @($normalizedKeys)
}
}
else {
$allowListValidationErrors = @()
}
foreach ($allowListValidationError in $allowListValidationErrors) {
$errors.Add([string]$allowListValidationError)
}
@@ -167,6 +184,7 @@ function ConvertTo-NormalizedRegistryBackup {
SelectedFeatures = @($selectedFeatures)
SelectedUndoFeatures = @($selectedUndoFeatures)
RegistryKeys = @($normalizedKeys)
ExecutableValueWarnings = @($executableValueWarnings.ToArray())
}
}
@@ -182,6 +200,10 @@ function ConvertTo-NormalizedRegistryBackup {
A normalized backup object (as produced by ConvertTo-NormalizedRegistryBackup) whose
RegistryKeys snapshots should be restored.
.PARAMETER ConfirmUntrustedValues
Receives the freshly validated executable mismatches before registry writes or hive
loading. Must return Boolean true after user confirmation; otherwise restore is canceled.
.OUTPUTS
PSCustomObject
Returns an object with a Result property set to $true when the restore
@@ -190,9 +212,13 @@ function ConvertTo-NormalizedRegistryBackup {
function Restore-RegistryBackupState {
param(
[Parameter(Mandatory)]
$Backup
$Backup,
# Return Boolean true only after the user explicitly accepts the displayed mismatches.
[scriptblock]$ConfirmUntrustedValues
)
# Recompute warnings and blocking validation; backup-provided flags cannot authorize restoration.
$Backup = ConvertTo-NormalizedRegistryBackup -Backup $Backup
$friendlyTarget = Get-FriendlyRegistryBackupTarget -Target ([string]$Backup.Target)
if ($script:Params.ContainsKey("WhatIf")) {
@@ -200,6 +226,23 @@ function Restore-RegistryBackupState {
return [PSCustomObject]@{ Result = $true }
}
if (@($Backup.ExecutableValueWarnings).Count -gt 0) {
Write-Host "Registry restore for $friendlyTarget requires confirmation of $(@($Backup.ExecutableValueWarnings).Count) unrecognized executable setting(s)." -ForegroundColor Yellow
foreach ($mismatch in $Backup.ExecutableValueWarnings) {
Write-Host "Unrecognized executable registry setting: $($mismatch | ConvertTo-Json -Compress -Depth 10)"
}
if (-not $ConfirmUntrustedValues) {
Write-Host 'Registry restore blocked: executable settings require explicit user confirmation.'
throw (Get-Translation -Key 'BackupExecutableConfirmationRequired')
}
$approved = & $ConfirmUntrustedValues $Backup.ExecutableValueWarnings
if ($approved -isnot [bool] -or -not $approved) {
Write-Host 'Registry restore canceled: user did not approve the unrecognized executable settings.'
return [PSCustomObject]@{ Result = $false }
}
Write-Host 'User approved restoring the unrecognized executable settings.'
}
$restoreAction = {
param($normalizedBackup)
+14 -2
View File
@@ -31,7 +31,10 @@ function Show-MessageBox {
[System.Windows.Window]$Owner = $null,
[Parameter(Mandatory=$false)]
[int]$Width = 0
[int]$Width = 0,
[ValidateSet('OK', 'Cancel', 'Yes', 'No')]
[string]$DefaultResult
)
Add-Type -AssemblyName PresentationFramework,PresentationCore,WindowsBase | Out-Null
@@ -91,7 +94,8 @@ function Show-MessageBox {
default { [System.Windows.MessageBoxImage]::None }
}
$nativeResult = [System.Windows.MessageBox]::Show($Message, $Title, $nativeButton, $nativeIcon)
$nativeDefault = if ($DefaultResult) { [System.Windows.MessageBoxResult]::$DefaultResult } else { [System.Windows.MessageBoxResult]::None }
$nativeResult = [System.Windows.MessageBox]::Show($Message, $Title, $nativeButton, $nativeIcon, $nativeDefault)
return [string]$nativeResult
}
$reader = [System.Xml.XmlReader]::Create([System.IO.StringReader]::new($xaml))
@@ -187,6 +191,14 @@ function Show-MessageBox {
}
}
if ($DefaultResult) {
$useSecondButton = $DefaultResult -in @('Cancel', 'No')
$button1.IsDefault = -not $useSecondButton
$button2.IsDefault = $useSecondButton
$defaultButton = if ($useSecondButton) { $button2 } else { $button1 }
$msgWindow.Add_ContentRendered({ $null = $defaultButton.Focus() })
}
# Title bar drag to move window
$titleBar.Add_MouseLeftButtonDown({
$msgWindow.DragMove()
+1
View File
@@ -331,6 +331,7 @@ function Show-RestoreBackupDialog {
}
}
catch {
Write-Error "Failed to load registry backup '$($openDialog.FileName)': $($_.Exception.Message)" -ErrorAction Continue
Show-MessageBox -Owner $window -Title (Get-Translation -Key 'RestoreInvalidBackupTitle') -Message (Get-Translation -Key 'RestoreInvalidBackupMessage' -FormatArgs @($_.Exception.Message)) -Button 'OK' -Icon 'Error' | Out-Null
return
}
+10 -1
View File
@@ -31,7 +31,16 @@ function Show-RestoreBackupWindow {
}
Write-Host "User confirmed registry restore for $($backup.Target)."
$restoreOpResult = Restore-RegistryBackupState -Backup $backup
$confirmUntrustedValues = {
param($mismatches)
$details = @($mismatches | ForEach-Object {
$valueName = if ([string]::IsNullOrEmpty($_.Name)) { '(Default)' } else { $_.Name }
Get-Translation -Key 'BackupExecutableMismatchDetails' -FormatArgs @($_.Path, $valueName, $_.Kind, ($_.Data | ConvertTo-Json -Compress -Depth 10))
}) -join "`n`n"
$message = Get-Translation -Key 'BackupExecutableWarningMessage' -FormatArgs @($details)
return (Show-MessageBox -Owner $Owner -Title (Get-Translation -Key 'BackupExecutableWarningTitle') -Message $message -Button 'OKCancel' -Icon 'Warning' -DefaultResult 'Cancel' -Width 700) -eq 'OK'
}
$restoreOpResult = Restore-RegistryBackupState -Backup $backup -ConfirmUntrustedValues $confirmUntrustedValues
if ($restoreOpResult -and $restoreOpResult.Result) {
$restoreResult.RestoredRegistry = $true
if ($script:Params.ContainsKey("WhatIf")) {
+43
View File
@@ -104,6 +104,49 @@ function Remove-RegistrySubKeyTreeIfExists {
}
}
<#
.SYNOPSIS
Calls Windows' empty-only registry deletion API.
#>
function Invoke-RegistryEmptyKeyDeletion {
param($RootKey, [string]$SubKeyPath)
if (-not ('Win11Debloat.RegistryEmptyKey' -as [type])) {
Add-Type -Namespace Win11Debloat -Name RegistryEmptyKey -MemberDefinition @'
[System.Runtime.InteropServices.DllImport("shlwapi.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode, ExactSpelling = true)]
public static extern int SHDeleteEmptyKeyW(Microsoft.Win32.SafeHandles.SafeRegistryHandle hkey, string subKey);
'@
}
return [Win11Debloat.RegistryEmptyKey]::SHDeleteEmptyKeyW($RootKey.Handle, $SubKeyPath)
}
<#
.SYNOPSIS
Removes an empty key, retaining keys containing values or subkeys.
#>
function Remove-RegistryEmptyKeyIfExists {
param(
[Parameter(Mandatory)]$RootKey,
[Parameter(Mandatory)][string]$SubKeyPath
)
$status = Invoke-RegistryEmptyKeyDeletion -RootKey $RootKey -SubKeyPath $SubKeyPath
# Success, file not found, and path not found all satisfy cleanup.
if ($status -in @(0, 2, 3)) { return }
# A concurrent writer may have populated the key after the restore's initial check.
$key = $RootKey.OpenSubKey($SubKeyPath, $false)
if ($null -eq $key) { return }
try {
if (@($key.GetValueNames()).Count -gt 0 -or @($key.GetSubKeyNames()).Count -gt 0) { return }
}
finally {
$key.Close()
}
throw (New-Object System.ComponentModel.Win32Exception -ArgumentList ([int]$status))
}
<#
.SYNOPSIS
Returns a feature's registry-file path, using the Sysprep layout when targeting another profile.