Private/Backup/Restore-ACLOperation.ps1
|
#region Restore-ACLOperation.ps1 - Core ACL Restoration Module function Set-ObjectACL { <# .SYNOPSIS Applies ACL settings to Active Directory objects from validated backup data. .DESCRIPTION Core function for applying Access Control Lists to Active Directory objects using validated backup data. Handles proper security descriptor conversion, application, and verification of successful ACL restoration. This function performs the actual ACL modification operations and should only be called with backup data that Test-BackupIntegrity has validated. It does not check the target. Restore-IndividualObject, its caller, runs Get-RestorationTarget first, so that a restore reads the object once. A target that does not exist fails in the write, and the result then has Success False and the message of the directory. .PARAMETER TargetObjectDN Distinguished name of the target Active Directory object for ACL application. The caller has checked that the object exists and that its ACL can be read. .PARAMETER BackupData Validated backup data containing SDDL and metadata for restoration. Must be validated using Test-BackupIntegrity before use. .PARAMETER VerifyApplication Whether to verify successful ACL application after setting. Recommended for critical operations requiring confirmation. .PARAMETER WhatIf Shows what ACL changes would be applied without making modifications. Useful for validation and approval workflows. .PARAMETER CorrelationId Unique identifier for tracking this ACL operation across logs. .EXAMPLE PS> Set-ObjectACL -TargetObjectDN "CN=TestUser,CN=Users,DC=contoso,DC=com" -BackupData $validatedBackup DESCRIPTION: Applies ACL from validated backup to target user object OUTPUT: ACLOperationResult with success status and details USE CASE: Direct ACL restoration for specific object .EXAMPLE PS> Set-ObjectACL -TargetObjectDN $dn -BackupData $backup -VerifyApplication -WhatIf DESCRIPTION: Preview ACL application with verification enabled OUTPUT: Shows what would be applied and verification results USE CASE: Pre-validation for critical ACL changes .INPUTS [string] TargetObjectDN from pipeline [PSCustomObject] Validated backup data .OUTPUTS [PSCustomObject] ACLOperationResult with properties: - Success: Boolean indicating operation success - TargetObjectDN: DN of the modified object - ModificationsApplied: Number of ACL entries applied - VerificationResult: Optional verification outcome - Duration: Time taken for the operation - CorrelationId: Tracking identifier .NOTES Author: Jeffrey Stuhr Blog: https://www.techbyjeff.net LinkedIn: https://www.linkedin.com/in/jeffrey-stuhr-034214aa/ SECURITY CONSIDERATIONS: - Requires Modify Permissions permission on target object - Validates SDDL format before application TROUBLESHOOTING: - For permission errors: .\Troubleshooting\Common\Backup-Restore-Issues.md .LINK .\Troubleshooting\Common\Backup-Restore-Issues.md .\Troubleshooting\Common\Backup-Restore-Issues.md #> [CmdletBinding(SupportsShouldProcess)] [OutputType('ACLOperationResult')] param( [Parameter(Mandatory, ValueFromPipeline)] [ValidateNotNullOrEmpty()] [string]$TargetObjectDN, [Parameter(Mandatory)] [ValidateNotNull()] [PSCustomObject]$BackupData, [Parameter()] [switch]$VerifyApplication, [Parameter()] [string]$CorrelationId = [System.Guid]::NewGuid().ToString() ) begin { Write-Verbose "Starting ACL application operations - CorrelationId: $CorrelationId" # Validate backup data has required properties $requiredProperties = @('SDDL', 'ObjectDN', 'ValidationSignature') foreach ($prop in $requiredProperties) { if (-not $BackupData.PSObject.Properties[$prop]) { $exception = [System.IO.InvalidDataException]::new("Backup data missing required property: $prop") $category = [System.Management.Automation.ErrorCategory]::InvalidData $errorRecord = [System.Management.Automation.ErrorRecord]::new( $exception, 'BackupDataPropertyMissing', $category, $prop) $PSCmdlet.ThrowTerminatingError($errorRecord) } } } process { $startTime = Get-Date # The target is not checked here: Restore-IndividualObject, the caller, has just run # Get-RestorationTarget, which is a Get-ADObject and a Get-Acl against the domain # controller (#160). Write-Verbose "Applying ACL to object: $TargetObjectDN - CorrelationId: $CorrelationId" try { # Prepare SDDL for application $sddlToApply = $BackupData.SDDL $modificationsCount = 0 if ($PSCmdlet.ShouldProcess($TargetObjectDN, "Apply ACL from backup")) { try { # Create security descriptor from SDDL $securityDescriptor = [System.DirectoryServices.ActiveDirectorySecurity]::new() $securityDescriptor.SetSecurityDescriptorSddlForm($sddlToApply) # Apply ACL to Active Directory object Set-DirectoryObjectAcl -DistinguishedName $TargetObjectDN -AclObject $securityDescriptor # Count ACE entries for reporting. @(): a descriptor with one entry gives one # string, which has no Count under strict mode. The error came after the # write, so a restore that was applied was reported as failed. $modificationsCount = @($sddlToApply -split '\(' | Where-Object { $_ -like '*;*' }).Count Write-Verbose "ACL applied successfully to $TargetObjectDN ($modificationsCount modifications) - CorrelationId: $CorrelationId" $success = $true $errorMessage = $null } catch { $success = $false # The text of the error as the write gave it. A replace that was meant to # take a password out of it matched the word followed by digits, which is # the form of a name: an object called Password1 lost its name in this # message. The module passes no password to the directory, so the error # of a write has none to take out (#216). $errorMessage = "ACL application failed: $($_.Exception.Message)" Write-Error $errorMessage } } else { # WhatIf mode - simulate the operation $success = $true $errorMessage = $null $modificationsCount = @($sddlToApply -split '\(' | Where-Object { $_ -like '*;*' }).Count Write-Verbose "WhatIf: Would apply ACL with $modificationsCount modifications to $TargetObjectDN" } # Perform verification if requested and operation succeeded $verificationResult = $null if ($success -and $VerifyApplication -and -not $WhatIfPreference) { $verificationResult = Confirm-RestorationSuccess -TargetObjectDN $TargetObjectDN -ExpectedData $BackupData -CorrelationId $CorrelationId } $duration = (Get-Date) - $startTime $result = [PSCustomObject]@{ PSTypeName = 'ACLOperationResult' Success = $success TargetObjectDN = $TargetObjectDN ModificationsApplied = $modificationsCount VerificationResult = $verificationResult Duration = $duration ErrorMessage = $errorMessage WhatIfMode = $WhatIfPreference CorrelationId = $CorrelationId CompletedAt = Get-Date } Write-Verbose "ACL operation completed - Success: $success - Duration: $($duration.TotalMilliseconds)ms - CorrelationId: $CorrelationId" return $result } catch { $errorResult = [PSCustomObject]@{ PSTypeName = 'ACLOperationResult' Success = $false TargetObjectDN = $TargetObjectDN ModificationsApplied = 0 VerificationResult = $null Duration = (Get-Date) - $startTime ErrorMessage = "ACL operation failed: $($_.Exception.Message)" WhatIfMode = $WhatIfPreference CorrelationId = $CorrelationId CompletedAt = Get-Date } Write-Error "ACL operation failed for $TargetObjectDN : $($_.Exception.Message) - CorrelationId: $CorrelationId" return $errorResult } } end { Write-Verbose "Completed ACL application operations - CorrelationId: $CorrelationId" } } function Get-RestorationTarget { <# .SYNOPSIS Validates and prepares target object for ACL restoration. .DESCRIPTION Performs comprehensive validation of target Active Directory objects before ACL restoration operations: the DN is well formed, the object exists, and its current ACL can be read. Write access is not probed. Rewriting a security descriptor needs WRITE_DAC, which no attribute read can show, and Set-Acl reports a permission failure itself when the restore is applied. The object is read with Get-ADObject, so the ActiveDirectory module must be loaded. .PARAMETER TargetObjectDN Distinguished name of the target object to validate. .PARAMETER CorrelationId Unique identifier for tracking this validation operation. .EXAMPLE PS> Get-RestorationTarget -TargetObjectDN "CN=TestUser,CN=Users,DC=contoso,DC=com" Validates target object for restoration readiness. .OUTPUTS [PSCustomObject] TargetValidationResult #> [CmdletBinding()] [OutputType('TargetValidationResult')] param( [Parameter(Mandatory, ValueFromPipeline)] [ValidateNotNullOrEmpty()] [string]$TargetObjectDN, [Parameter()] [string]$CorrelationId = [System.Guid]::NewGuid().ToString() ) process { try { $issues = @() # The attribute that names an object is set by its class, so any attribute name is # taken, as Test-ValidDistinguishedName does. Whether the object exists is settled # by the lookup below. if (-not ($TargetObjectDN -match '^([a-z][a-z0-9.-]*|\d+(\.\d+)+)=.+')) { $issues += "Invalid DN format: $TargetObjectDN" } # Check if object exists $objectExists = $false $objectType = $null try { $adObject = Get-ADObject -Identity $TargetObjectDN -Properties objectClass -ErrorAction Stop $objectExists = $true # ObjectClass is a single string from the AD module and the class chain from LDAP; # @()[-1] is the most specific class either way, never the last character $objectType = @($adObject.ObjectClass)[-1] Write-Verbose "Target object exists: $TargetObjectDN (Type: $objectType)" } catch { $issues += "Target object not found or inaccessible: $($_.Exception.Message)" } # Check ACL read permissions if object exists $aclReadable = $null if ($objectExists) { try { $null = Get-DirectoryObjectAcl -DistinguishedName $TargetObjectDN $aclReadable = $true Write-Verbose "ACL is readable for target object: $TargetObjectDN" } catch { $aclReadable = $false $issues += "Cannot read current ACL: $($_.Exception.Message)" } } return [PSCustomObject]@{ PSTypeName = 'TargetValidationResult' IsValid = $issues.Count -eq 0 TargetObjectDN = $TargetObjectDN ObjectExists = $objectExists ObjectType = $objectType ACLReadable = $aclReadable Issues = $issues CorrelationId = $CorrelationId ValidatedAt = Get-Date } } catch { return [PSCustomObject]@{ PSTypeName = 'TargetValidationResult' IsValid = $false TargetObjectDN = $TargetObjectDN ObjectExists = $false ObjectType = $null ACLReadable = $false Issues = @("Validation error: $($_.Exception.Message)") CorrelationId = $CorrelationId ValidatedAt = Get-Date } } } } function Confirm-RestorationSuccess { <# .SYNOPSIS Verifies successful ACL restoration by comparing applied vs expected permissions. .DESCRIPTION Performs post-restoration verification by reading the current ACL from the target object and comparing it with the expected backup data. Provides detailed analysis of restoration success and any discrepancies. NOTE: Verification failures are often expected and normal behavior. See troubleshooting documentation for interpreting verification results. .PARAMETER TargetObjectDN Distinguished name of the object to verify. .PARAMETER ExpectedData Backup data containing the expected ACL configuration. .PARAMETER ToleranceLevel Level of tolerance for verification differences: Strict, Standard, or Permissive. .PARAMETER CorrelationId Unique identifier for tracking this verification operation. .EXAMPLE PS> Confirm-RestorationSuccess -TargetObjectDN $dn -ExpectedData $backup Verifies restoration with standard tolerance for normal environment changes. .OUTPUTS [PSCustomObject] RestorationVerificationResult #> [CmdletBinding()] [OutputType('RestorationVerificationResult')] param( [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string]$TargetObjectDN, [Parameter(Mandatory)] [ValidateNotNull()] [PSCustomObject]$ExpectedData, [Parameter()] [ValidateSet('Strict', 'Standard', 'Permissive')] [string]$ToleranceLevel = 'Standard', [Parameter()] [string]$CorrelationId = [System.Guid]::NewGuid().ToString() ) process { try { Write-Verbose "Starting restoration verification for $TargetObjectDN - CorrelationId: $CorrelationId" # Read current ACL from target object $currentAcl = $null $currentSddl = $null try { $currentAcl = Get-DirectoryObjectAcl -DistinguishedName $TargetObjectDN $currentSddl = $currentAcl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.AccessControlSections]::All) } catch { return [PSCustomObject]@{ PSTypeName = 'RestorationVerificationResult' IsVerified = $false TargetObjectDN = $TargetObjectDN VerificationIssues = @("Failed to read current ACL: $($_.Exception.Message)") ExpectedEntries = 0 ActualEntries = 0 MatchedEntries = 0 CorrelationId = $CorrelationId } } # Parse ACE entries for comparison $expectedAces = @() $actualAces = @() # Extract ACEs from expected SDDL if ($ExpectedData.SDDL) { $expectedAces = @($ExpectedData.SDDL -split '\(' | Where-Object { $_ -like '*;*' } | ForEach-Object { "($_" }) } # Extract ACEs from current SDDL if ($currentSddl) { $actualAces = @($currentSddl -split '\(' | Where-Object { $_ -like '*;*' } | ForEach-Object { "($_" }) } # Compare ACE entries $matchedCount = 0 $verificationIssues = @() # Count matches (basic comparison for now) foreach ($expectedAce in $expectedAces) { if ($actualAces -contains $expectedAce) { $matchedCount++ } } # Determine verification success based on tolerance level $isVerified = $false $toleranceThreshold = switch ($ToleranceLevel) { 'Strict' { 1.0 } # 100% match required 'Standard' { 0.8 } # 80% match acceptable 'Permissive' { 0.6 } # 60% match acceptable } if ($expectedAces.Count -gt 0) { $matchPercentage = $matchedCount / $expectedAces.Count $isVerified = $matchPercentage -ge $toleranceThreshold } else { $isVerified = $actualAces.Count -eq 0 } # Generate verification issues if (-not $isVerified) { $verificationIssues += "Verification failed with $ToleranceLevel tolerance" $verificationIssues += "Expected $($expectedAces.Count) entries, found $($actualAces.Count), matched $matchedCount" if (($expectedAces.Count - $actualAces.Count) -gt 3) { $verificationIssues += "Significant entry count difference detected" } } # Note: This is expected behavior - see troubleshooting documentation if ($verificationIssues.Count -gt 0) { Write-Verbose "Verification differences detected (this is often normal): $($verificationIssues -join '; ') - CorrelationId: $CorrelationId" } return [PSCustomObject]@{ PSTypeName = 'RestorationVerificationResult' IsVerified = $isVerified TargetObjectDN = $TargetObjectDN ToleranceLevel = $ToleranceLevel VerificationIssues = $verificationIssues ExpectedEntries = $expectedAces.Count ActualEntries = $actualAces.Count MatchedEntries = $matchedCount MatchPercentage = if ($expectedAces.Count -gt 0) { [math]::Round(($matchedCount / $expectedAces.Count) * 100, 1) } else { 0 } CorrelationId = $CorrelationId VerifiedAt = Get-Date } } catch { return [PSCustomObject]@{ PSTypeName = 'RestorationVerificationResult' IsVerified = $false TargetObjectDN = $TargetObjectDN ToleranceLevel = $ToleranceLevel VerificationIssues = @("Verification error: $($_.Exception.Message)") ExpectedEntries = 0 ActualEntries = 0 MatchedEntries = 0 MatchPercentage = 0 CorrelationId = $CorrelationId VerifiedAt = Get-Date } } } } #endregion |