The reason I’d trust OrphanedSid in someone else’s domain is the backup. The first post walks through it: before Remove-OrphanedSid touches an object, it writes the object’s full security descriptor to a Clixml file with a hash, and Restore-OrphanedSidBackup puts it back. If I removed the wrong thing, I can undo it.

Through 1.0.1, that held for the case the lab seeds, one orphaned SID per object. Past that, the backups had gaps.

With this being a detect and removal, I wanted to be able to restore if someone removed things incorrectly. Handed off to a lower tier admin, or automated in a changing environment, etc.

One backup per SID

The removal loop called Remove-OrphanedSidEntry once for every orphaned result, and every call made its own backup first:

1
2
3
4
5
$removalParams = @{
    ObjectDN = $orphanedResult.ObjectDN
    OrphanedSIDs = @($orphanedResult.OrphanedSID)
    CorrelationId = $CorrelationId
}

For an object with two orphaned SIDs, the first call backed up the ACL and removed the first SID. The second call backed up the ACL again, now missing the first SID, and removed the second. Restore uses the newest backup for each object, so it could only bring back the second.

I gave a group on the lab DC orphaned entries for RIDs 91001 and 91002, and it got two backups 1.2 seconds apart. The first held both SIDs. The second held only 91002. After Restore-OrphanedSidBackup -Force, the group had 91002 back and 91001 gone for good.

It could be worse than that. Backup files are named <DN>_<yyyyMMdd_HHmmss>.xml, so two backups of one object in the same second got the same name, and Export-Clixml -Force overwrote the first one. If you were unlucky with the timing, the only complete backup was the one that got replaced.

Remove-OrphanedSidEntry already took an array of SIDs. It just never got more than one. 1.1.0 collects an object’s verified orphaned SIDs and makes one call:

1
2
3
4
5
$sidsToRemove = @($verifiedResults | Where-Object { -not $_.IsInherited } | ForEach-Object { $_.OrphanedSID } | Select-Object -Unique)
if ($sidsToRemove.Count -gt 0) {
    $objectDN = $currentObject.DistinguishedName
    $sidList = $sidsToRemove -join ', '
    $target = "$objectDN - SIDs: $sidList"

Each object now gets one backup, one confirmation and one result. The same group on the DC, with the fix staged, gave one result with ActualRemovals = 2 and one backup file, and a restore brought both SIDs back.

New-ACLBackup also refuses to overwrite now. A second backup of the same object in the same second gets a counter:

1
2
3
4
5
6
7
# Never overwrite an earlier backup: a second backup of the same object in the same second
# gets a counter. The suffix space is kept free by the name budget above.
$sequence = 1
while (Test-Path -LiteralPath $backupFile) {
    $sequence++
    $backupFile = Join-Path $BackupPath "${safeName}_${timestamp}_$sequence.xml"
}

The 1.1.0 changelog lists the behavior changes that came with it. Remove-OrphanedSid returns one result per object instead of one per SID. And because the security check validates a call’s SIDs together, one blocked SID now leaves that object’s other orphaned SIDs in place too. That’s the conservative direction, and blocks are rare, since discovery already filters out protected and well-known SIDs.

Inherited entries on the wrong object

With -IncludeInherited, discovery reports orphaned entries an object inherits from its parent. Removal then tried to take them off the child, which can’t work: an inherited entry lives on the object that sets it. So on 1.0.x the child got backed up, nothing on it changed, and the result said this:

1
2
3
ActualRemovals = 1
Success        = False
Verification failed: 1 of 1 SIDs still present

The inherited entry stayed on the child and on its parent OU. In 1.1.0, removal leaves inherited-only SIDs out of the object’s call and says so:

1
Not removing inherited entry for orphaned SID <SID> on <DN>: it is inherited from a parent object, so remove it there

If nothing explicit is left on the object, it isn’t backed up or changed at all. The removal and verification steps both count explicit entries only, so an object that holds a SID both ways verifies once its explicit entry is gone. On the DC, an orphaned inheritable entry on a test OU and -IncludeInherited -Force on its child group gave no result, no backup, and the warning in the log.

The fix for that warning is a removal against the object’s parent, or against a search base that includes it.

A file name that didn’t fit

New-ACLBackup names each file after the object’s DN, sanitized. A long DN got cut at 200 characters with _truncated added, then the timestamp:

1
2
if ($safeName.Length -gt 200) {
    $safeName = $safeName.Substring(0, 200) + "_truncated"

A file name could run to 230 characters before you add the folder. Remove-OrphanedSid writes into <BackupPath>\<yyyyMMdd_HHmmss>\, and Windows PowerShell 5.1 runs on .NET Framework, which enforces the 260-character path limit unless long paths are turned on. A backup folder path longer than about 30 characters was enough to push a long DN past it.

The backup comes before every removal, so when it fails, that object’s orphaned entries don’t get removed at all. Deeply nested OUs reach 200-character DNs in real directories. A unit test found this first: “Truncates a very long DN in the filename” passed on the GitHub runner and failed under 5.1 on a machine with a longer temp path. It was one of the failures the test cleanup kept and filed.

The name is now sized against the full path length:

1
2
3
4
5
6
# The whole path must stay under the 260-character Windows limit, which .NET Framework
# enforces on Windows PowerShell 5.1: folder, separator, name and "_yyyyMMdd_HHmmss.xml".
# The object's DN is recorded inside the backup, so the name only has to be unique.
$maxPathLength = 259
# Room for the timestamp and a same-second counter (_2 to _99) added below
$suffixLength = '_yyyyMMdd_HHmmss_99.xml'.Length

A shortened name ends in the first eight hex characters of a SHA256 of the full DN, so two long DNs that share a prefix can’t collide in the same second. A folder too long to hold any backup file is refused up front with a message saying so, before anything is removed.

Since 1.0.1, restore matches on the ObjectDN recorded inside each backup, so a shortened name doesn’t change what gets restored.

Checks that should have refused a backup

A restore validates the backup before applying it. A case-insensitive hash comparison and a check that skipped empty values both let through backups they should’ve refused.

The SDDL hash is stored as Base64, and Base64 is case-sensitive. The comparison used -ne, which isn’t:

1
2
'Ab3+' -ne 'aB3+'    # False: PowerShell says they match
'Ab3+' -cne 'aB3+'   # True

A hash that differed from the computed one only in letter case passed the integrity check. Both comparisons use -cne now.

The empty-value gap was in two places. The hash and SDDL tests ran only when both properties had values, and the required-property check only looked for the property names. A backup with an empty SDDL and an empty SDDLHash passed Standard validation. The restore still failed later, when it tried to build an ACL from an empty SDDL, so the object’s ACL stayed as it was. But anything that trusted the validation result was told an empty backup was fine. An empty required property fails validation at every level now.

A permissions check that only read

Before a restore, Get-RestorationTarget reported whether you could write the object’s security descriptor. It found out by opening the object over LDAP and reading nTSecurityDescriptor. Reading it shows read access. An account that could read the descriptor and couldn’t change it passed the check and then failed at Set-Acl.

Reading nTSecurityDescriptor can’t tell you whether you have WRITE_DAC, the right a restore needs. Set-Acl already fails with the real permission error when you don’t, and the restore reports it. The probe and its WritePermissions property are gone.

Removing it had a side benefit. The probe built a [System.DirectoryServices.DirectoryEntry] directly. Pester can’t mock that, so the integration test had to replace Get-RestorationTarget to get a restore to run at all. With the probe gone, the integration test runs a restore end to end with every function in the module running for real.

The same function had one more bug. When the AD module returned ObjectClass as a single string, it took the last element with [-1], and [-1] on a string is its last character. A user object came out as r. Indexing a string where an array was expected has turned up more than once in this series.