From 5b72bdae4dae647c7dc2c86a6c0ca01693972008 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 06:23:26 +0000 Subject: [PATCH 001/100] fix(ad): preserve collection evidence and expand directory metadata --- .../ad/protocol/ConvertFrom-MtLdapValue.ps1 | 4 +-- .../ad/queries/Get-MtLdapComputer.ps1 | 8 ++++-- .../Get-MtLdapConfigurationContainer.ps1 | 18 +++++++++--- .../ad/queries/Get-MtLdapOptionalFeature.ps1 | 2 +- .../ad/queries/Get-MtLdapSchemaObject.ps1 | 4 +-- .../ad/queries/Get-MtLdapServiceAccount.ps1 | 6 ++-- .../services/ad/queries/Get-MtLdapUser.ps1 | 3 +- .../ad/transport/Get-MtSysvolContent.ps1 | 4 ++- .../services/ad/Get-MtADDomainState.ps1 | 8 +++++- .../public/services/ad/Get-MtADGpoState.ps1 | 17 +++++++++-- .../transport/Get-MtSysvolContent.Tests.ps1 | 28 +++++++++++++++++++ 11 files changed, 82 insertions(+), 20 deletions(-) diff --git a/powershell/internal/services/ad/protocol/ConvertFrom-MtLdapValue.ps1 b/powershell/internal/services/ad/protocol/ConvertFrom-MtLdapValue.ps1 index 92192b89c0..3384d6305f 100644 --- a/powershell/internal/services/ad/protocol/ConvertFrom-MtLdapValue.ps1 +++ b/powershell/internal/services/ad/protocol/ConvertFrom-MtLdapValue.ps1 @@ -162,7 +162,7 @@ if ($Value -is [byte[]]) { switch ($normalizedAttributeName) { - { $_ -in @('objectsid', 'sidhistory', 'securityidentifier') } { + { $_ -in @('objectsid', 'sidhistory', 'securityidentifier', 'ms-ds-creatorsid') } { try { return New-Object System.Security.Principal.SecurityIdentifier -ArgumentList $Value, 0 } @@ -206,7 +206,7 @@ } if ($Value -is [System.Security.Principal.SecurityIdentifier]) { - if ($normalizedAttributeName -in @('objectsid', 'sidhistory', 'securityidentifier')) { + if ($normalizedAttributeName -in @('objectsid', 'sidhistory', 'securityidentifier', 'ms-ds-creatorsid')) { return $Value } diff --git a/powershell/internal/services/ad/queries/Get-MtLdapComputer.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapComputer.ps1 index 8b6b46a2e3..4fb591401f 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapComputer.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapComputer.ps1 @@ -9,8 +9,9 @@ ) if ([string]::IsNullOrWhiteSpace($SearchBase)) { $SearchBase = (Get-MtLdapRootDse -Connection $Connection).DefaultNamingContext } - $attributes = @('distinguishedName', 'name', 'sAMAccountName', 'userAccountControl', 'operatingSystem', 'operatingSystemVersion', 'dNSHostName', 'whenCreated', 'whenChanged', 'lastLogonTimestamp', 'pwdLastSet', 'servicePrincipalName', 'primaryGroupID', 'objectSid', 'isCriticalSystemObject', 'managedBy', 'sIDHistory') - $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter '(objectClass=computer)' -Attributes $attributes) + $attributes = @('distinguishedName', 'name', 'sAMAccountName', 'userAccountControl', 'operatingSystem', 'operatingSystemVersion', 'dNSHostName', 'whenCreated', 'whenChanged', 'lastLogonTimestamp', 'pwdLastSet', 'servicePrincipalName', 'primaryGroupID', 'objectSid', 'isCriticalSystemObject', 'managedBy', 'sIDHistory', 'msDS-AllowedToDelegateTo', 'msDS-AllowedToActOnBehalfOfOtherIdentity', 'mS-DS-CreatorSID') + # Managed service accounts derive from computer but are not workstation/server inventory. + $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter '(&(objectClass=computer)(!(|(objectClass=msDS-ManagedServiceAccount)(objectClass=msDS-GroupManagedServiceAccount)(objectClass=msDS-DelegatedManagedServiceAccount))))' -Attributes $attributes) return @($entries | ForEach-Object { $uac = if ($null -ne $_.userAccountControl) { ConvertFrom-MtLdapUserAccountControl -UserAccountControl ([int]$_.userAccountControl) } else { $null } [PSCustomObject]@{ @@ -20,6 +21,9 @@ PasswordLastSet = $_.pwdLastSet; PasswordExpired = if ($null -ne $uac) { $uac.PasswordExpired } else { $null }; PasswordNeverExpires = if ($null -ne $uac) { $uac.DontExpirePassword } else { $null } PasswordNotRequired = if ($null -ne $uac) { $uac.PasswordNotRequired } else { $null }; TrustedForDelegation = if ($null -ne $uac) { $uac.TrustedForDelegation } else { $null } TrustedToAuthForDelegation = if ($null -ne $uac) { $uac.TrustedToAuthForDelegation } else { $null }; ServicePrincipalName = [string[]]@($_.servicePrincipalName | Where-Object { $null -ne $_ }) + AllowedToDelegateTo = [string[]]@($_.'msDS-AllowedToDelegateTo' | Where-Object { $null -ne $_ }) + HasResourceBasedConstrainedDelegation = $null -ne $_.'msDS-AllowedToActOnBehalfOfOtherIdentity' + CreatorSid = $_.'mS-DS-CreatorSID' PrimaryGroupId = $_.primaryGroupID; Sid = $_.objectSid; UserAccountControl = [int]$_.userAccountControl IsCriticalSystemObject = if ($null -ne $_.isCriticalSystemObject) { [bool]$_.isCriticalSystemObject } else { $null }; ManagedBy = [string]$_.managedBy; SidHistory = @($_.sIDHistory | Where-Object { $null -ne $_ }) } diff --git a/powershell/internal/services/ad/queries/Get-MtLdapConfigurationContainer.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapConfigurationContainer.ps1 index ef341ea54b..710e8b156f 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapConfigurationContainer.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapConfigurationContainer.ps1 @@ -58,7 +58,16 @@ $_ }) - $dhcp = Invoke-ConfigurationSearchSafe -RelativeSearchBase 'CN=NetServices,CN=Services' -Scope OneLevel -Filter '(|(objectClass=dhcpClass)(objectClass=dhcpServer)(objectClass=serviceConnectionPoint))' -Attributes ($commonAttributes + @('serviceBindingInformation', 'keywords')) + $dhcpObjects = Invoke-ConfigurationSearchSafe -RelativeSearchBase 'CN=NetServices,CN=Services' -Scope OneLevel -Filter '(objectClass=dhcpClass)' -Attributes ($commonAttributes + @('dhcpServers')) + # MS-DHCPE: authorization entries are dhcpServers values, not one server per object. + $dhcp = @(foreach ($registration in @($dhcpObjects | ForEach-Object { $_.dhcpServers } | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) } | Sort-Object -Unique)) { + $match = [regex]::Match([string]$registration, '^i(?[^$]+)\$rcn=(?[^$]*)\$f(?[^$]*)\$s(?[^$]*)\$$', [System.Text.RegularExpressions.RegexOptions]::IgnoreCase) + [pscustomobject]@{ + DnsName = if ($match.Success) { $match.Groups['server'].Value } else { 'Unknown (unrecognized registration format)' } + IPAddress = if ($match.Success) { $match.Groups['ip'].Value } else { $null } + RegistrationParsed = $match.Success + } + }) $authN = Invoke-ConfigurationSearchSafe -RelativeSearchBase 'CN=AuthN Policy Configuration,CN=Services' -Scope Subtree -Filter '(objectClass=*)' -Attributes ($commonAttributes + @('msDS-ServiceAllowedToAuthenticateFrom', 'msDS-ServiceAllowedToAuthenticateTo')) @@ -77,13 +86,13 @@ $policies = Invoke-ConfigurationSearchSafe -RelativeSearchBase 'CN=Query Policies,CN=Directory Service,CN=Windows NT,CN=Services' -Scope OneLevel -Filter '(objectClass=queryPolicy)' -Attributes ($commonAttributes + @('lDAPAdminLimits')) - $directoryService = Invoke-ConfigurationSearchSafe -RelativeSearchBase 'CN=Directory Service,CN=Windows NT,CN=Services' -Scope Base -Filter '(objectClass=nTDSService)' -Attributes @('tombstoneLifetime', 'dSHeuristics', 'sPNMappings') | Select-Object -First 1 + $directoryService = Invoke-ConfigurationSearchSafe -RelativeSearchBase 'CN=Directory Service,CN=Windows NT,CN=Services' -Scope Base -Filter '(objectClass=*)' -Attributes @('distinguishedName', 'tombstoneLifetime', 'dSHeuristics', 'sPNMappings') | Select-Object -First 1 # Use safe search so a NoSuchObject error (common when KDS has never been used) returns @() # rather than throwing and nulling the entire Configuration category $kds = Invoke-ConfigurationSearchSafe -RelativeSearchBase 'CN=Master Root Keys,CN=Group Key Distribution Service,CN=Services' -Scope OneLevel -Filter '(objectClass=msKds-ProvRootKey)' -Attributes ($commonAttributes + @('msKds-CreateTime', 'msKds-DomainID')) - $activation = Invoke-ConfigurationSearchSafe -RelativeSearchBase 'CN=Activation Objects,CN=Microsoft SPP,CN=Services' -Scope OneLevel -Filter '(|(objectClass=msImaging-PSP)(objectClass=serviceConnectionPoint))' -Attributes ($commonAttributes + @('keywords', 'serviceBindingInformation')) + $activation = Invoke-ConfigurationSearchSafe -RelativeSearchBase 'CN=Activation Objects,CN=Microsoft SPP,CN=Services' -Scope OneLevel -Filter '(objectClass=msSPP-ActivationObject)' -Attributes $commonAttributes $enrollmentTemplates = [string[]]@($enterprise | ForEach-Object { @($_.certificateTemplates) } | Sort-Object -Unique) @@ -92,8 +101,9 @@ TrustedRootCAs = @($trustedRoots); IntermediateCAs = @($intermediate); EnterpriseCAs = @($enterprise); CertificateTemplates = @($templates) EnrollmentTemplates = $enrollmentTemplates; CrlDistributionPoints = @($cdp); NtAuthCertificates = @($ntAuth); LdapQueryPolicies = @($policies) TombstoneLifetime = if ($null -ne $directoryService) { $directoryService.tombstoneLifetime } else { $null } + DirectoryServiceRetrieved = $null -ne $directoryService DsHeuristics = if ($null -ne $directoryService) { $directoryService.dSHeuristics } else { $null } - SpnMappings = if ($null -ne $directoryService) { @($directoryService.sPNMappings | Where-Object { $null -ne $_ }) } else { @() } + SpnMappings = if ($null -ne $directoryService) { @($directoryService.sPNMappings | Where-Object { $null -ne $_ }) } else { $null } KdsRootKeys = @($kds); ActivationObjects = @($activation) } } diff --git a/powershell/internal/services/ad/queries/Get-MtLdapOptionalFeature.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapOptionalFeature.ps1 index 647e45386f..232f4ff488 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapOptionalFeature.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapOptionalFeature.ps1 @@ -12,5 +12,5 @@ $searchBase = "CN=Optional Features,CN=Directory Service,CN=Windows NT,CN=Services,$ConfigurationNamingContext" $attributes = @('distinguishedName', 'name', 'msDS-OptionalFeatureGUID', 'msDS-EnabledFeatureBL', 'msDS-RequiredForestBehaviorVersion') $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $searchBase -Scope Subtree -Filter '(objectClass=msDS-OptionalFeature)' -Attributes $attributes) - return @($entries | ForEach-Object { [PSCustomObject]@{ Name = [string]$_.name; DistinguishedName = [string]$_.DistinguishedName; FeatureGUID = $_.'msDS-OptionalFeatureGUID'; IsEnabled = (@($_.'msDS-EnabledFeatureBL' | Where-Object { $null -ne $_ }).Count -gt 0); RequiredForestBehaviorVersion = $_.'msDS-RequiredForestBehaviorVersion' } }) + return @($entries | ForEach-Object { [PSCustomObject]@{ Name = [string]$_.name; DistinguishedName = [string]$_.DistinguishedName; FeatureGUID = $_.'msDS-OptionalFeatureGUID'; IsEnabled = (@($_.'msDS-EnabledFeatureBL' | Where-Object { $null -ne $_ }).Count -gt 0); EnabledScopes = [string[]]@($_.'msDS-EnabledFeatureBL' | Where-Object { $null -ne $_ }); RequiredForestBehaviorVersion = $_.'msDS-RequiredForestBehaviorVersion' } }) } diff --git a/powershell/internal/services/ad/queries/Get-MtLdapSchemaObject.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapSchemaObject.ps1 index 37b603f4c2..3fca785fea 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapSchemaObject.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapSchemaObject.ps1 @@ -9,6 +9,6 @@ [string] $SchemaNamingContext ) - $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SchemaNamingContext -Scope Subtree -Filter '(objectClass=*)' -Attributes @('distinguishedName', 'name', 'objectClass', 'whenCreated', 'objectVersion')) - return @($entries | ForEach-Object { [PSCustomObject]@{ DistinguishedName = [string]$_.DistinguishedName; Name = [string]$_.name; ObjectClass = @($_.objectClass | Where-Object { $null -ne $_ }); WhenCreated = $_.whenCreated; ObjectVersion = $_.objectVersion } }) + $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SchemaNamingContext -Scope Subtree -Filter '(objectClass=*)' -Attributes @('distinguishedName', 'name', 'lDAPDisplayName', 'objectClass', 'whenCreated', 'objectVersion')) + return @($entries | ForEach-Object { [PSCustomObject]@{ DistinguishedName = [string]$_.DistinguishedName; Name = [string]$_.name; LdapDisplayName = [string]$_.lDAPDisplayName; ObjectClass = @($_.objectClass | Where-Object { $null -ne $_ }); WhenCreated = $_.whenCreated; ObjectVersion = $_.objectVersion } }) } diff --git a/powershell/internal/services/ad/queries/Get-MtLdapServiceAccount.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapServiceAccount.ps1 index 4a60f57a4a..42a12bbe96 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapServiceAccount.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapServiceAccount.ps1 @@ -9,7 +9,7 @@ ) if ([string]::IsNullOrWhiteSpace($SearchBase)) { $SearchBase = (Get-MtLdapRootDse -Connection $Connection).DefaultNamingContext } - $attributes = @('distinguishedName', 'name', 'sAMAccountName', 'dNSHostName', 'whenCreated', 'whenChanged', 'objectSid') - $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter '(objectClass=msDS-GroupManagedServiceAccount)' -Attributes $attributes) - return @($entries | ForEach-Object { [PSCustomObject]@{ DistinguishedName = [string]$_.DistinguishedName; Name = [string]$_.name; SamAccountName = [string]$_.sAMAccountName; DnsHostName = [string]$_.dNSHostName; Created = $_.whenCreated; Modified = $_.whenChanged; Sid = $_.objectSid } }) + $attributes = @('distinguishedName', 'name', 'sAMAccountName', 'dNSHostName', 'whenCreated', 'whenChanged', 'objectSid', 'objectClass', 'msDS-DelegatedMSAState') + $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter '(|(objectClass=msDS-ManagedServiceAccount)(objectClass=msDS-GroupManagedServiceAccount)(objectClass=msDS-DelegatedManagedServiceAccount))' -Attributes $attributes) + return @($entries | ForEach-Object { [PSCustomObject]@{ DistinguishedName = [string]$_.DistinguishedName; Name = [string]$_.name; SamAccountName = [string]$_.sAMAccountName; DnsHostName = [string]$_.dNSHostName; Created = $_.whenCreated; Modified = $_.whenChanged; Sid = $_.objectSid; ObjectClass = @($_.objectClass); DelegatedMsaState = $_.'msDS-DelegatedMSAState' } }) } diff --git a/powershell/internal/services/ad/queries/Get-MtLdapUser.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapUser.ps1 index 4828b3735b..75090d437d 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapUser.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapUser.ps1 @@ -9,7 +9,7 @@ ) if ([string]::IsNullOrWhiteSpace($SearchBase)) { $SearchBase = (Get-MtLdapRootDse -Connection $Connection).DefaultNamingContext } - $attributes = @('distinguishedName', 'name', 'sAMAccountName', 'userAccountControl', 'adminCount', 'homeDirectory', 'badPasswordTime', 'lastLogonTimestamp', 'lockoutTime', 'logonHours', 'userWorkstations', 'managedBy', 'manager', 'pwdLastSet', 'profilePath', 'scriptPath', 'objectSid', 'sIDHistory', 'servicePrincipalName', 'whenCreated', 'whenChanged', 'isCriticalSystemObject') + $attributes = @('distinguishedName', 'name', 'sAMAccountName', 'userAccountControl', 'adminCount', 'homeDirectory', 'badPasswordTime', 'lastLogonTimestamp', 'lockoutTime', 'logonHours', 'userWorkstations', 'managedBy', 'manager', 'pwdLastSet', 'profilePath', 'scriptPath', 'objectSid', 'sIDHistory', 'servicePrincipalName', 'whenCreated', 'whenChanged', 'isCriticalSystemObject', 'primaryGroupID') $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter '(&(objectClass=user)(!(objectClass=computer)))' -Attributes $attributes) return @($entries | ForEach-Object { $uac = if ($null -ne $_.userAccountControl) { ConvertFrom-MtLdapUserAccountControl -UserAccountControl ([int]$_.userAccountControl) } else { $null } @@ -21,6 +21,7 @@ ManagedBy = [string]$_.managedBy; Manager = [string]$_.manager; PasswordExpired = if ($null -ne $uac) { $uac.PasswordExpired } else { $null }; PasswordLastSet = $_.pwdLastSet PasswordNeverExpires = if ($null -ne $uac) { $uac.DontExpirePassword } else { $null }; PasswordNotRequired = if ($null -ne $uac) { $uac.PasswordNotRequired } else { $null }; ProfilePath = [string]$_.profilePath ScriptPath = [string]$_.scriptPath; Sid = $_.objectSid; SidHistory = @($_.sIDHistory | Where-Object { $null -ne $_ }); ServicePrincipalName = [string[]]@($_.servicePrincipalName | Where-Object { $null -ne $_ }) + PrimaryGroupId = $_.primaryGroupID TrustedForDelegation = if ($null -ne $uac) { $uac.TrustedForDelegation } else { $null }; TrustedToAuthForDelegation = if ($null -ne $uac) { $uac.TrustedToAuthForDelegation } else { $null }; UseDESKeyOnly = if ($null -ne $uac) { $uac.UseDesKeyOnly } else { $null } UserAccountControl = if ($null -ne $_.userAccountControl) { [int]$_.userAccountControl } else { $null }; Created = $_.whenCreated; Modified = $_.whenChanged; IsCriticalSystemObject = if ($null -ne $_.isCriticalSystemObject) { [bool]$_.isCriticalSystemObject } else { $null } } diff --git a/powershell/internal/services/ad/transport/Get-MtSysvolContent.ps1 b/powershell/internal/services/ad/transport/Get-MtSysvolContent.ps1 index 8777578f30..a91b1eb0d2 100644 --- a/powershell/internal/services/ad/transport/Get-MtSysvolContent.ps1 +++ b/powershell/internal/services/ad/transport/Get-MtSysvolContent.ps1 @@ -797,7 +797,9 @@ function Get-MtSysvolContent { $gppXml.Add((ConvertFrom-MtSysvolGppXml -Content (& $invokeAdapter 'ReadText' $TimeoutSeconds) -RelativePath $path)) } catch { - Write-Verbose "Could not parse SYSVOL XML file '$path': $($_.Exception.Message)" + # Parser/transport errors may contain file contents. Do not expose those + # values or return a clean scan after skipping an unreadable XML file. + throw "SYSVOL XML file '$path' could not be fully assessed; the password scan is incomplete." } } elseif ($path -match '(?i)(^|/)GptTmpl\.inf$') { diff --git a/powershell/public/services/ad/Get-MtADDomainState.ps1 b/powershell/public/services/ad/Get-MtADDomainState.ps1 index 7f42bb3893..42180f5cf9 100644 --- a/powershell/public/services/ad/Get-MtADDomainState.ps1 +++ b/powershell/public/services/ad/Get-MtADDomainState.ps1 @@ -495,7 +495,7 @@ } } Schema = @{ - Properties = @('SchemaObjects', 'SchemaContainer', 'LapsInstalled') + Properties = @('SchemaObjects', 'SchemaContainer', 'LapsInstalled', 'WindowsLapsInstalled', 'DelegatedMsaSupported') Dependencies = @() Collector = { $result = [ordered]@{} @@ -503,6 +503,10 @@ $result['SchemaObjects'] = $schemaObjects $result['SchemaContainer'] = $schemaObjects | Where-Object { $_.DistinguishedName -eq $protocolRootDse.SchemaNamingContext } | Select-Object -First 1 $result['LapsInstalled'] = [bool]($schemaObjects | Where-Object { $_.Name -eq 'ms-Mcs-AdmPwd' } | Select-Object -First 1) + # Schema availability only: never retrieve password attribute values. + $schemaNames = @($schemaObjects | ForEach-Object { if ($_.LdapDisplayName) { $_.LdapDisplayName } else { $_.Name } }) + $result['WindowsLapsInstalled'] = ($schemaNames -contains 'msLAPS-Password') -and ($schemaNames -contains 'msLAPS-PasswordExpirationTime') + $result['DelegatedMsaSupported'] = $schemaNames -contains 'msDS-DelegatedManagedServiceAccount' return $result } } @@ -625,6 +629,8 @@ SchemaContainer = $null Printers = @() LapsInstalled = $false + WindowsLapsInstalled = $false + DelegatedMsaSupported = $false DaclEntries = @() FineGrainedPasswordPolicies = @() } diff --git a/powershell/public/services/ad/Get-MtADGpoState.ps1 b/powershell/public/services/ad/Get-MtADGpoState.ps1 index fcf944230e..7dcd3e4e0d 100644 --- a/powershell/public/services/ad/Get-MtADGpoState.ps1 +++ b/powershell/public/services/ad/Get-MtADGpoState.ps1 @@ -103,6 +103,7 @@ } catch { Write-Verbose "Could not collect GPO metadata: $($_.Exception.Message)" + $gpoState['GPOs'] = $null } $parsedGpoLinks = [System.Collections.Generic.List[object]]::new() @@ -199,9 +200,12 @@ $hasDenyAce = [bool]($access | Where-Object { $_.AccessControlType -eq 'Deny' } | Select-Object -First 1) $hasApplyGroupPolicyAce = [bool]($access | Where-Object { $_.AccessControlType -eq 'Allow' -and - (([string]$_.ObjectType -eq $applyGroupPolicyGuid) -or + [string]$_.AceFlags -notmatch 'InheritOnly' -and + (([string]$_.ActiveDirectoryRights -match 'GenericAll') -or ([string]$_.ActiveDirectoryRights -match 'ApplyGroupPolicy') -or - (([string]$_.ActiveDirectoryRights -match 'ExtendedRight') -and ([string]$_.ObjectType -eq $applyGroupPolicyGuid))) + (([string]$_.ActiveDirectoryRights -match 'ExtendedRight') -and + (([string]$_.ObjectType -eq $applyGroupPolicyGuid) -or + ([string]$_.ObjectType -eq [guid]::Empty.ToString())))) } | Select-Object -First 1) } @@ -234,13 +238,18 @@ } $hasVersionMismatch = $null + $sysvolVersion = $null $cpasswordFound = $null $defaultPasswordFound = $null $errors = [System.Collections.Generic.List[object]]::new() try { Write-Verbose "Collecting SYSVOL content for GPO '$gpoGuid'" $sysvolContent = Get-MtSysvolContent -Operation Connect -GpoGuid $gpoGuid + if ($null -eq $sysvolContent -or $null -eq $sysvolContent.CpasswordFound -or $null -eq $sysvolContent.DefaultPasswordFound) { + throw 'SYSVOL content scanning did not return a complete result.' + } if ($null -ne $sysvolContent.GptIni -and $null -ne $sysvolContent.GptIni.Version) { + $sysvolVersion = [long]$sysvolContent.GptIni.Version $hasVersionMismatch = [long]$gpo.VersionNumber -ne [long]$sysvolContent.GptIni.Version } $cpasswordFound = [bool]$sysvolContent.CpasswordFound @@ -263,6 +272,8 @@ Name = $gpo.DisplayName DisabledLinks = if ($null -ne $gpoLinks) { @($gpoLinks | Where-Object { $_.IsDisabled }).Count } else { $null } HasVersionMismatch = $hasVersionMismatch + DirectoryVersion = $gpo.VersionNumber + SysvolVersion = $sysvolVersion CpasswordFound = $cpasswordFound DefaultPasswordFound = $defaultPasswordFound HasApplyGroupPolicyAce = $hasApplyGroupPolicyAce @@ -282,7 +293,7 @@ } catch { Write-Verbose "Could not build GPO reports: $($_.Exception.Message)" - $gpoState['GPOReports'] = @() + $gpoState['GPOReports'] = $null } $__MtSession.ADCache[$cacheKey] = $gpoState diff --git a/powershell/tests/ad/transport/Get-MtSysvolContent.Tests.ps1 b/powershell/tests/ad/transport/Get-MtSysvolContent.Tests.ps1 index 63da610348..752adb7bc0 100644 --- a/powershell/tests/ad/transport/Get-MtSysvolContent.Tests.ps1 +++ b/powershell/tests/ad/transport/Get-MtSysvolContent.Tests.ps1 @@ -129,6 +129,34 @@ Describe 'Get-MtSysvolContent transport contract' { } } + It 'does not return a clean password scan when an XML file is malformed or unreadable' -ForEach @( + @{ Windows = $true; ReadFailure = $false } + @{ Windows = $false; ReadFailure = $false } + @{ Windows = $true; ReadFailure = $true } + @{ Windows = $false; ReadFailure = $true } + ) { + $script:readFailure = $ReadFailure + $script:useWindowsAdapter = $Windows + Mock Test-MtSysvolWindowsPlatform -ModuleName Maester { $script:useWindowsAdapter } + $adapterMock = { + if ($Operation -eq 'List') { + return [PSCustomObject]@{ RelativePath = 'Machine/Preferences/Groups/Groups.xml'; Name = 'Groups.xml'; Length = 50 } + } + if ($Operation -eq 'ReadText') { + if ($script:readFailure) { throw 'read failed SECRET-MUST-NOT-PRINT' } + return ' Date: Sun, 8 Nov 2026 06:23:26 +0000 Subject: [PATCH 002/100] fix(ad): consolidate GPO age and direct-link inventories --- .../tests/functions/ADGpoInventory.Tests.ps1 | 70 +++++++++ tests/ad/gpo/Test.AD-GPO-01.ps1 | 9 +- tests/ad/gpo/Test.AD-GPO-02.md | 25 ++- tests/ad/gpo/Test.AD-GPO-02.ps1 | 80 +++++----- tests/ad/gpo/Test.AD-GPO-03.md | 30 ---- tests/ad/gpo/Test.AD-GPO-03.ps1 | 86 ---------- tests/ad/gpo/Test.AD-GPO-04.md | 4 +- tests/ad/gpo/Test.AD-GPO-04.ps1 | 25 ++- tests/ad/gpo/Test.AD-GPO-05.md | 38 ----- tests/ad/gpo/Test.AD-GPO-05.ps1 | 148 ------------------ tests/ad/gpo/Test.AD-GPOL-01.md | 2 +- tests/ad/gpo/Test.AD-GPOL-03.md | 17 +- tests/ad/gpo/Test.AD-GPOL-03.ps1 | 44 +++--- tests/ad/gpo/Test.AD-GPOL-04.md | 2 +- tests/ad/gpo/Test.AD-GPOL-06.md | 37 ----- tests/ad/gpo/Test.AD-GPOL-06.ps1 | 87 ---------- 16 files changed, 168 insertions(+), 536 deletions(-) create mode 100644 powershell/tests/functions/ADGpoInventory.Tests.ps1 delete mode 100644 tests/ad/gpo/Test.AD-GPO-03.md delete mode 100644 tests/ad/gpo/Test.AD-GPO-03.ps1 delete mode 100644 tests/ad/gpo/Test.AD-GPO-05.md delete mode 100644 tests/ad/gpo/Test.AD-GPO-05.ps1 delete mode 100644 tests/ad/gpo/Test.AD-GPOL-06.md delete mode 100644 tests/ad/gpo/Test.AD-GPOL-06.ps1 diff --git a/powershell/tests/functions/ADGpoInventory.Tests.ps1 b/powershell/tests/functions/ADGpoInventory.Tests.ps1 new file mode 100644 index 0000000000..211764a6c0 --- /dev/null +++ b/powershell/tests/functions/ADGpoInventory.Tests.ps1 @@ -0,0 +1,70 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'AD GPO modification age and link inventories' { + BeforeEach { + $script:now = [datetime]'2026-11-08T12:00:00' + $script:state = [pscustomobject]@{ + GPOs = @([pscustomobject]@{ + Id = '{11111111-1111-1111-1111-111111111111}' + DisplayName = 'Policy | pilot' + CreationTime = [datetime]'2000-01-01' + ModificationTime = [datetime]'2026-01-01' + }) + GPOLinks = @([pscustomobject]@{ GpoGuid = '11111111-1111-1111-1111-111111111111' }) + LinkContainers = @([pscustomobject]@{ ObjectClass = @('organizationalUnit'); DistinguishedName = 'OU=Pilot|test,DC=example,DC=com'; GpLink = '' }) + SiteContainers = @() + } + Mock -ModuleName Maester Get-MtADGpoState { $script:state } + Mock -ModuleName Maester Get-Date { $script:now } + Mock -ModuleName Maester Add-MtTestResultDetail { } + } + + It 'does not fail an old creation date when modification is recent' { + InModuleScope Maester { Test-MtAdGpoStale | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { + $Result -match '2000-01-01' -and $Result -match '2026-01-01' -and $Result -match '|' + } + } + + It 'fails stale modifications using five years by default' { + $script:state.GPOs[0].ModificationTime = [datetime]'2021-11-08T11:59:59' + InModuleScope Maester { Test-MtAdGpoStale | Should -BeFalse } + } + + It 'accepts a modification exactly at the cutoff' { + $script:state.GPOs[0].ModificationTime = $script:now.AddYears(-5) + InModuleScope Maester { Test-MtAdGpoStale | Should -BeTrue } + } + + It 'honors a configurable age limit' { + $script:state.GPOs[0].ModificationTime = [datetime]'2022-01-01' + InModuleScope Maester { Test-MtAdGpoStale -MaximumAgeYears 3 | Should -BeFalse } + } + + It 'errors on missing modification dates' { + $script:state.GPOs[0].ModificationTime = $null + InModuleScope Maester { { Test-MtAdGpoStale } | Should -Throw '*no modification date*' } + } + + It 'recognizes normalized links despite braces around the inventory identifier' { + InModuleScope Maester { Test-MtAdGpoUnlinkedCount | Should -BeTrue } + } + + It 'lists unlinked policies with both dates' { + $script:state.GPOLinks = @() + InModuleScope Maester { Test-MtAdGpoUnlinkedCount | Should -BeFalse } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Result -match '2000-01-01' -and $Result -match '2026-01-01' } + } + + It 'errors rather than treating failed link collection as no links' { + $script:state.GPOLinks = $null + InModuleScope Maester { { Test-MtAdGpoUnlinkedCount } | Should -Throw '*cannot be assessed*' } + } + + It 'investigates a target without direct links without claiming missing effective policy' { + InModuleScope Maester { Test-MtAdGpoUnlinkedTargetCount | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate -and $Result -match 'OU=Pilot|test' } + } +} diff --git a/tests/ad/gpo/Test.AD-GPO-01.ps1 b/tests/ad/gpo/Test.AD-GPO-01.ps1 index b07ee29bd1..0786a6b03b 100644 --- a/tests/ad/gpo/Test.AD-GPO-01.ps1 +++ b/tests/ad/gpo/Test.AD-GPO-01.ps1 @@ -19,7 +19,7 @@ #> [MaesterTest( Id = 'AD-GPO-01', - Title = 'GPO total count should be retrievable', + Title = 'GPO inventory should be investigated', Product = 'ad', Feature = 'group-policy', Area = 'infrastructure', @@ -40,9 +40,8 @@ $gpoState = Get-MtADGpoState # If unable to retrieve GPO data, skip the test - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $gpoState -or $null -eq $gpoState.GPOs) { + throw 'The GPO inventory could not be retrieved.' } $gpos = $gpoState.GPOs @@ -65,7 +64,7 @@ $testResultMarkdown = "Unable to retrieve Active Directory Group Policy Objects. Ensure you have appropriate permissions and the Group Policy Management Console is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/gpo/Test.AD-GPO-02.md b/tests/ad/gpo/Test.AD-GPO-02.md index be1132b58b..cb6ee5a1b6 100644 --- a/tests/ad/gpo/Test.AD-GPO-02.md +++ b/tests/ad/gpo/Test.AD-GPO-02.md @@ -1,28 +1,21 @@ -Group Policy Objects (GPOs) created a long time ago can be a sign of policy growth over time. Older GPOs may contain outdated security settings, legacy configuration patterns, and assumptions that no longer match your current security baseline. +Checks that each Group Policy Object (GPO) has been modified within the configured age limit, **five calendar years** by default. -Tracking the count of GPOs created before 2020 helps you quickly identify areas that may benefit from review and modernization. +The last modification date drives pass/fail; creation and modification dates are shown together for every policy. A policy created many years ago but modified recently passes. Age is a hygiene indicator, not proof that a policy is insecure, and changing a timestamp alone is not a security review. -#### Control Type +#### Remediation action -**Detective** - -#### Security Recommendation - -- **Review legacy GPOs regularly**: Older GPOs are more likely to include security configurations that are no longer aligned to current best practices. -- **Validate intended changes**: Before updating or removing an older GPO, validate its purpose, inheritance, and scope to avoid unintended access or availability impacts. -- **Plan for modernization**: Consolidate redundant GPOs and update policy settings to match current compliance and security requirements. +1. In **Group Policy Management**, review each stale policy with its owner against the current baseline, intended scope and dependencies. +2. Update settings that are no longer appropriate, test with a pilot group and retain a backup before deployment. Archive or remove redundant policies only after verifying they are unused. +3. If your organization uses a different review interval, set `MaximumAgeYears` under this test's `TestSettings[].Parameters` in `maester-config.json`. #### How the Test Works -This test retrieves GPO state from Active Directory using **Get-MtADGpoState** (it uses `$gpoState.GPOs`). - -It then filters all GPOs where the `CreationTime` is earlier than **January 1st, 2020** and reports the resulting count. +This test uses the cached `Get-MtADGpoState` inventory. It fails if any `ModificationTime` is earlier than the run's current date minus `MaximumAgeYears`. Missing inventory or modification dates produce Error rather than a clean pass. The cutoff is exclusive: a date exactly at the cutoff is within the limit. #### Related Tests -- `Test-MtAdGpoTotalCount` - Total GPO inventory -- `Test-MtAdGpoUnlinkedCount` - GPOs not linked anywhere -- `Test-MtAdGpoLinkedCount` - GPOs that are actively linked +- `AD-GPO-01` — GPO inventory +- `AD-GPO-04` — Unlinked GPO count and details %TestResult% diff --git a/tests/ad/gpo/Test.AD-GPO-02.ps1 b/tests/ad/gpo/Test.AD-GPO-02.ps1 index e9ceff5ad0..a6b3814946 100644 --- a/tests/ad/gpo/Test.AD-GPO-02.ps1 +++ b/tests/ad/gpo/Test.AD-GPO-02.ps1 @@ -1,33 +1,31 @@ -function Test-MtAdGpoCreatedBefore2020Count { +function Test-MtAdGpoStale { <# .SYNOPSIS - Counts the number of Group Policy Objects (GPOs) created before 2020 in Active Directory. + Checks that GPOs have been modified within the configured age limit. .DESCRIPTION - This test retrieves Active Directory GPO state information using Get-MtADGpoState, then counts - the number of GPOs with a CreationTime earlier than January 1st, 2020. - - Knowing how many older GPOs exist helps identify potential legacy policy sprawl that may - include outdated security settings. + Uses the cached GPO inventory. Fails when a GPO's last modification is older than + MaximumAgeYears (five calendar years by default). Reports creation and modification + dates together; an old creation date alone does not cause failure. .EXAMPLE - Test-MtAdGpoCreatedBefore2020Count - - Returns $true if GPO data is accessible, $false otherwise. + Test-MtAdGpoStale - The test result includes the count of GPOs created before 2020. + Returns $true when no GPO exceeds the modification-age limit. .LINK - https://maester.dev/docs/commands/Test-MtAdGpoCreatedBefore2020Count + https://maester.dev/docs/tests/AD-GPO-02 #> [MaesterTest( Id = 'AD-GPO-02', - Title = 'GPO created before 2020 count should be retrievable', + Title = 'GPOs should be modified within the configured age limit', Product = 'ad', Feature = 'group-policy', Area = 'infrastructure', ResourceType = 'GroupPolicy', - Severity = 'Info', + Severity = 'Low', + UserImpact = 'Low', + ImplementationCost = 'Medium', Mitre = 'None', Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), @@ -35,41 +33,33 @@ )] [CmdletBinding()] [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdGpoCreatedBefore2020Count" + param( + # Maximum age of a GPO's last modification, in calendar years. + [ValidateRange(1, 100)] + [int] $MaximumAgeYears = 5 + ) $gpoState = Get-MtADGpoState - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $gpoState -or $null -eq $gpoState.GPOs) { + throw 'The GPO inventory could not be retrieved; modification age cannot be assessed.' } - $gpos = $gpoState.GPOs - - $cutoffDate = Get-Date -Year 2020 -Month 1 -Day 1 - $oldGpos = $gpos | Where-Object { $_.CreationTime -lt $cutoffDate } - - $oldCount = ($oldGpos | Measure-Object).Count - $totalCount = ($gpos | Measure-Object).Count - - $testResult = $totalCount -ge 0 - - if ($testResult) { - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| GPOs created before $($cutoffDate.ToString('yyyy-MM-dd')) | $oldCount |" + "`n" - $result += "| Total GPOs | $totalCount |" + "`n" - - $testResultMarkdown = "Active Directory Group Policy Objects have been analyzed. The domain contains $oldCount GPO(s) created before $($cutoffDate.ToString('yyyy-MM-dd')).`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result + $gpos = @($gpoState.GPOs) + if (@($gpos | Where-Object { $null -eq $_.ModificationTime }).Count -gt 0) { + throw 'One or more GPOs have no modification date; modification age cannot be assessed.' } - else { - $testResultMarkdown = 'Unable to retrieve Active Directory Group Policy Objects. Ensure you have appropriate permissions and the Group Policy Management Console is installed.' + $cutoffDate = (Get-Date).AddYears(-$MaximumAgeYears) + $stale = @($gpos | Where-Object { [datetime]$_.ModificationTime -lt $cutoffDate }) + $result = "Total GPOs: $($gpos.Count). Stale GPOs: $($stale.Count). Modification cutoff: $($cutoffDate.ToString('yyyy-MM-dd HH:mm:ss')).`n`n" + $result += "| GPO | Created | Modified | Assessment |`n| --- | --- | --- | --- |`n" + foreach ($gpo in ($gpos | Sort-Object DisplayName)) { + $name = ([string]$gpo.DisplayName).Replace('|', '|') -replace '[\r\n]+', ' ' + $created = if ($null -ne $gpo.CreationTime) { ([datetime]$gpo.CreationTime).ToString('yyyy-MM-dd HH:mm:ss') } else { 'Unknown' } + $modified = ([datetime]$gpo.ModificationTime).ToString('yyyy-MM-dd HH:mm:ss') + $assessment = if ([datetime]$gpo.ModificationTime -lt $cutoffDate) { 'Stale' } else { 'Within limit' } + $result += "| $name | $created | $modified | $assessment |`n" } - - # Generate markdown results - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult + $message = if ($stale.Count -eq 0) { 'Well done. No GPO exceeds the configured modification-age limit.' } else { "Review and update $($stale.Count) GPO(s) not modified within $MaximumAgeYears years. Age is a hygiene indicator, not proof of insecure settings." } + Add-MtTestResultDetail -Result "$message`n`n$result" + return ($stale.Count -eq 0) } diff --git a/tests/ad/gpo/Test.AD-GPO-03.md b/tests/ad/gpo/Test.AD-GPO-03.md deleted file mode 100644 index 8f44f31350..0000000000 --- a/tests/ad/gpo/Test.AD-GPO-03.md +++ /dev/null @@ -1,30 +0,0 @@ -Group Policy Objects (GPOs) that have not been modified for a long time can become "stale". -Stale GPOs may contain outdated security configurations, which can create security gaps -if they no longer match your current security baselines. - -#### Control Type - -**Operational** - -#### Security Recommendation - -Regularly review GPOs that have not changed recently. Consider: - -- Validating that security settings are still required and aligned with your current baseline -- Removing or updating policies that are no longer used or no longer appropriate -- Establishing a review cadence for long-lived policies - -#### How the Test Works - -This test uses `Get-MtADGpoState` to retrieve cached GPO data. -It filters GPOs where `ModificationTime` is earlier than `2020-01-01` and calculates: - -- Total number of GPOs -- Number and percentage of stale GPOs - -#### Related Tests - -- `Test-MtAdGpoTotalCount` - Counts the total number of GPOs - - -%TestResult% diff --git a/tests/ad/gpo/Test.AD-GPO-03.ps1 b/tests/ad/gpo/Test.AD-GPO-03.ps1 deleted file mode 100644 index 3fbc824563..0000000000 --- a/tests/ad/gpo/Test.AD-GPO-03.ps1 +++ /dev/null @@ -1,86 +0,0 @@ -function Test-MtAdGpoChangedBefore2020Count { - <# - .SYNOPSIS - Counts Group Policy Objects (GPOs) last changed before 2020. - - .DESCRIPTION - This test counts GPOs whose ModificationTime is earlier than 2020-01-01. - These GPOs can be considered "stale" and may contain outdated security configurations. - - Stale or unmaintained GPOs can create security gaps if they no longer align with - current security baselines and organizational requirements. - - .EXAMPLE - Test-MtAdGpoChangedBefore2020Count - - Returns $true if the cached GPO data is accessible, $null if Active Directory data - cannot be retrieved. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoChangedBefore2020Count - #> - [MaesterTest( - Id = 'AD-GPO-03', - Title = 'GPO stale-before-2020 count should be investigated', - Product = 'ad', - Feature = 'group-policy', - Area = 'infrastructure', - ResourceType = 'GroupPolicy', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdGpoChangedBefore2020Count" - - # Get AD GPO state data (uses cached data if available) - $gpoState = Get-MtADGpoState - - # If unable to retrieve GPO data, skip the test - if ($null -eq $gpoState -or $null -eq $gpoState.GPOs) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $gpos = $gpoState.GPOs - - $staleDate = [datetime]'2020-01-01' - $staleGpos = @( - $gpos | Where-Object { - $null -ne $_.ModificationTime -and ([datetime]$_.ModificationTime -lt $staleDate) - } - ) - - # Counts - $totalCount = ($gpos | Measure-Object).Count - $staleCount = ($staleGpos | Measure-Object).Count - $stalePercentage = if ($totalCount -gt 0) { [math]::Round(($staleCount / $totalCount) * 100, 2) } else { 0 } - - # Data retrieved successfully - $testResult = $true - - # Generate markdown results - $resultTable = "| Metric | Value |" + "`n" - $resultTable += "| --- | --- |" + "`n" - $resultTable += "| Total GPOs | $totalCount |" + "`n" - $resultTable += "| Stale GPOs (Modified before 2020-01-01) | $staleCount |" + "`n" - $resultTable += "| Stale GPOs % | $stalePercentage% |" + "`n" - - if ($staleCount -gt 0) { - $recommendation = "⚠️ Found $staleCount stale GPO(s) (not modified since before 2020-01-01). Stale policies can contain outdated security settings and create security gaps. Consider regular review and remediation of unchanged policies." - } else { - $recommendation = "✅ No stale GPOs were detected (no GPOs have a ModificationTime earlier than 2020-01-01). Continue periodic reviews to ensure security configurations remain current." - } - - $testResultMarkdown = "$recommendation`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $resultTable - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - - return $testResult -} diff --git a/tests/ad/gpo/Test.AD-GPO-04.md b/tests/ad/gpo/Test.AD-GPO-04.md index e38c511b86..2c222d3501 100644 --- a/tests/ad/gpo/Test.AD-GPO-04.md +++ b/tests/ad/gpo/Test.AD-GPO-04.md @@ -8,7 +8,7 @@ Unlinked (or orphaned) Group Policy Objects (GPOs) exist in Active Directory but **Detective** -#### Security Recommendation +#### Remediation action After verification, **remove unlinked GPOs** to reduce risk and simplify policy management: @@ -29,7 +29,7 @@ This test retrieves Active Directory Group Policy state data using `Get-MtADGpoS - `Test-MtAdGpoTotalCount` - Counts the total number of GPOs - `Test-MtAdGpoLinkedCount` - Identifies GPOs that are actively linked -- `Test-MtAdGpoCreatedBefore2020Count` - Identifies potentially outdated GPOs +- `AD-GPO-02` - Checks modification age and shows creation and modification dates %TestResult% diff --git a/tests/ad/gpo/Test.AD-GPO-04.ps1 b/tests/ad/gpo/Test.AD-GPO-04.ps1 index e9a6ca2b13..9ef84cb9ac 100644 --- a/tests/ad/gpo/Test.AD-GPO-04.ps1 +++ b/tests/ad/gpo/Test.AD-GPO-04.ps1 @@ -18,7 +18,7 @@ #> [MaesterTest( Id = 'AD-GPO-04', - Title = 'Unlinked GPO count should be compliant', + Title = 'GPOs should have at least one link', Product = 'ad', Feature = 'group-policy', Area = 'infrastructure', @@ -41,9 +41,8 @@ $gpoState = Get-MtADGpoState # If unable to retrieve GPO data, skip the test - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $gpoState -or $null -eq $gpoState.GPOs -or $null -eq $gpoState.GPOLinks) { + throw 'GPO metadata or domain, OU and site links were not retrieved; unlinked GPOs cannot be assessed.' } $gpos = $gpoState.GPOs @@ -55,6 +54,9 @@ $gpLinks = $gpoState.GPOLinks if ($gpLinks) { foreach ($linkObject in $gpLinks) { + if ($null -ne $linkObject.GpoGuid) { + $null = $linkedGpoIds.Add(([string]$linkObject.GpoGuid).Trim('{}')) + } $gPLinkValue = $linkObject.gPLink if ([string]::IsNullOrWhiteSpace($gPLinkValue)) { continue @@ -74,7 +76,8 @@ # Identify unlinked/orphaned GPOs by comparing the GPO IDs against collected link targets. $unlinkedGpos = @() foreach ($gpo in $gpos) { - $gpoId = if ($null -ne $gpo.Id) { [string]$gpo.Id } else { $null } + $gpoId = if ($null -ne $gpo.Id) { ([string]$gpo.Id).Trim('{}') } else { $null } + if (-not $gpoId) { throw 'A GPO has no identifier; its links cannot be assessed.' } # Optional fallback: some environments may surface unlinked wording in GpoStatus. $statusText = if ($null -ne $gpo.GpoStatus) { [string]$gpo.GpoStatus } else { $null } @@ -116,11 +119,19 @@ $result += "| Linked GPOs | $linkedCount |" + "`n" $result += "| Unlinked GPOs | $unlinkedCount |" + "`n" if ($unlinkedCount -gt 0 -and $sampleNamesText) { - $result += "| Sample Unlinked GPOs | $sampleNamesText |" + "`n" + $safeNames = $sampleNamesText.Replace('|', '|') -replace '[\r\n]+', ' ' + $result += "| Sample Unlinked GPOs | $safeNames |" + "`n" + } + $result += "`n| Unlinked GPO | Created | Modified |`n| --- | --- | --- |`n" + foreach ($gpo in ($unlinkedGpos | Sort-Object DisplayName)) { + $name = ([string]$gpo.DisplayName).Replace('|', '|') -replace '[\r\n]+', ' ' + $created = if ($null -ne $gpo.CreationTime) { ([datetime]$gpo.CreationTime).ToString('yyyy-MM-dd HH:mm:ss') } else { 'Unknown' } + $modified = if ($null -ne $gpo.ModificationTime) { ([datetime]$gpo.ModificationTime).ToString('yyyy-MM-dd HH:mm:ss') } else { 'Unknown' } + $result += "| $name | $created | $modified |`n" } if ($testResult) { - $testResultMarkdown = "✅ Unlinked/orphaned GPOs have not been found. Active Directory Group Policy Objects have been analyzed successfully.`n`n%TestResult%" + $testResultMarkdown = "Well done. All GPOs have at least one link.`n`n%TestResult%" } else { $testResultMarkdown = "⚠️ Unlinked/orphaned GPOs were found. These GPOs consume resources while providing no effective policy, and they can be accidentally linked later, applying unknown settings. After verification, remove or remediate unlinked GPOs.`n`n%TestResult%" } diff --git a/tests/ad/gpo/Test.AD-GPO-05.md b/tests/ad/gpo/Test.AD-GPO-05.md deleted file mode 100644 index bde927d31d..0000000000 --- a/tests/ad/gpo/Test.AD-GPO-05.md +++ /dev/null @@ -1,38 +0,0 @@ -Unlinked Group Policy Objects (GPOs) are policies that exist in Active Directory but are not linked to any -site, domain, or organizational unit (OU). Even when unlinked, these GPOs still represent configuration -artifacts that can create operational overhead and increase risk. - -- **Security risk**: Unused policies may still contain insecure settings that could be re-enabled accidentally. -- **Operational complexity**: GPO sprawl makes it harder to reason about what policies actually apply. -- **Maintenance hygiene**: Tracking unlinked GPOs supports safe cleanup and ongoing policy governance. - -#### Control Type - -**Operational** - -#### Security Recommendation - -Review the returned unlinked GPOs and consider removing those that are no longer needed. - -This reduces the attack surface by removing unused policies that could be re-linked or misconfigured -in the future. - -#### How the Test Works - -This test uses `Get-MtADGpoState` to retrieve cached GPO data (`$gpoState.GPOs`). It then identifies unlinked -GPOs and generates a markdown table containing: - -- **GPO DisplayName** -- **CreationTime** -- **ModificationTime** - -The table is intended to support quick review during GPO cleanup and maintenance activities. - -#### Related Tests - -- `Test-MtAdGpoUnlinkedCount` - Identifies how many GPOs are not linked to any location -- `Test-MtAdGpoLinkedCount` - Counts GPOs that are actively linked -- `Test-MtAdGpoTotalCount` - Counts the total number of GPOs in the domain - - -%TestResult% diff --git a/tests/ad/gpo/Test.AD-GPO-05.ps1 b/tests/ad/gpo/Test.AD-GPO-05.ps1 deleted file mode 100644 index c102a37d54..0000000000 --- a/tests/ad/gpo/Test.AD-GPO-05.ps1 +++ /dev/null @@ -1,148 +0,0 @@ -function Test-MtAdGpoUnlinkedDetails { - <# - .SYNOPSIS - Returns details of unlinked Group Policy Objects (GPOs) in Active Directory. - - .DESCRIPTION - This test analyzes the Group Policy Objects (GPOs) in Active Directory and returns a list of - unlinked GPOs (including the GPO DisplayName, CreationTime, and ModificationTime). - - Knowing which GPOs are unlinked helps identify policies that are no longer in use. Reviewing - and removing unused GPOs reduces operational complexity and can help reduce attack surface. - - .EXAMPLE - Test-MtAdGpoUnlinkedDetails - - Returns $true if GPO data is accessible, $false otherwise. - The test result includes a markdown table with the details of unlinked GPOs. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoUnlinkedDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-GPO-05', - Title = 'GPO unlinked details should be compliant', - Product = 'ad', - Feature = 'group-policy', - Area = 'infrastructure', - ResourceType = 'GroupPolicy', - Severity = 'Low', - UserImpact = 'Low', - ImplementationCost = 'Medium', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdGpoUnlinkedDetails" - - # Get AD GPO state data (uses cached data if available) - $gpoState = Get-MtADGpoState - - # If unable to retrieve GPO data, skip the test - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $gpos = $gpoState.GPOs - if ($null -eq $gpos) { - Add-MtTestResultDetail -Result 'Unable to retrieve Active Directory Group Policy Objects. Ensure you have appropriate permissions and that the Group Policy Management Console is installed.' - return $false - } - - # Collect GPO IDs that appear in GPOLinks (gPLink) across the collected AD containers. - # Get-MtADGpoState currently retrieves GPOLinks from configuration naming context. - $linkedGpoIds = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase) - $gpLinks = $gpoState.GPOLinks - if ($gpLinks) { - foreach ($linkObject in $gpLinks) { - $gPLinkValue = $linkObject.gPLink - if ([string]::IsNullOrWhiteSpace($gPLinkValue)) { - continue - } - - # gPLink contains one or more entries like: - # LDAP://CN=...,CN=Policies,CN=System,DC=example,DC=com;{GPO-GUID};0 - foreach ($match in ([regex]::Matches($gPLinkValue, '\{([0-9a-fA-F-]{36})\}'))) { - $guid = $match.Groups[1].Value - if (-not [string]::IsNullOrWhiteSpace($guid)) { - $linkedGpoIds.Add($guid) | Out-Null - } - } - } - } - - # Identify unlinked/orphaned GPOs. - $unlinkedGpos = @() - foreach ($gpo in $gpos) { - $gpoId = if ($null -ne $gpo.Id) { [string]$gpo.Id } else { $null } - - # Optional fallback: some environments may surface unlinked wording in GpoStatus. - $statusText = if ($null -ne $gpo.GpoStatus) { [string]$gpo.GpoStatus } else { $null } - $looksUnlinked = $false - if ($statusText -and ($statusText -match 'Unlinked|No links|Not linked')) { - $looksUnlinked = $true - } - - $isLinked = $false - if ($gpoId) { - $isLinked = $linkedGpoIds.Contains($gpoId) - } - - if (-not $isLinked -or $looksUnlinked) { - $unlinkedGpos += $gpo - } - } - - $unlinkedGpoCount = @($unlinkedGpos).Count - - # Security intent: pass only when no unlinked/orphaned GPOs exist. - $testResult = $unlinkedGpoCount -eq 0 - - # Build the markdown table with details of unlinked GPOs - $table = "| GPO DisplayName | CreationTime | ModificationTime |" + "`n" - $table += '| --- | --- | --- |' + "`n" - - foreach ($gpo in @($unlinkedGpos | Sort-Object DisplayName)) { - $displayName = [string]$gpo.DisplayName - $displayName = $displayName -replace '\|', '\\|' - - $creationTime = $null - if ($null -ne $gpo.CreationTime) { - $creationTime = ([datetime]$gpo.CreationTime).ToString('yyyy-MM-dd HH:mm:ss') - } else { - $creationTime = '' - } - - $modificationTime = $null - if ($null -ne $gpo.ModificationTime) { - $modificationTime = ([datetime]$gpo.ModificationTime).ToString('yyyy-MM-dd HH:mm:ss') - } else { - $modificationTime = '' - } - - $table += "| $displayName | $creationTime | $modificationTime |" + "`n" - } - - $recommendation = if ($testResult) { - '✅ Unlinked/orphaned GPOs have not been found. Active Directory Group Policy Objects have been analyzed successfully.' - } else { - "⚠️ Unlinked/orphaned GPOs were found ($unlinkedGpoCount). Review these policies for removal to reduce GPO sprawl and lower risk from unused (and potentially misconfigured) policies." - } - - $testResultMarkdown = "$recommendation`n`n%TestResult%" - if ($unlinkedGpoCount -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $table - } else { - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', "" - } - - Add-MtTestResultDetail -Result $testResultMarkdown - return $testResult -} diff --git a/tests/ad/gpo/Test.AD-GPOL-01.md b/tests/ad/gpo/Test.AD-GPOL-01.md index 2583e100dd..d38497061a 100644 --- a/tests/ad/gpo/Test.AD-GPOL-01.md +++ b/tests/ad/gpo/Test.AD-GPOL-01.md @@ -31,7 +31,7 @@ It then: - `Test-MtAdGpoTotalCount` - Total GPO inventory - `Test-MtAdGpoUnlinkedCount` - GPOs not linked anywhere - `Test-MtAdGpoCreatedBefore2020Count` - Potentially legacy GPOs -- `Test-MtAdGpoChangedBefore2020Count` - Potentially stale GPOs +- `AD-GPO-02` - Potentially stale GPOs, based on configurable modification age %TestResult% diff --git a/tests/ad/gpo/Test.AD-GPOL-03.md b/tests/ad/gpo/Test.AD-GPOL-03.md index 18020d2d4c..c49eb2fb42 100644 --- a/tests/ad/gpo/Test.AD-GPOL-03.md +++ b/tests/ad/gpo/Test.AD-GPOL-03.md @@ -1,37 +1,36 @@ -Active Directory targets (OUs, the domain root, and sites) without any Group Policy links may indicate incomplete security policy coverage. +Reports direct Group Policy links on OUs, domain roots and sites for **Investigate**, including counts of linked and unlinked OUs and details of targets without direct links. -When a target has no GPO links, security and configuration baselines may not be applied consistently—creating gaps that attackers or misconfigurations can exploit. +An OU can inherit policy from its parent or domain without a direct link. A direct link also does not prove that a policy applies: link status, inheritance, security filtering and WMI filtering affect the effective result. This inventory therefore does not pass or fail a security baseline. #### Control Type **Operational** -#### Security Recommendation +#### Remediation action -Investigate any unlinked targets and remediate the policy coverage gap: +In **Group Policy Management**, review targets without direct links: - Confirm the target should receive baseline policies (security requirements, ownership, and intended design). - Add the appropriate GPO links (typically security baselines and auditing policies) to restore consistent enforcement. - Review GPO inheritance/blocking design to ensure links are not unintentionally prevented. - Maintain a deployment cadence so new OUs/domains/sites do not remain unlinked. -Unlinked targets can represent missing or outdated configurations, so treat results as potential security configuration gaps. +Use Group Policy Results or Modeling to verify effective policy before adding links. #### How the Test Works This test uses `Get-MtADGpoState` (and its cached `GPOLinks`/AD data) and: -1. Enumerates all OUs using `Get-ADOrganizationalUnit`. +1. Enumerates OU and domain containers from cached LDAP data. 2. Reads the `gPLink` value for the domain root. -3. Identifies site link objects from `Get-MtADGpoState` (`$gpoState.SiteContainers`). +3. Identifies site objects from `Get-MtADGpoState` (`$gpoState.SiteContainers`). 4. Counts each target whose `gPLink` value contains no GPO GUID references (i.e., no GPO links). #### Related Tests - `Test-MtAdGpoUnlinkedCount` - Identifies GPOs that are not linked to any location - `Test-MtAdGpoLinkedCount` - Counts distinct GPOs that are actively linked -- `Test-MtAdGpoUnlinkedDetails` - Returns details of unlinked GPOs -- `Test-MtAdGpoLinkedOUCount` - (if implemented) OUs with GPO links +- `AD-GPO-04` - Returns counts and details of unlinked GPOs %TestResult% diff --git a/tests/ad/gpo/Test.AD-GPOL-03.ps1 b/tests/ad/gpo/Test.AD-GPOL-03.ps1 index f9734c0be5..de7f253e1f 100644 --- a/tests/ad/gpo/Test.AD-GPOL-03.ps1 +++ b/tests/ad/gpo/Test.AD-GPOL-03.ps1 @@ -1,34 +1,29 @@ function Test-MtAdGpoUnlinkedTargetCount { <# .SYNOPSIS - Counts AD targets (OUs, domains, sites) that do not have any GPO links. + Reports direct GPO links on OUs, domain roots and sites for investigation. .DESCRIPTION - This test identifies policy deployment gaps by counting Active Directory targets - (organizational units, the domain root, and site link objects) that have no GPO links. - - Targets without GPO links may indicate incomplete security policy coverage and can lead - to inconsistent enforcement of security baselines. + Counts linked and unlinked OUs and lists targets with no direct GPO links. + A target can inherit policy from its parent, so absence of a direct link is not + proof of a policy gap. This inventory requires manual review of effective policy. .EXAMPLE Test-MtAdGpoUnlinkedTargetCount - Returns $true if no unlinked targets were found, $false if targets without any GPO links exist, - and $null if AD/GPO data is not accessible. + Reports Investigate when target collection succeeds. .LINK https://maester.dev/docs/commands/Test-MtAdGpoUnlinkedTargetCount #> [MaesterTest( Id = 'AD-GPOL-03', - Title = 'GPO unlinked target count should be compliant', + Title = 'Direct GPO link coverage should be investigated', Product = 'ad', Feature = 'group-policy', Area = 'infrastructure', ResourceType = 'OrganizationalUnit', - Severity = 'Low', - UserImpact = 'Low', - ImplementationCost = 'Medium', + Severity = 'Info', Mitre = 'None', Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), @@ -44,9 +39,8 @@ $gpoState = Get-MtADGpoState # If unable to retrieve GPO data, skip the test - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $gpoState -or $null -eq $gpoState.LinkContainers -or $null -eq $gpoState.SiteContainers) { + throw 'Domain, OU or site GPO link containers were not retrieved.' } function Test-MtGpoLinkPresent { @@ -125,7 +119,7 @@ $unlinkedCountSites = @($unlinkedSites).Count $totalUnlinkedTargets = $unlinkedCountOus + $unlinkedCountDomains + $unlinkedCountSites - $testResult = $totalUnlinkedTargets -eq 0 + $testResult = $true # Sample unlinked targets $sampleLimit = 5 @@ -156,8 +150,9 @@ $result += "| Unlinked OUs | $unlinkedCountOus |" + "`n" $result += "| Total Domains | $totalDomains |" + "`n" $result += "| Unlinked Domains | $unlinkedCountDomains |" + "`n" - $result += "| Total Sites (siteLink) | $totalSites |" + "`n" - $result += "| Unlinked Sites (siteLink) | $unlinkedCountSites |" + "`n" + $result += "| OUs with direct links | $($totalOus - $unlinkedCountOus) |" + "`n" + $result += "| Total Sites | $totalSites |" + "`n" + $result += "| Sites without direct links | $unlinkedCountSites |" + "`n" $result += "| Total Unlinked Targets | $totalUnlinkedTargets |" + "`n" if ($sampleText) { # Avoid breaking markdown tables when DNs contain pipes @@ -166,15 +161,16 @@ $result += "| Sample Unlinked Targets | $safeSampleText |" + "`n" } - if ($testResult) { - $testResultMarkdown = "✅ All analyzed targets (OUs, domain root, and sites) have at least one GPO link. This indicates consistent GPO-based security policy coverage.`n`n%TestResult%" - } - else { - $testResultMarkdown = "⚠️ One or more Active Directory targets do not have any GPO links ($totalUnlinkedTargets). Unlinked targets can indicate incomplete policy coverage, leading to inconsistent security enforcement across the environment.`n`n%TestResult%" + $result += "`n| Target without direct links | Distinguished name |`n| --- | --- |`n" + foreach ($target in @($unlinkedOus) + @($unlinkedDomains) + @($unlinkedSites)) { + $dn = ([string]$target.DistinguishedName).Replace('|', '|') -replace '[\r\n]+', ' ' + $type = @($target.ObjectClass)[-1] + $result += "| $type | $dn |`n" } + $testResultMarkdown = "Investigate direct GPO links and inherited policy. $totalUnlinkedTargets target(s) have no direct links; this does not establish whether security policy is effective.`n`n%TestResult%" $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/gpo/Test.AD-GPOL-04.md b/tests/ad/gpo/Test.AD-GPOL-04.md index 75aef9d0a2..4786650e20 100644 --- a/tests/ad/gpo/Test.AD-GPOL-04.md +++ b/tests/ad/gpo/Test.AD-GPOL-04.md @@ -25,7 +25,7 @@ This test retrieves Active Directory GPO state from `Get-MtADGpoState` (using `$ - `Test-MtAdGpoTotalCount` - Counts total GPO inventory - `Test-MtAdGpoLinkedCount` - Identifies GPOs that are actively linked - `Test-MtAdGpoUnlinkedCount` - Identifies GPOs not linked anywhere -- `Test-MtAdGpoUnlinkedDetails` - Shows unlinked GPO details +- `AD-GPO-04` - Shows unlinked GPO counts and details %TestResult% diff --git a/tests/ad/gpo/Test.AD-GPOL-06.md b/tests/ad/gpo/Test.AD-GPOL-06.md deleted file mode 100644 index f27e29e9ef..0000000000 --- a/tests/ad/gpo/Test.AD-GPOL-06.md +++ /dev/null @@ -1,37 +0,0 @@ -Understanding the distribution of GPO links across Organizational Units is important for several security reasons: - -- **Policy Coverage**: Identifies OUs that may lack necessary security policies -- **Compliance Assessment**: Helps ensure all organizational units receive appropriate policy coverage -- **Security Gaps**: OUs without GPO links may rely solely on domain-level policies, potentially missing OU-specific security controls -- **Policy Management**: Provides visibility into how broadly GPOs are deployed across the directory structure - -#### Control Type - -**Operational** - -#### Security Recommendation - -Review OUs without GPO links to ensure: - -- They inherit appropriate policies from parent containers -- They don't require OU-specific security policies -- Critical security settings are not being missed -- Consider creating OU-specific policies for organizational units with unique security requirements - -#### How the Test Works - -This test retrieves all Organizational Units from Active Directory and counts: -- Total number of OUs in the domain -- Number of OUs with GPO links (gPLink attribute is populated) -- Number of OUs without GPO links - -The gPLink attribute is checked to determine if any GPOs are linked to each OU. - -#### Related Tests - -- `Test-MtAdGpoLinkedCount` - Counts distinct GPOs with links -- `Test-MtAdGpoUnlinkedTargetCount` - Counts targets without GPO links -- `Test-MtAdComputerOUCount` - Counts distinct OUs containing computers - - -%TestResult% diff --git a/tests/ad/gpo/Test.AD-GPOL-06.ps1 b/tests/ad/gpo/Test.AD-GPOL-06.ps1 deleted file mode 100644 index 3b62cd26ef..0000000000 --- a/tests/ad/gpo/Test.AD-GPOL-06.ps1 +++ /dev/null @@ -1,87 +0,0 @@ -function Test-MtAdGpoLinkedOUCount { - <# - .SYNOPSIS - Counts the number of Organizational Units with GPO links in Active Directory. - - .DESCRIPTION - This test retrieves the count of OUs that have one or more GPOs linked to them. - Understanding GPO distribution across OUs helps assess policy coverage and - identify potential gaps in security policy application. - - .EXAMPLE - Test-MtAdGpoLinkedOUCount - - Returns $true if GPO link data is accessible, $false otherwise. - The test result includes counts of OUs with and without GPO links. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoLinkedOUCount - #> - [MaesterTest( - Id = 'AD-GPOL-06', - Title = 'GPO linked OU count should be retrievable', - Product = 'ad', - Feature = 'group-policy', - Area = 'infrastructure', - ResourceType = 'OrganizationalUnit', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - # Get AD GPO state data (uses cached data if available) - $gpoState = Get-MtADGpoState - - # If unable to retrieve GPO data, skip the test - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - # Get all OUs in the domain - try { - $allOUs = @($gpoState.LinkContainers | Where-Object { @($_.ObjectClass) -contains 'organizationalUnit' }) - $totalOUs = ($allOUs | Measure-Object).Count - - # Count OUs with GPO links (gPLink is not null or empty) - $linkedOUs = $allOUs | Where-Object { $_.gPLink -and $_.gPLink -ne '' } - $linkedOUCount = ($linkedOUs | Measure-Object).Count - $unlinkedOUCount = $totalOUs - $linkedOUCount - - # Test passes if we successfully retrieved data - $testResult = $totalOUs -ge 0 - - # Generate markdown results - if ($testResult) { - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total OUs | $totalOUs |" + "`n" - $result += "| OUs with GPO Links | $linkedOUCount |" + "`n" - $result += "| OUs without GPO Links | $unlinkedOUCount |" + "`n" - - if ($totalOUs -gt 0) { - $linkedPercentage = [Math]::Round(($linkedOUCount / $totalOUs) * 100, 2) - $result += "| Linked OU Percentage | $linkedPercentage% |" + "`n" - } - - $testResultMarkdown = "Active Directory Organizational Units have been analyzed. $linkedOUCount out of $totalOUs OUs have GPO links.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory OU data. Ensure you have appropriate permissions." - } - } - catch { - Write-Verbose "Error retrieving OU data: $($_.Exception.Message)" - $testResult = $false - $testResultMarkdown = "Error retrieving OU data: $($_.Exception.Message)" - } - - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult -} From 41e557dd482f3d84a78472a7995221199de5c623 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 06:23:26 +0000 Subject: [PATCH 003/100] refactor(ad): consolidate GPO permission and link checks --- .../ActiveDirectoryGpoPermissions.Tests.ps1 | 8 +- tests/ad/gpo-state/Test.AD-GPOREP-01.md | 26 +--- tests/ad/gpo-state/Test.AD-GPOREP-01.ps1 | 124 ++++------------ tests/ad/gpo-state/Test.AD-GPOREP-02.md | 27 ---- tests/ad/gpo-state/Test.AD-GPOREP-02.ps1 | 99 ------------- tests/ad/gpo-state/Test.AD-GPOREP-03.md | 26 +--- tests/ad/gpo-state/Test.AD-GPOREP-03.ps1 | 117 +++------------ tests/ad/gpo-state/Test.AD-GPOREP-04.md | 27 ---- tests/ad/gpo-state/Test.AD-GPOREP-04.ps1 | 98 ------------ tests/ad/gpo-state/Test.AD-GPOREP-07.md | 25 +--- tests/ad/gpo-state/Test.AD-GPOREP-07.ps1 | 139 +++--------------- tests/ad/gpo-state/Test.AD-GPOREP-08.md | 26 ---- tests/ad/gpo-state/Test.AD-GPOREP-08.ps1 | 121 --------------- tests/ad/gpo-state/Test.AD-GPOREP-10.md | 25 +--- tests/ad/gpo-state/Test.AD-GPOREP-10.ps1 | 83 +++-------- tests/ad/gpo-state/Test.AD-GPOREP-11.md | 26 ---- tests/ad/gpo-state/Test.AD-GPOREP-11.ps1 | 74 ---------- tests/ad/gpo-state/Test.AD-GPOREP-12.md | 33 +---- tests/ad/gpo-state/Test.AD-GPOREP-12.ps1 | 39 +++-- tests/ad/gpo-state/Test.AD-GPOREP-13.md | 27 ---- tests/ad/gpo-state/Test.AD-GPOREP-13.ps1 | 84 ----------- 21 files changed, 142 insertions(+), 1112 deletions(-) delete mode 100644 tests/ad/gpo-state/Test.AD-GPOREP-02.md delete mode 100644 tests/ad/gpo-state/Test.AD-GPOREP-02.ps1 delete mode 100644 tests/ad/gpo-state/Test.AD-GPOREP-04.md delete mode 100644 tests/ad/gpo-state/Test.AD-GPOREP-04.ps1 delete mode 100644 tests/ad/gpo-state/Test.AD-GPOREP-08.md delete mode 100644 tests/ad/gpo-state/Test.AD-GPOREP-08.ps1 delete mode 100644 tests/ad/gpo-state/Test.AD-GPOREP-11.md delete mode 100644 tests/ad/gpo-state/Test.AD-GPOREP-11.ps1 delete mode 100644 tests/ad/gpo-state/Test.AD-GPOREP-13.md delete mode 100644 tests/ad/gpo-state/Test.AD-GPOREP-13.ps1 diff --git a/powershell/tests/functions/ActiveDirectoryGpoPermissions.Tests.ps1 b/powershell/tests/functions/ActiveDirectoryGpoPermissions.Tests.ps1 index 0e73dbb18f..ed2f3c0a84 100644 --- a/powershell/tests/functions/ActiveDirectoryGpoPermissions.Tests.ps1 +++ b/powershell/tests/functions/ActiveDirectoryGpoPermissions.Tests.ps1 @@ -2,10 +2,7 @@ # The native tests that read the permission summary of Get-MtADGpoState. Finding is the GPO permission # profile (see New-TestGpo) that the test must flag. $script:permissionTests = @( - @{ Id = 'AD-GPOREP-01'; Command = 'Test-MtAdGpoNoPermissionsCount'; Finding = 'EmptyDacl' } - @{ Id = 'AD-GPOREP-02'; Command = 'Test-MtAdGpoNoPermissionsDetails'; Finding = 'EmptyDacl' } - @{ Id = 'AD-GPOREP-03'; Command = 'Test-MtAdGpoNoAuthenticatedUsersCount'; Finding = 'DomainComputers' } - @{ Id = 'AD-GPOREP-04'; Command = 'Test-MtAdGpoNoAuthenticatedUsersDetails'; Finding = 'DomainComputers' } + # The consolidated 01/03 checks are covered by ADGpoReports.Tests.ps1. @{ Id = 'AD-GPOREP-05'; Command = 'Test-MtAdGpoNoEnterpriseDcCount'; Finding = 'NoEnterpriseDc' } @{ Id = 'AD-GPOREP-06'; Command = 'Test-MtAdGpoNoDomainComputersCount'; Finding = 'NoComputerAccess' } @{ Id = 'AD-GPOREP-09'; Command = 'Test-MtAdGpoInheritedPermissionsCount'; Finding = 'Inherited' } @@ -16,8 +13,7 @@ BeforeAll { Import-Module "$PSScriptRoot/../../Maester.psd1" -Force . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" # Check functions that became native tests are not exported. - Use-MtModuleFunction -Name Test-MtAdGpoNoPermissionsCount, Test-MtAdGpoNoPermissionsDetails, - Test-MtAdGpoNoAuthenticatedUsersCount, Test-MtAdGpoNoAuthenticatedUsersDetails, Test-MtAdGpoNoEnterpriseDcCount, + Use-MtModuleFunction -Name Test-MtAdGpoNoEnterpriseDcCount, Test-MtAdGpoNoDomainComputersCount, Test-MtAdGpoInheritedPermissionsCount $script:domainSid = 'S-1-5-21-1111111111-2222222222-3333333333' diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-01.md b/tests/ad/gpo-state/Test.AD-GPOREP-01.md index 05517fc097..e0d31d628b 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-01.md +++ b/tests/ad/gpo-state/Test.AD-GPOREP-01.md @@ -1,27 +1,13 @@ -#### Test-MtAdGpoNoPermissionsCount +Checks for Group Policy objects whose security descriptor has no permission entries. An empty DACL needs investigation because it can disrupt policy management and application. Unreadable descriptors are listed separately and never treated as clean. - Counts Group Policy Objects (GPOs) with missing permissions. +#### Remediation action -#### Why This Test Matters -- Detective control: counts GPO reports with missing permissions which could expose resources to unintended access. - -#### Control Type - -**Preventive** - -#### Security Recommendation -- Review and remediate missing permissions in GPO ACLs. - -#### How the Test Works -- Fetches GPO state, counts the GPO reports whose DACL has no entries (PermissionsPresent is false), and reports totals. -- A GPO whose permissions could not be read is reported as not evaluated instead of as a finding. The result is then Investigate, or Skipped when no GPO could be evaluated. - -#### Related Tests -- `Test-MtAdGpoNoPermissionsDetails`. +1. In **Group Policy Management**, inspect the listed GPO's **Delegation** and **Advanced** security settings. +2. Restore the intended permissions and confirm that authorized administrators and policy recipients retain the required access. Investigate any GPO whose descriptor could not be read. #### Related links -- [Microsoft Learn - Group Policy management](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) -- ANSSI checkpoint: https://www.anssi.gouv.fr/ + +* [Group Policy overview](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) %TestResult% diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-01.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-01.ps1 index d30537bd44..0986b58de1 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-01.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOREP-01.ps1 @@ -1,33 +1,16 @@ function Test-MtAdGpoNoPermissionsCount { <# .SYNOPSIS - Counts Group Policy Objects (GPOs) with missing permissions. - + Checks whether any GPO has an empty permissions list. .DESCRIPTION - This test retrieves GPO state data and counts how many GPO reports indicate that - permissions are not present. - - .EXAMPLE - Test-MtAdGpoNoPermissionsCount - - Returns $true when no GPOs are missing permissions, otherwise $false. - The test result includes a markdown table with the count. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoNoPermissionsCount + Counts GPOs with no DACL entries and lists affected and unreadable GPOs. #> [MaesterTest( Id = 'AD-GPOREP-01', - Title = 'No GPOs should be missing permissions', - Product = 'ad', - Feature = 'group-policy', - Area = 'access-control', - ResourceType = 'GroupPolicy', - Severity = 'Medium', - UserImpact = 'Low', - ImplementationCost = 'Medium', - Mitre = 'None', - Service = 'ActiveDirectory', + Title = 'No GPO should have an empty permissions list', + Product = 'ad', Feature = 'group-policy', Area = 'access-control', + ResourceType = 'GroupPolicy', Severity = 'Medium', UserImpact = 'Low', + ImplementationCost = 'Medium', Mitre = 'None', Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), Author = 'soulemike' )] @@ -35,80 +18,23 @@ [OutputType([bool])] param() - Write-Verbose "Starting Test-MtAdGpoNoPermissionsCount" - $gpoState = $null - $gpoState = Get-MtADGpoState -Write-Verbose "Retrieved AD state" - -if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting gpo no permissions count" - - $gpoReports = $gpoState.GPOReports - if ($null -eq $gpoReports) { - Add-MtTestResultDetail -Result 'Unable to retrieve GPO reports from Get-MtADGpoState.' - return $false - } - - $gpoReports = @($gpoReports | Where-Object { $null -ne $_ }) - # PermissionsPresent is $null when the security descriptor of a GPO could not be read: unknown, not missing. - $reportsWithNoPermissions = @($gpoReports | Where-Object { $false -eq $_.PermissionsPresent }) - $reportsNotEvaluated = @($gpoReports | Where-Object { $null -eq $_.PermissionsPresent }) - $notEvaluatedCount = $reportsNotEvaluated.Count - - if ($notEvaluatedCount -eq $gpoReports.Count) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "GPO permissions could not be read from Active Directory (0 of $($gpoReports.Count) GPOs evaluated), so this test could not be evaluated." - return $null - } - - $noPermissionsCount = ($reportsWithNoPermissions | Measure-Object).Count - $testResult = $noPermissionsCount -eq 0 - - $sampleLimit = 5 - $sampleGpo = $reportsWithNoPermissions | Select-Object -First $sampleLimit - $sampleNames = @($sampleGpo | ForEach-Object { - $name = $null - if ($_.PSObject.Properties.Name -contains 'Name') { $name = $_.Name } - if ([string]::IsNullOrWhiteSpace($name)) { $name = '' } - $name - }) | Where-Object { $_ } - $sampleNamesText = ($sampleNames -join ', ') - if ($noPermissionsCount -gt $sampleLimit -and $sampleNamesText) { - $sampleNamesText += " (showing first $sampleLimit)" - } - - $resultTable = "| Metric | Value |" + "`n" - $resultTable += "| --- | --- |" + "`n" - $resultTable += "| Total GPO Reports | $([int]($gpoReports | Measure-Object).Count) |" + "`n" - $resultTable += "| GPO Reports With No Permissions | $noPermissionsCount |" + "`n" - if ($noPermissionsCount -gt 0 -and $sampleNamesText) { - $resultTable += "| Sample GPO Reports | $sampleNamesText |" + "`n" - } - if ($notEvaluatedCount -gt 0) { - $notEvaluatedNames = @($reportsNotEvaluated | Select-Object -First $sampleLimit | ForEach-Object { [string]$_.Name }) -join ', ' - $resultTable += "| GPO Reports Not Evaluated (permissions could not be read) | $notEvaluatedCount |" + "`n" - $resultTable += "| Sample GPO Reports Not Evaluated | $notEvaluatedNames |" + "`n" - } - - # Nothing was flagged, but a GPO whose permissions could not be read is not a pass. - $needsInvestigation = $testResult -and $notEvaluatedCount -gt 0 - if ($needsInvestigation) { - $recommendation = "ℹ️ No GPO reports were found with missing permissions among the GPOs that could be evaluated, but the permissions of $notEvaluatedCount GPO(s) could not be read. Review those GPOs manually." - } - elseif ($testResult) { - $recommendation = '✅ No GPO reports were found with missing permissions. Active Directory GPO permissions were analyzed successfully.' - } - else { - $recommendation = "⚠️ GPO reports were found with missing permissions ($noPermissionsCount). Review and remediate GPO security so permissions are correctly applied to required principals." - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "$recommendation`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $resultTable - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate:$needsInvestigation - Write-Verbose "Completed Test-MtAdGpoNoPermissionsCount" - return $testResult + $state = Get-MtADGpoState + if ($null -eq $state -or $null -eq $state.GPOReports) { throw 'GPO permission reports could not be collected.' } + $reports = @($state.GPOReports | Where-Object { $null -ne $_ }) + if ($reports.Count -eq 0) { throw 'No GPO permission reports were collected; cannot establish an empty permissions list.' } + $missing = @($reports | Where-Object { $false -eq $_.PermissionsPresent }) + $unknown = @($reports | Where-Object { $null -eq $_.PermissionsPresent }) + $table = "| GPO | Permissions |`n| --- | --- |`n" + foreach ($report in @($missing + $unknown | Sort-Object Name)) { + $name = [System.Net.WebUtility]::HtmlEncode([string]$report.Name) -replace '\|', '|' + $status = if ($null -eq $report.PermissionsPresent) { 'Not evaluated' } else { 'Empty' } + $table += "| $name | $status |`n" + } + $pass = $missing.Count -eq 0 + $investigate = $pass -and $unknown.Count -gt 0 + $message = if ($investigate) { "Permissions could not be evaluated for $($unknown.Count) of $($reports.Count) GPOs." } + elseif ($pass) { "Well done. All $($reports.Count) GPOs have permissions." } + else { "$($missing.Count) of $($reports.Count) GPOs have no permissions; review their ACLs. $($unknown.Count) could not be evaluated." } + Add-MtTestResultDetail -Result "$message`n`n$table" -Investigate:$investigate + return $pass } diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-02.md b/tests/ad/gpo-state/Test.AD-GPOREP-02.md deleted file mode 100644 index baa207d3fa..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOREP-02.md +++ /dev/null @@ -1,27 +0,0 @@ -#### Test-MtAdGpoNoPermissionsDetails - - Returns details of GPO reports missing permissions. - -#### Why This Test Matters -- Detective control: identifies GPO reports with missing permissions which could enable unintended access. - -#### Control Type - -**Preventive** - -#### Security Recommendation -- Review and remediate missing permissions to ensure proper GPO deployment and ACLs. - -#### How the Test Works -- Aggregates GPO reports and lists the ones whose DACL has no entries (PermissionsPresent is false) in a Markdown table. -- A GPO whose permissions could not be read is reported as not evaluated instead of as a finding. The result is then Investigate, or Skipped when no GPO could be evaluated. - -#### Related Tests -- `Test-MtAdGpoNoPermissionsCount`. - -#### Related links -- [Microsoft Learn - Group Policy management](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) -- ANSSI checkpoint: https://www.anssi.gouv.fr/ - - -%TestResult% diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-02.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-02.ps1 deleted file mode 100644 index 456b292094..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOREP-02.ps1 +++ /dev/null @@ -1,99 +0,0 @@ -function Test-MtAdGpoNoPermissionsDetails { - <# - .SYNOPSIS - Returns details of GPO reports missing permissions. - - .DESCRIPTION - This test retrieves GPO state data and returns a markdown table listing the GPO - reports where permissions are not present. - - .EXAMPLE - Test-MtAdGpoNoPermissionsDetails - - Returns $true when no GPOs are missing permissions, otherwise $false. - The test result includes a markdown table with the affected GPO report names. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoNoPermissionsDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-GPOREP-02', - Title = 'No GPOs should be missing permissions', - Product = 'ad', - Feature = 'group-policy', - Area = 'access-control', - ResourceType = 'GroupPolicy', - Severity = 'Medium', - UserImpact = 'Low', - ImplementationCost = 'Medium', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdGpoNoPermissionsDetails" - $gpoState = $null - $gpoState = Get-MtADGpoState -Write-Verbose "Retrieved AD state" - -if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting gpo no permissions details" - - $gpoReports = $gpoState.GPOReports - if ($null -eq $gpoReports) { - Add-MtTestResultDetail -Result 'Unable to retrieve GPO reports from Get-MtADGpoState.' - return $false - } - - $gpoReports = @($gpoReports | Where-Object { $null -ne $_ }) - # PermissionsPresent is $null when the security descriptor of a GPO could not be read: unknown, not missing. - $reportsWithNoPermissions = @($gpoReports | Where-Object { $false -eq $_.PermissionsPresent }) - $reportsNotEvaluated = @($gpoReports | Where-Object { $null -eq $_.PermissionsPresent }) - $notEvaluatedCount = $reportsNotEvaluated.Count - - if ($notEvaluatedCount -eq $gpoReports.Count) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "GPO permissions could not be read from Active Directory (0 of $($gpoReports.Count) GPOs evaluated), so this test could not be evaluated." - return $null - } - - $noPermissionsCount = ($reportsWithNoPermissions | Measure-Object).Count - $testResult = $noPermissionsCount -eq 0 - - $table = "| GPO Name | PermissionsPresent |" + "`n" - $table += '| --- | --- |' + "`n" - - foreach ($report in @(@($reportsWithNoPermissions) + @($reportsNotEvaluated) | Sort-Object Name)) { - $name = if ($null -ne $report.Name) { [string]$report.Name } else { '' } - $name = $name -replace '\|', '\\|' - - $permissionsPresent = $report.PermissionsPresent - if ($null -eq $permissionsPresent) { $permissionsPresent = 'Not evaluated (permissions could not be read)' } - $table += "| $name | $permissionsPresent |" + "`n" - } - - # Nothing was flagged, but a GPO whose permissions could not be read is not a pass. - $needsInvestigation = $testResult -and $notEvaluatedCount -gt 0 - $recommendation = if ($needsInvestigation) { - "ℹ️ No GPO reports were found with missing permissions among the GPOs that could be evaluated, but the permissions of $notEvaluatedCount GPO(s) could not be read. Review those GPOs manually." - } elseif ($testResult) { - '✅ No GPO reports were found with missing permissions.' - } else { - "⚠️ GPO reports were found with missing permissions ($noPermissionsCount)." - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "$recommendation`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $table - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate:$needsInvestigation - Write-Verbose "Completed Test-MtAdGpoNoPermissionsDetails" - return $testResult -} diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-03.md b/tests/ad/gpo-state/Test.AD-GPOREP-03.md index 17db835eb5..7425e90d32 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-03.md +++ b/tests/ad/gpo-state/Test.AD-GPOREP-03.md @@ -1,27 +1,13 @@ -#### Control Type +Inventories GPOs without an Authenticated Users allow entry. An alternative security-filtering group may be intentional; a missing entry alone does not prove the GPO is insecure. Unreadable permissions are reported separately. -**Detective** +#### Remediation action -#### Test-MtAdGpoNoAuthenticatedUsersCount - - Counts GPO reports that do not include Authenticated Users. - -#### Why This Test Matters -- Detective control: counts GPO reports missing Authenticated Users which could widen access. - -#### Security Recommendation -- Review missing Authenticated Users and adjust GPO ACLs as needed. - -#### How the Test Works -- Uses Get-MtADGpoState, counts the GPO reports without an access-allowed entry for Authenticated Users (HasAuthenticatedUsers is false), and reports totals. -- A GPO whose permissions could not be read is reported as not evaluated instead of as a finding. The result is then Investigate, or Skipped when no GPO could be evaluated. - -#### Related Tests -- `Test-MtAdGpoNoAuthenticatedUsersDetails`. +1. In **Group Policy Management**, inspect each listed GPO's **Scope** > **Security Filtering** and **Delegation** settings. +2. Confirm that intended users or computers can read and apply the GPO; add an appropriate allow entry only when necessary. Investigate permissions that could not be evaluated. #### Related links -- [Microsoft Learn - Group Policy management](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) -- ANSSI checkpoint: https://www.anssi.gouv.fr/ + +* [Group Policy overview](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) %TestResult% diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-03.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-03.ps1 index 2a07192497..300c23f914 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-03.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOREP-03.ps1 @@ -1,32 +1,15 @@ function Test-MtAdGpoNoAuthenticatedUsersCount { <# .SYNOPSIS - Counts GPO reports that do not include Authenticated Users. - + Checks GPO permissions for Authenticated Users. .DESCRIPTION - This test retrieves GPO state data and counts how many GPO reports indicate that - Authenticated Users are not present. - - .EXAMPLE - Test-MtAdGpoNoAuthenticatedUsersCount - - Returns $true when no GPO reports are missing Authenticated Users, otherwise $false. - The test result includes a markdown table with the count. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoNoAuthenticatedUsersCount + Lists GPOs without an Authenticated Users allow entry and those with unreadable permissions. #> [MaesterTest( Id = 'AD-GPOREP-03', - Title = 'GPOs without authenticated users count should be retrievable', - Product = 'ad', - Feature = 'group-policy', - Area = 'access-control', - ResourceType = 'GroupPolicy', - Severity = 'Medium', - UserImpact = 'Low', - ImplementationCost = 'Medium', - Mitre = 'None', + Title = 'GPOs should permit Authenticated Users where required', + Product = 'ad', Feature = 'group-policy', Area = 'access-control', + ResourceType = 'GroupPolicy', Severity = 'Info', Mitre = 'None', Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), Author = 'soulemike' @@ -35,80 +18,18 @@ [OutputType([bool])] param() - Write-Verbose "Starting Test-MtAdGpoNoAuthenticatedUsersCount" - $gpoState = $null - $gpoState = Get-MtADGpoState -Write-Verbose "Retrieved AD state" - -if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting gpo no authenticated users count" - - $gpoReports = $gpoState.GPOReports - if ($null -eq $gpoReports) { - Add-MtTestResultDetail -Result 'Unable to retrieve GPO reports from Get-MtADGpoState.' - return $false - } - - $gpoReports = @($gpoReports | Where-Object { $null -ne $_ }) - # HasAuthenticatedUsers is $null when the security descriptor of a GPO could not be read: unknown, not missing. - $reportsWithNoAuthenticatedUsers = @($gpoReports | Where-Object { $false -eq $_.HasAuthenticatedUsers }) - $reportsNotEvaluated = @($gpoReports | Where-Object { $null -eq $_.HasAuthenticatedUsers }) - $notEvaluatedCount = $reportsNotEvaluated.Count - - if ($notEvaluatedCount -eq $gpoReports.Count) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "GPO permissions could not be read from Active Directory (0 of $($gpoReports.Count) GPOs evaluated), so this test could not be evaluated." - return $null - } - - $noAuthenticatedUsersCount = ($reportsWithNoAuthenticatedUsers | Measure-Object).Count - $testResult = $noAuthenticatedUsersCount -eq 0 - - $sampleLimit = 5 - $sampleGpo = $reportsWithNoAuthenticatedUsers | Select-Object -First $sampleLimit - $sampleNames = @($sampleGpo | ForEach-Object { - $name = $null - if ($_.PSObject.Properties.Name -contains 'Name') { $name = $_.Name } - if ([string]::IsNullOrWhiteSpace($name)) { $name = '' } - $name - }) | Where-Object { $_ } - $sampleNamesText = ($sampleNames -join ', ') - if ($noAuthenticatedUsersCount -gt $sampleLimit -and $sampleNamesText) { - $sampleNamesText += " (showing first $sampleLimit)" - } - - $resultTable = "| Metric | Value |" + "`n" - $resultTable += "| --- | --- |" + "`n" - $resultTable += "| Total GPO Reports | $([int]($gpoReports | Measure-Object).Count) |" + "`n" - $resultTable += "| GPO Reports Without Authenticated Users | $noAuthenticatedUsersCount |" + "`n" - if ($noAuthenticatedUsersCount -gt 0 -and $sampleNamesText) { - $resultTable += "| Sample GPO Reports | $sampleNamesText |" + "`n" - } - if ($notEvaluatedCount -gt 0) { - $notEvaluatedNames = @($reportsNotEvaluated | Select-Object -First $sampleLimit | ForEach-Object { [string]$_.Name }) -join ', ' - $resultTable += "| GPO Reports Not Evaluated (permissions could not be read) | $notEvaluatedCount |" + "`n" - $resultTable += "| Sample GPO Reports Not Evaluated | $notEvaluatedNames |" + "`n" - } - - # Nothing was flagged, but a GPO whose permissions could not be read is not a pass. - $needsInvestigation = $testResult -and $notEvaluatedCount -gt 0 - if ($needsInvestigation) { - $recommendation = "ℹ️ No GPO reports were found missing Authenticated Users among the GPOs that could be evaluated, but the permissions of $notEvaluatedCount GPO(s) could not be read. Review those GPOs manually." - } - elseif ($testResult) { - $recommendation = '✅ No GPO reports were found missing Authenticated Users. GPO permissions were analyzed successfully.' - } - else { - $recommendation = "⚠️ GPO reports were found missing Authenticated Users ($noAuthenticatedUsersCount). Review and remediate GPO security ACLs." - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "$recommendation`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $resultTable - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate:$needsInvestigation - Write-Verbose "Completed Test-MtAdGpoNoAuthenticatedUsersCount" - return $testResult + $state = Get-MtADGpoState + if ($null -eq $state -or $null -eq $state.GPOReports) { throw 'GPO permission reports could not be collected.' } + $reports = @($state.GPOReports | Where-Object { $null -ne $_ }) + if ($reports.Count -eq 0) { throw 'No GPO permission reports were collected.' } + $missing = @($reports | Where-Object { $false -eq $_.HasAuthenticatedUsers }) + $unknown = @($reports | Where-Object { $null -eq $_.HasAuthenticatedUsers }) + $table = "| GPO | Authenticated Users access |`n| --- | --- |`n" + foreach ($report in @($missing + $unknown | Sort-Object Name)) { + $name = [System.Net.WebUtility]::HtmlEncode([string]$report.Name) -replace '\|', '|' + $status = if ($null -eq $report.HasAuthenticatedUsers) { 'Not evaluated' } else { 'No allow entry' } + $table += "| $name | $status |`n" + } + Add-MtTestResultDetail -Result "Review Authenticated Users permissions for $($missing.Count) of $($reports.Count) GPOs; $($unknown.Count) could not be evaluated. An alternative security-filtering group may be intentional.`n`n$table" -Investigate + return $true } diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-04.md b/tests/ad/gpo-state/Test.AD-GPOREP-04.md deleted file mode 100644 index b9291b4275..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOREP-04.md +++ /dev/null @@ -1,27 +0,0 @@ -#### Control Type - -**Detective** - -#### Test-MtAdGpoNoAuthenticatedUsersDetails - - Returns details of GPO reports without Authenticated Users. - -#### Why This Test Matters -- Detective control: detects GPO reports missing Authenticated Users which could widen access. - -#### Security Recommendation -- Review GPOs missing Authenticated Users to ensure access controls are appropriate. - -#### How the Test Works -- Obtains GPO state, selects the reports without an access-allowed entry for Authenticated Users (HasAuthenticatedUsers is false), and renders a details table. -- A GPO whose permissions could not be read is reported as not evaluated instead of as a finding. The result is then Investigate, or Skipped when no GPO could be evaluated. - -#### Related Tests -- `Test-MtAdGpoNoAuthenticatedUsersCount`. - -#### Related links -- [Microsoft Learn - Group Policy management](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) -- ANSSI checkpoint: https://www.anssi.gouv.fr/ - - -%TestResult% diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-04.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-04.ps1 deleted file mode 100644 index 37de10eaba..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOREP-04.ps1 +++ /dev/null @@ -1,98 +0,0 @@ -function Test-MtAdGpoNoAuthenticatedUsersDetails { - <# - .SYNOPSIS - Returns details of GPO reports without Authenticated Users. - - .DESCRIPTION - This test retrieves GPO state data and returns a markdown table listing the GPO - reports where Authenticated Users are not present. - - .EXAMPLE - Test-MtAdGpoNoAuthenticatedUsersDetails - - Returns $true when no GPO reports are missing Authenticated Users, otherwise $false. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoNoAuthenticatedUsersDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-GPOREP-04', - Title = 'GPOs without authenticated users details should be retrievable', - Product = 'ad', - Feature = 'group-policy', - Area = 'access-control', - ResourceType = 'GroupPolicy', - Severity = 'Medium', - UserImpact = 'Low', - ImplementationCost = 'Medium', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdGpoNoAuthenticatedUsersDetails" - $gpoState = $null - $gpoState = Get-MtADGpoState -Write-Verbose "Retrieved AD state" - -if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting gpo no authenticated users details" - - $gpoReports = $gpoState.GPOReports - if ($null -eq $gpoReports) { - Add-MtTestResultDetail -Result 'Unable to retrieve GPO reports from Get-MtADGpoState.' - return $false - } - - $gpoReports = @($gpoReports | Where-Object { $null -ne $_ }) - # HasAuthenticatedUsers is $null when the security descriptor of a GPO could not be read: unknown, not missing. - $reportsWithNoAuthenticatedUsers = @($gpoReports | Where-Object { $false -eq $_.HasAuthenticatedUsers }) - $reportsNotEvaluated = @($gpoReports | Where-Object { $null -eq $_.HasAuthenticatedUsers }) - $notEvaluatedCount = $reportsNotEvaluated.Count - - if ($notEvaluatedCount -eq $gpoReports.Count) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "GPO permissions could not be read from Active Directory (0 of $($gpoReports.Count) GPOs evaluated), so this test could not be evaluated." - return $null - } - - $noAuthenticatedUsersCount = ($reportsWithNoAuthenticatedUsers | Measure-Object).Count - $testResult = $noAuthenticatedUsersCount -eq 0 - - $table = "| GPO Name | HasAuthenticatedUsers |" + "`n" - $table += '| --- | --- |' + "`n" - - foreach ($report in @(@($reportsWithNoAuthenticatedUsers) + @($reportsNotEvaluated) | Sort-Object Name)) { - $name = if ($null -ne $report.Name) { [string]$report.Name } else { '' } - $name = $name -replace '\|', '\\|' - - $hasAuthenticatedUsers = $report.HasAuthenticatedUsers - if ($null -eq $hasAuthenticatedUsers) { $hasAuthenticatedUsers = 'Not evaluated (permissions could not be read)' } - $table += "| $name | $hasAuthenticatedUsers |" + "`n" - } - - # Nothing was flagged, but a GPO whose permissions could not be read is not a pass. - $needsInvestigation = $testResult -and $notEvaluatedCount -gt 0 - $recommendation = if ($needsInvestigation) { - "ℹ️ No GPO reports were found missing Authenticated Users among the GPOs that could be evaluated, but the permissions of $notEvaluatedCount GPO(s) could not be read. Review those GPOs manually." - } elseif ($testResult) { - '✅ No GPO reports were found missing Authenticated Users.' - } else { - "⚠️ GPO reports were found missing Authenticated Users ($noAuthenticatedUsersCount)." - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "$recommendation`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $table - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate:$needsInvestigation - Write-Verbose "Completed Test-MtAdGpoNoAuthenticatedUsersDetails" - return $testResult -} diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-07.md b/tests/ad/gpo-state/Test.AD-GPOREP-07.md index 07a98844a5..ecbb3cebea 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-07.md +++ b/tests/ad/gpo-state/Test.AD-GPOREP-07.md @@ -1,26 +1,13 @@ -#### Control Type +Inventories Group Policy objects with deny access entries. Deny ACEs override allow entries, but can also be intentional. Policies with unreadable security descriptors are listed as not evaluated. -**Detective** +#### Remediation action -#### Test-MtAdGpoDenyAceCount - - Counts GPO reports that include a Deny ACE. - -#### Why This Test Matters -- Detective control: checks for Deny ACEs in GPO reports which can override permissions. - -#### Security Recommendation -- Review or remove Deny ACEs to ensure proper permission handling. - -#### How the Test Works -- Aggregates GPO reports, counts those with HasDenyAce true, and reports totals and a sample of affected GPOs. - -#### Related Tests -- `Test-MtAdGpoDenyAceDetails`. +1. In **Group Policy Management**, inspect the listed GPOs under **Delegation** > **Advanced**. +2. Confirm each deny entry is required and does not prevent intended policy application; remove unintended entries after reviewing inheritance and scope. #### Related links -- [Microsoft Learn - Group Policy management](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) -- ANSSI checkpoint: https://www.anssi.gouv.fr/ + +* [Group Policy overview](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) %TestResult% diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-07.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-07.ps1 index c07689e0bc..23c2bb9698 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-07.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOREP-07.ps1 @@ -1,33 +1,14 @@ function Test-MtAdGpoDenyAceCount { <# .SYNOPSIS - Counts GPO reports that include a Deny ACE. - + Inventories GPOs with explicit deny entries. .DESCRIPTION - This test retrieves GPO state data and counts how many GPO reports indicate that - a Deny ACE is present. - - .EXAMPLE - Test-MtAdGpoDenyAceCount - - Returns $true when no GPO reports include a Deny ACE, otherwise $false. - The test result includes a markdown table with the count. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoDenyAceCount + Lists deny ACE findings for review; deny entries can be intentional. #> [MaesterTest( - Id = 'AD-GPOREP-07', - Title = 'GPOs with deny ACE count should be retrievable', - Product = 'ad', - Feature = 'group-policy', - Area = 'access-control', - ResourceType = 'GroupPolicy', - Severity = 'Medium', - UserImpact = 'Low', - ImplementationCost = 'Medium', - Mitre = 'None', - Service = 'ActiveDirectory', + Id = 'AD-GPOREP-07', Title = 'Review GPOs with deny access entries', + Product = 'ad', Feature = 'group-policy', Area = 'access-control', + ResourceType = 'GroupPolicy', Severity = 'Info', Mitre = 'None', Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), Author = 'soulemike' )] @@ -35,100 +16,18 @@ [OutputType([bool])] param() - Write-Verbose "Starting Test-MtAdGpoDenyAceCount" - $gpoState = $null - $gpoState = Get-MtADGpoState -Write-Verbose "Retrieved AD state" - -if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - if (-not $IsWindows -and $PSVersionTable.PSEdition -eq 'Core') { - Add-MtTestResultDetail -SkippedBecause NotSupported - return $null - } - Write-Verbose "Filtering/counting gpo deny ace count" - - $gpoReports = $null - if ($gpoState.PSObject.Properties.Name -contains 'GPOReports') { - $gpoReports = $gpoState.GPOReports - } - elseif ($gpoState.PSObject.Properties.Name -contains 'GpoReports') { - $gpoReports = $gpoState.GpoReports - } - else { - $gpoReports = @() - foreach ($gpo in @($gpoState.GPOs)) { - foreach ($prop in @('GpoReports', 'GPOReports', 'GpoReport', 'GPOReport')) { - if ($gpo.PSObject.Properties.Name -contains $prop -and $null -ne $gpo.$prop) { - $value = $gpo.$prop - if ($value -is [System.Collections.IEnumerable] -and -not ($value -is [string])) { - $gpoReports += @($value) - } - else { - $gpoReports += $value - } - } - } - } - } - - if ($null -eq $gpoReports) { - Add-MtTestResultDetail -Result 'Unable to retrieve GPO reports from Get-MtADGpoState.' - return $false - } - - $gpoReports = @($gpoReports) - $reportsWithDenyAce = @( - foreach ($report in $gpoReports) { - $hasDenyAce = $null - if ($report.PSObject.Properties.Name -contains 'HasDenyAce') { - $hasDenyAce = $report.HasDenyAce - } - - if ($hasDenyAce -eq $true) { - $report - } - } - ) - - $denyAceCount = ($reportsWithDenyAce | Measure-Object).Count - $testResult = $denyAceCount -eq 0 - - $sampleLimit = 5 - $sampleGpo = $reportsWithDenyAce | Select-Object -First $sampleLimit - $sampleNames = @($sampleGpo | ForEach-Object { - $name = $null - if ($_.PSObject.Properties.Name -contains 'Name') { $name = $_.Name } - if ([string]::IsNullOrWhiteSpace($name)) { $name = '' } - $name - }) | Where-Object { $_ } - $sampleNamesText = ($sampleNames -join ', ') - if ($denyAceCount -gt $sampleLimit -and $sampleNamesText) { - $sampleNamesText += " (showing first $sampleLimit)" - } - - $resultTable = "| Metric | Value |" + "`n" - $resultTable += "| --- | --- |" + "`n" - $resultTable += "| Total GPO Reports | $([int]($gpoReports | Measure-Object).Count) |" + "`n" - $resultTable += "| GPO Reports With Deny ACE | $denyAceCount |" + "`n" - if ($denyAceCount -gt 0 -and $sampleNamesText) { - $resultTable += "| Sample GPO Reports | $sampleNamesText |" + "`n" - } - - if ($testResult) { - $recommendation = '✅ No GPO reports include a Deny ACE.' - } - else { - $recommendation = "⚠️ GPO reports include a Deny ACE ($denyAceCount). Deny ACEs can override expected permissions and require careful review." - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "$recommendation`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $resultTable - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdGpoDenyAceCount" - return $testResult + $state = Get-MtADGpoState + if ($null -eq $state -or $null -eq $state.GPOReports) { throw 'GPO permission reports could not be collected.' } + $reports = @($state.GPOReports | Where-Object { $null -ne $_ }) + if ($reports.Count -eq 0) { throw 'No GPO permission reports were collected.' } + $found = @($reports | Where-Object { $true -eq $_.HasDenyAce }) + $unknown = @($reports | Where-Object { $null -eq $_.HasDenyAce }) + $table = "| GPO | Deny ACE |`n| --- | --- |`n" + foreach ($report in @($found + $unknown | Sort-Object Name)) { + $name = [System.Net.WebUtility]::HtmlEncode([string]$report.Name) -replace '\|', '|' + $status = if ($null -eq $report.HasDenyAce) { 'Not evaluated' } else { 'Present' } + $table += "| $name | $status |`n" + } + Add-MtTestResultDetail -Result "Review deny ACEs on $($found.Count) of $($reports.Count) GPOs; $($unknown.Count) could not be evaluated.`n`n$table" -Investigate + return $true } diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-08.md b/tests/ad/gpo-state/Test.AD-GPOREP-08.md deleted file mode 100644 index ae81fb543b..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOREP-08.md +++ /dev/null @@ -1,26 +0,0 @@ -#### Control Type - -**Detective** - -#### Test-MtAdGpoDenyAceDetails - - Returns details of GPO reports that include a Deny ACE. - -#### Why This Test Matters -- Detective control: lists GPO reports that contain a Deny ACE which could block legitimate policy application. - -#### Security Recommendation -- Review and minimize Deny ACE usage; remove unnecessary permissions to reduce risk. - -#### How the Test Works -- Reads GPO state, selects reports where HasDenyAce is true, and outputs a Markdown table of such GPOs. - -#### Related Tests -- `Test-MtAdGpoDenyAceCount`. - -#### Related links -- [Microsoft Learn - Group Policy management](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) -- ANSSI checkpoint: https://www.anssi.gouv.fr/ - - -%TestResult% diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-08.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-08.ps1 deleted file mode 100644 index 8bdfd8b231..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOREP-08.ps1 +++ /dev/null @@ -1,121 +0,0 @@ -function Test-MtAdGpoDenyAceDetails { - <# - .SYNOPSIS - Returns details of GPO reports that include a Deny ACE. - - .DESCRIPTION - This test retrieves GPO state data and returns a markdown table listing the GPO - reports where a Deny ACE is present. - - .EXAMPLE - Test-MtAdGpoDenyAceDetails - - Returns $true when no GPO reports include a Deny ACE, otherwise $false. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoDenyAceDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using Details')] - [MaesterTest( - Id = 'AD-GPOREP-08', - Title = 'GPOs with deny ACE details should be retrievable', - Product = 'ad', - Feature = 'group-policy', - Area = 'access-control', - ResourceType = 'GroupPolicy', - Severity = 'Medium', - UserImpact = 'Low', - ImplementationCost = 'Medium', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdGpoDenyAceDetails" - $gpoState = $null - $gpoState = Get-MtADGpoState -Write-Verbose "Retrieved AD state" - -if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - if (-not $IsWindows -and $PSVersionTable.PSEdition -eq 'Core') { - Add-MtTestResultDetail -SkippedBecause NotSupported - return $null - } - Write-Verbose "Filtering/counting gpo deny ace details" - - $gpoReports = $null - if ($gpoState.PSObject.Properties.Name -contains 'GPOReports') { - $gpoReports = $gpoState.GPOReports - } elseif ($gpoState.PSObject.Properties.Name -contains 'GpoReports') { - $gpoReports = $gpoState.GpoReports - } else { - $gpoReports = @() - foreach ($gpo in @($gpoState.GPOs)) { - foreach ($prop in @('GpoReports', 'GPOReports', 'GpoReport', 'GPOReport')) { - if ($gpo.PSObject.Properties.Name -contains $prop -and $null -ne $gpo.$prop) { - $value = $gpo.$prop - if ($value -is [System.Collections.IEnumerable] -and -not ($value -is [string])) { - $gpoReports += @($value) - } else { - $gpoReports += $value - } - } - } - } - } - - if ($null -eq $gpoReports) { - Add-MtTestResultDetail -Result 'Unable to retrieve GPO reports from Get-MtADGpoState.' - return $false - } - - $gpoReports = @($gpoReports) - $reportsWithDenyAce = @( - foreach ($report in $gpoReports) { - $hasDenyAce = $null - if ($report.PSObject.Properties.Name -contains 'HasDenyAce') { - $hasDenyAce = $report.HasDenyAce - } - - if ($hasDenyAce -eq $true) { - $report - } - } - ) - - $denyAceCount = ($reportsWithDenyAce | Measure-Object).Count - $testResult = $denyAceCount -eq 0 - - $table = "| GPO Name | HasDenyAce |" + "`n" - $table += '| --- | --- |' + "`n" - - foreach ($report in @($reportsWithDenyAce | Sort-Object Name)) { - $name = if ($null -ne $report.Name) { [string]$report.Name } else { '' } - $name = $name -replace '\|', '\\|' - - $hasDenyAce = $report.HasDenyAce - if ($null -eq $hasDenyAce) { $hasDenyAce = '' } - $table += "| $name | $hasDenyAce |" + "`n" - } - - $recommendation = if ($testResult) { - '✅ No GPO reports include a Deny ACE.' - } else { - "⚠️ GPO reports include a Deny ACE ($denyAceCount)." - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "$recommendation`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $table - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdGpoDenyAceDetails" - return $testResult -} diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-10.md b/tests/ad/gpo-state/Test.AD-GPOREP-10.md index fd451d53db..994bd99b02 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-10.md +++ b/tests/ad/gpo-state/Test.AD-GPOREP-10.md @@ -1,26 +1,15 @@ -#### Test-MtAdGpoNoApplyGroupPolicyAceCount +Checks that every GPO has an allow entry for the Apply Group Policy right. A policy without application rights cannot deliver its intended settings through that right. This is a policy-health check, not a calculation of effective permissions for every user or computer. - Counts the number of GPOs missing the "Apply Group Policy" ACE. +The check fails when an application entry is absent and errors when permissions are unreadable. Intentionally unused policies require review before granting access; archive or remove them if they are no longer needed. -#### Why This Test Matters -- Detective control: counts GPOs missing the Apply Group Policy ACE which governs policy application. +#### Remediation action -#### Control Type - -**Operational** - -#### Security Recommendation -- Ensure the ACE is present on necessary GPOs or document why it is absent. - -#### How the Test Works -- Evaluates GPO reports for HasApplyGroupPolicyAce, counts missing ACE occurrences, and provides a sample list. - -#### Related Tests -- `Test-MtAdGpoNoApplyGroupPolicyAceDetails`. +1. In **Group Policy Management**, inspect the listed GPO's **Scope** > **Security Filtering** and **Delegation** > **Advanced** settings. +2. Grant Apply Group Policy only to principals that should receive the policy. Document intentionally unused policies and investigate unreadable permissions. #### Related links -- [Microsoft Learn - Group Policy management](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) -- ANSSI checkpoint: https://www.anssi.gouv.fr/ + +* [Group Policy overview](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) %TestResult% diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-10.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-10.ps1 index 86af1d86e8..f0d6744d3b 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-10.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOREP-10.ps1 @@ -1,32 +1,15 @@ -<# #> -function Test-MtAdGpoNoApplyGroupPolicyAceCount { +function Test-MtAdGpoNoApplyGroupPolicyAceCount { <# .SYNOPSIS - Counts the number of GPOs missing the "Apply Group Policy" ACE. - + Checks that every GPO has an Apply Group Policy allow entry. .DESCRIPTION - This test retrieves Active Directory Group Policy state information using Get-MtADGpoState, - then analyzes each GPO report for whether it has an ACE granting the "Apply Group Policy" right. - - .EXAMPLE - Test-MtAdGpoNoApplyGroupPolicyAceCount - - Returns $true if GPO report data is accessible, $false otherwise. - The test result includes the count of GPOs without the required "Apply Group Policy" ACE. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoNoApplyGroupPolicyAceCount + Fails when a GPO has no Apply Group Policy allow entry. This checks the presence + of an application right, not the full effective access of every target principal. #> [MaesterTest( - Id = 'AD-GPOREP-10', - Title = 'GPO no-apply Group Policy ACE count should be investigated', - Product = 'ad', - Feature = 'group-policy', - Area = 'access-control', - ResourceType = 'GroupPolicy', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', + Id = 'AD-GPOREP-10', Title = 'GPOs should have an Apply Group Policy allow entry', + Product = 'ad', Feature = 'group-policy', Area = 'access-control', + ResourceType = 'GroupPolicy', Severity = 'Low', UserImpact = 'Low', ImplementationCost = 'Medium', Mitre = 'None', Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), Author = 'soulemike' )] @@ -34,42 +17,20 @@ function Test-MtAdGpoNoApplyGroupPolicyAceCount { [OutputType([bool])] param() - Write-Verbose "Starting Test-MtAdGpoNoApplyGroupPolicyAceCount" - $gpoState = Get-MtADGpoState - Write-Verbose "Retrieved AD state" - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - if (-not $IsWindows -and $PSVersionTable.PSEdition -eq 'Core') { - Add-MtTestResultDetail -SkippedBecause NotSupported - return $null - } - Write-Verbose "Filtering/counting gpo no apply group policy ace count" - - $gpoReports = $gpoState.GPOReports - if ($null -eq $gpoReports) { - Add-MtTestResultDetail -Result 'Unable to retrieve Active Directory GPO report data from Get-MtADGpoState.' - return $false + $state = Get-MtADGpoState + if ($null -eq $state -or $null -eq $state.GPOReports) { throw 'GPO permission reports could not be collected.' } + $reports = @($state.GPOReports | Where-Object { $null -ne $_ }) + if ($reports.Count -eq 0) { throw 'No GPO permission reports were collected.' } + $missing = @($reports | Where-Object { $false -eq $_.HasApplyGroupPolicyAce }) + $unknown = @($reports | Where-Object { $null -eq $_.HasApplyGroupPolicyAce }) + if ($unknown.Count -gt 0) { throw 'GPO application permissions could not be evaluated for every policy.' } + $table = "| GPO | Apply Group Policy ACE |`n| --- | --- |`n" + foreach ($report in @($missing + $unknown | Sort-Object Name)) { + $name = [System.Net.WebUtility]::HtmlEncode([string]$report.Name) -replace '\|', '|' + $status = if ($null -eq $report.HasApplyGroupPolicyAce) { 'Not evaluated' } else { 'Not present' } + $table += "| $name | $status |`n" } - - $gpoReportsArray = @($gpoReports | Where-Object { $null -ne $_ }) - - $gpoCount = $gpoReportsArray.Count - $noApplyAceCount = @($gpoReportsArray | Where-Object { $_.HasApplyGroupPolicyAce -eq $false }).Count - - $testResult = $true - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total GPOs | $gpoCount |" + "`n" - $result += "| GPOs missing Apply Group Policy ACE | $noApplyAceCount |" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory GPOs have been analyzed for Apply Group Policy permissions. $noApplyAceCount out of $gpoCount GPO(s) are missing the required ACE.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdGpoNoApplyGroupPolicyAceCount" - return $testResult + $message = if ($missing.Count -eq 0) { 'Well done. Every GPO has an Apply Group Policy allow entry.' } else { "Grant appropriate application rights or archive intentionally unused policies: $($missing.Count) of $($reports.Count) GPOs have no Apply Group Policy allow entry." } + Add-MtTestResultDetail -Result "$message`n`n$table" + return ($missing.Count -eq 0) } diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-11.md b/tests/ad/gpo-state/Test.AD-GPOREP-11.md deleted file mode 100644 index 926a562a00..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOREP-11.md +++ /dev/null @@ -1,26 +0,0 @@ -#### Test-MtAdGpoNoApplyGroupPolicyAceDetails - - Returns details of GPOs missing the "Apply Group Policy" ACE. - -#### Why This Test Matters -- Detective control: lists GPOs missing the Apply Group Policy ACE, which governs how policy is applied. - -#### Control Type - -**Operational** - -#### Security Recommendation -- Ensure required ACE is present or document why it is absent. - -#### How the Test Works -- Reads GPO state, filters for reports where HasApplyGroupPolicyAce is false, and outputs a Markdown table of findings. - -#### Related Tests -- `Test-MtAdGpoNoApplyGroupPolicyAceCount`. - -#### Related links -- [Microsoft Learn - Group Policy management](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) -- ANSSI checkpoint: https://www.anssi.gouv.fr/ - - -%TestResult% diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-11.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-11.ps1 deleted file mode 100644 index 5d288c92ec..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOREP-11.ps1 +++ /dev/null @@ -1,74 +0,0 @@ -<# #> -function Test-MtAdGpoNoApplyGroupPolicyAceDetails { - <# - .SYNOPSIS - Returns details of GPOs missing the "Apply Group Policy" ACE. - - .DESCRIPTION - This test retrieves Active Directory Group Policy state information using Get-MtADGpoState, - then analyzes each GPO report to identify which GPOs are missing the ACE required for - applying group policy. - - .EXAMPLE - Test-MtAdGpoNoApplyGroupPolicyAceDetails - - Returns $true if GPO report data is accessible, $false otherwise. - The test result includes a markdown table listing GPOs missing the required ACE. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoNoApplyGroupPolicyAceDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-GPOREP-11', - Title = 'GPO no-apply Group Policy ACE details should be investigated', - Product = 'ad', - Feature = 'group-policy', - Area = 'access-control', - ResourceType = 'GroupPolicy', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdGpoNoApplyGroupPolicyAceDetails" - $gpoState = Get-MtADGpoState - Write-Verbose "Retrieved AD state" - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting gpo no apply group policy ace details" - - $gpoReports = $gpoState.GPOReports - if ($null -eq $gpoReports) { - Add-MtTestResultDetail -Result 'Unable to retrieve Active Directory GPO report data from Get-MtADGpoState.' - return $false - } - - $gpoReportsArray = @($gpoReports | Where-Object { $null -ne $_ }) - $noApplyAceReports = @($gpoReportsArray | Where-Object { $_.HasApplyGroupPolicyAce -eq $false }) - - $table = "| GPO Name | HasApplyGroupPolicyAce |" + "`n" - $table += '| --- | --- |' + "`n" - - foreach ($report in ($noApplyAceReports | Sort-Object -Property Name)) { - $name = [string]$report.Name - $name = $name -replace '\|', '\\|' - $table += "| $name | $([bool]$report.HasApplyGroupPolicyAce) |" + "`n" - } - - $testResult = $true - Write-Verbose "Counts computed" - $testResultMarkdown = "GPO apply permissions were analyzed. $($noApplyAceReports.Count) GPO(s) are missing the required ACE.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $table - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdGpoNoApplyGroupPolicyAceDetails" - return $testResult -} diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-12.md b/tests/ad/gpo-state/Test.AD-GPOREP-12.md index 00bdc213ce..cb8f60a37f 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-12.md +++ b/tests/ad/gpo-state/Test.AD-GPOREP-12.md @@ -1,34 +1,13 @@ -Disabled GPO links represent a potential security and operational concern in Active Directory environments: +Inventories disabled GPO links, including the GPO and linked container for each disabled link. A disabled link can be intentional, but can also leave security settings unapplied. The count is of links, not distinct GPOs. -- **Policy Gaps**: Disabled links mean GPOs that are configured but not applied, potentially leaving systems without intended security controls -- **Configuration Drift**: Disabled links may indicate temporary troubleshooting that was never reverted -- **Audit Challenges**: Disabled links create confusion during security audits about which policies are actually enforced -- **Compliance Risks**: Unintentionally disabled links can result in non-compliance with security baselines +#### Remediation action -#### Security Recommendation +1. In **Group Policy Management**, navigate to the listed organizational unit, domain or site and inspect its linked GPOs. +2. Re-enable links that should apply, remove obsolete links, and document intentional exceptions. Confirm the effect of inherited policies before changing links. -Regularly review disabled GPO links and either: +#### Related links -- Re-enable links that were accidentally disabled -- Remove links that are no longer needed -- Document the justification for intentionally disabled links -- Ensure critical security policies are not inadvertently disabled - -#### How the Test Works - -This test retrieves GPO link information from Active Directory and counts: -- Total number of GPO links -- Number of enabled links (state 0) -- Number of disabled links (state 1) -- Number of enforced links (state 2) - -The gPLink attribute is parsed to determine the state of each link. - -#### Related Tests - -- `Test-MtAdGpoEnforcedCount` - Counts enforced GPO links -- `Test-MtAdGpoLinkedCount` - Counts distinct GPOs with links -- `Test-MtAdGpoUnlinkedCount` - Identifies GPOs with no links +* [Group Policy overview](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) %TestResult% diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-12.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-12.ps1 index f4432b1317..131bbb48d0 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-12.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOREP-12.ps1 @@ -1,21 +1,14 @@ function Test-MtCheckADGPOREP12 { <# .SYNOPSIS - GPO disabled link count should be retrievable - + Inventories disabled GPO links. .DESCRIPTION - Runs the shared check Test-MtAdGpoDisabledLinkCount. + Counts disabled links and lists their target policies and containers for review. #> [MaesterTest( - Id = 'AD-GPOREP-12', - Title = 'GPO disabled link count should be retrievable', - Product = 'ad', - Feature = 'group-policy', - Area = 'infrastructure', - ResourceType = 'GroupPolicy', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', + Id = 'AD-GPOREP-12', Title = 'Review disabled GPO links', + Product = 'ad', Feature = 'group-policy', Area = 'infrastructure', + ResourceType = 'GroupPolicy', Severity = 'Info', Mitre = 'None', Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), Author = 'soulemike' )] @@ -23,7 +16,23 @@ [OutputType([bool])] param() - $result = Test-MtAdGpoDisabledLinkCount - if ($null -eq $result) { return $null } - return $result + $state = Get-MtADGpoState + if ($null -eq $state -or $null -eq $state.GPOLinks -or $null -eq $state.GPOs) { + throw 'GPO links or GPO metadata could not be collected; cannot inventory disabled links.' + } + $links = @($state.GPOLinks | Where-Object { $null -ne $_ }) + if (@($links | Where-Object { $null -eq $_.IsDisabled }).Count -gt 0) { + throw 'One or more GPO link states could not be evaluated.' + } + $disabled = @($links | Where-Object { $true -eq $_.IsDisabled }) + $table = "| GPO | Linked container |`n| --- | --- |`n" + foreach ($link in @($disabled | Sort-Object DistinguishedName, GpoGuid)) { + $gpo = @($state.GPOs | Where-Object { ([string]$_.Id).Trim('{}') -eq ([string]$link.GpoGuid).Trim('{}') } | Select-Object -First 1) + $name = if ($gpo.Count -gt 0) { [string]$gpo[0].DisplayName } else { [string]$link.GpoGuid } + $name = [System.Net.WebUtility]::HtmlEncode($name) -replace '\|', '|' + $container = [System.Net.WebUtility]::HtmlEncode([string]$link.DistinguishedName) -replace '\|', '|' + $table += "| $name | $container |`n" + } + Add-MtTestResultDetail -Result "Review $($disabled.Count) disabled links among $($links.Count) GPO links; some may be intentionally disabled.`n`n$table" -Investigate + return $true } diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-13.md b/tests/ad/gpo-state/Test.AD-GPOREP-13.md deleted file mode 100644 index d9ba31d1f3..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOREP-13.md +++ /dev/null @@ -1,27 +0,0 @@ -#### Test-MtAdGpoDisabledLinkDetails - - Returns details of GPOs with disabled GPO links. - -#### Why This Test Matters -- Detective control: checks for GPOs with disabled links to identify potential misconfigurations that could affect policy delivery. -- Disabled links can lead to unexpected policy application gaps. - -#### Control Type - -**Operational** - -#### Security Recommendation -- Review and re-enable intentional GPO links or remove unused GPOs to restore intended policy application. - -#### How the Test Works -- Retrieves GPO state via Get-MtADGpoState, filters GPOReports for DisabledLinks greater than 0, and renders a Markdown table with the results. - -#### Related Tests -- `Test-MtAdGpoDisabledLinkCount` - Count of disabled links across GPOs. - -#### Related links -- [Microsoft Learn - Group Policy management](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) -- ANSSI checkpoint: https://www.anssi.gouv.fr/ - - -%TestResult% diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-13.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-13.ps1 deleted file mode 100644 index d91c3fb88c..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOREP-13.ps1 +++ /dev/null @@ -1,84 +0,0 @@ -<# #> -function Test-MtAdGpoDisabledLinkDetails { - <# - .SYNOPSIS - Returns details of GPOs with disabled GPO links. - - .DESCRIPTION - This test retrieves Active Directory Group Policy state information using Get-MtADGpoState, - then returns a markdown table listing all GPO reports whose DisabledLinks value is greater than 0. - - .EXAMPLE - Test-MtAdGpoDisabledLinkDetails - - Returns $true if GPO report data is accessible, $false otherwise. - The test result includes a markdown table of GPOs with disabled link(s). - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoDisabledLinkDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-GPOREP-13', - Title = 'GPO disabled link details should be investigated', - Product = 'ad', - Feature = 'group-policy', - Area = 'infrastructure', - ResourceType = 'GroupPolicy', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdGpoDisabledLinkDetails" - $gpoState = Get-MtADGpoState - Write-Verbose "Retrieved AD state" - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting gpo disabled link details" - - $gpoReports = $gpoState.GPOReports - if ($null -eq $gpoReports) { - Add-MtTestResultDetail -Result 'Unable to retrieve Active Directory GPO report data from Get-MtADGpoState.' - return $false - } - - $gpoReportsArray = @($gpoReports | Where-Object { $null -ne $_ }) - $disabled = $gpoReportsArray | Where-Object { [int]$_.DisabledLinks -gt 0 } - $disabledCount = @($disabled).Count - - $testResult = $true - - $table = "| GPO Name | DisabledLinks | Enforcement |" + "`n" - $table += '| --- | --- | --- |' + "`n" - - foreach ($report in ($disabled | Sort-Object -Property Name)) { - $name = [string]$report.Name - $name = $name -replace '\|', '|' - - $disabledLinks = [int]$report.DisabledLinks - $enforcement = [int]$report.Enforcement - $table += "| $name | $disabledLinks | $enforcement |" + "`n" - } - - $recommendation = if ($disabledCount -gt 0) { - "GPO disabled link details were returned ($disabledCount). Review these GPO links to ensure they are still intended." - } else { - '✅ No GPOs with disabled link configuration were found.' - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "$recommendation`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $table - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdGpoDisabledLinkDetails" - return $testResult -} From 0a32860ce1fbef2b53620e04eb787229e2f16980 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 06:23:26 +0000 Subject: [PATCH 004/100] fix(ad): consolidate GPO version and exposed-password checks --- .../tests/functions/ADGpoReports.Tests.ps1 | 125 ++++++++++++++++++ tests/ad/gpo-state/Test.AD-GPOREP-15.md | 25 +--- tests/ad/gpo-state/Test.AD-GPOREP-15.ps1 | 86 ++++-------- tests/ad/gpo-state/Test.AD-GPOREP-16.md | 26 ---- tests/ad/gpo-state/Test.AD-GPOREP-16.ps1 | 83 ------------ tests/ad/gpo-state/Test.AD-GPOREP-17.md | 25 +--- tests/ad/gpo-state/Test.AD-GPOREP-17.ps1 | 89 +++++-------- tests/ad/gpo-state/Test.AD-GPOREP-18.md | 27 ---- tests/ad/gpo-state/Test.AD-GPOREP-18.ps1 | 87 ------------ tests/ad/gpo-state/Test.AD-GPOREP-19.md | 26 ---- tests/ad/gpo-state/Test.AD-GPOREP-19.ps1 | 75 ----------- tests/ad/gpo-state/Test.AD-GPOREP-20.md | 28 ---- tests/ad/gpo-state/Test.AD-GPOREP-20.ps1 | 87 ------------ 13 files changed, 195 insertions(+), 594 deletions(-) create mode 100644 powershell/tests/functions/ADGpoReports.Tests.ps1 delete mode 100644 tests/ad/gpo-state/Test.AD-GPOREP-16.md delete mode 100644 tests/ad/gpo-state/Test.AD-GPOREP-16.ps1 delete mode 100644 tests/ad/gpo-state/Test.AD-GPOREP-18.md delete mode 100644 tests/ad/gpo-state/Test.AD-GPOREP-18.ps1 delete mode 100644 tests/ad/gpo-state/Test.AD-GPOREP-19.md delete mode 100644 tests/ad/gpo-state/Test.AD-GPOREP-19.ps1 delete mode 100644 tests/ad/gpo-state/Test.AD-GPOREP-20.md delete mode 100644 tests/ad/gpo-state/Test.AD-GPOREP-20.ps1 diff --git a/powershell/tests/functions/ADGpoReports.Tests.ps1 b/powershell/tests/functions/ADGpoReports.Tests.ps1 new file mode 100644 index 0000000000..eddf9853df --- /dev/null +++ b/powershell/tests/functions/ADGpoReports.Tests.ps1 @@ -0,0 +1,125 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name Test-MtAdGpoCpasswordFoundCount, Test-MtAdGpoVersionMismatchCount, Test-MtCheckADGPOREP12, Test-MtAdGpoNoApplyGroupPolicyAceCount, Test-MtAdGpoNoPermissionsCount, Test-MtAdGpoNoAuthenticatedUsersCount +} + +Describe 'Merged AD GPO report checks' { + BeforeEach { + $script:detail = $null + $script:report = [PSCustomObject]@{ + Name = 'Example GPO' + CpasswordFound = $false + DefaultPasswordFound = $false + HasVersionMismatch = $false + DirectoryVersion = 65538 + SysvolVersion = 65538 + Errors = @() + HasApplyGroupPolicyAce = $true + PermissionsPresent = $true + HasAuthenticatedUsers = $true + } + $script:state = [PSCustomObject]@{ + GPOs = @([PSCustomObject]@{ Id = '00000000-0000-0000-0000-000000000001'; DisplayName = 'Example GPO' }) + GPOReports = @($script:report) + GPOLinks = @() + } + Mock Get-MtADGpoState -ModuleName Maester { $script:state } + Mock Add-MtTestResultDetail -ModuleName Maester { $script:detail = $Result } + } + + It 'passes only after both secret scan flags are evaluated' { + Test-MtAdGpoCpasswordFoundCount | Should -BeTrue + $script:detail | Should -Match 'Well done' + } + + It 'fails when a GPO has no permissions and lists its name' { + $script:report.PermissionsPresent = $false + Test-MtAdGpoNoPermissionsCount | Should -BeFalse + $script:detail | Should -Match 'Example GPO' + } + + It 'marks unreadable permissions for investigation' { + $script:report.PermissionsPresent = $null + Test-MtAdGpoNoPermissionsCount | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Exactly 1 -ParameterFilter { $Investigate } + } + + It 'investigates alternative security filtering rather than failing Authenticated Users absence' { + $script:report.HasAuthenticatedUsers = $false + Test-MtAdGpoNoAuthenticatedUsersCount | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Exactly 1 -ParameterFilter { $Investigate } + $script:detail | Should -Match 'Example GPO' + } + + It 'passes when application rights are present' { + Test-MtAdGpoNoApplyGroupPolicyAceCount | Should -BeTrue + Should -Not -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + } + + It 'fails when application rights are absent' { + $script:report.HasApplyGroupPolicyAce = $false + Test-MtAdGpoNoApplyGroupPolicyAceCount | Should -BeFalse + $script:detail | Should -Match 'Example GPO' + } + + It 'errors rather than passing when application rights are unreadable' { + $script:report.HasApplyGroupPolicyAce = $null + { Test-MtAdGpoNoApplyGroupPolicyAceCount } | Should -Throw '*could not be evaluated*' + } + + It 'fails on cpassword alone without rendering the secret value' { + $script:report.CpasswordFound = $true + $script:report | Add-Member -NotePropertyName Password -NotePropertyValue 'SECRET-MUST-NOT-PRINT' + Test-MtAdGpoCpasswordFoundCount | Should -BeFalse + $script:detail | Should -Match 'Example GPO' + $script:detail | Should -Not -Match 'SECRET-MUST-NOT-PRINT' + } + + It 'fails on a default password alone' { + $script:report.DefaultPasswordFound = $true + Test-MtAdGpoCpasswordFoundCount | Should -BeFalse + $script:detail | Should -Match 'default passwords' + } + + It 'errors on null or missing scan flags and on SYSVOL collection errors' -ForEach @( + @{ Case = 'missing cpassword flag' } + @{ Case = 'missing default password flag' } + @{ Case = 'SYSVOL error' } + ) { + switch ($Case) { + 'missing cpassword flag' { $script:report.CpasswordFound = $null } + 'missing default password flag' { $script:report.DefaultPasswordFound = $null } + 'SYSVOL error' { $script:report.Errors = @([PSCustomObject]@{ Transport = 'SYSVOL'; Message = 'failed' }) } + } + { Test-MtAdGpoCpasswordFoundCount } | Should -Throw '*incomplete*' + } + + It 'errors if report collection silently drops a GPO' { + $script:state.GPOs += [PSCustomObject]@{ Id = '00000000-0000-0000-0000-000000000002'; DisplayName = 'Other GPO' } + { Test-MtAdGpoCpasswordFoundCount } | Should -Throw '*inventory*' + } + + It 'shows both versions for mismatched policies' { + $script:report.HasVersionMismatch = $true + $script:report.SysvolVersion = 65539 + Test-MtAdGpoVersionMismatchCount | Should -BeFalse + $script:detail | Should -Match '65538 \| 65539' + } + + It 'does not pass when SYSVOL version is missing' { + $script:report.SysvolVersion = $null + { Test-MtAdGpoVersionMismatchCount } | Should -Throw '*incomplete*' + } + + It 'inventories disabled links and lists their linked container' { + $script:state.GPOLinks = @([PSCustomObject]@{ + GpoGuid = '00000000-0000-0000-0000-000000000001' + DistinguishedName = 'OU=Clients,DC=example,DC=com' + IsDisabled = $true + }) + Test-MtCheckADGPOREP12 | Should -BeTrue + $script:detail | Should -Match '1 disabled links' + $script:detail | Should -Match 'OU=Clients' + } +} diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-15.md b/tests/ad/gpo-state/Test.AD-GPOREP-15.md index babf93248d..a5a5386b9b 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-15.md +++ b/tests/ad/gpo-state/Test.AD-GPOREP-15.md @@ -1,26 +1,13 @@ -#### Test-MtAdGpoVersionMismatchCount +Checks whether each GPO's directory version differs from its SYSVOL GPT.INI version. A mismatch can indicate replication or policy deployment problems. The result lists both versions for mismatched policies. Incomplete SYSVOL reads or missing version fields produce an error, never a clean result. - Counts the number of GPOs with a version mismatch. +#### Remediation action -#### Why This Test Matters -- Detective control: flags GPOs that have a version mismatch which could affect policy consistency across machines. - -#### Control Type - -**Detective** - -#### Security Recommendation -- Review mismatched GPOs and align versions with baseline configurations. - -#### How the Test Works -- Pulls GPO state, filters HasVersionMismatch, counts total/mismatched and computes a mismatch ratio. - -#### Related Tests -- `Test-MtAdGpoVersionMismatchDetails`. +1. In **Group Policy Management**, identify the listed GPOs and compare directory and SYSVOL policy versions. +2. Diagnose replication and GPT.INI access, then synchronize the affected policy files and directory metadata. Re-run the check after replication completes. #### Related links -- [Microsoft Learn - Group Policy management](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) -- ANSSI checkpoint: https://www.anssi.gouv.fr/ + +* [Group Policy overview](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) %TestResult% diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-15.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-15.ps1 index e94cf79e6c..bdcc08411e 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-15.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOREP-15.ps1 @@ -1,34 +1,15 @@ -<# #> -function Test-MtAdGpoVersionMismatchCount { +function Test-MtAdGpoVersionMismatchCount { <# .SYNOPSIS - Counts the number of GPOs with a version mismatch. - + Checks for mismatched Active Directory and SYSVOL GPO versions. .DESCRIPTION - This test retrieves Active Directory Group Policy state information using Get-MtADGpoState, - then counts how many returned GPO reports indicate a version mismatch. - - .EXAMPLE - Test-MtAdGpoVersionMismatchCount - - Returns $true if GPO report data is accessible, $false otherwise. - The test result includes the number of GPOs with version mismatch. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoVersionMismatchCount + Lists policies with differing directory and GPT.INI versions; incomplete scans are errors. #> [MaesterTest( - Id = 'AD-GPOREP-15', - Title = 'No GPOs should have version mismatches', - Product = 'ad', - Feature = 'group-policy', - Area = 'infrastructure', - ResourceType = 'GroupPolicy', - Severity = 'Medium', - UserImpact = 'Low', - ImplementationCost = 'Medium', - Mitre = 'None', - Service = 'ActiveDirectory', + Id = 'AD-GPOREP-15', Title = 'GPO directory and SYSVOL versions should match', + Product = 'ad', Feature = 'group-policy', Area = 'infrastructure', + ResourceType = 'GroupPolicy', Severity = 'Low', UserImpact = 'Low', + ImplementationCost = 'Medium', Mitre = 'None', Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), Author = 'soulemike' )] @@ -36,39 +17,26 @@ function Test-MtAdGpoVersionMismatchCount { [OutputType([bool])] param() - Write-Verbose "Starting Test-MtAdGpoVersionMismatchCount" - $gpoState = Get-MtADGpoState - Write-Verbose "Retrieved AD state" - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + $state = Get-MtADGpoState + if ($null -eq $state -or $null -eq $state.GPOReports -or $null -eq $state.GPOs) { + throw 'GPO version reports or GPO metadata could not be collected.' } - Write-Verbose "Filtering/counting gpo version mismatch count" - - $gpoReports = $gpoState.GPOReports - if ($null -eq $gpoReports) { - Add-MtTestResultDetail -Result 'Unable to retrieve Active Directory GPO report data from Get-MtADGpoState.' - return $false + $reports = @($state.GPOReports | Where-Object { $null -ne $_ }) + if ($reports.Count -eq 0 -or $reports.Count -ne @($state.GPOs).Count) { throw 'GPO version report count is empty or does not match GPO inventory.' } + $incomplete = @($reports | Where-Object { + $null -eq $_.HasVersionMismatch -or $null -eq $_.DirectoryVersion -or + $null -eq $_.SysvolVersion -or $null -eq $_.Errors -or @($_.Errors).Count -gt 0 + }) + if ($incomplete.Count -gt 0) { throw "Version comparison incomplete for $($incomplete.Count) GPOs; verify SYSVOL collection and GPT.INI access." } + $mismatched = @($reports | Where-Object { $true -eq $_.HasVersionMismatch }) + $table = "| GPO | Directory version | SYSVOL version |`n| --- | --- | --- |`n" + foreach ($report in @($mismatched | Sort-Object Name)) { + $name = [System.Net.WebUtility]::HtmlEncode([string]$report.Name) -replace '\|', '|' + $table += "| $name | $($report.DirectoryVersion) | $($report.SysvolVersion) |`n" } - - $gpoReportsArray = @($gpoReports | Where-Object { $null -ne $_ }) - $totalCount = $gpoReportsArray.Count - $mismatchCount = @($gpoReportsArray | Where-Object { [bool]$_.HasVersionMismatch }).Count - - $testResult = $mismatchCount -eq 0 - $mismatchPercentage = if ($totalCount -gt 0) { [Math]::Round(($mismatchCount / $totalCount) * 100, 2) } else { 0 } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total GPOs | $totalCount |" + "`n" - $result += "| GPOs with version mismatch | $mismatchCount |" + "`n" - $result += "| Mismatch ratio | $mismatchPercentage% |" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory GPOs have been analyzed for version mismatches. $mismatchCount out of $totalCount GPO(s) indicate a version mismatch.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdGpoVersionMismatchCount" - return $testResult + $pass = $mismatched.Count -eq 0 + $message = if ($pass) { "Well done. All $($reports.Count) GPO directory and SYSVOL versions match." } + else { "$($mismatched.Count) of $($reports.Count) GPOs have different directory and SYSVOL versions; investigate replication and GPT.INI." } + Add-MtTestResultDetail -Result "$message`n`n$table" + return $pass } diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-16.md b/tests/ad/gpo-state/Test.AD-GPOREP-16.md deleted file mode 100644 index d8abdeaa32..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOREP-16.md +++ /dev/null @@ -1,26 +0,0 @@ -#### Test-MtAdGpoVersionMismatchDetails - - Returns details of GPOs with a version mismatch. - -#### Why This Test Matters -- Detective control: identifies GPOs where the version reported has a mismatch, potentially indicating stale or misapplied policy definitions. - -#### Control Type - -**Detective** - -#### Security Recommendation -- Validate GPO versions against a known baseline and correct mismatches to ensure consistent policy behavior. - -#### How the Test Works -- Fetches GPO state, filters GPOReports for HasVersionMismatch being true, and presents a table of mismatched GPOs. - -#### Related Tests -- `Test-MtAdGpoVersionMismatchCount` - counts GPOs with version mismatches. - -#### Related links -- [Microsoft Learn - Group Policy management](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) -- ANSSI checkpoint: https://www.anssi.gouv.fr/ - - -%TestResult% diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-16.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-16.ps1 deleted file mode 100644 index 367680b91c..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOREP-16.ps1 +++ /dev/null @@ -1,83 +0,0 @@ -<# #> -function Test-MtAdGpoVersionMismatchDetails { - <# - .SYNOPSIS - Returns details of GPOs with a version mismatch. - - .DESCRIPTION - This test retrieves Active Directory Group Policy state information using Get-MtADGpoState, - then returns a markdown table listing all GPO reports whose HasVersionMismatch value is true. - - .EXAMPLE - Test-MtAdGpoVersionMismatchDetails - - Returns $true if GPO report data is accessible, $false otherwise. - The test result includes a markdown table of GPOs with version mismatches. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoVersionMismatchDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-GPOREP-16', - Title = 'No GPOs should have version mismatches', - Product = 'ad', - Feature = 'group-policy', - Area = 'infrastructure', - ResourceType = 'GroupPolicy', - Severity = 'Medium', - UserImpact = 'Low', - ImplementationCost = 'Medium', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdGpoVersionMismatchDetails" - $gpoState = Get-MtADGpoState - Write-Verbose "Retrieved AD state" - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting gpo version mismatch details" - - $gpoReports = $gpoState.GPOReports - if ($null -eq $gpoReports) { - Add-MtTestResultDetail -Result 'Unable to retrieve Active Directory GPO report data from Get-MtADGpoState.' - return $false - } - - $gpoReportsArray = @($gpoReports | Where-Object { $null -ne $_ }) - $mismatched = $gpoReportsArray | Where-Object { [bool]$_.HasVersionMismatch } - $mismatchCount = @($mismatched).Count - - $testResult = $mismatchCount -eq 0 - - $table = "| GPO Name | HasVersionMismatch |" + "`n" - $table += '| --- | --- |' + "`n" - - foreach ($report in ($mismatched | Sort-Object -Property Name)) { - $name = [string]$report.Name - $name = $name -replace '\|', '|' - $table += "| $name | $([bool]$report.HasVersionMismatch) |" + "`n" - } - - $recommendation = if ($mismatchCount -gt 0) { - "GPO version mismatch details were returned ($mismatchCount). Review these GPOs to ensure their versions are consistent." - } else { - '✅ No GPO version mismatches were found.' - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "$recommendation`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $table - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdGpoVersionMismatchDetails" - return $testResult -} diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-17.md b/tests/ad/gpo-state/Test.AD-GPOREP-17.md index 6cf044d88a..9b4e657942 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-17.md +++ b/tests/ad/gpo-state/Test.AD-GPOREP-17.md @@ -1,26 +1,13 @@ -#### Test-MtAdGpoCpasswordFoundCount +Checks all collected GPOs for both Group Policy Preferences `cpassword` values and default passwords in SYSVOL security templates. Any domain user with read access to these files can recover exposed credentials. The result lists only policy names and boolean findings, never password contents. Missing scan fields and SYSVOL errors produce an error rather than a clean pass. - Counts the number of GPOs that contain a cpassword. +#### Remediation action -#### Why This Test Matters -- Detective control: counts GPOs containing a cpassword which indicates potential credential exposure. - -#### Control Type - -**Detective** - -#### Security Recommendation -- Review cpassword occurrences and rotate credentials or secure storage as needed. - -#### How the Test Works -- Retrieves GPO state, filters for CpasswordFound, and reports totals and percentage of GPOs with cpasswords. - -#### Related Tests -- `Test-MtAdGpoCpasswordFoundDetails`. +1. In **Group Policy Management**, locate the listed GPOs and remove password-bearing preferences or security-template settings from SYSVOL. +2. Rotate every credential that was stored in these files, including accounts with privileged access. Migrate to a supported secret-management mechanism and rescan all GPOs. #### Related links -- [Microsoft Learn - Group Policy management](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) -- ANSSI checkpoint: https://www.anssi.gouv.fr/ + +* [Group Policy Preferences and passwords](https://learn.microsoft.com/security-updates/securitybulletins/2014/ms14-025) %TestResult% diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-17.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-17.ps1 index 93ee88bc5b..9c1374008b 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-17.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOREP-17.ps1 @@ -1,33 +1,15 @@ -<# #> -function Test-MtAdGpoCpasswordFoundCount { +function Test-MtAdGpoCpasswordFoundCount { <# .SYNOPSIS - Counts the number of GPOs that contain a cpassword. - + Checks for exposed secrets in Group Policy files. .DESCRIPTION - This test retrieves Active Directory Group Policy state information using Get-MtADGpoState, - then counts how many returned GPO reports indicate a cpassword was found. - - .EXAMPLE - Test-MtAdGpoCpasswordFoundCount - - Returns $true if GPO report data is accessible, $false otherwise. - The test result includes the number of GPOs with cpassword present. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoCpasswordFoundCount + Flags either Group Policy Preferences cpassword or security-template default passwords, including cases with only one finding type. Never includes credential values. #> [MaesterTest( - Id = 'AD-GPOREP-17', - Title = 'No GPOs should contain a cpassword', - Product = 'ad', - Feature = 'group-policy', - Area = 'authentication', - ResourceType = 'GroupPolicy', - Severity = 'Critical', - UserImpact = 'Low', - ImplementationCost = 'Medium', - Mitre = 'T1552.006', + Id = 'AD-GPOREP-17', Title = 'No GPO should expose cpassword or default passwords', + Product = 'ad', Feature = 'group-policy', Area = 'authentication', + ResourceType = 'GroupPolicy', Severity = 'Critical', UserImpact = 'Low', + ImplementationCost = 'Medium', Mitre = ('T1552.001', 'T1552.006'), Control = ('nist-800-53-r5:IA-5(1)', 'nist-800-53-r5:SC-28'), Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), @@ -37,39 +19,30 @@ function Test-MtAdGpoCpasswordFoundCount { [OutputType([bool])] param() - Write-Verbose "Starting Test-MtAdGpoCpasswordFoundCount" - $gpoState = Get-MtADGpoState - Write-Verbose "Retrieved AD state" - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + $state = Get-MtADGpoState + if ($null -eq $state -or $null -eq $state.GPOReports -or $null -eq $state.GPOs) { + throw 'GPO secret scan reports or GPO metadata could not be collected.' } - Write-Verbose "Filtering/counting gpo cpassword found count" - - $gpoReports = $gpoState.GPOReports - if ($null -eq $gpoReports) { - Add-MtTestResultDetail -Result 'Unable to retrieve Active Directory GPO report data from Get-MtADGpoState.' - return $false + $reports = @($state.GPOReports | Where-Object { $null -ne $_ }) + if ($reports.Count -eq 0 -or $reports.Count -ne @($state.GPOs).Count) { throw 'GPO secret scan reports are empty or do not match the GPO inventory.' } + $incomplete = @($reports | Where-Object { + $null -eq $_.CpasswordFound -or $null -eq $_.DefaultPasswordFound -or + $null -eq $_.Errors -or @($_.Errors).Count -gt 0 + }) + if ($incomplete.Count -gt 0) { + throw "SYSVOL secret scan incomplete for $($incomplete.Count) GPOs; check access and scan errors before claiming no exposed passwords." } - - $gpoReportsArray = @($gpoReports | Where-Object { $null -ne $_ }) - $totalCount = $gpoReportsArray.Count - $cpasswordCount = @($gpoReportsArray | Where-Object { [bool]$_.CpasswordFound }).Count - - $testResult = $cpasswordCount -eq 0 - $cpasswordPercentage = if ($totalCount -gt 0) { [Math]::Round(($cpasswordCount / $totalCount) * 100, 2) } else { 0 } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total GPOs | $totalCount |" + "`n" - $result += "| GPOs with cpassword | $cpasswordCount |" + "`n" - $result += "| cpassword ratio | $cpasswordPercentage% |" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory GPOs have been analyzed for cpassword usage. $cpasswordCount out of $totalCount GPO(s) contain a cpassword.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdGpoCpasswordFoundCount" - return $testResult + $cpassword = @($reports | Where-Object { $true -eq $_.CpasswordFound }) + $defaultPassword = @($reports | Where-Object { $true -eq $_.DefaultPasswordFound }) + $found = @($reports | Where-Object { $true -eq $_.CpasswordFound -or $true -eq $_.DefaultPasswordFound }) + $table = "| GPO | cpassword present | Default password present |`n| --- | --- | --- |`n" + foreach ($report in @($found | Sort-Object Name)) { + $name = [System.Net.WebUtility]::HtmlEncode([string]$report.Name) -replace '\|', '|' + $table += "| $name | $([bool]$report.CpasswordFound) | $([bool]$report.DefaultPasswordFound) |`n" + } + $pass = $found.Count -eq 0 + $message = if ($pass) { "Well done. No cpassword or default password found in $($reports.Count) scanned GPOs." } + else { "$($found.Count) of $($reports.Count) GPOs expose passwords ($($cpassword.Count) with cpassword, $($defaultPassword.Count) with default passwords). Remove the secrets and rotate the affected credentials." } + Add-MtTestResultDetail -Result "$message`n`n$table" + return $pass } diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-18.md b/tests/ad/gpo-state/Test.AD-GPOREP-18.md deleted file mode 100644 index 3a12363450..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOREP-18.md +++ /dev/null @@ -1,27 +0,0 @@ -#### Test-MtAdGpoCpasswordFoundDetails - - Returns details of GPOs that contain a cpassword. - -#### Why This Test Matters -- Detective control: detects GPOs that contain a Cpassword which could be exploited if leaked. -- Cpasswords expose sensitive credentials and should be protected. - -#### Control Type - -**Detective** - -#### Security Recommendation -- Rotate or remove the cpasswords where necessary and apply proper protection controls. - -#### How the Test Works -- Uses Get-MtADGpoState to obtain GPO data, filters for reports where CpasswordFound is true, and formats a Markdown table. - -#### Related Tests -- `Test-MtAdGpoCpasswordFoundCount` - counts GPOs with cpasswords. - -#### Related links -- [Microsoft Learn - Group Policy security](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) -- ANSSI checkpoint: https://www.anssi.gouv.fr/ - - -%TestResult% diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-18.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-18.ps1 deleted file mode 100644 index 9cc49bc68d..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOREP-18.ps1 +++ /dev/null @@ -1,87 +0,0 @@ -<# #> -function Test-MtAdGpoCpasswordFoundDetails { - <# - .SYNOPSIS - Returns details of GPOs that contain a cpassword. - - .DESCRIPTION - This test retrieves Active Directory Group Policy state information using Get-MtADGpoState, - then returns a markdown table listing all GPO reports whose CpasswordFound value is true. - - .EXAMPLE - Test-MtAdGpoCpasswordFoundDetails - - Returns $true if GPO report data is accessible, $false otherwise. - The test result includes a markdown table of GPOs with cpassword. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoCpasswordFoundDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-GPOREP-18', - Title = 'No GPOs should contain a cpassword', - Product = 'ad', - Feature = 'group-policy', - Area = 'authentication', - ResourceType = 'GroupPolicy', - Severity = 'Critical', - UserImpact = 'Low', - ImplementationCost = 'Medium', - Mitre = 'T1552.006', - Control = ('nist-800-53-r5:IA-5(1)', 'nist-800-53-r5:SC-28'), - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdGpoCpasswordFoundDetails" - $gpoState = Get-MtADGpoState - Write-Verbose "Retrieved AD state" - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting gpo cpassword found details" - - $gpoReports = $gpoState.GPOReports - if ($null -eq $gpoReports) { - Add-MtTestResultDetail -Result 'Unable to retrieve Active Directory GPO report data from Get-MtADGpoState.' - return $false - } - - $gpoReportsArray = @($gpoReports | Where-Object { $null -ne $_ }) - $found = $gpoReportsArray | Where-Object { [bool]$_.CpasswordFound } - $foundCount = @($found).Count - - $testResult = $foundCount -eq 0 - - $table = "| GPO Name | CpasswordFound | DefaultPasswordFound |" + "`n" - $table += '| --- | --- | --- |' + "`n" - - foreach ($report in ($found | Sort-Object -Property Name)) { - $name = [string]$report.Name - $name = $name -replace '\|', '|' - - $cpasswordFound = [bool]$report.CpasswordFound - $defaultPasswordFound = [bool]$report.DefaultPasswordFound - $table += "| $name | $cpasswordFound | $defaultPasswordFound |" + "`n" - } - - $recommendation = if ($foundCount -gt 0) { - "GPO cpassword details were returned ($foundCount). Review these GPOs to ensure Group Policy Preferences passwords are handled securely." - } else { - '✅ No GPOs with cpassword were found.' - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "$recommendation`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $table - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdGpoCpasswordFoundDetails" - return $testResult -} diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-19.md b/tests/ad/gpo-state/Test.AD-GPOREP-19.md deleted file mode 100644 index 5c1c6b2ce3..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOREP-19.md +++ /dev/null @@ -1,26 +0,0 @@ -#### Test-MtAdGpoDefaultPasswordFoundCount - - Counts the number of GPOs that contain a default password. - -#### Why This Test Matters -- Detective control: counts GPOs where a default password is found in the report. - -#### Control Type - -**Detective** - -#### Security Recommendation -- Investigate and remediate GPOs that embed default passwords. - -#### How the Test Works -- Retrieves GPO state, filters DefaultPasswordFound, and reports totals and a percentage. - -#### Related Tests -- `Test-MtAdGpoDefaultPasswordFoundDetails`. - -#### Related links -- [Microsoft Learn - Group Policy management](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) -- ANSSI checkpoint: https://www.anssi.gouv.fr/ - - -%TestResult% diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-19.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-19.ps1 deleted file mode 100644 index cc36725d09..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOREP-19.ps1 +++ /dev/null @@ -1,75 +0,0 @@ -<# #> -function Test-MtAdGpoDefaultPasswordFoundCount { - <# - .SYNOPSIS - Counts the number of GPOs that contain a default password (decoded from cpassword). - - .DESCRIPTION - This test retrieves Active Directory Group Policy state information using Get-MtADGpoState, - then counts how many returned GPO reports indicate DefaultPasswordFound was true. - - .EXAMPLE - Test-MtAdGpoDefaultPasswordFoundCount - - Returns $true if GPO report data is accessible, $false otherwise. - The test result includes the number of GPOs with DefaultPasswordFound. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoDefaultPasswordFoundCount - #> - [MaesterTest( - Id = 'AD-GPOREP-19', - Title = 'No GPOs should contain a default password', - Product = 'ad', - Feature = 'group-policy', - Area = 'authentication', - ResourceType = 'GroupPolicy', - Severity = 'High', - UserImpact = 'Low', - ImplementationCost = 'Medium', - Mitre = ('T1552.001', 'T1552.006'), - Control = ('nist-800-53-r5:IA-5(1)', 'nist-800-53-r5:SC-28'), - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdGpoDefaultPasswordFoundCount" - $gpoState = Get-MtADGpoState - Write-Verbose "Retrieved AD state" - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting gpo default password found count" - - $gpoReports = $gpoState.GPOReports - if ($null -eq $gpoReports) { - Add-MtTestResultDetail -Result 'Unable to retrieve Active Directory GPO report data from Get-MtADGpoState.' - return $false - } - - $gpoReportsArray = @($gpoReports | Where-Object { $null -ne $_ }) - $totalCount = $gpoReportsArray.Count - $defaultPasswordCount = @($gpoReportsArray | Where-Object { [bool]$_.DefaultPasswordFound }).Count - - $testResult = $defaultPasswordCount -eq 0 - $defaultPasswordPercentage = if ($totalCount -gt 0) { [Math]::Round(($defaultPasswordCount / $totalCount) * 100, 2) } else { 0 } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total GPOs | $totalCount |" + "`n" - $result += "| GPOs with default password | $defaultPasswordCount |" + "`n" - $result += "| Default password ratio | $defaultPasswordPercentage% |" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory GPOs have been analyzed for default password usage. $defaultPasswordCount out of $totalCount GPO(s) contain a default password.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdGpoDefaultPasswordFoundCount" - return $testResult -} diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-20.md b/tests/ad/gpo-state/Test.AD-GPOREP-20.md deleted file mode 100644 index c58eef1aea..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOREP-20.md +++ /dev/null @@ -1,28 +0,0 @@ -#### Test-MtAdGpoDefaultPasswordFoundDetails - - Returns details of GPOs that contain a default password. - -#### Why This Test Matters -- Detective control: verifies whether any GPO reports contain a default password and highlights those findings for remediation. -- In security terms, default passwords in GPOs are a common misconfiguration risk that attackers could exploit. - -#### Control Type - -**Detective** - -#### Security Recommendation -- Review GPOs listed in the report and replace default passwords with secure, unique credentials per policy. Remove any passwords that are no longer needed. - -#### How the Test Works -- Invokes Get-MtADGpoState to fetch GPO state data, then filters GPO reports where DefaultPasswordFound is true. -- Builds a Markdown table of GPO name and the DefaultPasswordFound flag, plus a summary line with counts. - -#### Related Tests -- `Test-MtAdGpoDefaultPasswordFoundCount` - Counts how many GPOs have a default password. - -#### Related links -- [Microsoft Learn - Group Policy security best practices](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/group-policy/group-policy-overview) -- ANSSI checkpoint: https://www.anssi.gouv.fr/ - - -%TestResult% diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-20.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-20.ps1 deleted file mode 100644 index 488c60bdd4..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOREP-20.ps1 +++ /dev/null @@ -1,87 +0,0 @@ -<# #> -function Test-MtAdGpoDefaultPasswordFoundDetails { - <# - .SYNOPSIS - Returns details of GPOs that contain a default password. - - .DESCRIPTION - This test retrieves Active Directory Group Policy state information using Get-MtADGpoState, - then returns a markdown table listing all GPO reports whose DefaultPasswordFound value is true. - - .EXAMPLE - Test-MtAdGpoDefaultPasswordFoundDetails - - Returns $true if GPO report data is accessible, $false otherwise. - The test result includes a markdown table of GPOs with a default password. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoDefaultPasswordFoundDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-GPOREP-20', - Title = 'No GPOs should contain a default password', - Product = 'ad', - Feature = 'group-policy', - Area = 'authentication', - ResourceType = 'GroupPolicy', - Severity = 'High', - UserImpact = 'Low', - ImplementationCost = 'Medium', - Mitre = ('T1552.001', 'T1552.006'), - Control = ('nist-800-53-r5:IA-5(1)', 'nist-800-53-r5:SC-28'), - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdGpoDefaultPasswordFoundDetails" - $gpoState = Get-MtADGpoState - Write-Verbose "Retrieved AD state" - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting gpo default password found details" - - $gpoReports = $gpoState.GPOReports - if ($null -eq $gpoReports) { - Add-MtTestResultDetail -Result 'Unable to retrieve Active Directory GPO report data from Get-MtADGpoState.' - return $false - } - - $gpoReportsArray = @($gpoReports | Where-Object { $null -ne $_ }) - $found = $gpoReportsArray | Where-Object { [bool]$_.DefaultPasswordFound } - $foundCount = @($found).Count - - $testResult = $foundCount -eq 0 - - $table = "| GPO Name | DefaultPasswordFound | CpasswordFound |" + "`n" - $table += '| --- | --- | --- |' + "`n" - - foreach ($report in ($found | Sort-Object -Property Name)) { - $name = [string]$report.Name - $name = $name -replace '\|', '|' - - $defaultPasswordFound = [bool]$report.DefaultPasswordFound - $cpasswordFound = [bool]$report.CpasswordFound - $table += "| $name | $defaultPasswordFound | $cpasswordFound |" + "`n" - } - - $recommendation = if ($foundCount -gt 0) { - "GPO default password details were returned ($foundCount). Review these GPOs to ensure Group Policy Preferences passwords are handled securely." - } else { - '✅ No GPOs with default password were found.' - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "$recommendation`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $table - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdGpoDefaultPasswordFoundDetails" - return $testResult -} From 4f354a2de68025d659b24dd681c719a66983b550 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 06:23:26 +0000 Subject: [PATCH 005/100] refactor(ad): consolidate DACL conflict and deny inventories --- tests/ad/dacl/Test.AD-DACL-02.md | 2 +- tests/ad/dacl/Test.AD-DACL-03.md | 7 +-- tests/ad/dacl/Test.AD-DACL-03.ps1 | 36 ++++++++---- tests/ad/dacl/Test.AD-DACL-04.md | 28 --------- tests/ad/dacl/Test.AD-DACL-04.ps1 | 93 ------------------------------ tests/ad/dacl/Test.AD-DACL-05.md | 5 +- tests/ad/dacl/Test.AD-DACL-05.ps1 | 36 ++++++++---- tests/ad/dacl/Test.AD-DACL-06.md | 28 --------- tests/ad/dacl/Test.AD-DACL-06.ps1 | 94 ------------------------------- 9 files changed, 55 insertions(+), 274 deletions(-) delete mode 100644 tests/ad/dacl/Test.AD-DACL-04.md delete mode 100644 tests/ad/dacl/Test.AD-DACL-04.ps1 delete mode 100644 tests/ad/dacl/Test.AD-DACL-06.md delete mode 100644 tests/ad/dacl/Test.AD-DACL-06.ps1 diff --git a/tests/ad/dacl/Test.AD-DACL-02.md b/tests/ad/dacl/Test.AD-DACL-02.md index 65cdda1fd6..efaa24b4fd 100644 --- a/tests/ad/dacl/Test.AD-DACL-02.md +++ b/tests/ad/dacl/Test.AD-DACL-02.md @@ -20,7 +20,7 @@ This test retrieves `$adState.DaclEntries`, filters entries where `ObjectClass` - `Test-MtAdDaclDistinctObjectCount` - `Test-MtAdDaclDenyAceCount` -- `Test-MtAdDaclDenyAceDetails` +- `AD-DACL-05` — Deny ACE counts and details > **Note:** This test is `LongRunning`. It loads the full DACL dataset, which can consume significant memory in large Active Directory environments. Use `Invoke-Maester -IncludeLongRunning` to run it. diff --git a/tests/ad/dacl/Test.AD-DACL-03.md b/tests/ad/dacl/Test.AD-DACL-03.md index ab6f5cfb17..ecb3c9b0bd 100644 --- a/tests/ad/dacl/Test.AD-DACL-03.md +++ b/tests/ad/dacl/Test.AD-DACL-03.md @@ -8,19 +8,18 @@ Conflict objects with `CNF` markers typically originate from replication or nami **Operational** -#### Security Recommendation +#### Remediation action Investigate conflict objects and confirm whether they are expected remnants, still referenced, or safe to clean up. Review their permissions before remediation to understand any delegated access that may still exist. #### How the Test Works -This test retrieves `$adState.DaclEntries`, searches for `CNF` within `ObjectDN`, deduplicates matching distinguished names, and reports the number of unique conflict objects and associated DACL entries. +This test retrieves `$adState.DaclEntries`, finds escaped conflict markers (`\0ACNF:`) in `ObjectDN`, and reports unique conflict objects, associated ACE counts, and each affected object's DN, class and ACE count. This is an inventory for review, not a pass/fail judgement on conflict objects. #### Related Tests -- `Test-MtAdDaclConflictObjectDetails` - `Test-MtAdDaclDistinctObjectCount` -- `Test-MtAdDaclDenyAceDetails` +- `Test-MtAdDaclDenyAceCount` > **Note:** This test is `LongRunning`. It loads the full DACL dataset, which can consume significant memory in large Active Directory environments. Use `Invoke-Maester -IncludeLongRunning` to run it. diff --git a/tests/ad/dacl/Test.AD-DACL-03.ps1 b/tests/ad/dacl/Test.AD-DACL-03.ps1 index 3ad7d39af4..b9181f0579 100644 --- a/tests/ad/dacl/Test.AD-DACL-03.ps1 +++ b/tests/ad/dacl/Test.AD-DACL-03.ps1 @@ -1,7 +1,7 @@ function Test-MtAdDaclConflictObjectCount { <# .SYNOPSIS - Counts conflict objects represented in DACL data. + Counts conflict objects and lists their DACL entries by object. .DESCRIPTION This informational test identifies conflict objects in collected DACL data by looking for CNF @@ -19,7 +19,7 @@ #> [MaesterTest( Id = 'AD-DACL-03', - Title = 'Conflict object count should be investigated', + Title = 'Conflict objects and their DACL entries should be investigated', Product = 'ad', Feature = 'permissions', Area = 'infrastructure', @@ -27,6 +27,7 @@ Severity = 'Info', Mitre = 'None', Service = 'ActiveDirectory', + Platform = 'Windows', Permission = ('ActiveDirectory:Ldap:*.ntSecurityDescriptor:ReadControl'), LongRunning, Author = 'soulemike' @@ -42,18 +43,19 @@ } $adState = Get-MtADDomainState -Categories @('DaclEntries') Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'Not connected to Active Directory.' - return $null - } - if ($null -eq $adState.DaclEntries) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'DACL data is unavailable.' - return $null + if ($null -eq $adState -or $null -eq $adState.DaclEntries) { + throw 'DACL data is unavailable.' } Write-Verbose "Filtering/counting dacl conflict object count" - $daclEntries = @($adState.DaclEntries) - $conflictEntries = @($daclEntries | Where-Object { $_.ObjectDN -match 'CNF' }) + $daclEntries = @($adState.DaclEntries | Where-Object { $null -ne $_ }) + if ($daclEntries.Count -eq 0) { + throw 'No DACL entries were collected; cannot assess conflict objects.' + } + if (@($daclEntries | Where-Object { [string]::IsNullOrWhiteSpace($_.ObjectDN) }).Count -gt 0) { + throw 'DACL entries are missing object distinguished names.' + } + $conflictEntries = @($daclEntries | Where-Object { [string]$_.ObjectDN -match '\\0ACNF:' }) $conflictObjectDns = @( $conflictEntries | Where-Object { -not [string]::IsNullOrWhiteSpace($_.ObjectDN) } | @@ -68,9 +70,19 @@ $result += "| --- | --- |" + "`n" $result += "| Conflict Objects In DACL Data | $conflictObjectCount |" + "`n" $result += "| DACL Entries On Conflict Objects | $conflictAceCount |" + "`n" + $result += "`n| Object DN | Object Class | ACE Count |`n| --- | --- | --- |`n" + foreach ($group in @($conflictEntries | Group-Object ObjectDN | Sort-Object -Property @{ Expression = 'Count'; Descending = $true }, Name)) { + $sample = $group.Group | Select-Object -First 1 + $objectDn = ([string]$sample.ObjectDN) -replace '\|', '|' + $objectClass = ([string]$sample.ObjectClass) -replace '\|', '|' + $result += "| $objectDn | $objectClass | $($group.Count) |`n" + } + if ($conflictObjectCount -eq 0) { + $result += "| No conflict objects found | | 0 |`n" + } Write-Verbose "Counts computed" - $testResultMarkdown = "Active Directory DACL data has been reviewed for conflict objects. $conflictObjectCount conflict object(s) with CNF markers were identified in the DACL dataset.`n`n%TestResult%" + $testResultMarkdown = "Active Directory DACL data contains $conflictObjectCount conflict object(s) with CNF markers.`n`n%TestResult%" $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result Add-MtTestResultDetail -Result $testResultMarkdown -Investigate diff --git a/tests/ad/dacl/Test.AD-DACL-04.md b/tests/ad/dacl/Test.AD-DACL-04.md deleted file mode 100644 index 5420c97fe6..0000000000 --- a/tests/ad/dacl/Test.AD-DACL-04.md +++ /dev/null @@ -1,28 +0,0 @@ -High-level counts are useful, but remediation usually requires object-level detail. This test helps administrators pinpoint each conflict object present in the DACL dataset and understand how many ACEs are attached to it. - -- **Shows the exact conflict objects** found in DACL analysis -- **Supports cleanup validation** by exposing object class and DN -- **Quantifies ACE volume** on each conflict object - -#### Control Type - -**Operational** - -#### Security Recommendation - -Review each listed conflict object, confirm why it exists, and determine whether it is still needed. If an object is obsolete, validate dependencies and permissions before cleanup. - -#### How the Test Works - -This test retrieves `$adState.DaclEntries`, filters for entries whose `ObjectDN` contains `CNF`, groups them by object distinguished name, and returns each object with its class and ACE count. - -#### Related Tests - -- `Test-MtAdDaclConflictObjectCount` -- `Test-MtAdDaclDenyAceDetails` -- `Test-MtAdDaclOuObjectCount` - -> **Note:** This test is `LongRunning`. It loads the full DACL dataset, which can consume significant memory in large Active Directory environments. Use `Invoke-Maester -IncludeLongRunning` to run it. - - -%TestResult% diff --git a/tests/ad/dacl/Test.AD-DACL-04.ps1 b/tests/ad/dacl/Test.AD-DACL-04.ps1 deleted file mode 100644 index 401a89375c..0000000000 --- a/tests/ad/dacl/Test.AD-DACL-04.ps1 +++ /dev/null @@ -1,93 +0,0 @@ -function Test-MtAdDaclConflictObjectDetails { - <# - .SYNOPSIS - Returns detailed information for conflict objects represented in DACL data. - - .DESCRIPTION - This informational test identifies conflict objects in the DACL dataset by searching for CNF in - the object distinguished name, then returns a detailed breakdown of each affected object. The - output helps administrators review replication-conflict remnants and understand how many ACEs are - associated with each conflict object. - - .EXAMPLE - Test-MtAdDaclConflictObjectDetails - - Returns $true if DACL data is accessible. - - .LINK - https://maester.dev/docs/commands/Test-MtAdDaclConflictObjectDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-DACL-04', - Title = 'Conflict object details should be investigated', - Product = 'ad', - Feature = 'permissions', - Area = 'infrastructure', - ResourceType = 'Tenant', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:*.ntSecurityDescriptor:ReadControl'), - LongRunning, - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdDaclConflictObjectDetails" - if (-not (Test-MtAdDaclPlatformSupported)) { - Add-MtTestResultDetail -SkippedBecause NotSupported - return $null - } - $adState = Get-MtADDomainState -Categories @('DaclEntries') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'Not connected to Active Directory.' - return $null - } - if ($null -eq $adState.DaclEntries) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'DACL data is unavailable.' - return $null - } - Write-Verbose "Filtering/counting dacl conflict object details" - - $daclEntries = @($adState.DaclEntries) - $conflictEntries = @($daclEntries | Where-Object { $_.ObjectDN -match 'CNF' }) - $conflictGroups = @($conflictEntries | Group-Object -Property ObjectDN | Sort-Object -Property Count, Name -Descending) - $conflictObjectCount = ($conflictGroups | Measure-Object).Count - $conflictAceCount = ($conflictEntries | Measure-Object).Count - $testResult = $true - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Conflict Objects | $conflictObjectCount |" + "`n" - $result += "| DACL Entries On Conflict Objects | $conflictAceCount |" + "`n" + "`n" - - if ($conflictObjectCount -gt 0) { - $result += "| Object DN | Object Class | ACE Count |" + "`n" - $result += "| --- | --- | --- |" + "`n" - - foreach ($group in $conflictGroups) { - $sample = $group.Group | Select-Object -First 1 - $objectDn = if ($null -ne $sample.ObjectDN) { ([string]$sample.ObjectDN) -replace '\|', '\\|' } else { '' } - $objectClass = if ($null -ne $sample.ObjectClass) { ([string]$sample.ObjectClass) -replace '\|', '\\|' } else { '' } - $result += "| $objectDn | $objectClass | $($group.Count) |" + "`n" - } - } else { - $result += "**No conflict objects were identified in the collected DACL data.**" + "`n" - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory DACL conflict-object details have been compiled. $conflictObjectCount conflict object(s) were identified in the dataset.`n`n%TestResult%" - if ($conflictObjectCount -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", "" - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdDaclConflictObjectDetails" - return $testResult -} diff --git a/tests/ad/dacl/Test.AD-DACL-05.md b/tests/ad/dacl/Test.AD-DACL-05.md index dbd3093e3a..f1b49e9120 100644 --- a/tests/ad/dacl/Test.AD-DACL-05.md +++ b/tests/ad/dacl/Test.AD-DACL-05.md @@ -8,17 +8,16 @@ Deny ACEs are powerful because they can override allow permissions and create ac **Operational** -#### Security Recommendation +#### Remediation action Review deny ACE usage carefully. Ensure each deny entry is intentional, documented, and still required. Excessive or poorly understood deny entries can create administrative confusion and mask broader permission issues. #### How the Test Works -This test retrieves `$adState.DaclEntries`, filters entries where `AccessControlType` contains `Deny`, and reports the total deny ACE count along with the number of affected objects. +This test retrieves `$adState.DaclEntries`, filters entries where `AccessControlType` is `Deny` (the collector's normalized value), reports total ACEs, deny ACEs and affected objects, and lists deny ACE counts for each object and identity. Deny ACEs are not automatically misconfigurations; review their intent. #### Related Tests -- `Test-MtAdDaclDenyAceDetails` - `Test-MtAdDaclDistinctObjectCount` - `Test-MtAdDaclOuObjectCount` diff --git a/tests/ad/dacl/Test.AD-DACL-05.ps1 b/tests/ad/dacl/Test.AD-DACL-05.ps1 index c8382d9bc3..2e54be19df 100644 --- a/tests/ad/dacl/Test.AD-DACL-05.ps1 +++ b/tests/ad/dacl/Test.AD-DACL-05.ps1 @@ -1,7 +1,7 @@ function Test-MtAdDaclDenyAceCount { <# .SYNOPSIS - Counts deny authorization ACEs in collected DACL data. + Counts deny authorization ACEs and lists affected objects and identities. .DESCRIPTION This informational test reviews collected Active Directory DACL data and counts ACEs where the @@ -19,7 +19,7 @@ #> [MaesterTest( Id = 'AD-DACL-05', - Title = 'Deny ACE count should be investigated', + Title = 'Deny ACEs and affected identities should be investigated', Product = 'ad', Feature = 'permissions', Area = 'access-control', @@ -27,6 +27,7 @@ Severity = 'Info', Mitre = 'None', Service = 'ActiveDirectory', + Platform = 'Windows', Permission = ('ActiveDirectory:Ldap:*.ntSecurityDescriptor:ReadControl'), LongRunning, Author = 'soulemike' @@ -42,19 +43,20 @@ } $adState = Get-MtADDomainState -Categories @('DaclEntries') Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'Not connected to Active Directory.' - return $null - } - if ($null -eq $adState.DaclEntries) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'DACL data is unavailable.' - return $null + if ($null -eq $adState -or $null -eq $adState.DaclEntries) { + throw 'DACL data is unavailable.' } Write-Verbose "Filtering/counting dacl deny ace count" - $daclEntries = @($adState.DaclEntries) + $daclEntries = @($adState.DaclEntries | Where-Object { $null -ne $_ }) + if ($daclEntries.Count -eq 0) { + throw 'No DACL entries were collected; cannot assess deny ACEs.' + } + if (@($daclEntries | Where-Object { [string]::IsNullOrWhiteSpace($_.ObjectDN) -or [string]::IsNullOrWhiteSpace($_.AccessControlType) }).Count -gt 0) { + throw 'DACL entries are missing object names or access control types.' + } $totalDaclEntryCount = ($daclEntries | Measure-Object).Count - $denyEntries = @($daclEntries | Where-Object { $_.AccessControlType -match 'Deny' }) + $denyEntries = @($daclEntries | Where-Object { $_.AccessControlType -eq 'Deny' }) $denyAceCount = ($denyEntries | Measure-Object).Count $affectedObjects = (@( $denyEntries | @@ -69,6 +71,18 @@ $result += "| Total DACL Entries | $totalDaclEntryCount |" + "`n" $result += "| Deny ACEs | $denyAceCount |" + "`n" $result += "| Objects With Deny ACEs | $affectedObjects |" + "`n" + $result += "`n| Object Name | Object Class | Object DN | Identity Reference | Deny ACE Count |`n| --- | --- | --- | --- | --- |`n" + foreach ($group in @($denyEntries | Group-Object ObjectDN, IdentityReference | Sort-Object -Property @{ Expression = 'Count'; Descending = $true }, Name)) { + $sample = $group.Group | Select-Object -First 1 + $objectName = ([string]$sample.ObjectName) -replace '\|', '|' + $objectClass = ([string]$sample.ObjectClass) -replace '\|', '|' + $objectDn = ([string]$sample.ObjectDN) -replace '\|', '|' + $identity = ([string]$sample.IdentityReference) -replace '\|', '|' + $result += "| $objectName | $objectClass | $objectDn | $identity | $($group.Count) |`n" + } + if ($denyAceCount -eq 0) { + $result += "| No deny ACEs found | | | | 0 |`n" + } Write-Verbose "Counts computed" $testResultMarkdown = "Active Directory DACL data has been reviewed for deny authorizations. $denyAceCount deny ACE(s) were identified across $affectedObjects object(s).`n`n%TestResult%" diff --git a/tests/ad/dacl/Test.AD-DACL-06.md b/tests/ad/dacl/Test.AD-DACL-06.md deleted file mode 100644 index 30d70ebfd7..0000000000 --- a/tests/ad/dacl/Test.AD-DACL-06.md +++ /dev/null @@ -1,28 +0,0 @@ -When deny ACEs exist, administrators need to know exactly which identities are denied on which objects. Grouping deny ACEs by object and identity makes it easier to review intent and spot concentrated or unusual deny patterns. - -- **Maps denied principals to specific objects** -- **Supports delegated access reviews** -- **Helps identify concentrated deny patterns** that deserve validation - -#### Control Type - -**Operational** - -#### Security Recommendation - -Review each deny ACE grouping to confirm it reflects an intentional control. Focus especially on privileged objects, administrative groups, and OUs used for delegation. - -#### How the Test Works - -This test retrieves `$adState.DaclEntries`, filters entries where `AccessControlType` contains `Deny`, groups results by `ObjectDN` and `IdentityReference`, and reports the count of deny ACEs for each combination. - -#### Related Tests - -- `Test-MtAdDaclDenyAceCount` -- `Test-MtAdDaclConflictObjectDetails` -- `Test-MtAdDaclOuObjectCount` - -> **Note:** This test is `LongRunning`. It loads the full DACL dataset, which can consume significant memory in large Active Directory environments. Use `Invoke-Maester -IncludeLongRunning` to run it. - - -%TestResult% diff --git a/tests/ad/dacl/Test.AD-DACL-06.ps1 b/tests/ad/dacl/Test.AD-DACL-06.ps1 deleted file mode 100644 index 4beb64f68b..0000000000 --- a/tests/ad/dacl/Test.AD-DACL-06.ps1 +++ /dev/null @@ -1,94 +0,0 @@ -function Test-MtAdDaclDenyAceDetails { - <# - .SYNOPSIS - Returns a breakdown of deny authorization ACEs by object and identity. - - .DESCRIPTION - This informational test filters DACL data to deny ACEs and groups the results by object and - identity reference. The output helps administrators understand which principals are explicitly - denied access to which objects and where deny ACE concentration exists in the directory. - - .EXAMPLE - Test-MtAdDaclDenyAceDetails - - Returns $true if DACL data is accessible. - - .LINK - https://maester.dev/docs/commands/Test-MtAdDaclDenyAceDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-DACL-06', - Title = 'Deny ACE details should be investigated', - Product = 'ad', - Feature = 'permissions', - Area = 'access-control', - ResourceType = 'Permission', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:*.ntSecurityDescriptor:ReadControl'), - LongRunning, - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdDaclDenyAceDetails" - if (-not (Test-MtAdDaclPlatformSupported)) { - Add-MtTestResultDetail -SkippedBecause NotSupported - return $null - } - $adState = Get-MtADDomainState -Categories @('DaclEntries') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'Not connected to Active Directory.' - return $null - } - if ($null -eq $adState.DaclEntries) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'DACL data is unavailable.' - return $null - } - Write-Verbose "Filtering/counting dacl deny ace details" - - $daclEntries = @($adState.DaclEntries) - $denyEntries = @($daclEntries | Where-Object { $_.AccessControlType -match 'Deny' }) - $denyAceCount = ($denyEntries | Measure-Object).Count - $denyGroups = @($denyEntries | Group-Object -Property ObjectDN, IdentityReference | Sort-Object -Property Count, Name -Descending) - $denyGroupCount = ($denyGroups | Measure-Object).Count - $testResult = $true - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Deny ACEs | $denyAceCount |" + "`n" - $result += "| Object and Identity Combinations | $denyGroupCount |" + "`n" + "`n" - - if ($denyGroupCount -gt 0) { - $result += "| Object Name | Object Class | Object DN | Identity Reference | Deny ACE Count |" + "`n" - $result += "| --- | --- | --- | --- | --- |" + "`n" - - foreach ($group in $denyGroups) { - $sample = $group.Group | Select-Object -First 1 - $objectName = if ($null -ne $sample.ObjectName) { ([string]$sample.ObjectName) -replace '\|', '\\|' } else { '' } - $objectClass = if ($null -ne $sample.ObjectClass) { ([string]$sample.ObjectClass) -replace '\|', '\\|' } else { '' } - $objectDn = if ($null -ne $sample.ObjectDN) { ([string]$sample.ObjectDN) -replace '\|', '\\|' } else { '' } - $identityReference = if ($null -ne $sample.IdentityReference) { ([string]$sample.IdentityReference) -replace '\|', '\\|' } else { '' } - $result += "| $objectName | $objectClass | $objectDn | $identityReference | $($group.Count) |" + "`n" - } - } else { - $result += "**No deny ACEs were identified in the collected DACL data.**" + "`n" - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory DACL deny-ACE details have been compiled. The results are grouped by object and identity reference for review.`n`n%TestResult%" - if ($denyGroupCount -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", "" - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdDaclDenyAceDetails" - return $testResult -} From e51ff267d111b1cb10e961d86a396c347e593da9 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 06:23:26 +0000 Subject: [PATCH 006/100] refactor(ad): consolidate DACL identity and privileged rights inventories --- .../functions/ActiveDirectoryDacl.Tests.ps1 | 16 +- tests/ad/dacl/Test.AD-DACL-07.md | 5 +- tests/ad/dacl/Test.AD-DACL-07.ps1 | 33 ++-- tests/ad/dacl/Test.AD-DACL-08.md | 28 ---- tests/ad/dacl/Test.AD-DACL-08.ps1 | 102 ------------ tests/ad/dacl/Test.AD-DACL-09.md | 5 +- tests/ad/dacl/Test.AD-DACL-09.ps1 | 35 ++-- tests/ad/dacl/Test.AD-DACL-10.md | 28 ---- tests/ad/dacl/Test.AD-DACL-10.ps1 | 153 ------------------ tests/ad/dacl/Test.AD-DACL-11.md | 6 +- tests/ad/dacl/Test.AD-DACL-11.ps1 | 93 +++++++++-- tests/ad/dacl/Test.AD-DACL-12.md | 28 ---- tests/ad/dacl/Test.AD-DACL-12.ps1 | 121 -------------- tests/ad/dacl/Test.AD-DACL-13.md | 30 ---- tests/ad/dacl/Test.AD-DACL-13.ps1 | 134 --------------- 15 files changed, 143 insertions(+), 674 deletions(-) delete mode 100644 tests/ad/dacl/Test.AD-DACL-08.md delete mode 100644 tests/ad/dacl/Test.AD-DACL-08.ps1 delete mode 100644 tests/ad/dacl/Test.AD-DACL-10.md delete mode 100644 tests/ad/dacl/Test.AD-DACL-10.ps1 delete mode 100644 tests/ad/dacl/Test.AD-DACL-12.md delete mode 100644 tests/ad/dacl/Test.AD-DACL-12.ps1 delete mode 100644 tests/ad/dacl/Test.AD-DACL-13.md delete mode 100644 tests/ad/dacl/Test.AD-DACL-13.ps1 diff --git a/powershell/tests/functions/ActiveDirectoryDacl.Tests.ps1 b/powershell/tests/functions/ActiveDirectoryDacl.Tests.ps1 index f386635794..482d1e0d63 100644 --- a/powershell/tests/functions/ActiveDirectoryDacl.Tests.ps1 +++ b/powershell/tests/functions/ActiveDirectoryDacl.Tests.ps1 @@ -4,11 +4,9 @@ . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" # Check functions that became native tests are not exported. Use-MtModuleFunction -Name @( - 'Test-MtAdDaclIdentityAceDistribution' + 'Test-MtAdDaclDistinctIdentityCount' 'Test-MtAdDaclPrivilegedAllowAceCount' - 'Test-MtAdDaclPrivilegedAllowAceDetails' 'Test-MtAdDaclPrivilegedExtendedRightCount' - 'Test-MtAdDaclPrivilegedExtendedRightDetails' ) $domainSid = 'S-1-5-21-1004336348-1177238915-682003330' @@ -81,8 +79,8 @@ } } - It 'AD-DACL-08 (Test-MtAdDaclIdentityAceDistribution) splits the ACEs of each identity into allow and deny' { - Test-MtAdDaclIdentityAceDistribution | Should -BeTrue + It 'AD-DACL-07 splits the ACEs of each identity into allow and deny' { + Test-MtAdDaclDistinctIdentityCount | Should -BeTrue # IdentityReference | ACE Count | Distinct Objects | Allow ACEs | Deny ACEs $script:Result | Should -BeLike "*| $helpdesk | 2 | 1 | 2 | 0 |*" @@ -103,8 +101,8 @@ $script:Result | Should -BeLike '*| ACEs containing ExtendedRight | 2 |*' } - It 'AD-DACL-10 (Test-MtAdDaclPrivilegedAllowAceDetails) lists the object that holds privileged allow ACEs' { - Test-MtAdDaclPrivilegedAllowAceDetails | Should -BeTrue + It 'AD-DACL-09 lists the object that holds privileged allow ACEs' { + Test-MtAdDaclPrivilegedAllowAceCount | Should -BeTrue # Object Name | Object Class | ACE Count | Distinct Identities | Privileged Rights | Object DN $script:Result | Should -BeLike '*| Sales | organizationalUnit | 4 | 2 | ExtendedRight, GenericAll, WriteDacl, WriteOwner | OU=Sales,DC=contoso,DC=com |*' @@ -120,8 +118,8 @@ $script:Result | Should -BeLike '*| Distinct objects with ExtendedRight | 1 |*' } - It 'AD-DACL-12 (Test-MtAdDaclPrivilegedExtendedRightDetails) lists each ObjectType granted through an ExtendedRight allow ACE' { - Test-MtAdDaclPrivilegedExtendedRightDetails | Should -BeTrue + It 'AD-DACL-11 lists each ObjectType granted through an ExtendedRight allow ACE' { + Test-MtAdDaclPrivilegedExtendedRightCount | Should -BeTrue # ObjectType | ACE Count | Distinct Objects | Distinct Identities $script:Result | Should -BeLike "*| $resetPassword | 1 | 1 | 1 |*" diff --git a/tests/ad/dacl/Test.AD-DACL-07.md b/tests/ad/dacl/Test.AD-DACL-07.md index 1b9272eec4..012259fe61 100644 --- a/tests/ad/dacl/Test.AD-DACL-07.md +++ b/tests/ad/dacl/Test.AD-DACL-07.md @@ -8,17 +8,16 @@ Every DACL ACE references a security principal. Tracking the number of distinct **Operational** -#### Security Recommendation +#### Remediation action Keep delegation models simple and intentional. Prefer group-based administration over direct assignment to many individual accounts or SIDs. #### How the Test Works -This test reads `DaclEntries` from `Get-MtADDomainState`, extracts unique `IdentityReference` values, and reports how many distinct identities appear across all collected ACEs. +This test reads `DaclEntries` from `Get-MtADDomainState`, reports total ACEs, distinct identities and objects, and lists each identity's ACE count, distinct objects, allow ACEs and deny ACEs. These are inventory metrics, not an assertion that any particular count is safe. #### Related Tests -- `Test-MtAdDaclIdentityAceDistribution` - `Test-MtAdDaclPrivilegedAllowAceCount` - `Test-MtAdDaclPrivilegedExtendedRightCount` diff --git a/tests/ad/dacl/Test.AD-DACL-07.ps1 b/tests/ad/dacl/Test.AD-DACL-07.ps1 index ec0d53b8bc..8960d1bbf3 100644 --- a/tests/ad/dacl/Test.AD-DACL-07.ps1 +++ b/tests/ad/dacl/Test.AD-DACL-07.ps1 @@ -1,7 +1,7 @@ function Test-MtAdDaclDistinctIdentityCount { <# .SYNOPSIS - Counts distinct identities referenced by DACL ACEs. + Counts distinct identities and reports ACE distribution by identity. .DESCRIPTION This test retrieves cached DACL entry data from Active Directory and counts the @@ -19,7 +19,7 @@ #> [MaesterTest( Id = 'AD-DACL-07', - Title = 'Distinct DACL identity count should be investigated', + Title = 'DACL identity counts and ACE distribution should be investigated', Product = 'ad', Feature = 'permissions', Area = 'access-control', @@ -27,6 +27,7 @@ Severity = 'Info', Mitre = 'None', Service = 'ActiveDirectory', + Platform = 'Windows', Permission = ('ActiveDirectory:Ldap:*.ntSecurityDescriptor:ReadControl'), LongRunning, Author = 'soulemike' @@ -42,17 +43,18 @@ } $adState = Get-MtADDomainState -Categories @('DaclEntries') Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - if ($null -eq $adState.DaclEntries) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'DACL data is unavailable.' - return $null + if ($null -eq $adState -or $null -eq $adState.DaclEntries) { + throw 'DACL data is unavailable.' } Write-Verbose "Filtering/counting dacl distinct identity count" - $daclEntries = @($adState.DaclEntries) + $daclEntries = @($adState.DaclEntries | Where-Object { $null -ne $_ }) + if ($daclEntries.Count -eq 0) { + throw 'No DACL entries were collected; cannot assess identity distribution.' + } + if (@($daclEntries | Where-Object { [string]::IsNullOrWhiteSpace($_.ObjectDN) -or [string]::IsNullOrWhiteSpace($_.AccessControlType) }).Count -gt 0) { + throw 'DACL entries are missing object names or access control types.' + } $totalAceCount = ($daclEntries | Measure-Object).Count $distinctIdentityReferences = @( $daclEntries | @@ -86,6 +88,17 @@ $result += "| Identity with most ACEs | $largestIdentityName |" + "`n" $result += "| ACEs for most represented identity | $($largestIdentityGroup.Count) |" + "`n" } + $result += "`n| Identity Reference | ACE Count | Distinct Objects | Allow ACEs | Deny ACEs |`n| --- | --- | --- | --- | --- |`n" + foreach ($group in @($daclEntries | Where-Object { -not [string]::IsNullOrWhiteSpace($_.IdentityReference) } | Group-Object IdentityReference | Sort-Object -Property @{ Expression = 'Count'; Descending = $true }, Name)) { + $identity = ([string]$group.Name) -replace '\|', '|' + $objects = @($group.Group | Where-Object { -not [string]::IsNullOrWhiteSpace($_.ObjectDN) } | Select-Object -ExpandProperty ObjectDN -Unique).Count + $allows = @($group.Group | Where-Object { $_.AccessControlType -eq 'Allow' }).Count + $denies = @($group.Group | Where-Object { $_.AccessControlType -eq 'Deny' }).Count + $result += "| $identity | $($group.Count) | $objects | $allows | $denies |`n" + } + if ($distinctIdentityCount -eq 0) { + $result += "| No identities found | 0 | 0 | 0 | 0 |`n" + } Write-Verbose "Counts computed" $testResultMarkdown = "This informational test summarizes how many unique identities are present across collected DACL ACEs.`n`n%TestResult%" diff --git a/tests/ad/dacl/Test.AD-DACL-08.md b/tests/ad/dacl/Test.AD-DACL-08.md deleted file mode 100644 index 25bd4bc926..0000000000 --- a/tests/ad/dacl/Test.AD-DACL-08.md +++ /dev/null @@ -1,28 +0,0 @@ -Knowing which identities appear most frequently in DACLs helps identify central delegation patterns, inherited administrative groups, and accounts that may have accumulated permissions over time. - -- **Hotspot Detection**: Frequently occurring identities can represent broad administrative reach. -- **Permission Hygiene**: Distribution data helps distinguish expected administrative groups from unusual direct assignments. -- **Operational Review**: Repeated counts per identity make it easier to validate changes after cleanup or redesign. - -#### Control Type - -**Operational** - -#### Security Recommendation - -Review identities with unusually high ACE counts. Confirm they are expected administrative groups and not stale accounts, orphaned SIDs, or overly broad delegated principals. - -#### How the Test Works - -This test reads `DaclEntries` from `Get-MtADDomainState`, groups entries by `IdentityReference`, and reports the number of ACEs associated with each identity. - -#### Related Tests - -- `Test-MtAdDaclDistinctIdentityCount` -- `Test-MtAdDaclPrivilegedAllowAceDetails` -- `Test-MtAdDaclPrivilegedExtendedRightDetails` - -> **Note:** This test is `LongRunning`. It loads the full DACL dataset, which can consume significant memory in large Active Directory environments. Use `Invoke-Maester -IncludeLongRunning` to run it. - - -%TestResult% diff --git a/tests/ad/dacl/Test.AD-DACL-08.ps1 b/tests/ad/dacl/Test.AD-DACL-08.ps1 deleted file mode 100644 index e0ef39e2ca..0000000000 --- a/tests/ad/dacl/Test.AD-DACL-08.ps1 +++ /dev/null @@ -1,102 +0,0 @@ -function Test-MtAdDaclIdentityAceDistribution { - <# - .SYNOPSIS - Returns the ACE distribution per identity in collected DACL data. - - .DESCRIPTION - This test groups DACL access control entries by IdentityReference and reports how - many ACEs are associated with each identity. The output helps highlight identities - that appear frequently across directory object permissions and may warrant review. - - .EXAMPLE - Test-MtAdDaclIdentityAceDistribution - - Returns $true if DACL data is accessible. - - .LINK - https://maester.dev/docs/commands/Test-MtAdDaclIdentityAceDistribution - #> - [MaesterTest( - Id = 'AD-DACL-08', - Title = 'DACL ACE distribution per identity should be investigated', - Product = 'ad', - Feature = 'permissions', - Area = 'access-control', - ResourceType = 'Permission', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:*.ntSecurityDescriptor:ReadControl'), - LongRunning, - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdDaclIdentityAceDistribution" - if (-not (Test-MtAdDaclPlatformSupported)) { - Add-MtTestResultDetail -SkippedBecause NotSupported - return $null - } - $adState = Get-MtADDomainState -Categories @('DaclEntries') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - if ($null -eq $adState.DaclEntries) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'DACL data is unavailable.' - return $null - } - Write-Verbose "Filtering/counting dacl identity ace distribution" - - $daclEntries = @($adState.DaclEntries) - $identityDistribution = @( - $daclEntries | - Where-Object { -not [string]::IsNullOrWhiteSpace($_.IdentityReference) } | - Group-Object IdentityReference | - Sort-Object -Property @{ Expression = 'Count'; Descending = $true }, @{ Expression = 'Name'; Descending = $false } | - ForEach-Object { - $entriesForIdentity = @($_.Group) - [PSCustomObject]@{ - IdentityReference = $_.Name - AceCount = $_.Count - DistinctObjectCount = @( - $entriesForIdentity | - Where-Object { -not [string]::IsNullOrWhiteSpace($_.ObjectDN) } | - Select-Object -ExpandProperty ObjectDN -Unique - ).Count - AllowAceCount = @($entriesForIdentity | Where-Object { $_.AccessControlType -eq 'Allow' }).Count - DenyAceCount = @($entriesForIdentity | Where-Object { $_.AccessControlType -eq 'Deny' }).Count - } - } - ) - - $testResult = $true - - $summary = "| Metric | Value |" + "`n" - $summary += "| --- | --- |" + "`n" - $summary += "| Total identities | $($identityDistribution.Count) |" + "`n" - $summary += "| Total DACL ACEs | $((@($daclEntries) | Measure-Object).Count) |" + "`n" - - $table = "| IdentityReference | ACE Count | Distinct Objects | Allow ACEs | Deny ACEs |" + "`n" - $table += "| --- | --- | --- | --- | --- |" + "`n" - - foreach ($identity in $identityDistribution) { - $identityName = [string]$identity.IdentityReference - $identityName = $identityName -replace '\|', '\\|' - $table += "| $identityName | $($identity.AceCount) | $($identity.DistinctObjectCount) | $($identity.AllowAceCount) | $($identity.DenyAceCount) |" + "`n" - } - - if ($identityDistribution.Count -eq 0) { - $table += "| No identities found | 0 | 0 | 0 | 0 |" + "`n" - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "This informational test shows how DACL ACEs are distributed across identities.`n`n$summary`n$table" - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdDaclIdentityAceDistribution" - return $testResult -} diff --git a/tests/ad/dacl/Test.AD-DACL-09.md b/tests/ad/dacl/Test.AD-DACL-09.md index 4fab9e45de..93d87e88ee 100644 --- a/tests/ad/dacl/Test.AD-DACL-09.md +++ b/tests/ad/dacl/Test.AD-DACL-09.md @@ -8,17 +8,16 @@ Allow ACEs that grant `GenericAll`, `WriteDacl`, `WriteOwner`, or `ExtendedRight **Operational** -#### Security Recommendation +#### Remediation action Limit privileged rights to tightly controlled administrative groups. Investigate unexpected identities or objects that accumulate these permissions. #### How the Test Works -This test reads `DaclEntries` from `Get-MtADDomainState`, filters to allow ACEs, and counts entries where `ActiveDirectoryRights` includes `GenericAll`, `WriteDacl`, `WriteOwner`, or `ExtendedRight`. +This test reads `DaclEntries` from `Get-MtADDomainState`, filters allow ACEs for `GenericAll`, `WriteDacl`, `WriteOwner`, or `ExtendedRight`, reports aggregate counts and lists each affected object's ACE count, identities and matched rights. These rights require human review; their presence alone is not a failure. #### Related Tests -- `Test-MtAdDaclPrivilegedAllowAceDetails` - `Test-MtAdDaclPrivilegedExtendedRightCount` - `Test-MtAdDaclDistinctIdentityCount` diff --git a/tests/ad/dacl/Test.AD-DACL-09.ps1 b/tests/ad/dacl/Test.AD-DACL-09.ps1 index dbee236ff2..ae5438a53d 100644 --- a/tests/ad/dacl/Test.AD-DACL-09.ps1 +++ b/tests/ad/dacl/Test.AD-DACL-09.ps1 @@ -1,7 +1,7 @@ function Test-MtAdDaclPrivilegedAllowAceCount { <# .SYNOPSIS - Counts privileged allow ACEs in collected DACL data. + Counts privileged allow ACEs and lists affected objects in collected DACL data. .DESCRIPTION This test identifies allow ACEs that include high-impact Active Directory rights @@ -18,7 +18,7 @@ #> [MaesterTest( Id = 'AD-DACL-09', - Title = 'Privileged allow ACE count should be investigated', + Title = 'Privileged allow ACEs and affected objects should be investigated', Product = 'ad', Feature = 'permissions', Area = 'privileged-access', @@ -26,6 +26,7 @@ Severity = 'Info', Mitre = ('T1098', 'T1222.001'), Service = 'ActiveDirectory', + Platform = 'Windows', Permission = ('ActiveDirectory:Ldap:*.ntSecurityDescriptor:ReadControl'), LongRunning, Author = 'soulemike' @@ -41,13 +42,8 @@ } $adState = Get-MtADDomainState -Categories @('DaclEntries') Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - if ($null -eq $adState.DaclEntries) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'DACL data is unavailable.' - return $null + if ($null -eq $adState -or $null -eq $adState.DaclEntries) { + throw 'DACL data is unavailable.' } Write-Verbose "Filtering/counting dacl privileged allow ace count" @@ -64,7 +60,13 @@ ) } - $daclEntries = @($adState.DaclEntries) + $daclEntries = @($adState.DaclEntries | Where-Object { $null -ne $_ }) + if ($daclEntries.Count -eq 0) { + throw 'No DACL entries were collected; cannot assess privileged ACEs.' + } + if (@($daclEntries | Where-Object { [string]::IsNullOrWhiteSpace($_.ObjectDN) -or [string]::IsNullOrWhiteSpace($_.AccessControlType) -or [string]::IsNullOrWhiteSpace($_.ActiveDirectoryRights) }).Count -gt 0) { + throw 'DACL entries are missing object names, access control types or rights.' + } $privilegedAllowEntries = @( foreach ($entry in $daclEntries) { if ($entry.AccessControlType -ne 'Allow') { @@ -97,6 +99,19 @@ $rightCount = @($privilegedAllowEntries | Where-Object { $_.MatchedRights -contains $right }).Count $result += "| ACEs containing $right | $rightCount |" + "`n" } + $result += "`n| Object Name | Object Class | ACE Count | Distinct Identities | Privileged Rights | Object DN |`n| --- | --- | --- | --- | --- | --- |`n" + foreach ($group in @($privilegedAllowEntries | Group-Object ObjectDN | Sort-Object -Property @{ Expression = 'Count'; Descending = $true }, Name)) { + $sample = $group.Group | Select-Object -First 1 + $objectName = ([string]$sample.ObjectName) -replace '\|', '|' + $objectClass = ([string]$sample.ObjectClass) -replace '\|', '|' + $objectDn = ([string]$sample.ObjectDN) -replace '\|', '|' + $identityCount = @($group.Group | Where-Object { -not [string]::IsNullOrWhiteSpace($_.IdentityReference) } | Select-Object -ExpandProperty IdentityReference -Unique).Count + $rights = (@($group.Group | ForEach-Object { $_.MatchedRights } | Sort-Object -Unique) -join ', ') -replace '\|', '|' + $result += "| $objectName | $objectClass | $($group.Count) | $identityCount | $rights | $objectDn |`n" + } + if ($privilegedAllowEntries.Count -eq 0) { + $result += "| No privileged allow ACEs found | | 0 | 0 | | |`n" + } Write-Verbose "Counts computed" $testResultMarkdown = "This informational test counts allow ACEs that grant high-impact Active Directory rights.`n`n%TestResult%" diff --git a/tests/ad/dacl/Test.AD-DACL-10.md b/tests/ad/dacl/Test.AD-DACL-10.md deleted file mode 100644 index f2462ed162..0000000000 --- a/tests/ad/dacl/Test.AD-DACL-10.md +++ /dev/null @@ -1,28 +0,0 @@ -A count alone does not show where powerful ACEs are applied. Grouping privileged allow ACEs by object helps identify high-value directory objects that carry sensitive delegated rights. - -- **Object-Centric Review**: Highlights which objects hold the most powerful ACEs. -- **Delegation Validation**: Makes it easier to confirm whether privileged rights are intentional. -- **Attack Path Awareness**: Sensitive permissions on administrative objects can enable escalation. - -#### Control Type - -**Operational** - -#### Security Recommendation - -Review objects with privileged allow ACEs and confirm the assigned identities and rights are justified. Reduce direct assignments where possible and prefer auditable group-based delegation. - -#### How the Test Works - -This test reads `DaclEntries` from `Get-MtADDomainState`, filters to allow ACEs containing `GenericAll`, `WriteDacl`, `WriteOwner`, or `ExtendedRight`, and groups the results by object. - -#### Related Tests - -- `Test-MtAdDaclPrivilegedAllowAceCount` -- `Test-MtAdDaclIdentityAceDistribution` -- `Test-MtAdDaclPrivilegedExtendedRightDetails` - -> **Note:** This test is `LongRunning`. It loads the full DACL dataset, which can consume significant memory in large Active Directory environments. Use `Invoke-Maester -IncludeLongRunning` to run it. - - -%TestResult% diff --git a/tests/ad/dacl/Test.AD-DACL-10.ps1 b/tests/ad/dacl/Test.AD-DACL-10.ps1 deleted file mode 100644 index 24bc899308..0000000000 --- a/tests/ad/dacl/Test.AD-DACL-10.ps1 +++ /dev/null @@ -1,153 +0,0 @@ -function Test-MtAdDaclPrivilegedAllowAceDetails { - <# - .SYNOPSIS - Returns details for privileged allow ACEs in collected DACL data. - - .DESCRIPTION - This test identifies allow ACEs that contain high-impact Active Directory rights - such as GenericAll, WriteDacl, WriteOwner, or ExtendedRight and groups them by - object. The output provides a concise breakdown of where privileged rights appear. - - .EXAMPLE - Test-MtAdDaclPrivilegedAllowAceDetails - - Returns $true if DACL data is accessible. - - .LINK - https://maester.dev/docs/commands/Test-MtAdDaclPrivilegedAllowAceDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-DACL-10', - Title = 'Privileged allow ACE details should be investigated', - Product = 'ad', - Feature = 'permissions', - Area = 'privileged-access', - ResourceType = 'Permission', - Severity = 'Info', - Mitre = ('T1098', 'T1222.001'), - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:*.ntSecurityDescriptor:ReadControl'), - LongRunning, - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdDaclPrivilegedAllowAceDetails" - if (-not (Test-MtAdDaclPlatformSupported)) { - Add-MtTestResultDetail -SkippedBecause NotSupported - return $null - } - $adState = Get-MtADDomainState -Categories @('DaclEntries') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - if ($null -eq $adState.DaclEntries) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'DACL data is unavailable.' - return $null - } - Write-Verbose "Filtering/counting dacl privileged allow ace details" - - $privilegedRights = @('GenericAll', 'WriteDacl', 'WriteOwner', 'ExtendedRight') - $getPrivilegedRights = { - param($rightsText) - - @( - foreach ($right in $privilegedRights) { - if ([string]$rightsText -match "(^|,\s*)$right(,|$)") { - $right - } - } - ) - } - - $daclEntries = @($adState.DaclEntries) - $privilegedAllowEntries = @( - foreach ($entry in $daclEntries) { - if ($entry.AccessControlType -ne 'Allow') { - continue - } - - $matchedRights = @(& $getPrivilegedRights $entry.ActiveDirectoryRights) - if ($matchedRights.Count -gt 0) { - [PSCustomObject]@{ - ObjectDN = $entry.ObjectDN - ObjectClass = $entry.ObjectClass - ObjectName = $entry.ObjectName - IdentityReference = $entry.IdentityReference - MatchedRights = $matchedRights - } - } - } - ) - - $objectBreakdown = @( - $privilegedAllowEntries | - Group-Object ObjectDN | - Sort-Object -Property @{ Expression = 'Count'; Descending = $true }, @{ Expression = 'Name'; Descending = $false } | - ForEach-Object { - $entriesForObject = @($_.Group) - $firstEntry = $entriesForObject | Select-Object -First 1 - [PSCustomObject]@{ - ObjectName = $firstEntry.ObjectName - ObjectClass = $firstEntry.ObjectClass - ObjectDN = if ([string]::IsNullOrWhiteSpace($_.Name)) { '[Unknown ObjectDN]' } else { $_.Name } - AceCount = $_.Count - IdentityCount = @( - $entriesForObject | - Where-Object { -not [string]::IsNullOrWhiteSpace($_.IdentityReference) } | - Select-Object -ExpandProperty IdentityReference -Unique - ).Count - Rights = (@( - $entriesForObject | - ForEach-Object { $_.MatchedRights } | - Sort-Object -Unique - ) -join ', ') - } - } - ) - - $testResult = $true - - $table = "| Object Name | Object Class | ACE Count | Distinct Identities | Privileged Rights | Object DN |" + "`n" - $table += "| --- | --- | --- | --- | --- | --- |" + "`n" - - foreach ($item in $objectBreakdown) { - $objectName = [string]$item.ObjectName - if ([string]::IsNullOrWhiteSpace($objectName)) { - $objectName = '[Unnamed Object]' - } - $objectName = $objectName -replace '\|', '\\|' - - $objectClass = [string]$item.ObjectClass - $objectClass = $objectClass -replace '\|', '\\|' - - $rights = [string]$item.Rights - $rights = $rights -replace '\|', '\\|' - - $objectDn = [string]$item.ObjectDN - $objectDn = $objectDn -replace '\|', '\\|' - - $table += "| $objectName | $objectClass | $($item.AceCount) | $($item.IdentityCount) | $rights | $objectDn |" + "`n" - } - - if ($objectBreakdown.Count -eq 0) { - $table += "| No privileged allow ACEs found | | 0 | 0 | | |" + "`n" - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "This informational test groups privileged allow ACEs by object and summarizes the rights observed.`n`n%TestResult%" - if ($objectBreakdown.Count -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $table - } else { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", "" - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdDaclPrivilegedAllowAceDetails" - return $testResult -} diff --git a/tests/ad/dacl/Test.AD-DACL-11.md b/tests/ad/dacl/Test.AD-DACL-11.md index 00bd3d2c62..677e220df4 100644 --- a/tests/ad/dacl/Test.AD-DACL-11.md +++ b/tests/ad/dacl/Test.AD-DACL-11.md @@ -8,19 +8,17 @@ Extended rights control specific privileged operations in Active Directory, such **Operational** -#### Security Recommendation +#### Remediation action Review principals granted extended rights and verify that those delegations are necessary, documented, and limited to the smallest practical scope. #### How the Test Works -This test reads `DaclEntries` from `Get-MtADDomainState`, filters to allow ACEs whose `ActiveDirectoryRights` includes `ExtendedRight`, and reports counts across identities, objects, and object types. +This test reads `DaclEntries` from `Get-MtADDomainState`, filters allow ACEs whose rights include `ExtendedRight` (including combined rights), reports counts across identities, objects and object types, lists counts by `ObjectType` GUID, then lists identities granted specifically named sensitive rights such as password reset or replication. A blank or all-zero GUID is counted as `All / Not specified` but is not assigned a named right. All findings are for review, not automatic failures. #### Related Tests -- `Test-MtAdDaclPrivilegedExtendedRightDetails` - `Test-MtAdDaclPrivilegedAllowAceCount` -- `Test-MtAdDaclPrivilegedAllowAceDetails` > **Note:** This test is `LongRunning`. It loads the full DACL dataset, which can consume significant memory in large Active Directory environments. Use `Invoke-Maester -IncludeLongRunning` to run it. diff --git a/tests/ad/dacl/Test.AD-DACL-11.ps1 b/tests/ad/dacl/Test.AD-DACL-11.ps1 index bfb57cffcb..ea8afa704a 100644 --- a/tests/ad/dacl/Test.AD-DACL-11.ps1 +++ b/tests/ad/dacl/Test.AD-DACL-11.ps1 @@ -1,7 +1,7 @@ function Test-MtAdDaclPrivilegedExtendedRightCount { <# .SYNOPSIS - Counts allow ACEs that grant the ExtendedRight permission. + Counts ExtendedRight allow ACEs and lists right types and identities. .DESCRIPTION This test reviews DACL entries and counts allow ACEs that include the @@ -18,7 +18,7 @@ #> [MaesterTest( Id = 'AD-DACL-11', - Title = 'Privileged extended right count should be investigated', + Title = 'ExtendedRight delegations and identities should be investigated', Product = 'ad', Feature = 'permissions', Area = 'privileged-access', @@ -26,6 +26,7 @@ Severity = 'Info', Mitre = ('T1003.006', 'T1098'), Service = 'ActiveDirectory', + Platform = 'Windows', Permission = ('ActiveDirectory:Ldap:*.ntSecurityDescriptor:ReadControl'), LongRunning, Author = 'soulemike' @@ -41,17 +42,18 @@ } $adState = Get-MtADDomainState -Categories @('DaclEntries') Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - if ($null -eq $adState.DaclEntries) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'DACL data is unavailable.' - return $null + if ($null -eq $adState -or $null -eq $adState.DaclEntries) { + throw 'DACL data is unavailable.' } Write-Verbose "Filtering/counting dacl privileged extended right count" - $daclEntries = @($adState.DaclEntries) + $daclEntries = @($adState.DaclEntries | Where-Object { $null -ne $_ }) + if ($daclEntries.Count -eq 0) { + throw 'No DACL entries were collected; cannot assess extended rights.' + } + if (@($daclEntries | Where-Object { [string]::IsNullOrWhiteSpace($_.ObjectDN) -or [string]::IsNullOrWhiteSpace($_.AccessControlType) -or [string]::IsNullOrWhiteSpace($_.ActiveDirectoryRights) }).Count -gt 0) { + throw 'DACL entries are missing object names, access control types or rights.' + } $extendedRightEntries = @( $daclEntries | Where-Object { $_.AccessControlType -eq 'Allow' -and @@ -79,9 +81,78 @@ $result += "| Distinct ObjectType values | $(@($normalizedObjectTypes | Sort-Object -Unique).Count) |" + "`n" $result += "| Distinct identities with ExtendedRight | $(@($extendedRightEntries | Where-Object { -not [string]::IsNullOrWhiteSpace($_.IdentityReference) } | Select-Object -ExpandProperty IdentityReference -Unique).Count) |" + "`n" $result += "| Distinct objects with ExtendedRight | $(@($extendedRightEntries | Where-Object { -not [string]::IsNullOrWhiteSpace($_.ObjectDN) } | Select-Object -ExpandProperty ObjectDN -Unique).Count) |" + "`n" + $result += "`n| ObjectType | ACE Count | Distinct Objects | Distinct Identities |`n| --- | --- | --- | --- |`n" + $typedEntries = @( + foreach ($entry in $extendedRightEntries) { + [PSCustomObject]@{ + ObjectType = if ([string]::IsNullOrWhiteSpace($entry.ObjectType) -or $entry.ObjectType -eq '00000000-0000-0000-0000-000000000000') { 'All / Not specified' } else { [string]$entry.ObjectType } + ObjectDN = $entry.ObjectDN + IdentityReference = $entry.IdentityReference + } + } + ) + foreach ($group in @($typedEntries | Group-Object ObjectType | Sort-Object -Property @{ Expression = 'Count'; Descending = $true }, Name)) { + $objectType = ([string]$group.Name) -replace '\|', '|' + $objects = @($group.Group | Where-Object { -not [string]::IsNullOrWhiteSpace($_.ObjectDN) } | Select-Object -ExpandProperty ObjectDN -Unique).Count + $identities = @($group.Group | Where-Object { -not [string]::IsNullOrWhiteSpace($_.IdentityReference) } | Select-Object -ExpandProperty IdentityReference -Unique).Count + $result += "| $objectType | $($group.Count) | $objects | $identities |`n" + } + if ($typedEntries.Count -eq 0) { + $result += "| No ExtendedRight allow ACEs found | 0 | 0 | 0 |`n" + } + + # The GUID list formerly used by AD-DACL-13 identifies sensitive extended rights for identity review. + $privilegedExtendedRights = @{ + '440820ad-65b4-11d1-a3da-0000f875ae0d' = 'Add GUID' + 'e2a36dc9-ae17-47c3-b58b-be34c55ba633' = 'Create Inbound Forest Trust' + '3e0f7e18-4434-48c6-a534-0b62eb6d8b2c' = 'DS-Clone-Domain-Controller' + '2f16c4a5-b98e-432c-952a-cb388ba33f2e' = 'DS-Execute-Intentions-Script' + '9923a32a-3607-11d2-b9be-0000f87a36b2' = 'DS-Install-Replica' + '1131f6aa-9c07-11d1-f79f-00c04fc2dcd2' = 'DS-Replication-Get-Changes' + '1131f6ad-9c07-11d1-f79f-00c04fc2dcd2' = 'DS-Replication-Get-Changes-All' + '89e95b76-444d-4c62-991a-0facbeda640c' = 'DS-Replication-Get-Changes-In-Filtered-Set' + '1131f6ac-9c07-11d1-f79f-00c04fc2dcd2' = 'DS-Replication-Manage-Topology' + '05c74c5e-4deb-43b5-bc7c-0dfc1ed58fbd' = 'Enable Per User Reversibly Encrypted Password' + '7c0e2a7c-a419-48e4-a995-10180aad54dd' = 'Manage-Optional-Features' + 'ba33815a-4f93-4c76-87f3-57574bff8109' = 'Migrate SID History' + '4b6e08c2-a6b3-11d0-afd3-00c04fd930c9' = 'msmq-Open-Connector' + '06bd3201-df3e-11d1-9c86-006008764d0e' = 'msmq-Peek' + '4b6e08c3-a6b3-11d0-afd3-00c04fd930c9' = 'msmq-Peek-computer-Journal' + '4b6e08c4-a6b3-11d0-afd3-00c04fd930c9' = 'msmq-Peek-Dead-Letter' + '06bd3200-df3e-11d1-9c86-006008764d0e' = 'msmq-Receive' + '4b6e08c5-a6b3-11d0-afd3-00c04fd930c9' = 'msmq-Receive-computer-Journal' + '4b6e08c6-a6b3-11d0-afd3-00c04fd930c9' = 'msmq-Receive-Dead-Letter' + '06bd3203-df3e-11d1-9c86-006008764d0e' = 'msmq-Receive-journal' + '06bd3202-df3e-11d1-9c86-006008764d0e' = 'msmq-Send' + '1131f6ae-9c07-11d1-f79f-00c04fc2dcd2' = 'Read Only Replication Secret Synchronization' + '45ec5156-db7e-47bb-b53f-dbeb2d03c40f' = 'Reanimate Tombstones' + '62dd28a8-7f46-11d2-b9ad-00c04f79f805' = 'Recalculate Security Inheritance' + 'ab721a56-1e2f-11d0-9819-00aa0040529b' = 'Receive As' + '7726b9d5-a4b4-4288-a6b2-dce952e80a7f' = 'Run Protect Admin Groups Task' + '91d67418-0135-4acc-8d79-c08e857cfbec' = 'Enumerate Entire SAM Domain' + 'ab721a54-1e2f-11d0-9819-00aa0040529b' = 'Send As' + 'ccc2dc7d-a6ad-4a7a-8846-c04e3cc53501' = 'Unexpire Password' + '280f369c-67c7-438e-ae98-1d46f3f5c52f' = 'Update Password Not Required Bit' + 'ab721a53-1e2f-11d0-9819-00aa0040529b' = 'Change Password' + '00299570-246d-11d0-a768-00aa006e0529' = 'Reset Password' + } + $sensitiveEntries = @($extendedRightEntries | Where-Object { + -not [string]::IsNullOrWhiteSpace($_.IdentityReference) -and + -not [string]::IsNullOrWhiteSpace($_.ObjectType) -and + $privilegedExtendedRights.ContainsKey(([string]$_.ObjectType).ToLowerInvariant()) + }) + $result += "`n| Identity Reference | Privileged Extended Rights | ACE Count |`n| --- | --- | --- |`n" + foreach ($group in @($sensitiveEntries | Group-Object IdentityReference | Sort-Object -Property @{ Expression = 'Count'; Descending = $true }, Name)) { + $identity = ([string]$group.Name) -replace '\|', '|' + $rights = @($group.Group | ForEach-Object { $privilegedExtendedRights[([string]$_.ObjectType).ToLowerInvariant()] } | Sort-Object -Unique) -join ', ' + $result += "| $identity | $rights | $($group.Count) |`n" + } + if ($sensitiveEntries.Count -eq 0) { + $result += "| No named privileged extended rights found | | 0 |`n" + } Write-Verbose "Counts computed" - $testResultMarkdown = "This informational test counts allow ACEs that grant the ExtendedRight permission.`n`n%TestResult%" + $testResultMarkdown = "This informational test counts ExtendedRight allow ACEs and groups them by ObjectType and by identities holding named sensitive rights.`n`n%TestResult%" $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result Add-MtTestResultDetail -Result $testResultMarkdown -Investigate diff --git a/tests/ad/dacl/Test.AD-DACL-12.md b/tests/ad/dacl/Test.AD-DACL-12.md deleted file mode 100644 index cca394740b..0000000000 --- a/tests/ad/dacl/Test.AD-DACL-12.md +++ /dev/null @@ -1,28 +0,0 @@ -Extended rights are most useful when you can see which specific `ObjectType` values are being delegated. Grouping ACEs by GUID reveals whether permissions are narrowly targeted or broadly applied. - -- **GUID-Level Visibility**: Highlights which extended-right object types occur most often. -- **Delegation Review**: Helps correlate control-access permissions with documented administration patterns. -- **Change Tracking**: Makes it easier to compare extended-right usage over time. - -#### Control Type - -**Operational** - -#### Security Recommendation - -Document the purpose of delegated extended rights and review object types with high counts or unexpected identity coverage. - -#### How the Test Works - -This test reads `DaclEntries` from `Get-MtADDomainState`, filters to allow ACEs containing `ExtendedRight`, normalizes missing `ObjectType` values, and groups the results by `ObjectType`. - -#### Related Tests - -- `Test-MtAdDaclPrivilegedExtendedRightCount` -- `Test-MtAdDaclPrivilegedAllowAceDetails` -- `Test-MtAdDaclIdentityAceDistribution` - -> **Note:** This test is `LongRunning`. It loads the full DACL dataset, which can consume significant memory in large Active Directory environments. Use `Invoke-Maester -IncludeLongRunning` to run it. - - -%TestResult% diff --git a/tests/ad/dacl/Test.AD-DACL-12.ps1 b/tests/ad/dacl/Test.AD-DACL-12.ps1 deleted file mode 100644 index a30ab809d3..0000000000 --- a/tests/ad/dacl/Test.AD-DACL-12.ps1 +++ /dev/null @@ -1,121 +0,0 @@ -function Test-MtAdDaclPrivilegedExtendedRightDetails { - <# - .SYNOPSIS - Returns a breakdown of ExtendedRight allow ACEs by ObjectType. - - .DESCRIPTION - This test reviews DACL entries, filters to allow ACEs that include the - ExtendedRight permission, and groups them by ObjectType GUID. This helps identify - which extended rights are most commonly delegated in the environment. - - .EXAMPLE - Test-MtAdDaclPrivilegedExtendedRightDetails - - Returns $true if DACL data is accessible. - - .LINK - https://maester.dev/docs/commands/Test-MtAdDaclPrivilegedExtendedRightDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-DACL-12', - Title = 'Privileged extended right details should be investigated', - Product = 'ad', - Feature = 'permissions', - Area = 'privileged-access', - ResourceType = 'Permission', - Severity = 'Info', - Mitre = ('T1003.006', 'T1098'), - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:*.ntSecurityDescriptor:ReadControl'), - LongRunning, - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdDaclPrivilegedExtendedRightDetails" - if (-not (Test-MtAdDaclPlatformSupported)) { - Add-MtTestResultDetail -SkippedBecause NotSupported - return $null - } - $adState = Get-MtADDomainState -Categories @('DaclEntries') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - if ($null -eq $adState.DaclEntries) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'DACL data is unavailable.' - return $null - } - Write-Verbose "Filtering/counting dacl privileged extended right details" - - $daclEntries = @($adState.DaclEntries) - $extendedRightEntries = @( - foreach ($entry in $daclEntries) { - if ($entry.AccessControlType -eq 'Allow' -and [string]$entry.ActiveDirectoryRights -match '(^|,\s*)ExtendedRight(,|$)') { - [PSCustomObject]@{ - ObjectType = if ([string]::IsNullOrWhiteSpace($entry.ObjectType) -or $entry.ObjectType -eq '00000000-0000-0000-0000-000000000000') { - 'All / Not specified' - } else { - [string]$entry.ObjectType - } - ObjectDN = $entry.ObjectDN - IdentityReference = $entry.IdentityReference - } - } - } - ) - - $breakdown = @( - $extendedRightEntries | - Group-Object ObjectType | - Sort-Object -Property @{ Expression = 'Count'; Descending = $true }, @{ Expression = 'Name'; Descending = $false } | - ForEach-Object { - $entriesForType = @($_.Group) - [PSCustomObject]@{ - ObjectType = $_.Name - AceCount = $_.Count - DistinctObjectCount = @( - $entriesForType | - Where-Object { -not [string]::IsNullOrWhiteSpace($_.ObjectDN) } | - Select-Object -ExpandProperty ObjectDN -Unique - ).Count - DistinctIdentityCount = @( - $entriesForType | - Where-Object { -not [string]::IsNullOrWhiteSpace($_.IdentityReference) } | - Select-Object -ExpandProperty IdentityReference -Unique - ).Count - } - } - ) - - $testResult = $true - - $table = "| ObjectType | ACE Count | Distinct Objects | Distinct Identities |" + "`n" - $table += "| --- | --- | --- | --- |" + "`n" - - foreach ($item in $breakdown) { - $objectType = [string]$item.ObjectType - $objectType = $objectType -replace '\|', '\\|' - $table += "| $objectType | $($item.AceCount) | $($item.DistinctObjectCount) | $($item.DistinctIdentityCount) |" + "`n" - } - - if ($breakdown.Count -eq 0) { - $table += "| No ExtendedRight allow ACEs found | 0 | 0 | 0 |" + "`n" - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "This informational test groups ExtendedRight allow ACEs by ObjectType GUID.`n`n%TestResult%" - if ($breakdown.Count -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $table - } else { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", "" - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdDaclPrivilegedExtendedRightDetails" - return $testResult -} diff --git a/tests/ad/dacl/Test.AD-DACL-13.md b/tests/ad/dacl/Test.AD-DACL-13.md deleted file mode 100644 index be06f641a2..0000000000 --- a/tests/ad/dacl/Test.AD-DACL-13.md +++ /dev/null @@ -1,30 +0,0 @@ -Privileged extended rights in Active Directory can authorize sensitive operations that go beyond standard read or write permissions. - -- **Privilege escalation risk**: Rights such as password reset or replication access can enable takeover paths -- **Delegation review**: Extended rights are often assigned during admin delegation and may persist longer than intended -- **Exposure visibility**: Grouping by identity shows which principals hold high-impact rights across the directory - -#### Control Type - -**Operational** - -#### Security Recommendation - -- Review every identity granted privileged extended rights -- Confirm the assignment is documented, approved, and still required -- Remove stale delegations, especially for replication and password-management rights - -#### How the Test Works - -This test reads `$adState.DaclEntries`, filters for allow ACEs with `ActiveDirectoryRights = ExtendedRight`, matches them to a set of privileged extended right GUIDs, and groups the results by `IdentityReference`. - -#### Related Tests - -- `Test-MtAdDaclPrivilegedExtendedRightCount` - Counts privileged extended rights in use -- `Test-MtAdDaclPrivilegedExtendedRightDetails` - Breaks down privileged extended rights by type -- `Test-MtAdDaclNonInheritedAceCount` - Counts explicit DACL entries that may represent custom delegations - -> **Note:** This test is `LongRunning`. It loads the full DACL dataset, which can consume significant memory in large Active Directory environments. Use `Invoke-Maester -IncludeLongRunning` to run it. - - -%TestResult% diff --git a/tests/ad/dacl/Test.AD-DACL-13.ps1 b/tests/ad/dacl/Test.AD-DACL-13.ps1 deleted file mode 100644 index c11017c7a2..0000000000 --- a/tests/ad/dacl/Test.AD-DACL-13.ps1 +++ /dev/null @@ -1,134 +0,0 @@ -function Test-MtAdDaclPrivilegedExtendedRightIdentity { - <# - .SYNOPSIS - Returns identities with privileged extended rights in Active Directory DACLs. - - .DESCRIPTION - This test analyzes DACL entries collected by Get-MtADDomainState -Categories @('DaclEntries') and identifies - identities that are granted privileged extended rights through allow ACEs. - Extended rights such as password reset and replication-related permissions can - enable sensitive directory operations and should be tightly controlled. - - .EXAMPLE - Test-MtAdDaclPrivilegedExtendedRightIdentity - - Returns $true if DACL data is accessible. - - .LINK - https://maester.dev/docs/commands/Test-MtAdDaclPrivilegedExtendedRightIdentity - #> - [MaesterTest( - Id = 'AD-DACL-13', - Title = 'Privileged extended right identities should be investigated', - Product = 'ad', - Feature = 'permissions', - Area = 'privileged-access', - ResourceType = 'Permission', - Severity = 'Info', - Mitre = ('T1003.006', 'T1098'), - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:*.ntSecurityDescriptor:ReadControl'), - LongRunning, - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdDaclPrivilegedExtendedRightIdentity" - if (-not (Test-MtAdDaclPlatformSupported)) { - Add-MtTestResultDetail -SkippedBecause NotSupported - return $null - } - $adState = Get-MtADDomainState -Categories @('DaclEntries') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - if ($null -eq $adState.DaclEntries) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'DACL data is unavailable.' - return $null - } - Write-Verbose "Filtering/counting dacl privileged extended right identity" - - $daclEntries = @($adState.DaclEntries | Where-Object { $null -ne $_ }) - - $privilegedExtendedRights = @{ - '440820ad-65b4-11d1-a3da-0000f875ae0d' = 'Add GUID' - 'e2a36dc9-ae17-47c3-b58b-be34c55ba633' = 'Create Inbound Forest Trust' - '3e0f7e18-4434-48c6-a534-0b62eb6d8b2c' = 'DS-Clone-Domain-Controller' - '2f16c4a5-b98e-432c-952a-cb388ba33f2e' = 'DS-Execute-Intentions-Script' - '9923a32a-3607-11d2-b9be-0000f87a36b2' = 'DS-Install-Replica' - '1131f6aa-9c07-11d1-f79f-00c04fc2dcd2' = 'DS-Replication-Get-Changes' - '1131f6ad-9c07-11d1-f79f-00c04fc2dcd2' = 'DS-Replication-Get-Changes-All' - '89e95b76-444d-4c62-991a-0facbeda640c' = 'DS-Replication-Get-Changes-In-Filtered-Set' - '1131f6ac-9c07-11d1-f79f-00c04fc2dcd2' = 'DS-Replication-Manage-Topology' - '05c74c5e-4deb-43b5-bc7c-0dfc1ed58fbd' = 'Enable Per User Reversibly Encrypted Password' - '7c0e2a7c-a419-48e4-a995-10180aad54dd' = 'Manage-Optional-Features' - 'ba33815a-4f93-4c76-87f3-57574bff8109' = 'Migrate SID History' - '4b6e08c2-a6b3-11d0-afd3-00c04fd930c9' = 'msmq-Open-Connector' - '06bd3201-df3e-11d1-9c86-006008764d0e' = 'msmq-Peek' - '4b6e08c3-a6b3-11d0-afd3-00c04fd930c9' = 'msmq-Peek-computer-Journal' - '4b6e08c4-a6b3-11d0-afd3-00c04fd930c9' = 'msmq-Peek-Dead-Letter' - '06bd3200-df3e-11d1-9c86-006008764d0e' = 'msmq-Receive' - '4b6e08c5-a6b3-11d0-afd3-00c04fd930c9' = 'msmq-Receive-computer-Journal' - '4b6e08c6-a6b3-11d0-afd3-00c04fd930c9' = 'msmq-Receive-Dead-Letter' - '06bd3203-df3e-11d1-9c86-006008764d0e' = 'msmq-Receive-journal' - '06bd3202-df3e-11d1-9c86-006008764d0e' = 'msmq-Send' - '1131f6ae-9c07-11d1-f79f-00c04fc2dcd2' = 'Read Only Replication Secret Synchronization' - '45ec5156-db7e-47bb-b53f-dbeb2d03c40f' = 'Reanimate Tombstones' - '62dd28a8-7f46-11d2-b9ad-00c04f79f805' = 'Recalculate Security Inheritance' - 'ab721a56-1e2f-11d0-9819-00aa0040529b' = 'Receive As' - '7726b9d5-a4b4-4288-a6b2-dce952e80a7f' = 'Run Protect Admin Groups Task' - '91d67418-0135-4acc-8d79-c08e857cfbec' = 'Enumerate Entire SAM Domain' - 'ab721a54-1e2f-11d0-9819-00aa0040529b' = 'Send As' - 'ccc2dc7d-a6ad-4a7a-8846-c04e3cc53501' = 'Unexpire Password' - '280f369c-67c7-438e-ae98-1d46f3f5c52f' = 'Update Password Not Required Bit' - 'ab721a53-1e2f-11d0-9819-00aa0040529b' = 'Change Password' - '00299570-246d-11d0-a768-00aa006e0529' = 'Reset Password' - } - - $privilegedEntries = @( - $daclEntries | Where-Object { - $_.AccessControlType -eq 'Allow' -and - $_.ActiveDirectoryRights -eq 'ExtendedRight' -and - -not [string]::IsNullOrWhiteSpace([string]$_.IdentityReference) -and - -not [string]::IsNullOrWhiteSpace([string]$_.ObjectType) -and - $privilegedExtendedRights.ContainsKey(([string]$_.ObjectType).ToLowerInvariant()) - } - ) - - $identityGroups = @( - $privilegedEntries | - Group-Object -Property IdentityReference | - Sort-Object @{ Expression = 'Count'; Descending = $true }, @{ Expression = 'Name'; Descending = $false } - ) - - $result = '| IdentityReference | Privileged Extended Rights | ACE Count |' + "`n" - $result += '| --- | --- | --- |' + "`n" - - foreach ($group in $identityGroups) { - $identity = [string]$group.Name - $identity = $identity -replace '\|', '\\|' - - $rights = @( - $group.Group | - ForEach-Object { $privilegedExtendedRights[([string]$_.ObjectType).ToLowerInvariant()] } | - Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | - Sort-Object -Unique - ) - - $rightList = ($rights | ForEach-Object { $_ -replace '\|', '\\|' }) -join ', ' - $result += "| $identity | $rightList | $($group.Count) |" + "`n" - } - - $testResult = $true - Write-Verbose "Counts computed" - $testResultMarkdown = "Active Directory DACL entries were analyzed for privileged extended rights. $($identityGroups.Count) identity reference(s) have at least one privileged extended right ACE.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdDaclPrivilegedExtendedRightIdentity" - return $testResult -} From 3361b031173da791c26c2c468161e62c80cceb1b Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 06:23:26 +0000 Subject: [PATCH 007/100] refactor(ad): consolidate DACL unresolved identities and inheritance --- .../functions/ADDaclConsolidation.Tests.ps1 | 67 ++++++++++++ tests/ad/dacl/Test.AD-DACL-15.md | 7 +- tests/ad/dacl/Test.AD-DACL-15.ps1 | 31 ++++-- tests/ad/dacl/Test.AD-DACL-16.md | 30 ------ tests/ad/dacl/Test.AD-DACL-16.ps1 | 100 ------------------ tests/ad/dacl/Test.AD-DACL-17.md | 7 +- tests/ad/dacl/Test.AD-DACL-17.ps1 | 29 +++-- tests/ad/dacl/Test.AD-DACL-18.md | 30 ------ tests/ad/dacl/Test.AD-DACL-18.ps1 | 97 ----------------- 9 files changed, 115 insertions(+), 283 deletions(-) create mode 100644 powershell/tests/functions/ADDaclConsolidation.Tests.ps1 delete mode 100644 tests/ad/dacl/Test.AD-DACL-16.md delete mode 100644 tests/ad/dacl/Test.AD-DACL-16.ps1 delete mode 100644 tests/ad/dacl/Test.AD-DACL-18.md delete mode 100644 tests/ad/dacl/Test.AD-DACL-18.ps1 diff --git a/powershell/tests/functions/ADDaclConsolidation.Tests.ps1 b/powershell/tests/functions/ADDaclConsolidation.Tests.ps1 new file mode 100644 index 0000000000..e4ceb8f9ca --- /dev/null +++ b/powershell/tests/functions/ADDaclConsolidation.Tests.ps1 @@ -0,0 +1,67 @@ +Describe 'Consolidated Active Directory DACL inventory' { + BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name @( + 'Test-MtAdDaclConflictObjectCount' + 'Test-MtAdDaclDenyAceCount' + 'Test-MtAdDaclDistinctIdentityCount' + 'Test-MtAdDaclPrivilegedAllowAceCount' + 'Test-MtAdDaclPrivilegedExtendedRightCount' + 'Test-MtAdDaclUnresolvedSidCount' + 'Test-MtAdDaclInheritedObjectTypeCount' + ) + $script:Entries = @( + [PSCustomObject]@{ ObjectDN = 'CN=Dup\0ACNF:123,DC=example,DC=com'; ObjectClass = 'user'; ObjectName = 'Dup'; AccessControlType = 'Allow'; ActiveDirectoryRights = 'GenericAll'; IdentityReference = 'S-1-5-21-1-2-3-99'; ObjectType = [guid]::Empty.ToString(); InheritedObjectType = '11111111-1111-1111-1111-111111111111' } + [PSCustomObject]@{ ObjectDN = 'CN=Dup\0ACNF:123,DC=example,DC=com'; ObjectClass = 'user'; ObjectName = 'Dup'; AccessControlType = 'Allow'; ActiveDirectoryRights = 'ReadProperty, ExtendedRight'; IdentityReference = 'EXAMPLE\Admin'; ObjectType = '00299570-246d-11d0-a768-00aa006e0529'; InheritedObjectType = '11111111-1111-1111-1111-111111111111' } + [PSCustomObject]@{ ObjectDN = 'OU=Other,DC=example,DC=com'; ObjectClass = 'organizationalUnit'; ObjectName = 'Other'; AccessControlType = 'Deny'; ActiveDirectoryRights = 'ExtendedRight'; IdentityReference = 'EXAMPLE\Admin'; ObjectType = '00299570-246d-11d0-a768-00aa006e0529'; InheritedObjectType = [guid]::Empty.ToString() } + ) + } + + BeforeEach { + $script:Detail = $null + Mock -ModuleName Maester Test-MtAdDaclPlatformSupported { $true } + Mock -ModuleName Maester Get-MtADDomainState { [PSCustomObject]@{ DaclEntries = $script:Entries } } + Mock -ModuleName Maester Add-MtTestResultDetail { param($Result) $script:Detail = $Result } + } + + It 'keeps counts and object details together for conflict objects and deny ACEs' { + Test-MtAdDaclConflictObjectCount | Should -BeTrue + $script:Detail | Should -BeLike '*| Conflict Objects In DACL Data | 1 |*' + $script:Detail | Should -BeLike '*| CN=Dup* | user | 2 |*' + Test-MtAdDaclDenyAceCount | Should -BeTrue + $script:Detail | Should -BeLike '*| Deny ACEs | 1 |*' + $script:Detail | Should -BeLike '*| Other | organizationalUnit | OU=Other,DC=example,DC=com | EXAMPLE\Admin | 1 |*' + } + + It 'reports identity distribution and distinct counts in one result' { + Test-MtAdDaclDistinctIdentityCount | Should -BeTrue + $script:Detail | Should -BeLike '*| Distinct identities | 2 |*' + $script:Detail | Should -BeLike '*| EXAMPLE\Admin | 2 | 2 | 1 | 1 |*' + } + + It 'includes privileged allow objects and named extended-right identities without counting deny grants' { + Test-MtAdDaclPrivilegedAllowAceCount | Should -BeTrue + $script:Detail | Should -BeLike '*| Privileged allow ACEs | 2 |*' + $script:Detail | Should -BeLike '*| Dup | user | 2 | 2 | ExtendedRight, GenericAll |*' + Test-MtAdDaclPrivilegedExtendedRightCount | Should -BeTrue + $script:Detail | Should -BeLike '*| ExtendedRight allow ACEs | 1 |*' + $script:Detail | Should -BeLike '*| EXAMPLE\Admin | Reset Password | 1 |*' + } + + It 'includes unresolved SID and inheritance-target breakdowns' { + Test-MtAdDaclUnresolvedSidCount | Should -BeTrue + $script:Detail | Should -BeLike '*| Distinct Unresolved SIDs | 1 |*' + $script:Detail | Should -BeLike '*| CN=Dup* | 1 | S-1-5-21-1-2-3-99 |*' + Test-MtAdDaclInheritedObjectTypeCount | Should -BeTrue + $script:Detail | Should -BeLike '*| Distinct InheritedObjectType GUIDs | 1 |*' + $script:Detail | Should -BeLike '*| 11111111-1111-1111-1111-111111111111 | 2 | 1 |*' + } + + It 'does not report an inventory from missing DACL data' { + Mock -ModuleName Maester Get-MtADDomainState { [PSCustomObject]@{ DaclEntries = $null } } + foreach ($check in @('Test-MtAdDaclConflictObjectCount', 'Test-MtAdDaclDenyAceCount', 'Test-MtAdDaclDistinctIdentityCount', 'Test-MtAdDaclPrivilegedAllowAceCount', 'Test-MtAdDaclPrivilegedExtendedRightCount', 'Test-MtAdDaclUnresolvedSidCount', 'Test-MtAdDaclInheritedObjectTypeCount')) { + { & $check } | Should -Throw '*DACL data is unavailable*' + } + } +} diff --git a/tests/ad/dacl/Test.AD-DACL-15.md b/tests/ad/dacl/Test.AD-DACL-15.md index 120ede20cf..c9d01640d7 100644 --- a/tests/ad/dacl/Test.AD-DACL-15.md +++ b/tests/ad/dacl/Test.AD-DACL-15.md @@ -8,7 +8,7 @@ Unresolved SIDs in DACLs often indicate deleted users or groups, stale migration **Operational** -#### Security Recommendation +#### Remediation action - Investigate unresolved SID ACEs and determine whether they can be removed - Validate that deprovisioning and migration processes clean up obsolete permissions @@ -16,13 +16,12 @@ Unresolved SIDs in DACLs often indicate deleted users or groups, stale migration #### How the Test Works -This test reads `$adState.DaclEntries` and looks for entries whose `IdentityReference` starts with `S-1-5-21`, which commonly indicates a SID that did not resolve to a friendly name. +This test reads `$adState.DaclEntries`, counts entries with an `IdentityReference` beginning `S-1-5-21`, and lists affected object DNs with distinct unresolved SID counts and SID values. A raw SID can also result from a translation failure, so confirm identities before removing ACEs. This is an inventory for investigation, not a finding that an account was deleted. #### Related Tests -- `Test-MtAdDaclUnresolvedSidDetails` - Lists unresolved SID references by object - `Test-MtAdDaclDistinctIdentityCount` - Counts distinct identities present in ACEs -- `Test-MtAdDaclIdentityAceDistribution` - Shows ACE distribution across identities +- `Test-MtAdDaclDistinctIdentityCount` - Shows ACE distribution across identities > **Note:** This test is `LongRunning`. It loads the full DACL dataset, which can consume significant memory in large Active Directory environments. Use `Invoke-Maester -IncludeLongRunning` to run it. diff --git a/tests/ad/dacl/Test.AD-DACL-15.ps1 b/tests/ad/dacl/Test.AD-DACL-15.ps1 index 9f22e78ba2..b3191a9bb9 100644 --- a/tests/ad/dacl/Test.AD-DACL-15.ps1 +++ b/tests/ad/dacl/Test.AD-DACL-15.ps1 @@ -1,7 +1,7 @@ function Test-MtAdDaclUnresolvedSidCount { <# .SYNOPSIS - Counts unresolved SID references in Active Directory DACL entries. + Counts unresolved SID references and lists affected objects. .DESCRIPTION This test reviews DACL entries from Get-MtADDomainState -Categories @('DaclEntries') and identifies ACEs whose @@ -19,7 +19,7 @@ #> [MaesterTest( Id = 'AD-DACL-15', - Title = 'Unresolved SID count should be investigated', + Title = 'Unresolved SID counts and affected objects should be investigated', Product = 'ad', Feature = 'permissions', Area = 'access-control', @@ -27,6 +27,7 @@ Severity = 'Info', Mitre = 'None', Service = 'ActiveDirectory', + Platform = 'Windows', Permission = ('ActiveDirectory:Ldap:*.ntSecurityDescriptor:ReadControl'), LongRunning, Author = 'soulemike' @@ -42,16 +43,17 @@ return $null } $adState = Get-MtADDomainState -Categories @('DaclEntries') - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - if ($null -eq $adState.DaclEntries) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'DACL data is unavailable.' - return $null + if ($null -eq $adState -or $null -eq $adState.DaclEntries) { + throw 'DACL data is unavailable.' } $daclEntries = @($adState.DaclEntries | Where-Object { $null -ne $_ }) + if ($daclEntries.Count -eq 0) { + throw 'No DACL entries were collected; cannot assess unresolved SIDs.' + } + if (@($daclEntries | Where-Object { [string]::IsNullOrWhiteSpace($_.ObjectDN) }).Count -gt 0) { + throw 'DACL entries are missing object distinguished names.' + } $unresolvedEntries = @( $daclEntries | Where-Object { [string]$_.IdentityReference -like 'S-1-5-21-*' @@ -70,6 +72,17 @@ $result += "| Total DACL Entries | $($daclEntries.Count) |" + "`n" $result += "| ACEs with Unresolved SID IdentityReference | $($unresolvedEntries.Count) |" + "`n" $result += "| Distinct Unresolved SIDs | $distinctUnresolvedSidCount |" + "`n" + $result += "`n| Object DN | Distinct Unresolved SID Count | Unresolved SIDs |`n| --- | --- | --- |`n" + foreach ($group in @($unresolvedEntries | Group-Object ObjectDN | Sort-Object -Property @{ Expression = 'Count'; Descending = $true }, Name)) { + $objectDn = if ([string]::IsNullOrWhiteSpace($group.Name)) { '(No ObjectDN)' } else { [string]$group.Name } + $objectDn = $objectDn -replace '\|', '|' + $sids = @($group.Group | Select-Object -ExpandProperty IdentityReference -Unique) + $sidList = (@($sids | ForEach-Object { ([string]$_) -replace '\|', '|' }) -join ', ') + $result += "| $objectDn | $($sids.Count) | $sidList |`n" + } + if ($unresolvedEntries.Count -eq 0) { + $result += "| No unresolved SID references found | 0 | |`n" + } $testResultMarkdown = "Active Directory DACL identities were analyzed. $distinctUnresolvedSidCount unresolved SID reference(s) were found across $($unresolvedEntries.Count) ACE(s).`n`n%TestResult%" $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result diff --git a/tests/ad/dacl/Test.AD-DACL-16.md b/tests/ad/dacl/Test.AD-DACL-16.md deleted file mode 100644 index e742e47b8a..0000000000 --- a/tests/ad/dacl/Test.AD-DACL-16.md +++ /dev/null @@ -1,30 +0,0 @@ -Knowing which directory objects contain orphaned SID ACEs helps target cleanup work where it matters most. - -- **Object-focused remediation**: Grouping unresolved SIDs by object shows exactly where stale ACEs exist -- **Audit clarity**: Makes manual DACL review easier during privileged access assessments -- **Change tracking**: Helps confirm whether decommissioned identities still linger on important objects - -#### Control Type - -**Operational** - -#### Security Recommendation - -- Remove orphaned ACEs after confirming the referenced SID is no longer valid -- Prioritize cleanup on privileged OUs, admin groups, and delegation-heavy containers -- Document recurring sources of unresolved SIDs to improve identity lifecycle processes - -#### How the Test Works - -This test reads `$adState.DaclEntries`, filters unresolved `IdentityReference` values that begin with `S-1-5-21`, and groups them by `ObjectDN`. - -#### Related Tests - -- `Test-MtAdDaclUnresolvedSidCount` - Counts unresolved SID references -- `Test-MtAdDaclNonInheritedAceCount` - Counts explicit ACEs that may require review -- `Test-MtAdDaclInheritedObjectTypeDetails` - Shows inheritance targeting across ACEs - -> **Note:** This test is `LongRunning`. It loads the full DACL dataset, which can consume significant memory in large Active Directory environments. Use `Invoke-Maester -IncludeLongRunning` to run it. - - -%TestResult% diff --git a/tests/ad/dacl/Test.AD-DACL-16.ps1 b/tests/ad/dacl/Test.AD-DACL-16.ps1 deleted file mode 100644 index d94f32d616..0000000000 --- a/tests/ad/dacl/Test.AD-DACL-16.ps1 +++ /dev/null @@ -1,100 +0,0 @@ -function Test-MtAdDaclUnresolvedSidDetails { - <# - .SYNOPSIS - Returns unresolved SID details from Active Directory DACL entries. - - .DESCRIPTION - This test analyzes DACL entries from Get-MtADDomainState -Categories @('DaclEntries') and groups orphaned SID - references by directory object. Reviewing unresolved SIDs by object helps identify - where stale ACEs remain after account deletions, migrations, or delegated access - changes. - - .EXAMPLE - Test-MtAdDaclUnresolvedSidDetails - - Returns $true if DACL data is accessible. - - .LINK - https://maester.dev/docs/commands/Test-MtAdDaclUnresolvedSidDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-DACL-16', - Title = 'Unresolved SID details should be investigated', - Product = 'ad', - Feature = 'permissions', - Area = 'access-control', - ResourceType = 'Permission', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:*.ntSecurityDescriptor:ReadControl'), - LongRunning, - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdDaclUnresolvedSidDetails" - - if (-not (Test-MtAdDaclPlatformSupported)) { - Add-MtTestResultDetail -SkippedBecause NotSupported - return $null - } - $adState = Get-MtADDomainState -Categories @('DaclEntries') - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - if ($null -eq $adState.DaclEntries) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'DACL data is unavailable.' - return $null - } - - $daclEntries = @($adState.DaclEntries | Where-Object { $null -ne $_ }) - $unresolvedEntries = @( - $daclEntries | Where-Object { - [string]$_.IdentityReference -like 'S-1-5-21-*' - } - ) - - $objectGroups = @( - $unresolvedEntries | - Group-Object -Property ObjectDN | - Sort-Object @{ Expression = 'Count'; Descending = $true }, @{ Expression = 'Name'; Descending = $false } - ) - - $result = '| ObjectDN | Distinct Unresolved SID Count | Unresolved SIDs |' + "`n" - $result += '| --- | --- | --- |' + "`n" - - foreach ($group in $objectGroups) { - $objectDn = [string]$group.Name - if ([string]::IsNullOrWhiteSpace($objectDn)) { - $objectDn = '(No ObjectDN)' - } - - $objectDn = $objectDn -replace '\|', '\\|' - - $sidList = @( - $group.Group | - ForEach-Object { [string]$_.IdentityReference } | - Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | - Sort-Object -Unique - ) - - $sidListJoined = ($sidList | ForEach-Object { $_ -replace '\|', '\\|' }) -join ', ' - $result += "| $objectDn | $($sidList.Count) | $sidListJoined |" + "`n" - } - - $testResult = $true - $testResultMarkdown = "Active Directory DACL entries were analyzed for orphaned SID references. $($objectGroups.Count) object(s) contain unresolved SID ACEs.`n`n%TestResult%" - if ($objectGroups.Count -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result - } else { - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', "" - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - return $testResult -} diff --git a/tests/ad/dacl/Test.AD-DACL-17.md b/tests/ad/dacl/Test.AD-DACL-17.md index 73c99de453..c5d49ba002 100644 --- a/tests/ad/dacl/Test.AD-DACL-17.md +++ b/tests/ad/dacl/Test.AD-DACL-17.md @@ -8,7 +8,7 @@ Inherited object type GUIDs define which descendant object classes an inheritabl **Operational** -#### Security Recommendation +#### Remediation action - Review inherited ACEs that target sensitive descendant object classes - Prefer precise scoping over overly broad inheritance where possible @@ -16,13 +16,12 @@ Inherited object type GUIDs define which descendant object classes an inheritabl #### How the Test Works -This test reads `$adState.DaclEntries`, filters for `InheritedObjectType` GUIDs that are not the all-zero default value, and counts the distinct GUIDs present. +This test reads `$adState.DaclEntries`, filters for nonblank `InheritedObjectType` GUIDs other than the all-zero default, and reports total ACEs, specific targeting ACEs, distinct GUIDs and the ACE and distinct object counts for each GUID. This is an inventory for review, not evidence of unsafe inheritance by itself. #### Related Tests -- `Test-MtAdDaclInheritedObjectTypeDetails` - Provides a breakdown by inherited object type GUID - `Test-MtAdDaclNonInheritedAceCount` - Counts ACEs that are explicitly assigned -- `Test-MtAdDaclPrivilegedAllowAceDetails` - Shows privileged allow authorizations in DACLs +- `Test-MtAdDaclPrivilegedAllowAceCount` - Shows privileged allow authorizations in DACLs > **Note:** This test is `LongRunning`. It loads the full DACL dataset, which can consume significant memory in large Active Directory environments. Use `Invoke-Maester -IncludeLongRunning` to run it. diff --git a/tests/ad/dacl/Test.AD-DACL-17.ps1 b/tests/ad/dacl/Test.AD-DACL-17.ps1 index 69794ec8db..eabfe99224 100644 --- a/tests/ad/dacl/Test.AD-DACL-17.ps1 +++ b/tests/ad/dacl/Test.AD-DACL-17.ps1 @@ -1,7 +1,7 @@ function Test-MtAdDaclInheritedObjectTypeCount { <# .SYNOPSIS - Counts inherited object types referenced by Active Directory DACL entries. + Counts inherited object type GUIDs and lists their ACE distribution. .DESCRIPTION This test analyzes DACL entries from Get-MtADDomainState -Categories @('DaclEntries') and counts distinct @@ -19,7 +19,7 @@ #> [MaesterTest( Id = 'AD-DACL-17', - Title = 'Inherited object type count should be investigated', + Title = 'Inherited object type counts and details should be investigated', Product = 'ad', Feature = 'permissions', Area = 'access-control', @@ -27,6 +27,7 @@ Severity = 'Info', Mitre = 'None', Service = 'ActiveDirectory', + Platform = 'Windows', Permission = ('ActiveDirectory:Ldap:*.ntSecurityDescriptor:ReadControl'), LongRunning, Author = 'soulemike' @@ -42,17 +43,18 @@ } $adState = Get-MtADDomainState -Categories @('DaclEntries') Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - if ($null -eq $adState.DaclEntries) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'DACL data is unavailable.' - return $null + if ($null -eq $adState -or $null -eq $adState.DaclEntries) { + throw 'DACL data is unavailable.' } Write-Verbose "Filtering/counting dacl inherited object type count" $daclEntries = @($adState.DaclEntries | Where-Object { $null -ne $_ }) + if ($daclEntries.Count -eq 0) { + throw 'No DACL entries were collected; cannot assess inheritance targeting.' + } + if (@($daclEntries | Where-Object { [string]::IsNullOrWhiteSpace($_.ObjectDN) }).Count -gt 0) { + throw 'DACL entries are missing object distinguished names.' + } $filteredEntries = @( $daclEntries | Where-Object { $inheritedObjectType = [string]$_.InheritedObjectType @@ -73,6 +75,15 @@ $result += "| Total DACL Entries | $($daclEntries.Count) |" + "`n" $result += "| ACEs with Specific InheritedObjectType | $($filteredEntries.Count) |" + "`n" $result += "| Distinct InheritedObjectType GUIDs | $distinctInheritedObjectTypeCount |" + "`n" + $result += "`n| InheritedObjectType | ACE Count | Distinct ObjectDN Count |`n| --- | --- | --- |`n" + foreach ($group in @($filteredEntries | Group-Object InheritedObjectType | Sort-Object -Property @{ Expression = 'Count'; Descending = $true }, Name)) { + $inheritedObjectType = ([string]$group.Name) -replace '\|', '|' + $objects = @($group.Group | Where-Object { -not [string]::IsNullOrWhiteSpace($_.ObjectDN) } | Select-Object -ExpandProperty ObjectDN -Unique).Count + $result += "| $inheritedObjectType | $($group.Count) | $objects |`n" + } + if ($filteredEntries.Count -eq 0) { + $result += "| No specific inherited object type GUIDs found | 0 | 0 |`n" + } Write-Verbose "Counts computed" $testResultMarkdown = "Active Directory DACL inheritance targets were analyzed. $distinctInheritedObjectTypeCount distinct inherited object type GUID(s) were referenced across $($filteredEntries.Count) ACE(s).`n`n%TestResult%" diff --git a/tests/ad/dacl/Test.AD-DACL-18.md b/tests/ad/dacl/Test.AD-DACL-18.md deleted file mode 100644 index 381d23ad59..0000000000 --- a/tests/ad/dacl/Test.AD-DACL-18.md +++ /dev/null @@ -1,30 +0,0 @@ -Inherited object type detail helps explain where inheritable ACEs are intended to apply. - -- **Scoping transparency**: Reveals which descendant object classes are targeted most often -- **Delegation review**: Helps validate whether inherited permissions are narrowly or broadly applied -- **Troubleshooting support**: Useful when investigating unexpected effective permissions on child objects - -#### Control Type - -**Operational** - -#### Security Recommendation - -- Review heavily used inherited object type targets for overly broad delegations -- Confirm that inherited ACE scope matches intended administrative boundaries -- Reassess inherited rights on sensitive containers if descendant object targeting is not well understood - -#### How the Test Works - -This test reads `$adState.DaclEntries`, filters out the all-zero `InheritedObjectType` value, and groups the remaining ACEs by inherited object type GUID. - -#### Related Tests - -- `Test-MtAdDaclInheritedObjectTypeCount` - Counts distinct inherited object type GUIDs -- `Test-MtAdDaclPrivilegedExtendedRightIdentity` - Shows identities with privileged extended rights -- `Test-MtAdDaclUnresolvedSidDetails` - Lists objects containing orphaned SID ACEs - -> **Note:** This test is `LongRunning`. It loads the full DACL dataset, which can consume significant memory in large Active Directory environments. Use `Invoke-Maester -IncludeLongRunning` to run it. - - -%TestResult% diff --git a/tests/ad/dacl/Test.AD-DACL-18.ps1 b/tests/ad/dacl/Test.AD-DACL-18.ps1 deleted file mode 100644 index a710174da2..0000000000 --- a/tests/ad/dacl/Test.AD-DACL-18.ps1 +++ /dev/null @@ -1,97 +0,0 @@ -function Test-MtAdDaclInheritedObjectTypeDetails { - <# - .SYNOPSIS - Returns inherited object type breakdown from Active Directory DACL entries. - - .DESCRIPTION - This test analyzes DACL entries from Get-MtADDomainState -Categories @('DaclEntries') and groups ACEs by the - specific inherited object type GUID they target. This helps reviewers understand - which descendant object classes are in scope for inherited delegations. - - .EXAMPLE - Test-MtAdDaclInheritedObjectTypeDetails - - Returns $true if DACL data is accessible. - - .LINK - https://maester.dev/docs/commands/Test-MtAdDaclInheritedObjectTypeDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-DACL-18', - Title = 'Inherited object type details should be investigated', - Product = 'ad', - Feature = 'permissions', - Area = 'access-control', - ResourceType = 'Permission', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:*.ntSecurityDescriptor:ReadControl'), - LongRunning, - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdDaclInheritedObjectTypeDetails" - if (-not (Test-MtAdDaclPlatformSupported)) { - Add-MtTestResultDetail -SkippedBecause NotSupported - return $null - } - $adState = Get-MtADDomainState -Categories @('DaclEntries') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - if ($null -eq $adState.DaclEntries) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'DACL data is unavailable.' - return $null - } - Write-Verbose "Filtering/counting dacl inherited object type details" - - $daclEntries = @($adState.DaclEntries | Where-Object { $null -ne $_ }) - $filteredEntries = @( - $daclEntries | Where-Object { - $inheritedObjectType = [string]$_.InheritedObjectType - -not [string]::IsNullOrWhiteSpace($inheritedObjectType) -and - $inheritedObjectType -ne '00000000-0000-0000-0000-000000000000' - } - ) - - $groups = @( - $filteredEntries | - Group-Object -Property InheritedObjectType | - Sort-Object @{ Expression = 'Count'; Descending = $true }, @{ Expression = 'Name'; Descending = $false } - ) - - $result = '| InheritedObjectType | ACE Count | Distinct ObjectDN Count |' + "`n" - $result += '| --- | --- | --- |' + "`n" - - foreach ($group in $groups) { - $inheritedObjectType = [string]$group.Name - $inheritedObjectType = $inheritedObjectType -replace '\|', '\\|' - - $distinctObjectCount = @( - $group.Group | - Group-Object -Property ObjectDN - ).Count - - $result += "| $inheritedObjectType | $($group.Count) | $distinctObjectCount |" + "`n" - } - - $testResult = $true - Write-Verbose "Counts computed" - $testResultMarkdown = "Active Directory DACL inheritance targets were grouped by inherited object type. $($groups.Count) inherited object type GUID group(s) were identified.`n`n%TestResult%" - if ($groups.Count -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result - } else { - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', "" - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdDaclInheritedObjectTypeDetails" - return $testResult -} From 811414ce169c4e941cf4fadde60d3f66a1e298b4 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 06:23:26 +0000 Subject: [PATCH 008/100] fix(ad): distinguish directory configuration inventories from baselines --- tests/ad/config/Test.AD-CFG-02.md | 24 ++++--------------- tests/ad/config/Test.AD-CFG-02.ps1 | 37 ++++++++++-------------------- tests/ad/config/Test.AD-CFG-03.md | 11 ++++----- tests/ad/config/Test.AD-CFG-03.ps1 | 15 ++++++++---- tests/ad/config/Test.AD-CFG-06.md | 23 ++++--------------- tests/ad/config/Test.AD-CFG-06.ps1 | 7 +++--- tests/ad/config/Test.AD-CFG-07.md | 23 ++++--------------- tests/ad/config/Test.AD-CFG-07.ps1 | 7 +++--- tests/ad/config/Test.AD-CFG-08.md | 23 +++---------------- tests/ad/config/Test.AD-CFG-08.ps1 | 7 +++--- tests/ad/config/Test.AD-CFG-09.md | 21 ++++------------- tests/ad/config/Test.AD-CFG-09.ps1 | 7 +++--- tests/ad/config/Test.AD-CFG-10.md | 21 ++++------------- tests/ad/config/Test.AD-CFG-10.ps1 | 19 +++++---------- tests/ad/config/Test.AD-CFG-11.md | 21 +++++------------ tests/ad/config/Test.AD-CFG-11.ps1 | 13 +++++++---- 16 files changed, 87 insertions(+), 192 deletions(-) diff --git a/tests/ad/config/Test.AD-CFG-02.md b/tests/ad/config/Test.AD-CFG-02.md index 5772987bb2..0334f988d7 100644 --- a/tests/ad/config/Test.AD-CFG-02.md +++ b/tests/ad/config/Test.AD-CFG-02.md @@ -1,28 +1,12 @@ -**dSHeuristics** is an AD configuration setting that controls behavior for advanced directory features and legacy compatibility. Because it influences protocol-level behavior (including areas such as LDAP security expectations and feature gating), an incorrect or unexpected dSHeuristics value can: +`dSHeuristics` is a position-dependent string on the Directory Service configuration object. An unset attribute is not the same as an unreadable directory configuration. Each position controls a different behavior; dividing its length by two does not count enabled settings. -- Leave AD behaving in a more **legacy/less secure** mode -- Cause authentication and directory access **inconsistencies** across clients -- Increase the likelihood of **unsafe fallback behaviors** when clients interact with AD +#### Remediation action -#### Control Type - -**Operational** - -#### Security Recommendation -- Confirm dSHeuristics is set according to your domain’s **hardening baseline** (and any guidance for your forest/domain functional level). -- Avoid “trial-and-error” changes; instead, validate configuration changes in a controlled test window. -- Prioritize alignment with modern security requirements (including enforcing secure LDAP behavior where applicable). - -#### How the Test Works -This test queries AD configuration for the dSHeuristics setting(s) and reports a count-style metric indicating how many relevant dSHeuristics values are present/active so you can assess whether the environment matches your expected security baseline. - -#### Related Tests -- `Test-MtAdLdapQueryPolicyCount` - Helps ensure LDAP is protected by sane query limits. +Compare the reported raw value (or unset state) against the documented settings for your forest and your organization's approved baseline. Investigate individual positions before changing them; there is no universally safe replacement string. #### Related links -- [Microsoft Learn: dSHeuristics attribute (MS-ADTS)](https://learn.microsoft.com/openspecs/windows_protocols/ms-adts/e5899be4-862e-496f-9a38-33950617d2c5) -- [ANSSI Active Directory checkpoints: Dangerous dsHeuristics settings](https://www.cert.ssi.gouv.fr/uploads/ad_checklist.html#vuln_dsheuristics_bad) +- [Microsoft ADTS: dSHeuristics](https://learn.microsoft.com/openspecs/windows_protocols/ms-adts/e5899be4-862e-496f-9a38-33950617d2c5) %TestResult% diff --git a/tests/ad/config/Test.AD-CFG-02.ps1 b/tests/ad/config/Test.AD-CFG-02.ps1 index 144804dc32..5c33f0bbf5 100644 --- a/tests/ad/config/Test.AD-CFG-02.ps1 +++ b/tests/ad/config/Test.AD-CFG-02.ps1 @@ -1,12 +1,12 @@ function Test-MtAdDsHeuristicsCount { <# .SYNOPSIS - Counts Active Directory dSHeuristics configuration settings. + Reports Active Directory dSHeuristics for review. .DESCRIPTION Phase 14 (AD Configuration tests) - AD-CFG-02. - This test retrieves $config.DsHeuristics and calculates the count as (string length / 2). - If dSHeuristics is null, the count is 0. + Reports the configured dSHeuristics string for human review. Its positions + have independent meanings; the string length is not a count of settings. .EXAMPLE Test-MtAdDsHeuristicsCount @@ -18,7 +18,7 @@ #> [MaesterTest( Id = 'AD-CFG-02', - Title = 'dSHeuristics count should be retrievable', + Title = 'dSHeuristics value should be investigated', Product = 'ad', Feature = 'directory-configuration', Area = 'infrastructure', @@ -37,30 +37,17 @@ $adState = Get-MtADDomainState -Categories @('Configuration') - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $adState -or $null -eq $adState.Configuration) { + throw 'Directory Service configuration could not be retrieved.' } $config = $adState.Configuration - $dsHeuristics = if ($null -ne $config) { $config.DsHeuristics } else { $null } - - $dsHeuristicsCount = if ($null -ne $dsHeuristics) { [int]($dsHeuristics.Length / 2) } else { 0 } - $testResult = $null -ne $config - - if ($testResult) { - $result = "| Property | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| dSHeuristics | $dsHeuristics |" + "`n" - $result += "| dSHeuristics Count (length/2) | $dsHeuristicsCount |" + "`n" + "`n" - - $testResultMarkdown = "Active Directory dSHeuristics configuration has been analyzed.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } - else { - $testResultMarkdown = "Unable to retrieve Active Directory configuration. Ensure you have appropriate permissions and the Active Directory module is installed." + if ($config.PSObject.Properties.Name -contains 'DirectoryServiceRetrieved' -and $config.DirectoryServiceRetrieved -ne $true) { + throw 'Directory Service object could not be retrieved; dSHeuristics is unknown.' } + $dsHeuristics = $config.DsHeuristics - Add-MtTestResultDetail -Result $testResultMarkdown - return $testResult + $value = if ([string]::IsNullOrEmpty([string]$dsHeuristics)) { '(not set)' } else { [string]$dsHeuristics } + Add-MtTestResultDetail -Result "Review the position-specific dSHeuristics value against your directory baseline: $value" -Investigate + return $true } diff --git a/tests/ad/config/Test.AD-CFG-03.md b/tests/ad/config/Test.AD-CFG-03.md index 47f2879089..b6ac7e51c6 100644 --- a/tests/ad/config/Test.AD-CFG-03.md +++ b/tests/ad/config/Test.AD-CFG-03.md @@ -1,4 +1,4 @@ -**SPN mappings** are used to support legacy or non-FQDN client behavior by mapping service principal names to the correct Kerberos realm/host context. While this can improve compatibility, misconfigured SPN mappings can create security and reliability issues, such as: +**SPN mappings** (`sPNMappings` on the Directory Service object) map service classes such as HTTP and CIFS to the HOST service class for Kerberos ticket lookup. They do not map clients to realms, and are not individual account `servicePrincipalName` values. Changes may affect service authentication. - **Authentication inconsistencies** (Kerberos vs. fallback behaviors) - Clients receiving **unexpected service identity** resolution @@ -9,15 +9,14 @@ **Operational** #### Security Recommendation -- Keep SPN mappings **as minimal as possible**—only those required for supported legacy interoperability. -- Periodically review and remove stale mappings tied to retired hostnames/services. -- Validate that SPN mappings resolve to the **correct** target identities (FQDN/realm) for all required workloads. +- Review HOST-class service mappings against the organization's supported services before making changes. +- Do not remove a mapping solely because this inventory reports it; doing so can break Kerberos service ticket resolution. #### How the Test Works -This test inspects the SPN mapping configuration exposed by AD, extracts the configured mappings, and provides a count/visibility metric so administrators can identify whether mappings exist that should not be present. +This inventory reports the raw `sPNMappings` entries and count. It does not inspect account SPNs or claim that any mapping is unsafe. #### Related Tests -- `Test-MtAdWellKnownSecurityPrincipalsCount` - Identifies additional security principal surface that should be consistent with Kerberos hardening. +- Account-level SPN checks in `tests/ad/spn/` assess a different setting (`servicePrincipalName`). %TestResult% diff --git a/tests/ad/config/Test.AD-CFG-03.ps1 b/tests/ad/config/Test.AD-CFG-03.ps1 index 2c13e74383..a450569b7c 100644 --- a/tests/ad/config/Test.AD-CFG-03.ps1 +++ b/tests/ad/config/Test.AD-CFG-03.ps1 @@ -37,14 +37,19 @@ $adState = Get-MtADDomainState -Categories @('Configuration') - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $adState -or $null -eq $adState.Configuration) { + throw 'SPN mapping configuration could not be retrieved.' } $config = $adState.Configuration - $spnMappings = if ($null -ne $config) { $config.SpnMappings } else { $null } - $spnMappingsSafe = if ($null -ne $spnMappings) { @($spnMappings) } else { @() } + if ($config.PSObject.Properties.Name -contains 'DirectoryServiceRetrieved' -and $config.DirectoryServiceRetrieved -ne $true) { + throw 'Directory Service object could not be retrieved; SPN mappings are unknown.' + } + $spnMappings = $config.SpnMappings + if ($null -eq $spnMappings) { + throw 'SPN mapping inventory could not be retrieved.' + } + $spnMappingsSafe = @($spnMappings) $spnMappingsCount = ($spnMappingsSafe | Measure-Object).Count $testResult = $null -ne $config diff --git a/tests/ad/config/Test.AD-CFG-06.md b/tests/ad/config/Test.AD-CFG-06.md index 8ea61a357d..de629a1d58 100644 --- a/tests/ad/config/Test.AD-CFG-06.md +++ b/tests/ad/config/Test.AD-CFG-06.md @@ -1,25 +1,12 @@ -**LDAP query policies** define resource limits for directory queries (for example, controlling maximum result sizes and query behaviors). Weak or missing limits can enable **resource exhaustion** against AD through: +This inventory counts LDAP query policy objects in the Directory Service Query Policies container. Counting policies alone cannot establish effective LDAP limits: directory defaults and per-controller policy assignments also matter. -- Expensive or unbounded queries -- Large searches that degrade DC performance -- Increased likelihood of availability-impacting denial-of-service (DoS) +#### Remediation action -This test helps ensure your directory query surface is bounded, making it harder for both accidental misconfigurations and malicious users to overwhelm AD. +Review the policy values and policy assignments against your DC workload requirements. Investigate unexpected changes; do not add policies merely to meet a count. -#### Control Type +#### Related links -**Operational** - -#### Security Recommendation -- Set LDAP query policies to enforce practical limits aligned with your operational needs. -- Ensure policies are applied consistently across relevant directory contexts/partitions. -- Combine with access controls: even with good limits, ensure only authorized clients can perform heavy queries. - -#### How the Test Works -This test reads LDAP query policy configuration from AD and produces a count/visibility metric indicating where query policies are present and/or set according to your expected baseline. - -#### Related Tests -- `Test-MtAdDefaultQueryPolicy` - Validates the baseline LDAP query limits. +- [Microsoft: LDAP policies](https://learn.microsoft.com/troubleshoot/windows-server/active-directory/view-set-ldap-policy-using-ntdsutil) %TestResult% diff --git a/tests/ad/config/Test.AD-CFG-06.ps1 b/tests/ad/config/Test.AD-CFG-06.ps1 index f7e4ad5c28..22dadea661 100644 --- a/tests/ad/config/Test.AD-CFG-06.ps1 +++ b/tests/ad/config/Test.AD-CFG-06.ps1 @@ -36,9 +36,8 @@ $adState = Get-MtADDomainState -Categories @('Configuration') - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $adState -or $null -eq $adState.Configuration -or $null -eq $adState.Configuration.LdapQueryPolicies) { + throw 'LDAP query policy inventory could not be retrieved.' } $config = $adState.Configuration @@ -60,6 +59,6 @@ $testResultMarkdown = "Unable to retrieve Active Directory configuration. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/config/Test.AD-CFG-07.md b/tests/ad/config/Test.AD-CFG-07.md index baf94a143c..e86847db30 100644 --- a/tests/ad/config/Test.AD-CFG-07.md +++ b/tests/ad/config/Test.AD-CFG-07.md @@ -1,25 +1,12 @@ -The **default query policy** sets baseline resource constraints for LDAP operations. If defaults are overly permissive, AD can be more vulnerable to availability attacks and performance degradation from: +This check inventories the `Default-Query-Policy` object and any explicit `lDAPAdminLimits` values. If the object or explicit limits are absent, effective LDAP limits may still be supplied by directory defaults; absence alone is not proof that LDAP queries are unlimited. -- Large/inefficient LDAP searches -- High-frequency query patterns -- Legitimate admin/service queries running with insufficient guardrails +#### Remediation action -Proper limits reduce the impact of both **misuse** and **mistakes**, improving DC resilience during incidents. +Review effective LDAP query policy limits and any per-DC overrides before changing settings. Confirm that limits accommodate legitimate applications and are aligned with your organization's availability baseline. -#### Control Type +#### Related links -**Operational** - -#### Security Recommendation -- Review the default query policy and ensure it matches your organization’s acceptable performance envelope. -- Keep defaults conservative, then selectively allow exceptions only where required. -- Re-validate defaults after upgrades, migrations, or schema/config changes. - -#### How the Test Works -This test retrieves the default LDAP query policy values and reports them as an analyzable metric so administrators can confirm baseline limits are configured as intended. - -#### Related Tests -- `Test-MtAdLdapQueryPolicyCount` - Ensures query policy coverage/consistency across partitions. +- [Microsoft: LDAP policies](https://learn.microsoft.com/troubleshoot/windows-server/active-directory/view-set-ldap-policy-using-ntdsutil) %TestResult% diff --git a/tests/ad/config/Test.AD-CFG-07.ps1 b/tests/ad/config/Test.AD-CFG-07.ps1 index 80ebe67890..fe1edf9bc1 100644 --- a/tests/ad/config/Test.AD-CFG-07.ps1 +++ b/tests/ad/config/Test.AD-CFG-07.ps1 @@ -38,9 +38,8 @@ $adState = Get-MtADDomainState -Categories @('Configuration') # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $adState -or $null -eq $adState.Configuration -or $null -eq $adState.Configuration.LdapQueryPolicies) { + throw 'Default LDAP query policy inventory could not be retrieved.' } $config = $adState.Configuration @@ -78,7 +77,7 @@ $testResultMarkdown = "Unable to retrieve LDAP query policy information. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/config/Test.AD-CFG-08.md b/tests/ad/config/Test.AD-CFG-08.md index a89c63bd3e..44e010c74d 100644 --- a/tests/ad/config/Test.AD-CFG-08.md +++ b/tests/ad/config/Test.AD-CFG-08.md @@ -1,25 +1,8 @@ -**Authentication policies** control how clients can authenticate to and interact with domain controllers for certain operations (depending on configuration and policy scope). Inadequate or unexpected authentication policy configuration can: +This inventory counts objects under the AD authentication policy configuration container. A container/object count does not show whether an authentication policy is assigned to an account, nor whether any particular policy is effective. -- Increase exposure of DC authentication endpoints -- Allow broader authentication patterns than intended -- Complicate incident investigations by enabling inconsistent authentication behavior +#### Remediation action -Because authentication to domain controllers is a critical trust boundary, this test focuses on ensuring policies are explicitly configured and managed. - -#### Control Type - -**Operational** - -#### Security Recommendation -- Ensure authentication policies are configured to restrict DC access to **authorized systems** and approved authentication behaviors. -- Use change control: treat authentication policy changes as security-critical. -- Validate that policy configuration aligns with your domain’s intended security baseline and any application/service requirements. - -#### How the Test Works -This test inspects AD authentication policy configuration and reports a count/visibility metric so administrators can confirm whether authentication policies are present and aligned with expectations. - -#### Related Tests -- `Test-MtAdDsHeuristicsCount` - Helps validate advanced directory behavior settings that can influence authentication-related behaviors. +Review the policies, policy silos and assignments where your organization uses authentication policies. A zero count alone does not establish a security failure; investigate whether the configuration matches your intended controls. %TestResult% diff --git a/tests/ad/config/Test.AD-CFG-08.ps1 b/tests/ad/config/Test.AD-CFG-08.ps1 index 006b26807f..5ed351efe6 100644 --- a/tests/ad/config/Test.AD-CFG-08.ps1 +++ b/tests/ad/config/Test.AD-CFG-08.ps1 @@ -36,9 +36,8 @@ $adState = Get-MtADDomainState -Categories @('Configuration') - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $adState -or $null -eq $adState.Configuration -or $null -eq $adState.Configuration.AuthNPolicyContainers) { + throw 'Authentication policy configuration could not be retrieved.' } $config = $adState.Configuration @@ -60,6 +59,6 @@ $testResultMarkdown = "Unable to retrieve Active Directory configuration. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/config/Test.AD-CFG-09.md b/tests/ad/config/Test.AD-CFG-09.md index eec4330279..4decc99fa1 100644 --- a/tests/ad/config/Test.AD-CFG-09.md +++ b/tests/ad/config/Test.AD-CFG-09.md @@ -1,23 +1,12 @@ -AD-based activation objects are used by Windows for volume activation and related discovery workflows. If these objects are created, deleted, or altered without authorization, it can indicate licensing/tampering activity and may also reflect broader Active Directory compromise or unauthorized configuration changes. +This inventory counts `msSPP-ActivationObject` objects in the AD-based activation configuration container. Activation objects relate to volume licensing; their count by itself does not prove unauthorized changes or compromise. -#### Control Type +#### Remediation action -**Operational** +Review unexpected activation objects against your deployment inventory and change records before removing anything. Investigate permissions and directory audit events if an unauthorized change is suspected. -#### Security Recommendation -- Treat activation-object changes as security-relevant change-management events. -- Restrict who can create/modify activation objects (least privilege) and remove unnecessary write permissions. -- Establish a known-good baseline for the number of activation objects per environment/forest and alert on deviations. -- Review recent directory change/audit events to identify the initiating account and purpose. +#### Related links -#### How the Test Works -- Enumerates activation-related objects stored in Active Directory. -- Counts the objects discovered in the activation container(s). -- Compares the count to an environment baseline and flags unexpected increases/decreases. - -#### Related Tests -- [Test-MtAdWellKnownSecurityPrincipalsCount](./Test-MtAdWellKnownSecurityPrincipalsCount.md): Detects unexpected identity/config changes that may accompany tampering. -- [Test-MtAdRegisteredDhcpServersCount](./Test-MtAdRegisteredDhcpServersCount.md): Detects unauthorized network services registered in AD. +- [Microsoft: ms-SPP-Activation-Object schema class](https://learn.microsoft.com/windows/win32/adschema/c-msspp-activationobject) %TestResult% diff --git a/tests/ad/config/Test.AD-CFG-09.ps1 b/tests/ad/config/Test.AD-CFG-09.ps1 index b072bfc3af..13d45403de 100644 --- a/tests/ad/config/Test.AD-CFG-09.ps1 +++ b/tests/ad/config/Test.AD-CFG-09.ps1 @@ -36,9 +36,8 @@ $adState = Get-MtADDomainState -Categories @('Configuration') - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $adState -or $null -eq $adState.Configuration -or $null -eq $adState.Configuration.ActivationObjects) { + throw 'Activation object inventory could not be retrieved.' } $config = $adState.Configuration @@ -60,6 +59,6 @@ $testResultMarkdown = "Unable to retrieve Active Directory configuration. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/config/Test.AD-CFG-10.md b/tests/ad/config/Test.AD-CFG-10.md index cc30911957..4e6daf3fe4 100644 --- a/tests/ad/config/Test.AD-CFG-10.md +++ b/tests/ad/config/Test.AD-CFG-10.md @@ -1,23 +1,12 @@ -Well-known security principals are built-in identities with special meaning in Active Directory (for example, principals that Windows and AD components rely on for system behavior). Unexpected changes to these principals can indicate tampering, malicious SID/object replacement, or unauthorized directory modification. +This check inventories objects in the WellKnown Security Principals configuration container. The number of entries can differ across versions and forests; neither 27 nor 33 is a universal baseline. A count alone does not identify malicious principals. -#### Control Type +#### Remediation action -**Operational** +Review the identity and SID of any unexpected entry against an appropriate forest-specific reference before changing the directory. Investigate suspected unauthorized changes in directory audit logs. -#### Security Recommendation -- Validate that only the expected well-known principals exist (default is **27** for typical configurations). -- Restrict permissions to the container(s) holding well-known principals so only AD administrators can modify them. -- Audit changes by enabling directory change auditing and reviewing security event logs for modifications. -- Investigate any deviation immediately as a potential sign of directory tampering. +#### Related links -#### How the Test Works -- Locates the AD container(s) that store well-known security principal objects. -- Enumerates those objects and counts how many are present. -- Compares the count to the expected baseline (default **27**) and flags any unexpected values. - -#### Related Tests -- [Test-MtAdAdActivationObjectsCount](./Test-MtAdAdActivationObjectsCount.md): Detects unexpected AD configuration objects that can reflect tampering. -- [Test-MtAdTrustedRootCaCount](./Test-MtAdTrustedRootCaCount.md): Identifies unauthorized trust anchors that can undermine authentication integrity. +- [Microsoft: special identity groups and their directory locations](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/understand-special-identities-groups) %TestResult% diff --git a/tests/ad/config/Test.AD-CFG-10.ps1 b/tests/ad/config/Test.AD-CFG-10.ps1 index 5085713991..9e28d52db0 100644 --- a/tests/ad/config/Test.AD-CFG-10.ps1 +++ b/tests/ad/config/Test.AD-CFG-10.ps1 @@ -5,7 +5,7 @@ .DESCRIPTION This test retrieves the Active Directory configuration data for the collection of - well-known security principals (default expected count: 27) and reports how many + well-known security principals and reports how many objects are present. .EXAMPLE @@ -37,38 +37,31 @@ $adState = Get-MtADDomainState -Categories @('Configuration') # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $adState -or $null -eq $adState.Configuration -or $null -eq $adState.Configuration.WellKnownSecurityPrincipals) { + throw 'Well-known security principal inventory could not be retrieved.' } $config = $adState.Configuration - $expectedCount = 27 - $wellKnownPrincipals = $config.WellKnownSecurityPrincipals + $wellKnownPrincipals = if ($null -ne $config) { $config.WellKnownSecurityPrincipals } else { $null } $wellKnownPrincipalsCount = @($wellKnownPrincipals).Count $hasData = $null -ne $config.WellKnownSecurityPrincipals # Return $true if configuration data was retrieved successfully. - # Compliance with the default expected count is reported in the markdown output. $testResult = $hasData - $meetsExpectedCount = $wellKnownPrincipalsCount -eq $expectedCount # Generate markdown results if ($hasData) { $result = "| Metric | Value |" + "`n" $result += "| --- | --- |" + "`n" $result += "| WellKnownSecurityPrincipals Count | $wellKnownPrincipalsCount |" + "`n" - $result += "| Expected Count | $expectedCount |" + "`n" - $result += "| Matches Expected Count | $meetsExpectedCount |" + "`n" - - $testResultMarkdown = "Active Directory well-known security principals have been counted. $wellKnownPrincipalsCount well-known security principal(s) were found (expected: $expectedCount).`n`n%TestResult%" + $testResultMarkdown = "Active Directory well-known security principals have been enumerated ($wellKnownPrincipalsCount found). Review the actual identities; counts vary by forest and OS version and do not establish tampering.`n`n%TestResult%" $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result } else { $testResultMarkdown = "Unable to retrieve Active Directory configuration data for WellKnownSecurityPrincipals. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/config/Test.AD-CFG-11.md b/tests/ad/config/Test.AD-CFG-11.md index d62bf81119..993eaef333 100644 --- a/tests/ad/config/Test.AD-CFG-11.md +++ b/tests/ad/config/Test.AD-CFG-11.md @@ -1,23 +1,14 @@ -DHCP servers registered in Active Directory are authorized to provide IP addresses to clients. If unauthorized DHCP servers are registered (or legitimate servers are removed), clients may receive incorrect network settings, experience instability, or be exposed to man-in-the-middle attacks via rogue DHCP. +This inventory counts distinct DHCP server authorization entries stored in the `dhcpServers` attribute of `dhcpClass` objects under the AD NetServices configuration container. It reports registered DNS names and IPv4 addresses, including entries whose format cannot be parsed, rather than treating a registration container as one server. -#### Control Type +A registration count does not identify an unauthorized server or prove that all DHCP servers are registered. The IPv4 value `255.0.0.1` can represent a DHCPv6 server registered without IPv4; it is not proof of an invalid server. -**Operational** +#### Remediation action -#### Security Recommendation -- Maintain a strict allowlist of approved DHCP servers and ensure only those servers are registered in AD. -- Remove stale/unneeded DHCP server registrations as part of routine hygiene. -- Restrict permissions for DHCP registration operations to only the DHCP administrators and automation workflows you trust. -- Alert on any change in the number of registered DHCP servers. +Compare each registration with the approved DHCP server inventory and investigate unexpected changes. Do not remove a registration based only on a count. -#### How the Test Works -- Searches Active Directory for directory objects representing authorized/registered DHCP servers. -- Counts the number of such registered server objects. -- Compares the count to an environment baseline and flags unexpected additions/removals. +#### Related links -#### Related Tests -- [Test-MtAdWellKnownSecurityPrincipalsCount](./Test-MtAdWellKnownSecurityPrincipalsCount.md): Helps confirm AD identity integrity. -- [Test-MtAdEnterpriseCaCount](./Test-MtAdEnterpriseCaCount.md): Complements service authorization checks for certificate infrastructure. +- [Microsoft MS-DHCPE: DHCP authorization attribute format](https://learn.microsoft.com/openspecs/windows_protocols/ms-dhcpe/52a47b66-fe0a-47e3-b4e0-92016f69c71f) %TestResult% diff --git a/tests/ad/config/Test.AD-CFG-11.ps1 b/tests/ad/config/Test.AD-CFG-11.ps1 index bb40fe78a7..02f7073658 100644 --- a/tests/ad/config/Test.AD-CFG-11.ps1 +++ b/tests/ad/config/Test.AD-CFG-11.ps1 @@ -36,9 +36,8 @@ $adState = Get-MtADDomainState -Categories @('Configuration') # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $adState -or $null -eq $adState.Configuration -or $null -eq $adState.Configuration.DhcpServers) { + throw 'DHCP server registrations could not be retrieved.' } $config = $adState.Configuration @@ -54,13 +53,19 @@ $result = "| Metric | Value |" + "`n" $result += "| --- | --- |" + "`n" $result += "| Registered DHCP Servers Count | $dhcpServersCount |" + "`n" + $result += "`n| Registered DNS name | IPv4 address | Parsed |`n| --- | --- | --- |`n" + foreach ($server in $dhcpServers) { + $name = ([string]$server.DnsName).Replace('|', '|') -replace '[\r\n]+', ' ' + $address = ([string]$server.IPAddress).Replace('|', '|') -replace '[\r\n]+', ' ' + $result += "| $name | $address | $($server.RegistrationParsed) |`n" + } $testResultMarkdown = "Active Directory registered DHCP servers have been counted. $dhcpServersCount DHCP server(s) were found.`n`n%TestResult%" $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result } else { $testResultMarkdown = "Unable to retrieve Active Directory configuration data for DhcpServers. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } From b6c84224ecfcfb02fce7f22590b0e22b881eff3e Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 06:23:26 +0000 Subject: [PATCH 009/100] fix(ad): consolidate tombstone and optional-feature assessments --- .../functions/ADConfigurationChecks.Tests.ps1 | 94 +++++++++++++++++++ tests/ad/config/Test.AD-CFG-01.md | 25 ----- tests/ad/config/Test.AD-CFG-01.ps1 | 74 --------------- tests/ad/config/Test.AD-CFG-04.md | 26 ----- tests/ad/config/Test.AD-CFG-04.ps1 | 67 ------------- tests/ad/config/Test.AD-CFG-05.md | 25 ----- tests/ad/config/Test.AD-CFG-05.ps1 | 81 ---------------- tests/ad/domain/Test.AD-FOR-03.md | 12 ++- tests/ad/domain/Test.AD-FOR-03.ps1 | 56 ++++------- tests/ad/domain/Test.AD-FOR-04.md | 2 +- tests/ad/domain/Test.AD-FOR-04.ps1 | 63 ++++--------- tests/ad/replication/Test.AD-FEAT-01.md | 31 +----- tests/ad/replication/Test.AD-FEAT-01.ps1 | 52 +++++----- tests/ad/replication/Test.AD-FEAT-02.md | 35 ------- tests/ad/replication/Test.AD-FEAT-02.ps1 | 81 ---------------- 15 files changed, 173 insertions(+), 551 deletions(-) create mode 100644 powershell/tests/functions/ADConfigurationChecks.Tests.ps1 delete mode 100644 tests/ad/config/Test.AD-CFG-01.md delete mode 100644 tests/ad/config/Test.AD-CFG-01.ps1 delete mode 100644 tests/ad/config/Test.AD-CFG-04.md delete mode 100644 tests/ad/config/Test.AD-CFG-04.ps1 delete mode 100644 tests/ad/config/Test.AD-CFG-05.md delete mode 100644 tests/ad/config/Test.AD-CFG-05.ps1 delete mode 100644 tests/ad/replication/Test.AD-FEAT-02.md delete mode 100644 tests/ad/replication/Test.AD-FEAT-02.ps1 diff --git a/powershell/tests/functions/ADConfigurationChecks.Tests.ps1 b/powershell/tests/functions/ADConfigurationChecks.Tests.ps1 new file mode 100644 index 0000000000..e3b05647e8 --- /dev/null +++ b/powershell/tests/functions/ADConfigurationChecks.Tests.ps1 @@ -0,0 +1,94 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name Test-MtAdTombstoneLifetime, Test-MtAdDsHeuristicsCount, Test-MtAdSpnMappings, Test-MtAdRecycleBinStatus, Test-MtAdOptionalFeatureCount, Test-MtAdKdsRootKeysCount +} + +Describe 'AD configuration, forest and optional-feature checks' { + BeforeEach { + $script:detail = $null + $script:state = [PSCustomObject]@{ + Forest = [PSCustomObject]@{ Name = 'example.test'; ForestMode = 'Windows2016Forest' } + Configuration = [PSCustomObject]@{ + DirectoryServiceRetrieved = $true + TombstoneLifetime = 180 + DsHeuristics = $null + SpnMappings = @('HOST=HTTP') + KdsRootKeys = @([PSCustomObject]@{ 'msKds-CreateTime' = [datetime]'2024-01-01' }) + } + OptionalFeatures = @( + [PSCustomObject]@{ Name = 'Recycle Bin Feature'; IsEnabled = $true; EnabledScopes = @('CN=Partitions,CN=Configuration,DC=example,DC=test') } + [PSCustomObject]@{ Name = 'Other Feature'; IsEnabled = $false; EnabledScopes = @() } + ) + } + Mock Get-MtADDomainState -ModuleName Maester { $script:state } + Mock Add-MtTestResultDetail -ModuleName Maester { $script:detail = $Result } + } + + It 'reports an explicitly configured 180-day tombstone lifetime, not the default' { + Test-MtAdTombstoneLifetime | Should -BeTrue + $script:detail | Should -Match 'Configured tombstoneLifetime \| 180 days' + $script:detail | Should -Match 'Effective tombstone lifetime \| 180 days' + $script:detail | Should -Match 'default \(60 days\) \| False' + } + + It 'reports 60 days as the effective lifetime only when the attribute is unset' { + $script:state.Configuration.TombstoneLifetime = $null + Test-MtAdTombstoneLifetime | Should -BeTrue + $script:detail | Should -Match 'Configured tombstoneLifetime \| Not set' + $script:detail | Should -Match 'Effective tombstone lifetime \| 60 days' + $script:detail | Should -Match 'default \(60 days\) \| True' + } + + It 'errors rather than assuming a default if the Directory Service object is missing' { + $script:state.Configuration.DirectoryServiceRetrieved = $false + $script:state.Configuration.TombstoneLifetime = $null + { Test-MtAdTombstoneLifetime } | Should -Throw '*Directory Service object*' + { Test-MtAdDsHeuristicsCount } | Should -Throw '*Directory Service object*' + { Test-MtAdSpnMappings } | Should -Throw '*Directory Service object*' + } + + It 'investigates unset dSHeuristics without treating it as an inventory error' { + Test-MtAdDsHeuristicsCount | Should -BeTrue + $script:detail | Should -Match 'not set' + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Exactly 1 -ParameterFilter { $Investigate } + } + + It 'fails when Recycle Bin exists but is not enabled' { + $script:state.OptionalFeatures[0].IsEnabled = $false + Test-MtAdRecycleBinStatus | Should -BeFalse + $script:detail | Should -Match 'not enabled' + } + + It 'combines available and enabled counts with feature scope details' { + Test-MtAdOptionalFeatureCount | Should -BeTrue + $script:detail | Should -Match 'Available optional features \| 2' + $script:detail | Should -Match 'Enabled optional features \| 1' + $script:detail | Should -Match 'Recycle Bin Feature \| True \| CN=Partitions' + $script:detail | Should -Match 'Other Feature \| False \| None' + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Exactly 1 -ParameterFilter { $Investigate } + } + + It 'errors when an optional feature is missing enabled-scope data' { + $script:state.OptionalFeatures[0].PSObject.Properties.Remove('EnabledScopes') + { Test-MtAdOptionalFeatureCount } | Should -Throw '*scopes were not collected*' + } + + It 'fails for zero KDS root keys rather than assuming gMSAs are unused' { + $script:state.Configuration.KdsRootKeys = @() + Test-MtAdKdsRootKeysCount | Should -BeFalse + $script:detail | Should -Match 'No KDS root keys' + } + + It 'investigates the documented two-key case with a single boolean return' { + $script:state.Configuration.KdsRootKeys += [PSCustomObject]@{ 'msKds-CreateTime' = [datetime]'2025-01-01' } + Test-MtAdKdsRootKeysCount | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Exactly 1 -ParameterFilter { $Investigate } + $script:detail | Should -Not -Match 'Recommended Count' + } + + It 'does not silently omit a KDS key with unavailable creation metadata' { + $script:state.Configuration.KdsRootKeys += [PSCustomObject]@{ Name = 'Unreadable metadata' } + { Test-MtAdKdsRootKeysCount } | Should -Throw '*inventory is incomplete*' + } +} diff --git a/tests/ad/config/Test.AD-CFG-01.md b/tests/ad/config/Test.AD-CFG-01.md deleted file mode 100644 index 1d19910262..0000000000 --- a/tests/ad/config/Test.AD-CFG-01.md +++ /dev/null @@ -1,25 +0,0 @@ -The **tombstone lifetime** determines how long Active Directory retains “deleted but not yet purged” objects (for example, users, groups, and computer accounts). This directly impacts your ability to recover from: - -- **Accidental deletions** performed by admins or during automation -- **Incident response actions** that remove objects and later need restoration -- **Mis-scoped deprovisioning** (bulk removals, OU moves, scripted cleanup) - -If tombstone lifetime is **too short**, recovery may fail before you notice the issue. If it is **too long**, AD can accumulate a larger tombstone dataset, increasing replication/database growth and operational overhead. - -#### Control Type - -**Operational** - -#### Security Recommendation -- Align tombstone lifetime with your **operational recovery window** (common baselines are ~180 days or longer, but choose based on your incident response and retention requirements). -- Document and periodically review your **maximum time-to-detect** for directory changes. -- Ensure paired recovery controls are in place (for example, **Recycle Bin** where appropriate) so deleted objects can be restored safely. - -#### How the Test Works -This test retrieves the environment’s configured tombstone lifetime value from AD configuration and reports it as an environment metric so you can verify it against your expected baseline. - -#### Related Tests -- `Test-MtAdTombstoneLifetime` - Phase 5: Reviews tombstone lifetime in the context of overall AD recovery expectations. - - -%TestResult% diff --git a/tests/ad/config/Test.AD-CFG-01.ps1 b/tests/ad/config/Test.AD-CFG-01.ps1 deleted file mode 100644 index ff0812bbc2..0000000000 --- a/tests/ad/config/Test.AD-CFG-01.ps1 +++ /dev/null @@ -1,74 +0,0 @@ -function Test-MtAdTombstoneLifetimeConfig { - <# - .SYNOPSIS - Returns the Active Directory tombstone lifetime configuration. - - .DESCRIPTION - Phase 14 (AD Configuration tests) - AD-CFG-01. - This test retrieves the tombstone lifetime (in days) from $adState.Configuration. - - .EXAMPLE - Test-MtAdTombstoneLifetimeConfig - - Returns $true if configuration data is accessible. - - .LINK - https://maester.dev/docs/commands/Test-MtAdTombstoneLifetimeConfig - #> - [MaesterTest( - Id = 'AD-CFG-01', - Title = 'Tombstone lifetime configuration should be retrievable', - Product = 'ad', - Feature = 'directory-configuration', - Area = 'infrastructure', - ResourceType = 'Tenant', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:Configuration/*:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdTombstoneLifetimeConfig" - - $adState = Get-MtADDomainState -Categories @('Configuration') - - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $config = $adState.Configuration - $tombstoneLifetime = if ($null -ne $config) { $config.TombstoneLifetime } else { $null } - - # Default values: 60 days for older forests, 180 days for newer forests - $defaultValue = 180 - if ($null -eq $tombstoneLifetime) { - $tombstoneLifetime = $defaultValue - $isDefault = $true - } else { - $isDefault = $false - } - - $testResult = $null -ne $config - - if ($testResult) { - $result = "| Property | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Tombstone Lifetime (days) | $tombstoneLifetime |" + "`n" - $result += "| Default Value | $defaultValue days |" + "`n" - $result += "| Using Default | $isDefault |" + "`n" + "`n" - - $testResultMarkdown = "Active Directory tombstone lifetime configuration has been retrieved.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } - else { - $testResultMarkdown = "Unable to retrieve Active Directory configuration. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - return $testResult -} diff --git a/tests/ad/config/Test.AD-CFG-04.md b/tests/ad/config/Test.AD-CFG-04.md deleted file mode 100644 index 2a19b5a9e7..0000000000 --- a/tests/ad/config/Test.AD-CFG-04.md +++ /dev/null @@ -1,26 +0,0 @@ -Active Directory **optional features** (and related feature flags) enable or enhance behaviors such as recoverability and directory management capabilities. Incorrectly enabled/disabled features can materially affect your security posture by: - -- Reducing your ability to recover from accidental or malicious deletion -- Leaving legacy behaviors in place longer than necessary -- Causing operational drift that attackers can exploit via misconfiguration - -In particular, features that improve recovery (such as those related to the Recycle Bin) directly impact resilience during incidents. - -#### Control Type - -**Operational** - -#### Security Recommendation -- Ensure critical recoverability features (notably **Recycle Bin**) are enabled for the partitions that contain important identity data. -- Treat optional feature changes as **security configuration changes**: use a change control process, test first, and validate after enabling/disabling. -- Keep optional feature configuration consistent across domains/partitions where required. - -#### How the Test Works -This test retrieves the set of enabled AD optional feature flags and reports them as a count/visibility metric so administrators can confirm whether the expected security-enhancing features are active. - -#### Related Tests -- `Test-MtAdRecycleBinEnabledPaths` - Shows where Recycle Bin is enabled. -- `Test-MtAdRecycleBinStatus` - Validates the Recycle Bin state. - - -%TestResult% diff --git a/tests/ad/config/Test.AD-CFG-04.ps1 b/tests/ad/config/Test.AD-CFG-04.ps1 deleted file mode 100644 index 9b70b48b4a..0000000000 --- a/tests/ad/config/Test.AD-CFG-04.ps1 +++ /dev/null @@ -1,67 +0,0 @@ -function Test-MtAdOptionalFeaturesCount { - <# - .SYNOPSIS - Counts the number of Active Directory optional features. - - .DESCRIPTION - This test retrieves all optional features available in Active Directory and returns the total count. - Optional features are used to represent forest and domain capabilities such as the Recycle Bin feature. - - .EXAMPLE - Test-MtAdOptionalFeaturesCount - - Returns $true if optional feature data is accessible. - - .LINK - https://maester.dev/docs/commands/Test-MtAdOptionalFeaturesCount - #> - [MaesterTest( - Id = 'AD-CFG-04', - Title = 'Optional features count should be retrievable', - Product = 'ad', - Feature = 'directory-configuration', - Area = 'infrastructure', - ResourceType = 'Tenant', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:msDS-OptionalFeature:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdOptionalFeaturesCount" - - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('OptionalFeatures') - - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $optionalFeatures = if ($null -ne $adState.OptionalFeatures) { @($adState.OptionalFeatures) } else { @() } - $optionalFeaturesCount = ($optionalFeatures | Measure-Object).Count - - # Test passes if we successfully retrieved optional feature data - $testResult = $null -ne $adState.OptionalFeatures - - # Generate markdown results - if ($testResult) { - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Optional Features Count | $optionalFeaturesCount |" + "`n" - - $testResultMarkdown = "Active Directory optional features have been analyzed. Found $optionalFeaturesCount optional feature(s).`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory optional features. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult -} diff --git a/tests/ad/config/Test.AD-CFG-05.md b/tests/ad/config/Test.AD-CFG-05.md deleted file mode 100644 index 5cb26db83f..0000000000 --- a/tests/ad/config/Test.AD-CFG-05.md +++ /dev/null @@ -1,25 +0,0 @@ -**Recycle Bin enabled paths** indicate which naming contexts/partitions have AD’s Recycle Bin functionality turned on. This matters because the Recycle Bin is a major control for limiting damage from: - -- **Accidental deletions** (including bulk removal mistakes) -- **Insider misuse** where deletion is used to cover tracks -- **Operational failures** where objects must be restored quickly to resume secure workflows - -Without Recycle Bin enabled for the right partitions, deleted objects may be **irrecoverable** once tombstone/purge timelines are exceeded. - -#### Control Type - -**Preventive** - -#### Security Recommendation -- Enable Recycle Bin for all partitions that store security-critical objects (for example, identity data in domains/NCs you manage). -- Ensure your recovery playbooks explicitly reference Recycle Bin vs. tombstone recovery. -- Monitor for unexpected changes to enabled partitions and investigate immediately. - -#### How the Test Works -This test enumerates AD partitions/paths and reports which ones have Recycle Bin enabled, giving administrators direct visibility into recoverability coverage. - -#### Related Tests -- `Test-MtAdRecycleBinStatus` - Confirms overall Recycle Bin functionality state. - - -%TestResult% diff --git a/tests/ad/config/Test.AD-CFG-05.ps1 b/tests/ad/config/Test.AD-CFG-05.ps1 deleted file mode 100644 index 4eb9ad09a2..0000000000 --- a/tests/ad/config/Test.AD-CFG-05.ps1 +++ /dev/null @@ -1,81 +0,0 @@ -function Test-MtAdRecycleBinEnabledPaths { - <# - .SYNOPSIS - Counts Active Directory paths where the Recycle Bin is enabled. - - .DESCRIPTION - This test examines Active Directory optional features for any feature related to the Recycle Bin - and counts the configured enabled scopes/paths. - - .EXAMPLE - Test-MtAdRecycleBinEnabledPaths - - Returns $true if optional feature data is accessible. - - .LINK - https://maester.dev/docs/commands/Test-MtAdRecycleBinEnabledPaths - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-CFG-05', - Title = 'Recycle bin enabled paths should be retrievable', - Product = 'ad', - Feature = 'directory-configuration', - Area = 'infrastructure', - ResourceType = 'Tenant', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:msDS-OptionalFeature:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdRecycleBinEnabledPaths" - - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('OptionalFeatures') - - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $optionalFeatures = $adState.OptionalFeatures - $recycleBinFeatures = @($optionalFeatures | Where-Object { - $_.Name -like "*Recycle Bin*" -and $_.IsEnabled - }) - - $enabledScopes = @( - $recycleBinFeatures | ForEach-Object { $_.DistinguishedName } - ) | Where-Object { $null -ne $_ } - - $enabledPathCount = ($enabledScopes | Measure-Object).Count - - # Test passes if we successfully retrieved optional feature data - $testResult = $null -ne $adState.OptionalFeatures - - # Generate markdown results - if ($testResult) { - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Recycle Bin Feature Matches | $($recycleBinFeatures.Count) |" + "`n" - $result += "| Recycle Bin Enabled Path Count | $enabledPathCount |" + "`n" - - if ($enabledPathCount -gt 0) { - $result += "| Enabled Scopes | $($enabledScopes -join ', ') |" + "`n" - } - - $testResultMarkdown = "Active Directory Recycle Bin enabled paths have been analyzed. Found $enabledPathCount enabled scope(s).`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory optional features for Recycle Bin evaluation. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult -} diff --git a/tests/ad/domain/Test.AD-FOR-03.md b/tests/ad/domain/Test.AD-FOR-03.md index 133ceaa40c..3fa0bf50b9 100644 --- a/tests/ad/domain/Test.AD-FOR-03.md +++ b/tests/ad/domain/Test.AD-FOR-03.md @@ -5,9 +5,7 @@ The tombstone lifetime determines how long deleted Active Directory objects are - **Backup Recovery**: Aligns with backup retention strategies for directory recovery - **Compliance**: Some regulations require specific retention periods for directory data -**Default Values**: -- **180 days**: Default for forests created on Windows Server 2003 SP1 and later -- **60 days**: Default for older forests (Windows 2000/2003 RTM) +When `tombstoneLifetime` is **not set**, Active Directory uses an effective **60 days** even in an upgraded forest. Newer forests can have an explicitly configured 180-day value; this check distinguishes the stored attribute from the effective value. #### Control Type @@ -15,7 +13,7 @@ The tombstone lifetime determines how long deleted Active Directory objects are #### Security Recommendation -- **Minimum 180 Days**: Maintain at least 180 days for adequate recovery time +- Choose a retention period appropriate to the recovery and replication window. Do not assume an unset attribute means 180 days. - **Align with Backups**: Ensure tombstone lifetime matches or exceeds backup retention - **Monitor Changes**: Track any modifications to this critical setting - **Document**: Record the current setting and any business requirements @@ -28,7 +26,11 @@ Set-ADObject -Identity "CN=Directory Service,CN=Windows NT,CN=Services,$configur #### How the Test Works -This test retrieves the tombstone lifetime from the Directory Service configuration object and reports the current value along with recommendations. +This test retrieves the tombstone lifetime from the Directory Service configuration object and reports both the configured attribute and effective value. It is an inventory check, not a pass/fail threshold for retention length. AD-CFG-01 was consolidated into this check. + +#### Related links + +- [Microsoft ADTS: tombstone lifetime and unset-attribute default](https://learn.microsoft.com/openspecs/windows_protocols/ms-adts/1887de08-2a9e-4694-95e2-898cde411180) #### Related Tests diff --git a/tests/ad/domain/Test.AD-FOR-03.ps1 b/tests/ad/domain/Test.AD-FOR-03.ps1 index 45f4d98068..39d6f9f8fd 100644 --- a/tests/ad/domain/Test.AD-FOR-03.ps1 +++ b/tests/ad/domain/Test.AD-FOR-03.ps1 @@ -40,46 +40,24 @@ # Get AD domain state data (uses cached data if available) $adState = Get-MtADDomainState -Categories @('Configuration', 'Forest') - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $adState -or $null -eq $adState.Configuration) { + throw 'Unable to retrieve the Directory Service configuration; tombstone lifetime cannot be determined.' } - - # Get tombstone lifetime from the collected directory configuration - $tombstoneLifetime = $adState.Configuration.TombstoneLifetime - - # Default values: 60 days for older forests, 180 days for newer forests - $defaultValue = 180 - if ($null -eq $tombstoneLifetime) { - $tombstoneLifetime = $defaultValue - $isDefault = $true - } else { - $isDefault = $false - } - - # Test passes if we successfully retrieved tombstone lifetime - $testResult = $null -ne $tombstoneLifetime - - # Generate markdown results - if ($testResult) { - $result = "| Property | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Tombstone Lifetime | $tombstoneLifetime days |" + "`n" - $result += "| Default Value | $defaultValue days |" + "`n" - $result += "| Using Default | $isDefault |" + "`n" - $result += "| Forest Name | $($adState.Forest.Name) |" + "`n" - - $recommendation = if ($tombstoneLifetime -ge 180) { "✅ Meets recommendation (180+ days)" } else { "⚠️ Below recommendation (180 days)" } - $result += "| Recommendation | $recommendation |" + "`n" - - $testResultMarkdown = "The Active Directory tombstone lifetime has been retrieved. Deleted objects are retained for $tombstoneLifetime days before permanent removal.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve tombstone lifetime. Ensure you have appropriate permissions and the Active Directory module is installed." + if ($adState.Configuration.PSObject.Properties.Name -contains 'DirectoryServiceRetrieved' -and + $adState.Configuration.DirectoryServiceRetrieved -ne $true) { + throw 'Directory Service object could not be retrieved; an absent tombstone lifetime cannot be inferred.' } - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult + $configured = $adState.Configuration.TombstoneLifetime + $usingDefault = $null -eq $configured -or [string]::IsNullOrWhiteSpace([string]$configured) + # An absent tombstoneLifetime attribute means 60 days, including in upgraded forests. + $effective = if ($usingDefault) { 60 } else { [int]$configured } + $configuredText = if ($usingDefault) { 'Not set' } else { "$configured days" } + $result = "| Property | Value |`n| --- | --- |`n" + $result += "| Configured tombstoneLifetime | $configuredText |`n" + $result += "| Effective tombstone lifetime | $effective days |`n" + $result += "| Using the unset-attribute default (60 days) | $usingDefault |`n" + $result += "| Forest name | $($adState.Forest.Name) |`n" + Add-MtTestResultDetail -Result "Well done. Tombstone lifetime was determined from the Directory Service configuration.`n`n$result" + return $true } diff --git a/tests/ad/domain/Test.AD-FOR-04.md b/tests/ad/domain/Test.AD-FOR-04.md index 0f83ba3166..03ef2d6e26 100644 --- a/tests/ad/domain/Test.AD-FOR-04.md +++ b/tests/ad/domain/Test.AD-FOR-04.md @@ -29,7 +29,7 @@ Enable-ADOptionalFeature -Identity "Recycle Bin Feature" -Scope ForestOrConfigur #### How the Test Works -This test checks the optional features in Active Directory to determine if the Recycle Bin Feature is enabled and reports its status. +This test fails if the Recycle Bin Feature exists but is not enabled, passes if enabled, and errors if the feature cannot be uniquely identified or its status was not retrieved. It does not treat successful enumeration as evidence of protection. AD-CFG-05 was consolidated into this check; AD-FEAT-01 inventories all optional features and their enabled scopes separately. #### Related Tests diff --git a/tests/ad/domain/Test.AD-FOR-04.ps1 b/tests/ad/domain/Test.AD-FOR-04.ps1 index cf9a4ce9fe..5537116fec 100644 --- a/tests/ad/domain/Test.AD-FOR-04.ps1 +++ b/tests/ad/domain/Test.AD-FOR-04.ps1 @@ -20,12 +20,14 @@ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] [MaesterTest( Id = 'AD-FOR-04', - Title = 'Recycle Bin status should be retrievable', + Title = 'Active Directory Recycle Bin should be enabled', Product = 'ad', Feature = 'directory-configuration', Area = 'infrastructure', ResourceType = 'Tenant', - Severity = 'Info', + Severity = 'Medium', + UserImpact = 'Low', + ImplementationCost = 'Medium', Mitre = 'None', Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:crossRef:ReadProperty', 'ActiveDirectory:Ldap:msDS-OptionalFeature:ReadProperty'), @@ -40,52 +42,25 @@ # Get AD domain state data (uses cached data if available) $adState = Get-MtADDomainState -Categories @('Forest', 'OptionalFeatures') - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $adState -or $null -eq $adState.OptionalFeatures) { + throw 'Unable to retrieve optional features; Recycle Bin status cannot be determined.' } - $forest = $adState.Forest - $optionalFeatures = $adState.OptionalFeatures - - # Check if Recycle Bin optional feature is enabled - $recycleBinFeature = $optionalFeatures | Where-Object { $_.Name -eq "Recycle Bin Feature" } - $isEnabled = $false - - if ($recycleBinFeature) { - $isEnabled = $recycleBinFeature.IsEnabled + $recycleBinFeature = @($adState.OptionalFeatures | Where-Object { $_.Name -eq 'Recycle Bin Feature' }) + if ($recycleBinFeature.Count -ne 1) { + throw 'Unable to identify exactly one Recycle Bin Feature in the optional-feature inventory. Verify directory access and the forest configuration.' } - - # Test passes if we successfully retrieved Recycle Bin status - $testResult = $null -ne $recycleBinFeature -or $optionalFeatures.Count -gt 0 - - # Generate markdown results - if ($testResult) { - $result = "| Property | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Recycle Bin Enabled | $isEnabled |" + "`n" - $result += "| Forest Name | $($forest.Name) |" + "`n" - $result += "| Forest Functional Level | $($forest.ForestMode) |" + "`n" - - $statusMessage = if ($isEnabled) { "✅ Enabled - Deleted objects can be recovered from the Recycle Bin" } else { "⚠️ Disabled - Deleted objects can only be recovered through tombstone reanimation or backup restore" } - $result += "| Status | $statusMessage |" + "`n" - - # Check if forest level supports Recycle Bin (requires Windows Server 2008 R2 or higher) - $supportedLevels = @("Windows2008R2Forest", "Windows2012Forest", "Windows2012R2Forest", "Windows2016Forest", "Windows2025Forest") - $forestLevelSupported = $supportedLevels -contains $forest.ForestMode - - if (-not $isEnabled -and -not $forestLevelSupported) { - $result += "| Note | Forest functional level must be Windows Server 2008 R2 or higher to enable Recycle Bin |" + "`n" - } - - $testResultMarkdown = "The Active Directory Recycle Bin status has been retrieved. The Recycle Bin is currently $(if($isEnabled){'ENABLED'}else{'DISABLED'}).`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Recycle Bin status. Ensure you have appropriate permissions and the Active Directory module is installed." + if ($null -eq $recycleBinFeature[0].IsEnabled) { + throw 'Recycle Bin enabled status could not be retrieved.' } - Add-MtTestResultDetail -Result $testResultMarkdown + $isEnabled = $recycleBinFeature[0].IsEnabled -eq $true + $forestName = $adState.Forest.Name + if ($isEnabled) { + Add-MtTestResultDetail -Result "Well done. Active Directory Recycle Bin is enabled in forest $forestName." + return $true + } - return $testResult + Add-MtTestResultDetail -Result "Active Directory Recycle Bin is not enabled in forest $forestName. Plan and enable the Recycle Bin after checking the forest functional level." + return $false } diff --git a/tests/ad/replication/Test.AD-FEAT-01.md b/tests/ad/replication/Test.AD-FEAT-01.md index 5201879e93..805023aeec 100644 --- a/tests/ad/replication/Test.AD-FEAT-01.md +++ b/tests/ad/replication/Test.AD-FEAT-01.md @@ -1,33 +1,12 @@ -Active Directory optional features extend the base functionality of AD and can significantly impact security capabilities: +This inventory shows which Active Directory optional features are available and which are enabled, including their enabled scopes. It combines the former feature-count and enabled-feature-detail inventories (AD-CFG-04 and AD-FEAT-02). A feature's existence does not mean it has been enabled. -- **Recycle Bin**: Critical for recovering accidentally or maliciously deleted objects -- **Privileged Access Management (PAM)**: Enables time-based group membership for just-in-time access -- **Feature Awareness**: Understanding available features helps assess security posture +#### Remediation action -Knowing which optional features are available helps administrators understand the full capabilities of their Active Directory environment and identify opportunities to enhance security. +Review feature names and enabled scopes against your forest's intended configuration before changing any optional feature. Enabling an optional feature may be irreversible. To evaluate whether the Recycle Bin is enabled, use AD-FOR-04; this inventory does not give its status a separate pass/fail result. -#### Control Type +#### Related links -**Operational** - -#### Security Recommendation - -- Enable the Active Directory Recycle Bin if not already enabled -- Consider PAM for privileged access scenarios -- Regularly review available optional features -- Keep domain and forest functional levels current to access newer features -- Document enabled optional features and their configuration - -#### How the Test Works - -This test retrieves all Active Directory optional features and counts: -- Total number of optional features available -- List of feature names - -#### Related Tests - -- `Test-MtAdOptionalFeatureEnabledDetails` - Provides detailed information about enabled features -- `Test-MtAdRecycleBinStatus` - Checks if the Recycle Bin is enabled +- [Microsoft: enable the Active Directory Recycle Bin](https://learn.microsoft.com/windows-server/identity/ad-ds/get-started/adac/advanced-ad-ds-management-using-active-directory-administrative-center--level-200-) %TestResult% diff --git a/tests/ad/replication/Test.AD-FEAT-01.ps1 b/tests/ad/replication/Test.AD-FEAT-01.ps1 index f694c47fa3..8a71778ae2 100644 --- a/tests/ad/replication/Test.AD-FEAT-01.ps1 +++ b/tests/ad/replication/Test.AD-FEAT-01.ps1 @@ -1,7 +1,7 @@ function Test-MtAdOptionalFeatureCount { <# .SYNOPSIS - Retrieves the count of Active Directory optional features. + Inventories available and enabled Active Directory optional features. .DESCRIPTION Active Directory optional features provide additional functionality beyond the @@ -23,7 +23,7 @@ #> [MaesterTest( Id = 'AD-FEAT-01', - Title = 'Optional feature count should be investigated', + Title = 'Optional features and enabled scopes should be investigated', Product = 'ad', Feature = 'directory-configuration', Area = 'infrastructure', @@ -42,28 +42,36 @@ $adState = Get-MtADDomainState -Categories @('OptionalFeatures') - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $adState -or $null -eq $adState.OptionalFeatures) { + throw 'Optional-feature inventory could not be retrieved.' } $optionalFeatures = $adState.OptionalFeatures - $featureCount = ($optionalFeatures | Measure-Object).Count - - $testResult = $true - - $result = "| Property | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Optional Features | $featureCount |" + "`n" - - if ($featureCount -gt 0) { - $result += "| Available Features | $(($optionalFeatures | ForEach-Object { $_.Name }) -join ', ') |" + "`n" + $featureCount = @($optionalFeatures).Count + foreach ($feature in $optionalFeatures) { + if ($feature.PSObject.Properties.Name -notcontains 'IsEnabled' -or $null -eq $feature.IsEnabled) { + throw "Enabled status could not be retrieved for optional feature '$($feature.Name)'." + } } - - $testResultMarkdown = "Active Directory optional features have been enumerated. These features extend AD capabilities beyond base functionality.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - - return $testResult + $enabledFeatures = @($optionalFeatures | Where-Object { $_.IsEnabled -eq $true }) + $result = "| Metric | Value |`n| --- | --- |`n" + $result += "| Available optional features | $featureCount |`n" + $result += "| Enabled optional features | $($enabledFeatures.Count) |`n`n" + $result += "| Feature | Enabled | Enabled scopes |`n| --- | --- | --- |`n" + foreach ($feature in $optionalFeatures) { + $scopeText = 'None' + if ($feature.PSObject.Properties.Name -notcontains 'EnabledScopes') { + throw "Enabled scopes were not collected for optional feature '$($feature.Name)'." + } + if ($null -eq $feature.EnabledScopes) { + throw "Enabled scopes could not be retrieved for optional feature '$($feature.Name)'." + } + if (@($feature.EnabledScopes).Count -gt 0) { + $scopeText = (@($feature.EnabledScopes) | ForEach-Object { ([string]$_).Replace('|', '|') }) -join '
' + } + $name = ([string]$feature.Name).Replace('|', '|') + $result += "| $name | $($feature.IsEnabled) | $scopeText |`n" + } + Add-MtTestResultDetail -Result "Optional features and their enabled scopes are listed for review. AD-FOR-04 separately checks whether Recycle Bin is enabled.`n`n$result" -Investigate + return $true } diff --git a/tests/ad/replication/Test.AD-FEAT-02.md b/tests/ad/replication/Test.AD-FEAT-02.md deleted file mode 100644 index eceac8955c..0000000000 --- a/tests/ad/replication/Test.AD-FEAT-02.md +++ /dev/null @@ -1,35 +0,0 @@ -Understanding which Active Directory optional features are enabled and their scope is crucial for security management: - -- **Recycle Bin**: Should be enabled at the forest level for object recovery capabilities -- **Privileged Access Management**: May be enabled for specific domains or the entire forest -- **Feature Scope**: Knowing where features are enabled helps ensure consistent security policies - -Enabled optional features represent additional capabilities that can enhance security but also increase the attack surface if not properly managed. - -#### Control Type - -**Operational** - -#### Security Recommendation - -- Enable Recycle Bin at the forest level if not already enabled -- Document all enabled optional features and their scope -- Regularly review enabled features to ensure they align with security requirements -- Understand the implications of each enabled feature -- Monitor for unauthorized enabling of optional features - -#### How the Test Works - -This test retrieves detailed information about enabled optional features: -- Total optional features available -- Number of features with enabled scopes -- Feature names and their enabled scope counts -- Detailed breakdown of each enabled feature - -#### Related Tests - -- `Test-MtAdOptionalFeatureCount` - Counts total available optional features -- `Test-MtAdRecycleBinStatus` - Specifically checks Recycle Bin status - - -%TestResult% diff --git a/tests/ad/replication/Test.AD-FEAT-02.ps1 b/tests/ad/replication/Test.AD-FEAT-02.ps1 deleted file mode 100644 index 10389709aa..0000000000 --- a/tests/ad/replication/Test.AD-FEAT-02.ps1 +++ /dev/null @@ -1,81 +0,0 @@ -function Test-MtAdOptionalFeatureEnabledDetails { - <# - .SYNOPSIS - Retrieves detailed information about enabled Active Directory optional features. - - .DESCRIPTION - Active Directory optional features can be enabled at different scopes - (forest or domain level). This test provides detailed information about - which optional features are enabled and their scope of application. - - Key optional features to monitor: - - Recycle Bin: Critical for object recovery, should be enabled - - PAM: Privileged Access Management for time-based access - - Other features relevant to your security requirements - - .EXAMPLE - Test-MtAdOptionalFeatureEnabledDetails - - Returns $true if optional feature data is accessible. - - .LINK - https://maester.dev/docs/commands/Test-MtAdOptionalFeatureEnabledDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-FEAT-02', - Title = 'Optional feature enabled details should be investigated', - Product = 'ad', - Feature = 'directory-configuration', - Area = 'infrastructure', - ResourceType = 'Tenant', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:msDS-OptionalFeature:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdOptionalFeatureEnabledDetails" - - $adState = Get-MtADDomainState -Categories @('OptionalFeatures') - - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $optionalFeatures = $adState.OptionalFeatures - $enabledFeatures = $optionalFeatures | Where-Object { $_.IsEnabled } - $enabledCount = ($enabledFeatures | Measure-Object).Count - - $testResult = $true - - $result = "| Property | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Optional Features | $(($optionalFeatures | Measure-Object).Count) |" + "`n" - $result += "| Enabled Features | $enabledCount |" + "`n" - - if ($enabledCount -gt 0) { - $result += "`n**Enabled Feature Details:**" + "`n" + "`n" - $result += "| Feature Name | IsEnabled |" + "`n" - $result += "| --- | --- |" + "`n" - foreach ($feature in $enabledFeatures) { - $result += "| $($feature.Name) | $($feature.IsEnabled) |" + "`n" - } - } - - $testResultMarkdown = "Active Directory optional feature details have been retrieved. Enabled features extend AD functionality.`n`n%TestResult%" - if ($enabledCount -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", "" - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - - return $testResult -} From 6fe413ec598f49bc548c49349c5ce11406e5c551 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 06:23:26 +0000 Subject: [PATCH 010/100] fix(ad): fail KDS readiness when no root keys exist --- tests/ad/config/Test.AD-CFG-22.md | 8 +++--- tests/ad/config/Test.AD-CFG-22.ps1 | 44 ++++++++++++++---------------- 2 files changed, 25 insertions(+), 27 deletions(-) diff --git a/tests/ad/config/Test.AD-CFG-22.md b/tests/ad/config/Test.AD-CFG-22.md index 0fe7e8c51e..6605a0d4ea 100644 --- a/tests/ad/config/Test.AD-CFG-22.md +++ b/tests/ad/config/Test.AD-CFG-22.md @@ -11,17 +11,17 @@ Monitoring the *count* of KDS root keys helps identify: **Operational** #### Security Recommendation -- Ensure one or three (or more) KDS root keys exist per forest. Exactly two keys can cause gMSA authentication failures in some sorting scenarios. +- At least one KDS root key is required to provision gMSAs. Exactly two keys can cause gMSA authentication failures in some sorting scenarios; multiple keys are not inherently invalid. - If exactly two keys exist, Microsoft's recommended workaround is to create a third key. Do not remove existing keys. - Validate the expected number of keys for your environment and alert on deviations. - Restrict administrative access to actions that can modify KDS root keys. #### How the Test Works The test enumerates KDS root keys present in Active Directory and evaluates the count: -- **0 keys**: gMSAs are not in use; the test is skipped. -- **1 key**: The recommended configuration; the test passes. +- **0 keys**: gMSA provisioning is unavailable; the test fails. This does not prove whether gMSAs are in use. +- **1 key**: The test passes. - **2 keys**: Can cause gMSA authentication failures in some scenarios; the test returns Investigate. -- **3+ keys**: Acceptable per Microsoft guidance (the workaround for the sorting issue is to add a third key); the test passes. +- **3+ keys**: The test passes; Microsoft's workaround for the two-key sorting issue is to add a third key. #### References diff --git a/tests/ad/config/Test.AD-CFG-22.ps1 b/tests/ad/config/Test.AD-CFG-22.ps1 index 7453931d2c..28fba4b4d8 100644 --- a/tests/ad/config/Test.AD-CFG-22.ps1 +++ b/tests/ad/config/Test.AD-CFG-22.ps1 @@ -7,8 +7,8 @@ KDS root keys are required for Group Managed Service Accounts (gMSA). This test checks the number of KDS root keys configured in the domain. - - Zero keys indicates gMSAs are not in use, so the test is skipped. - - Exactly one key is the recommended configuration; the test passes. + - Zero keys means gMSA provisioning cannot work; the test fails. + - One key supports gMSA operations; the test passes. - Exactly two keys can cause gMSA authentication failures in some scenarios; the test returns Investigate per Microsoft guidance. - Three or more keys is also acceptable (Microsoft's recommended workaround @@ -17,7 +17,7 @@ .EXAMPLE Test-MtAdKdsRootKeysCount - Returns $true when the KDS root key count is acceptable (1 or 3+). + Returns $true when at least one KDS root key exists and the two-key issue does not apply. .LINK https://maester.dev/docs/commands/Test-MtAdKdsRootKeysCount @@ -29,7 +29,9 @@ Feature = 'directory-configuration', Area = 'infrastructure', ResourceType = 'Tenant', - Severity = 'Info', + Severity = 'Low', + UserImpact = 'Low', + ImplementationCost = 'Low', Mitre = 'None', Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:Configuration/*:ReadProperty'), @@ -44,54 +46,50 @@ # Get AD domain state data (uses cached data if available) $adState = Get-MtADDomainState -Categories @('Configuration') - # If unable to retrieve AD data, skip the test if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + throw 'Unable to retrieve the AD configuration needed to count KDS root keys.' } $config = $adState.Configuration - # If the KDS query failed or the entire Configuration category is unavailable, skip + # A missing category is not evidence that there are zero keys. if ($null -eq $config) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'Unable to retrieve Active Directory configuration. The query may have failed or returned no data.' - return $null + throw 'Unable to retrieve Active Directory configuration; KDS root key inventory is unknown.' } if ($null -eq $config.KdsRootKeys) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason 'Unable to retrieve KDS root key information. Ensure you have appropriate permissions.' - return $null + throw 'Unable to retrieve KDS root key information; check directory access.' } - # Count valid KDS root keys (those with a creation timestamp) - $kdsRootKeys = @($config.KdsRootKeys | Where-Object { $null -ne $_.'msKds-CreateTime' }) + # Do not silently drop keys whose metadata was not returned. + $kdsRootKeys = @($config.KdsRootKeys | Where-Object { $null -ne $_ }) + if (@($kdsRootKeys | Where-Object { $null -eq $_.'msKds-CreateTime' }).Count -gt 0) { + throw 'KDS root key creation metadata was not returned; the key inventory is incomplete.' + } $kdsRootKeysCount = ($kdsRootKeys | Measure-Object).Count # Build the metric table once so both result paths can include it $result = "| Metric | Value |" + "`n" $result += "| --- | --- |" + "`n" $result += "| KDS Root Keys (gMSA) | $kdsRootKeysCount |" + "`n" - $result += "| Recommended Count | 1 |" + "`n" - - # Zero keys means gMSAs are not deployed; skip the test + # No keys means gMSA provisioning is unavailable; this does not prove gMSAs are unused. if ($kdsRootKeysCount -eq 0) { - Add-MtTestResultDetail -SkippedBecause 'Custom' -SkippedCustomReason 'No KDS root keys found. Group Managed Service Accounts (gMSA) are not in use in this environment.' - return $null + Add-MtTestResultDetail -Result "No KDS root keys were found. gMSA provisioning requires a KDS root key; review whether gMSAs are planned or already in use.`n`n$result" + return $false } - # Exactly one key is the desired state; three or more is also acceptable per Microsoft guidance - # (the workaround for the sorting issue is to create a third key) + # A nonzero count establishes presence, not a universal recommended key count. # Two keys triggers an Investigate result per the Microsoft article if ($kdsRootKeysCount -eq 2) { $testResultMarkdown = "⚠️ Exactly two KDS root keys exist. In some scenarios this can cause gMSA authentication failures. Microsoft's recommended workaround is to create a third KDS root key. Do not remove existing keys. See [Microsoft documentation](https://learn.microsoft.com/troubleshoot/windows-server/active-directory/gmsa-auth-failures-multiple-keys) for details.`n`n%TestResult%" $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - return $null + return $true } $testResult = ($kdsRootKeysCount -eq 1) -or ($kdsRootKeysCount -ge 3) if ($testResult) { - $testResultMarkdown = "✅ KDS root key count is acceptable. This is the recommended configuration for gMSA operations.`n`n%TestResult%" + $testResultMarkdown = "Well done. KDS root keys are present for gMSA operations.`n`n%TestResult%" } $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result From 8259b1709ef7f8f413b5e1c42588a89c58462804 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 06:23:26 +0000 Subject: [PATCH 011/100] fix(ad): consolidate non-DC delegation assessments --- tests/ad/computer/Test.AD-COMP-09.md | 33 ------- tests/ad/computer/Test.AD-COMP-09.ps1 | 102 -------------------- tests/ad/computer/Test.AD-COMP-10.md | 38 -------- tests/ad/computer/Test.AD-COMP-10.ps1 | 125 ------------------------- tests/ad/security/Test.AD-DCOMP-01.md | 5 +- tests/ad/security/Test.AD-DCOMP-01.ps1 | 67 +++++++++---- tests/ad/security/Test.AD-DCOMP-02.md | 53 ----------- tests/ad/security/Test.AD-DCOMP-02.ps1 | 98 ------------------- tests/ad/security/Test.AD-DCOMP-03.md | 7 +- tests/ad/security/Test.AD-DCOMP-03.ps1 | 98 +++++++++++-------- 10 files changed, 112 insertions(+), 514 deletions(-) delete mode 100644 tests/ad/computer/Test.AD-COMP-09.md delete mode 100644 tests/ad/computer/Test.AD-COMP-09.ps1 delete mode 100644 tests/ad/computer/Test.AD-COMP-10.md delete mode 100644 tests/ad/computer/Test.AD-COMP-10.ps1 delete mode 100644 tests/ad/security/Test.AD-DCOMP-02.md delete mode 100644 tests/ad/security/Test.AD-DCOMP-02.ps1 diff --git a/tests/ad/computer/Test.AD-COMP-09.md b/tests/ad/computer/Test.AD-COMP-09.md deleted file mode 100644 index e30fd80139..0000000000 --- a/tests/ad/computer/Test.AD-COMP-09.md +++ /dev/null @@ -1,33 +0,0 @@ -Kerberos delegation allows a service to impersonate users when accessing other resources. While necessary for some applications, delegation—especially unconstrained delegation—creates significant security risks: - -- **Unconstrained delegation**: The service can impersonate users to ANY service on ANY system (highest risk) -- **Constrained delegation**: Limited to specific services, but still requires careful management -- **Protocol transition**: Allows S4U2Self/S4U2Proxy operations that can be exploited -- **Lateral movement**: Attackers can abuse delegation for privilege escalation and lateral movement - -#### Control Type - -**Detective** - -#### Security Recommendation - -- **Minimize unconstrained delegation**: Use it only when absolutely necessary, and never on tier 0 systems -- **Prefer constrained delegation**: Limit services to only those they need to access -- **Use resource-based constrained delegation**: More secure alternative in modern environments -- **Regular audits**: Periodically review which computers have delegation enabled -- **Remove unused delegation**: Disable delegation on systems that no longer require it -- **Consider Group Managed Service Accounts (gMSA)**: These provide better security for service accounts - -#### How the Test Works - -This test counts computers with different delegation configurations: -- `TrustedForDelegation` (unconstrained delegation) -- `TrustedToAuthForDelegation` (constrained delegation with protocol transition) - -#### Related Tests - -- `Test-MtAdComputerDelegationDetails` - Provides detailed breakdown of delegation per computer -- `Test-MtAdComputerDormantCount` - Identifies stale accounts that may have delegation enabled - - -%TestResult% diff --git a/tests/ad/computer/Test.AD-COMP-09.ps1 b/tests/ad/computer/Test.AD-COMP-09.ps1 deleted file mode 100644 index da55631a85..0000000000 --- a/tests/ad/computer/Test.AD-COMP-09.ps1 +++ /dev/null @@ -1,102 +0,0 @@ -function Test-MtAdComputerDelegationCount { - <# - .SYNOPSIS - Counts computers with delegation configured. - - .DESCRIPTION - This test identifies computer objects that have Kerberos delegation configured. - Delegation allows a service to impersonate users when accessing resources, which - can be a security risk if not properly configured. This test counts: - - Unconstrained delegation (most risky) - - Constrained delegation - - Protocol transition delegation - - .EXAMPLE - Test-MtAdComputerDelegationCount - - Returns $true if computer object data is accessible, $false otherwise. - The test result includes the count of computers with various delegation types. - - .LINK - https://maester.dev/docs/commands/Test-MtAdComputerDelegationCount - #> - [MaesterTest( - Id = 'AD-COMP-09', - Title = 'Computer delegation count should be retrievable', - Product = 'ad', - Feature = 'computers', - Area = 'authentication', - ResourceType = 'Computer', - Severity = 'Info', - Mitre = ('T1558', 'T1550.003'), - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:computer:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdComputerDelegationCount" - - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('Computers') - - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - if ($null -eq $adState.Computers) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $computers = $adState.Computers - - # Count computers with different delegation types - $unconstrainedDelegation = $computers | Where-Object { - $_.TrustedForDelegation -eq $true - } - - $constrainedDelegation = $computers | Where-Object { - $_.TrustedToAuthForDelegation -eq $true - } - - $unconstrainedCount = ($unconstrainedDelegation | Measure-Object).Count - $constrainedCount = ($constrainedDelegation | Measure-Object).Count - $totalDelegationCount = $unconstrainedCount + $constrainedCount - - $enabledCount = ($computers | Where-Object { $_.Enabled -eq $true } | Measure-Object).Count - $totalCount = ($computers | Measure-Object).Count - - # Test passes if we successfully retrieved computer data - $testResult = $totalCount -gt 0 - - # Generate markdown results - if ($testResult) { - $delegationPercentage = if ($enabledCount -gt 0) { - [Math]::Round(($totalDelegationCount / $enabledCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Computers | $totalCount |" + "`n" - $result += "| Enabled Computers | $enabledCount |" + "`n" - $result += "| Computers with Any Delegation | $totalDelegationCount |" + "`n" - $result += "| Unconstrained Delegation | $unconstrainedCount |" + "`n" - $result += "| Constrained/Protocol Transition | $constrainedCount |" + "`n" - $result += "| Delegation Percentage | $delegationPercentage% |" + "`n" + "`n" - - $testResultMarkdown = "Active Directory computer objects have been analyzed. $totalDelegationCount out of $enabledCount enabled computers ($delegationPercentage%) have delegation configured.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory computer objects. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult -} diff --git a/tests/ad/computer/Test.AD-COMP-10.md b/tests/ad/computer/Test.AD-COMP-10.md deleted file mode 100644 index f6f39b59a9..0000000000 --- a/tests/ad/computer/Test.AD-COMP-10.md +++ /dev/null @@ -1,38 +0,0 @@ -Detailed visibility into Kerberos delegation configurations is essential for security because: - -- **Risk prioritization**: Unconstrained delegation poses significantly higher risk than constrained delegation -- **Attack path analysis**: Understanding delegation relationships helps identify potential lateral movement paths -- **Compliance requirements**: Many security frameworks require documentation of delegation configurations -- **Incident response**: Knowing which systems have delegation helps during security investigations - -Computers with unconstrained delegation should be treated as high-value targets requiring enhanced monitoring and protection. - -#### Control Type - -**Detective** - -#### Security Recommendation - -For each computer with delegation enabled: - -1. **Verify necessity**: Confirm the delegation is required for business operations -2. **Minimize scope**: Replace unconstrained with constrained delegation where possible -3. **Implement tiering**: Ensure tier 0 systems (Domain Controllers) never have unconstrained delegation -4. **Monitor closely**: Systems with delegation should have enhanced logging and monitoring -5. **Document exceptions**: Maintain a registry of systems requiring delegation with business justifications -6. **Regular review**: Quarterly review of delegation configurations - -#### How the Test Works - -This test provides a detailed breakdown of: -- Computers with unconstrained delegation (highest risk) -- Computers with constrained delegation and protocol transition -- Per-computer details including name, enabled status, and distinguished name - -#### Related Tests - -- `Test-MtAdComputerDelegationCount` - Provides summary counts of delegation -- `Test-MtAdComputerDormantCount` - Identifies stale accounts that may have delegation - - -%TestResult% diff --git a/tests/ad/computer/Test.AD-COMP-10.ps1 b/tests/ad/computer/Test.AD-COMP-10.ps1 deleted file mode 100644 index 53ad07d2b6..0000000000 --- a/tests/ad/computer/Test.AD-COMP-10.ps1 +++ /dev/null @@ -1,125 +0,0 @@ -function Test-MtAdComputerDelegationDetails { - <# - .SYNOPSIS - Provides detailed breakdown of delegation configuration per computer. - - .DESCRIPTION - This test provides a detailed analysis of Kerberos delegation configuration - across computer objects in Active Directory. It identifies: - - Computers with unconstrained delegation (full trust) - - Computers with constrained delegation (limited to specific services) - - Computers with protocol transition (S4U2Proxy) - - This detailed view helps security teams identify high-risk delegation - configurations that may need review or remediation. - - .EXAMPLE - Test-MtAdComputerDelegationDetails - - Returns $true if computer object data is accessible, $false otherwise. - The test result includes a detailed breakdown of delegation by computer. - - .LINK - https://maester.dev/docs/commands/Test-MtAdComputerDelegationDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using Details')] - [MaesterTest( - Id = 'AD-COMP-10', - Title = 'Computer delegation details should be retrievable', - Product = 'ad', - Feature = 'computers', - Area = 'authentication', - ResourceType = 'Computer', - Severity = 'Info', - Mitre = ('T1558', 'T1550.003'), - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:computer:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdComputerDelegationDetails" - - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('Computers') - - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $computers = $adState.Computers - - # Get computers with delegation - $computersWithUnconstrained = $computers | Where-Object { - $_.TrustedForDelegation -eq $true - } | Select-Object Name, DistinguishedName, Enabled, @{N = 'DelegationType'; E = { 'Unconstrained' } } - - $computersWithConstrained = $computers | Where-Object { - $_.TrustedToAuthForDelegation -eq $true - } | Select-Object Name, DistinguishedName, Enabled, @{N = 'DelegationType'; E = { 'Constrained/Protocol Transition' } } - - $allDelegationComputers = @($computersWithUnconstrained) + @($computersWithConstrained) - - $unconstrainedCount = ($computersWithUnconstrained | Measure-Object).Count - $constrainedCount = ($computersWithConstrained | Measure-Object).Count - $totalDelegationCount = $allDelegationComputers.Count - - $enabledCount = ($computers | Where-Object { $_.Enabled -eq $true } | Measure-Object).Count - $totalCount = ($computers | Measure-Object).Count - - # Test passes if we successfully retrieved computer data - $testResult = $totalCount -gt 0 - - # Generate markdown results - if ($testResult) { - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Computers | $totalCount |" + "`n" - $result += "| Enabled Computers | $enabledCount |" + "`n" - $result += "| Computers with Any Delegation | $totalDelegationCount |" + "`n" - $result += "| Unconstrained Delegation | $unconstrainedCount |" + "`n" - $result += "| Constrained/Protocol Transition | $constrainedCount |" + "`n" + "`n" - - if ($unconstrainedCount -gt 0) { - $result += "**Computers with Unconstrained Delegation (High Risk):**" + "`n" + "`n" - $result += "| Computer Name | Enabled | Distinguished Name |" + "`n" - $result += "| --- | --- | --- |" + "`n" - $computersWithUnconstrained | Select-Object -First 20 | ForEach-Object { - $result += "| $($_.Name) | $($_.Enabled) | $($_.DistinguishedName) |" + "`n" - } - if ($unconstrainedCount -gt 20) { - $result += "| ... | ... | ... ($($unconstrainedCount - 20) more) |" + "`n" - } - $result += "" + "`n" - } - - if ($constrainedCount -gt 0) { - $result += "**Computers with Constrained Delegation:**" + "`n" + "`n" - $result += "| Computer Name | Enabled | Distinguished Name |" + "`n" - $result += "| --- | --- | --- |" + "`n" - $computersWithConstrained | Select-Object -First 20 | ForEach-Object { - $result += "| $($_.Name) | $($_.Enabled) | $($_.DistinguishedName) |" + "`n" - } - if ($constrainedCount -gt 20) { - $result += "| ... | ... | ... ($($constrainedCount - 20) more) |" + "`n" - } - } - - $testResultMarkdown = "Active Directory computer delegation configuration has been analyzed. $totalDelegationCount computers have delegation configured.`n`n%TestResult%" - if ($totalCount -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", "" - } - } else { - $testResultMarkdown = "Unable to retrieve Active Directory computer objects. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult -} diff --git a/tests/ad/security/Test.AD-DCOMP-01.md b/tests/ad/security/Test.AD-DCOMP-01.md index 75f394737b..7cc00b0047 100644 --- a/tests/ad/security/Test.AD-DCOMP-01.md +++ b/tests/ad/security/Test.AD-DCOMP-01.md @@ -1,4 +1,4 @@ -- Unconstrained delegation is one of the most dangerous configurations in Active Directory. When enabled on a computer, it allows services on that computer to impersonate authenticated users to ANY service on ANY computer in the domain. +Unconstrained delegation on non-domain-controller computers exposes users' Kerberos tickets to any attacker who compromises the computer. This check fails when one or more non-DC computers have the `TrustedForDelegation` flag. DCs are counted separately but do not cause failure; percentages use only non-DC computers as the denominator. **Security Risks:** - **Complete Impersonation**: Attackers can impersonate any user who authenticates to the computer @@ -35,8 +35,7 @@ This test counts computers with the `TrustedForDelegation` flag enabled and cate #### Related Tests -- `Test-MtAdComputerNonDcUnconstrainedDelegationCount` - Focuses on non-DC computers (critical risk) -- `Test-MtAdComputerNonDcConstrainedDelegationCount` - Reviews constrained delegation +- `AD-DCOMP-03` - Reviews protocol transition on non-DC computers - `Test-MtAdUserDelegationConfiguredCount` - Reviews user account delegation #### Related links diff --git a/tests/ad/security/Test.AD-DCOMP-01.ps1 b/tests/ad/security/Test.AD-DCOMP-01.ps1 index e8c8533af8..4300de37bc 100644 --- a/tests/ad/security/Test.AD-DCOMP-01.ps1 +++ b/tests/ad/security/Test.AD-DCOMP-01.ps1 @@ -5,8 +5,8 @@ .DESCRIPTION Unconstrained delegation allows a service to impersonate a user to any other service. - This is a high-risk configuration that should be minimized. This test counts all - computers (including domain controllers) that have unconstrained delegation enabled. + This is a high-risk configuration on non-domain-controller computers. Domain + controllers are reported separately but excluded from the assessed population. Security Risk: - Unconstrained delegation allows full impersonation of authenticated users @@ -24,13 +24,16 @@ #> [MaesterTest( Id = 'AD-DCOMP-01', - Title = 'Computers with unconstrained delegation count should be investigated', + Title = 'Non-DC computers should not have unconstrained delegation', Product = 'ad', Feature = 'computers', Area = 'authentication', ResourceType = 'Computer', - Severity = 'Info', + Severity = 'High', + UserImpact = 'Low', + ImplementationCost = 'Medium', Mitre = ('T1558', 'T1550.003'), + Control = 'nist-800-53-r5:AC-6', Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:computer:ReadProperty', 'ActiveDirectory:Ldap:nTDSDSA:ReadProperty'), Author = 'soulemike' @@ -43,28 +46,47 @@ $adState = Get-MtADDomainState -Categories @('Computers', 'DomainControllers') Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $adState -or $null -eq $adState.Computers -or $null -eq $adState.DomainControllers) { + throw 'Computer and domain controller inventories are required to assess unconstrained delegation.' } Write-Verbose "Filtering/counting computer unconstrained delegation count" $computers = $adState.Computers $domainControllers = $adState.DomainControllers + if (@($computers).Count -eq 0 -or @($domainControllers).Count -eq 0) { + throw 'Computer and domain controller inventories must not be empty when assessing delegation.' + } - # Get list of DC names for reference - $dcNames = $domainControllers | ForEach-Object { $_.Name } + # DCs are identified by primary group, serverReference DN or matching DNS + # host name. Name alone is used only when the DC has neither reference nor DNS. + $dcReferences = @($domainControllers | Where-Object { $_.ServerReference } | ForEach-Object { $_.ServerReference }) + $dcDnsNames = @($domainControllers | Where-Object { $_.DnsHostName } | ForEach-Object { $_.DnsHostName }) + $dcWithoutReference = @($domainControllers | Where-Object { -not $_.ServerReference }) + $nonDcComputers = @($computers | Where-Object { + $computer = $_ + $isDc = $computer.PrimaryGroupId -in @(516, 521) -or $dcReferences -contains $computer.DistinguishedName + if (-not $isDc -and $computer.DnsHostName) { $isDc = $dcDnsNames -contains $computer.DnsHostName } + if (-not $isDc -and -not $computer.DnsHostName -and $computer.Name) { + $isDc = @($dcWithoutReference | Where-Object { -not $_.DnsHostName -and $_.Name -eq $computer.Name }).Count -gt 0 + } + -not $isDc + }) + if (@($nonDcComputers | Where-Object { $null -eq $_.TrustedForDelegation }).Count -gt 0) { + throw 'Unconstrained delegation flag is missing for non-DC computers.' + } # Find computers with unconstrained delegation $unconstrainedComputers = $computers | Where-Object { $_.TrustedForDelegation -eq $true } $unconstrainedCount = ($unconstrainedComputers | Measure-Object).Count # Count DCs vs non-DCs with unconstrained delegation - $dcUnconstrainedCount = ($unconstrainedComputers | Where-Object { $dcNames -contains $_.Name } | Measure-Object).Count - $nonDcUnconstrainedCount = $unconstrainedCount - $dcUnconstrainedCount + $nonDcUnconstrained = @($nonDcComputers | Where-Object { $_.TrustedForDelegation -eq $true }) + $dcUnconstrainedCount = $unconstrainedCount - $nonDcUnconstrained.Count + $nonDcUnconstrainedCount = $nonDcUnconstrained.Count - $totalComputers = ($computers | Measure-Object).Count - $testResult = $true + $totalComputers = @($computers).Count + $totalNonDcComputers = $nonDcComputers.Count + $testResult = $nonDcUnconstrainedCount -eq 0 $result = "| Metric | Value |" + "`n" $result += "| --- | --- |" + "`n" @@ -72,17 +94,24 @@ $result += "| Computers with Unconstrained Delegation | $unconstrainedCount |" + "`n" $result += "| Domain Controllers with Unconstrained Delegation | $dcUnconstrainedCount |" + "`n" $result += "| Non-DC Computers with Unconstrained Delegation | $nonDcUnconstrainedCount |" + "`n" - - if ($unconstrainedCount -gt 0) { - $percentage = [Math]::Round(($unconstrainedCount / $totalComputers) * 100, 2) - $result += "| Percentage with Unconstrained Delegation | $percentage% |" + "`n" + $result += "| Total Non-DC Computers | $totalNonDcComputers |" + "`n" + $percentage = if ($totalNonDcComputers -gt 0) { [Math]::Round(($nonDcUnconstrainedCount / $totalNonDcComputers) * 100, 2) } else { 0 } + $result += "| Non-DC Percentage with Unconstrained Delegation | $percentage% |" + "`n" + if (-not $testResult) { + $result += "`n| Non-DC Computer | Operating System |`n| --- | --- |`n" + foreach ($computer in @($nonDcUnconstrained | Select-Object -First 10)) { + $name = [string]$computer.Name -replace '\|', '\|' -replace '[\r\n]', ' ' + $os = [string]$computer.OperatingSystem -replace '\|', '\|' -replace '[\r\n]', ' ' + $result += "| $name | $os |`n" + } } Write-Verbose "Counts computed" - $testResultMarkdown = "Computers with unconstrained delegation have been identified. This configuration allows services to impersonate users to any service.`n`n%TestResult%" + $summary = if ($testResult) { 'Well done. No non-DC computers have unconstrained delegation.' } else { 'Non-DC computers with unconstrained delegation were found. Migrate their services to constrained delegation and remove unconstrained delegation.' } + $testResultMarkdown = "$summary`n`n%TestResult%" $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate + Add-MtTestResultDetail -Result $testResultMarkdown Write-Verbose "Completed Test-MtAdComputerUnconstrainedDelegationCount" return $testResult diff --git a/tests/ad/security/Test.AD-DCOMP-02.md b/tests/ad/security/Test.AD-DCOMP-02.md deleted file mode 100644 index 921198ffbf..0000000000 --- a/tests/ad/security/Test.AD-DCOMP-02.md +++ /dev/null @@ -1,53 +0,0 @@ -- Non-domain controller computers with unconstrained delegation represent a **CRITICAL** security vulnerability. While domain controllers may have legitimate reasons for unconstrained delegation in certain legacy scenarios, regular computers should **NEVER** have this configuration. - -**Critical Security Risks:** -- **Domain Compromise**: A single compromised computer with unconstrained delegation can lead to full domain compromise -- **Unrestricted Impersonation**: Any service on the computer can impersonate any domain user to any service -- **Attack Vector**: Common target for attackers seeking to escalate privileges -- **Stealthy Access**: Can be exploited without triggering typical security alerts - -**The target count for this test should ALWAYS be ZERO.** - -#### Control Type - -**Detective** - -#### Security Recommendation - -1. **Immediate Action Required**: - - Identify all non-DC computers with unconstrained delegation - - Remove unconstrained delegation immediately - - Investigate why it was configured - -2. **Replace with secure alternatives**: - - **Constrained Delegation**: Limit to specific required services - - **Resource-Based Constrained Delegation**: Modern, flexible approach - - **Managed Service Accounts**: Use gMSAs where possible - -3. **Audit and Monitor**: - - Regular audits of delegation settings - - Alert on any new unconstrained delegation configurations - - Review applications requiring delegation - -#### How the Test Works - -This test specifically identifies non-DC computers with the `TrustedForDelegation` flag enabled and reports: -- Count of affected computers -- Computer names and operating systems -- Compliance status (should be zero) - -**Pass Criteria**: Zero non-DC computers with unconstrained delegation - -#### Related Tests - -- `Test-MtAdComputerUnconstrainedDelegationCount` - Overall unconstrained delegation count -- `Test-MtAdComputerNonDcConstrainedDelegationCount` - Reviews constrained delegation on non-DCs -- `Test-MtAdComputerDelegationCount` - General delegation overview - -#### Related links - -- [Microsoft Defender for Identity: Unsecure Kerberos delegation](https://learn.microsoft.com/defender-for-identity/security-posture-assessments/accounts#unsecure-kerberos-delegation) -- [ANSSI Active Directory checkpoints: Unconstrained authentication delegation](https://www.cert.ssi.gouv.fr/uploads/ad_checklist.html#vuln_delegation_t4d) - - -%TestResult% diff --git a/tests/ad/security/Test.AD-DCOMP-02.ps1 b/tests/ad/security/Test.AD-DCOMP-02.ps1 deleted file mode 100644 index 52d41c13ee..0000000000 --- a/tests/ad/security/Test.AD-DCOMP-02.ps1 +++ /dev/null @@ -1,98 +0,0 @@ -function Test-MtAdComputerNonDcUnconstrainedDelegationCount { - <# - .SYNOPSIS - Counts non-domain controller computers with unconstrained delegation. - - .DESCRIPTION - Non-DC computers with unconstrained delegation represent a significant security risk. - While domain controllers may require unconstrained delegation for certain scenarios, - regular computers should never have this configuration. This test specifically - identifies non-DC computers with unconstrained delegation enabled. - - Security Risk: - - Non-DC computers with unconstrained delegation are a critical vulnerability - - Compromise of such a computer allows attackers to impersonate any domain user - - This configuration should be eliminated in favor of constrained delegation - - Zero non-DC computers should have unconstrained delegation - - .EXAMPLE - Test-MtAdComputerNonDcUnconstrainedDelegationCount - - Returns $true if no non-DC computers have unconstrained delegation (or if data is accessible). - - .LINK - https://maester.dev/docs/commands/Test-MtAdComputerNonDcUnconstrainedDelegationCount - #> - [MaesterTest( - Id = 'AD-DCOMP-02', - Title = 'Non-DC computers should not have unconstrained delegation', - Product = 'ad', - Feature = 'computers', - Area = 'authentication', - ResourceType = 'Computer', - Severity = 'High', - UserImpact = 'Low', - ImplementationCost = 'Medium', - Mitre = ('T1558', 'T1550.003'), - Control = 'nist-800-53-r5:AC-6', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:computer:ReadProperty', 'ActiveDirectory:Ldap:nTDSDSA:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdComputerNonDcUnconstrainedDelegationCount" - $adState = Get-MtADDomainState -Categories @('Computers', 'DomainControllers') - Write-Verbose "Retrieved AD state" - - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting computer non dc unconstrained delegation count" - - $computers = $adState.Computers - $domainControllers = $adState.DomainControllers - - # Get list of DC names - $dcNames = $domainControllers | ForEach-Object { $_.Name } - - # Find non-DC computers with unconstrained delegation - $nonDcComputers = $computers | Where-Object { $dcNames -notcontains $_.Name } - $nonDcUnconstrained = $nonDcComputers | Where-Object { $_.TrustedForDelegation -eq $true } - $nonDcUnconstrainedCount = ($nonDcUnconstrained | Measure-Object).Count - - $totalNonDcComputers = ($nonDcComputers | Measure-Object).Count - - # Test passes if no non-DC computers have unconstrained delegation - $testResult = ($nonDcUnconstrainedCount -eq 0) - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Non-DC Computers | $totalNonDcComputers |" + "`n" - $result += "| Non-DC Computers with Unconstrained Delegation | $nonDcUnconstrainedCount |" + "`n" - $result += "| Status | $(if ($testResult) { 'PASS - No non-DC computers with unconstrained delegation' } else { 'FAIL - Non-DC computers have unconstrained delegation' }) |" + "`n" - - if ($nonDcUnconstrainedCount -gt 0) { - $result += "`n**Non-DC Computers with Unconstrained Delegation:**" + "`n" + "`n" - $result += "| Computer Name | Operating System |" + "`n" - $result += "| --- | --- |" + "`n" - foreach ($comp in $nonDcUnconstrained | Select-Object -First 10) { - $result += "| $($comp.Name) | $($comp.operatingSystem) |" + "`n" - } - if ($nonDcUnconstrainedCount -gt 10) { - $result += "| ... and $($nonDcUnconstrainedCount - 10) more | |" + "`n" - } - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "Non-DC computers with unconstrained delegation represent a critical security risk and should be eliminated.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdComputerNonDcUnconstrainedDelegationCount" - - return $testResult -} diff --git a/tests/ad/security/Test.AD-DCOMP-03.md b/tests/ad/security/Test.AD-DCOMP-03.md index 045ef63a51..0acfe0b134 100644 --- a/tests/ad/security/Test.AD-DCOMP-03.md +++ b/tests/ad/security/Test.AD-DCOMP-03.md @@ -1,4 +1,4 @@ -- Constrained delegation (also known as "protocol transition" or S4U2Proxy) is safer than unconstrained delegation but still carries security risks. It allows a service to impersonate a user to specific services only, rather than any service in the domain. +This check inventories three separate indicators on non-domain-controller computer accounts: classic Kerberos constrained delegation (KCD) target SPNs from `msDS-AllowedToDelegateTo`, the `TrustedToAuthForDelegation` protocol-transition flag, and **presence** of an `msDS-AllowedToActOnBehalfOfOtherIdentity` resource-based constrained delegation (RBCD) descriptor. One computer can have multiple indicators. Descriptor presence neither identifies allowed principals nor proves effective delegation permissions. **Security Considerations:** - **Limited Scope**: Safer than unconstrained but still enables impersonation @@ -29,14 +29,11 @@ #### How the Test Works -This test counts non-DC computers with the `TrustedToAuthForDelegation` flag enabled, which indicates: -- Constrained delegation is configured -- Protocol transition may be enabled +The test reports separate non-DC counts for KCD target SPNs, protocol transition and RBCD descriptor presence, plus a deduplicated count and a sample of computers and KCD targets for review. A protocol-transition flag alone does not prove that a classic KCD target is configured. A present RBCD descriptor needs a separate permissions review; this test cannot resolve principals or effective access. Delegation on user or managed service accounts is outside this computer inventory. #### Related Tests - `Test-MtAdComputerUnconstrainedDelegationCount` - Overall unconstrained delegation -- `Test-MtAdComputerNonDcUnconstrainedDelegationCount` - Critical non-DC unconstrained delegation - `Test-MtAdUserDelegationConfiguredCount` - User account delegation settings #### Related links diff --git a/tests/ad/security/Test.AD-DCOMP-03.ps1 b/tests/ad/security/Test.AD-DCOMP-03.ps1 index e96f4ff665..e91440cdab 100644 --- a/tests/ad/security/Test.AD-DCOMP-03.ps1 +++ b/tests/ad/security/Test.AD-DCOMP-03.ps1 @@ -4,10 +4,11 @@ Counts non-domain controller computers with constrained delegation configured. .DESCRIPTION - Constrained delegation (also known as "protocol transition" or "S4U2Proxy") - allows a service to impersonate a user to specific services only. While safer - than unconstrained delegation, it should still be carefully reviewed and minimized. - This test identifies non-DC computers with constrained delegation enabled. + Inventories classic Kerberos constrained delegation target SPNs, the + TrustedToAuthForDelegation protocol-transition flag, and presence of an RBCD + security descriptor on non-DC computer objects. RBCD presence does not + identify allowed principals or establish effective access. These categories + can overlap and do not include delegation configured on user accounts. Security Considerations: - Constrained delegation is safer than unconstrained but still carries risk @@ -18,14 +19,14 @@ .EXAMPLE Test-MtAdComputerNonDcConstrainedDelegationCount - Returns $true if computer data is accessible. + Reports an Investigate inventory when the required computer fields are available. .LINK https://maester.dev/docs/commands/Test-MtAdComputerNonDcConstrainedDelegationCount #> [MaesterTest( Id = 'AD-DCOMP-03', - Title = 'Non-DC computers with constrained delegation count should be investigated', + Title = 'Non-DC computer constrained delegation should be investigated', Product = 'ad', Feature = 'computers', Area = 'authentication', @@ -44,59 +45,80 @@ $adState = Get-MtADDomainState -Categories @('Computers', 'DomainControllers') Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $adState -or $null -eq $adState.Computers -or $null -eq $adState.DomainControllers) { + throw 'Computer and domain controller inventories are required to review constrained delegation.' } Write-Verbose "Filtering/counting computer non dc constrained delegation count" $computers = $adState.Computers $domainControllers = $adState.DomainControllers + if (@($computers).Count -eq 0 -or @($domainControllers).Count -eq 0) { + throw 'Computer and domain controller inventories must not be empty when reviewing constrained delegation.' + } - # Get list of DC names - $dcNames = $domainControllers | ForEach-Object { $_.Name } - - # Find non-DC computers with constrained delegation - $nonDcComputers = $computers | Where-Object { $dcNames -notcontains $_.Name } - $nonDcConstrained = $nonDcComputers | Where-Object { $_.TrustedToAuthForDelegation -eq $true } - $nonDcConstrainedCount = ($nonDcConstrained | Measure-Object).Count - - # Also check for computers with both types of delegation - $nonDcBoth = $nonDcComputers | Where-Object { $_.TrustedToAuthForDelegation -eq $true -and $_.TrustedForDelegation -eq $true } - $nonDcBothCount = ($nonDcBoth | Measure-Object).Count + # Match DC computer DNs to serverReference first. The primary group also + # identifies writable DCs (516) and RODCs (521). DNS names also identify + # DCs; a name alone is used only when the DC has no reference or DNS name. + $dcReferences = @($domainControllers | Where-Object { $_.ServerReference } | ForEach-Object { $_.ServerReference }) + $dcDnsNames = @($domainControllers | Where-Object { $_.DnsHostName } | ForEach-Object { $_.DnsHostName }) + $dcWithoutReference = @($domainControllers | Where-Object { -not $_.ServerReference }) + $nonDcComputers = @($computers | Where-Object { + $computer = $_ + $isDc = $computer.PrimaryGroupId -in @(516, 521) -or $dcReferences -contains $computer.DistinguishedName + if (-not $isDc -and $computer.DnsHostName) { $isDc = $dcDnsNames -contains $computer.DnsHostName } + if (-not $isDc -and -not $computer.DnsHostName -and $computer.Name) { + $isDc = @($dcWithoutReference | Where-Object { -not $_.DnsHostName -and $_.Name -eq $computer.Name }).Count -gt 0 + } + -not $isDc + }) + if (@($nonDcComputers | Where-Object { + -not $_.PSObject.Properties['AllowedToDelegateTo'] -or $null -eq $_.AllowedToDelegateTo -or + -not $_.PSObject.Properties['HasResourceBasedConstrainedDelegation'] -or $null -eq $_.HasResourceBasedConstrainedDelegation -or + -not $_.PSObject.Properties['TrustedToAuthForDelegation'] -or $null -eq $_.TrustedToAuthForDelegation + }).Count -gt 0) { + throw 'Required delegation fields are missing from the non-DC computer inventory; a zero count cannot be trusted.' + } - $totalNonDcComputers = ($nonDcComputers | Measure-Object).Count - $testResult = $true + $classicKcd = @($nonDcComputers | Where-Object { @($_.AllowedToDelegateTo).Count -gt 0 }) + $protocolTransition = @($nonDcComputers | Where-Object { $_.TrustedToAuthForDelegation -eq $true }) + $rbcdPresent = @($nonDcComputers | Where-Object { $_.HasResourceBasedConstrainedDelegation -eq $true }) + $reviewComputers = @($nonDcComputers | Where-Object { + @($_.AllowedToDelegateTo).Count -gt 0 -or $_.TrustedToAuthForDelegation -eq $true -or $_.HasResourceBasedConstrainedDelegation -eq $true + }) + $totalNonDcComputers = $nonDcComputers.Count $result = "| Metric | Value |" + "`n" $result += "| --- | --- |" + "`n" $result += "| Total Non-DC Computers | $totalNonDcComputers |" + "`n" - $result += "| Non-DC Computers with Constrained Delegation | $nonDcConstrainedCount |" + "`n" - $result += "| Non-DC Computers with Both Delegation Types | $nonDcBothCount |" + "`n" - - if ($nonDcConstrainedCount -gt 0) { - $percentage = [Math]::Round(($nonDcConstrainedCount / $totalNonDcComputers) * 100, 2) - $result += "| Percentage with Constrained Delegation | $percentage% |" + "`n" + $result += "| Non-DC Computers with Classic KCD Target SPNs | $($classicKcd.Count) |`n" + $result += "| Non-DC Computers with Protocol Transition Flag | $($protocolTransition.Count) |`n" + $result += "| Non-DC Computers with RBCD Descriptor Present | $($rbcdPresent.Count) |`n" + $result += "| Distinct Non-DC Computers with One or More Indicators | $($reviewComputers.Count) |`n" + if ($totalNonDcComputers -gt 0) { + $percentage = [Math]::Round(($reviewComputers.Count / $totalNonDcComputers) * 100, 2) + $result += "| Percentage of Non-DC Computers with an Indicator | $percentage% |`n" } - if ($nonDcConstrainedCount -gt 0) { - $result += "`n**Non-DC Computers with Constrained Delegation:**" + "`n" + "`n" - $result += "| Computer Name | Operating System |" + "`n" - $result += "| --- | --- |" + "`n" - foreach ($comp in $nonDcConstrained | Select-Object -First 10) { - $result += "| $($comp.Name) | $($comp.operatingSystem) |" + "`n" + if ($reviewComputers.Count -gt 0) { + $result += "`n**Non-DC Computers to Review (Top 10):**`n`n" + $result += "| Computer | Classic KCD Target SPNs | Protocol Transition Flag | RBCD Descriptor Present |`n| --- | --- | --- | --- |`n" + foreach ($computer in $reviewComputers | Select-Object -First 10) { + $name = [string]$computer.Name -replace '\|', '\|' -replace '[\r\n]', ' ' + $spns = [string](@($computer.AllowedToDelegateTo) -join ', ') -replace '\|', '\|' -replace '[\r\n]', ' ' + if (-not $spns) { $spns = 'None' } + $result += "| $name | $spns | $($computer.TrustedToAuthForDelegation) | $($computer.HasResourceBasedConstrainedDelegation) |`n" } - if ($nonDcConstrainedCount -gt 10) { - $result += "| ... and $($nonDcConstrainedCount - 10) more | |" + "`n" + if ($reviewComputers.Count -gt 10) { + $result += "| ... and $($reviewComputers.Count - 10) more | | | |`n" } } Write-Verbose "Counts computed" - $testResultMarkdown = "Non-DC computers with constrained delegation have been identified. These should be reviewed to ensure they are necessary and properly configured.`n`n%TestResult%" + $testResultMarkdown = "Review non-DC classic KCD target SPNs, protocol transition and RBCD descriptor presence. RBCD presence does not identify allowed principals or prove effective access; categories can overlap.`n`n%TestResult%" $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result Add-MtTestResultDetail -Result $testResultMarkdown -Investigate Write-Verbose "Completed Test-MtAdComputerNonDcConstrainedDelegationCount" - return $testResult + return $true } From 9d1b59b9bd8eb0f14f2ba74c4f876660b8836316 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 06:23:26 +0000 Subject: [PATCH 012/100] refactor(ad): consolidate computer OS DNS and dormancy checks --- .../functions/ADComputerChecks.Tests.ps1 | 123 ++++++++++++++++++ .../functions/ActiveDirectoryIssues.Tests.ps1 | 10 +- tests/ad/computer/Test.AD-COMP-02.md | 34 ----- tests/ad/computer/Test.AD-COMP-02.ps1 | 111 ---------------- tests/ad/security/Test.AD-DCOMP-04.md | 2 +- tests/ad/security/Test.AD-DCOMP-04.ps1 | 15 ++- tests/ad/security/Test.AD-DCOMP-05.md | 50 ------- tests/ad/security/Test.AD-DCOMP-05.ps1 | 98 -------------- tests/ad/security/Test.AD-DCOMP-06.md | 2 +- tests/ad/security/Test.AD-DCOMP-06.ps1 | 22 ++-- tests/ad/security/Test.AD-DCOMP-07.md | 2 +- tests/ad/security/Test.AD-DCOMP-07.ps1 | 9 +- tests/ad/security/Test.AD-DCOMP-08.md | 2 +- tests/ad/security/Test.AD-DCOMP-08.ps1 | 36 ++--- tests/ad/security/Test.AD-DCOMP-09.md | 51 -------- tests/ad/security/Test.AD-DCOMP-09.ps1 | 122 ----------------- 16 files changed, 169 insertions(+), 520 deletions(-) create mode 100644 powershell/tests/functions/ADComputerChecks.Tests.ps1 delete mode 100644 tests/ad/computer/Test.AD-COMP-02.md delete mode 100644 tests/ad/computer/Test.AD-COMP-02.ps1 delete mode 100644 tests/ad/security/Test.AD-DCOMP-05.md delete mode 100644 tests/ad/security/Test.AD-DCOMP-05.ps1 delete mode 100644 tests/ad/security/Test.AD-DCOMP-09.md delete mode 100644 tests/ad/security/Test.AD-DCOMP-09.ps1 diff --git a/powershell/tests/functions/ADComputerChecks.Tests.ps1 b/powershell/tests/functions/ADComputerChecks.Tests.ps1 new file mode 100644 index 0000000000..a8344ea29b --- /dev/null +++ b/powershell/tests/functions/ADComputerChecks.Tests.ps1 @@ -0,0 +1,123 @@ +Describe 'Active Directory computer inventory checks' { + BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name @( + 'Test-MtAdComputerUnconstrainedDelegationCount' + 'Test-MtAdComputerNonDcConstrainedDelegationCount' + 'Test-MtAdComputerOperatingSystemCount' + 'Test-MtAdComputerPerOUAverage' + 'Test-MtAdComputerCreatorSidCount' + 'Test-MtAdComputerInDefaultContainer' + ) + } + + BeforeEach { + $script:Details = $null + $script:AdComputerState = [PSCustomObject]@{ + Computers = @( + [PSCustomObject]@{ Name = 'dc1'; DistinguishedName = 'CN=dc1,OU=Domain Controllers,DC=example,DC=com'; DnsHostName = 'dc1.example.com'; PrimaryGroupId = 516; Enabled = $true; TrustedForDelegation = $true; TrustedToAuthForDelegation = $false; AllowedToDelegateTo = @(); HasResourceBasedConstrainedDelegation = $false; OperatingSystem = 'Server' } + [PSCustomObject]@{ Name = 'app|one'; DistinguishedName = 'CN=app\,one,OU=Servers|Prod,DC=example,DC=com'; DnsHostName = 'app.example.com'; PrimaryGroupId = 515; Enabled = $true; TrustedForDelegation = $false; TrustedToAuthForDelegation = $true; AllowedToDelegateTo = @('HTTP/backend|one'); HasResourceBasedConstrainedDelegation = $true; OperatingSystem = '' } + [PSCustomObject]@{ Name = 'client'; DistinguishedName = 'CN=client,OU=Clients,DC=example,DC=com'; DnsHostName = 'client.example.com'; PrimaryGroupId = 515; Enabled = $true; TrustedForDelegation = $false; TrustedToAuthForDelegation = $false; AllowedToDelegateTo = @(); HasResourceBasedConstrainedDelegation = $false; OperatingSystem = 'Client' } + ) + DomainControllers = @([PSCustomObject]@{ Name = 'dc1'; ServerReference = 'CN=dc1,OU=Domain Controllers,DC=example,DC=com'; DnsHostName = 'dc1.example.com' }) + } + Mock -ModuleName Maester Get-MtADDomainState { $script:AdComputerState } + Mock -ModuleName Maester Add-MtTestResultDetail { param($Result, [switch] $Investigate) $script:Details = [PSCustomObject]@{ Text = $Result; Investigate = $Investigate.IsPresent } } + } + + It 'excludes DCs and uses only non-DC computers as the unconstrained percentage denominator' { + Test-MtAdComputerUnconstrainedDelegationCount | Should -BeTrue + $script:Details.Text | Should -BeLike '*| Total Non-DC Computers | 2 |*' + $script:Details.Text | Should -BeLike '*| Non-DC Percentage with Unconstrained Delegation | 0% |*' + + $script:AdComputerState.Computers[1].TrustedForDelegation = $true + Test-MtAdComputerUnconstrainedDelegationCount | Should -BeFalse + $script:Details.Text | Should -BeLike '*| Non-DC Percentage with Unconstrained Delegation | 50% |*' + $script:Details.Text | Should -Match 'app\\\|one' + } + + It 'inventories classic KCD, protocol transition, and RBCD descriptor presence independently' { + Test-MtAdComputerNonDcConstrainedDelegationCount | Should -BeTrue + $script:Details.Investigate | Should -BeTrue + $script:Details.Text | Should -BeLike '*| Non-DC Computers with Classic KCD Target SPNs | 1 |*' + $script:Details.Text | Should -BeLike '*| Non-DC Computers with Protocol Transition Flag | 1 |*' + $script:Details.Text | Should -BeLike '*| Non-DC Computers with RBCD Descriptor Present | 1 |*' + $script:Details.Text | Should -BeLike '*| Distinct Non-DC Computers with One or More Indicators | 1 |*' + $script:Details.Text | Should -Match 'HTTP/backend\\\|one' + + $script:AdComputerState.Computers[1].TrustedToAuthForDelegation = $false + $script:AdComputerState.Computers[2].HasResourceBasedConstrainedDelegation = $true + Test-MtAdComputerNonDcConstrainedDelegationCount | Should -BeTrue + $script:Details.Text | Should -BeLike '*| Non-DC Computers with Classic KCD Target SPNs | 1 |*' + $script:Details.Text | Should -BeLike '*| Non-DC Computers with Protocol Transition Flag | 0 |*' + $script:Details.Text | Should -BeLike '*| Non-DC Computers with RBCD Descriptor Present | 2 |*' + $script:Details.Text | Should -BeLike '*| Distinct Non-DC Computers with One or More Indicators | 2 |*' + } + + It 'does not treat missing delegation metadata as a clean result' { + $script:AdComputerState.Computers[1].PSObject.Properties.Remove('AllowedToDelegateTo') + { Test-MtAdComputerNonDcConstrainedDelegationCount } | Should -Throw '*Required delegation fields*' + $script:AdComputerState.Computers[1].TrustedForDelegation = $null + { Test-MtAdComputerUnconstrainedDelegationCount } | Should -Throw '*flag is missing*' + } + + It 'does not treat unknown RBCD descriptor presence as false' { + $script:AdComputerState.Computers[1].HasResourceBasedConstrainedDelegation = $null + { Test-MtAdComputerNonDcConstrainedDelegationCount } | Should -Throw '*Required delegation fields*' + } + + It 'excludes RODCs by primary group and DCs by DNS identity rather than a matching short name' { + $script:AdComputerState.Computers += [PSCustomObject]@{ Name = 'rodc-other'; DistinguishedName = 'CN=rodc-other,DC=example,DC=com'; DnsHostName = 'rodc-other.example.com'; PrimaryGroupId = 521; TrustedForDelegation = $true; TrustedToAuthForDelegation = $true; AllowedToDelegateTo = @('HTTP/dc'); HasResourceBasedConstrainedDelegation = $true } + $script:AdComputerState.Computers += [PSCustomObject]@{ Name = 'dc-alias'; DistinguishedName = 'CN=dc-alias,DC=example,DC=com'; DnsHostName = 'SECOND.example.com'; PrimaryGroupId = 515; TrustedForDelegation = $true; TrustedToAuthForDelegation = $true; AllowedToDelegateTo = @('HTTP/dc'); HasResourceBasedConstrainedDelegation = $true } + $script:AdComputerState.DomainControllers += [PSCustomObject]@{ Name = 'different-short-name'; ServerReference = ''; DnsHostName = 'second.EXAMPLE.com' } + + Test-MtAdComputerUnconstrainedDelegationCount | Should -BeTrue + $script:Details.Text | Should -BeLike '*| Total Non-DC Computers | 2 |*' + Test-MtAdComputerNonDcConstrainedDelegationCount | Should -BeTrue + $script:Details.Text | Should -BeLike '*| Total Non-DC Computers | 2 |*' + } + + It 'counts unknown operating systems without suggesting OS support or patch status' { + Test-MtAdComputerOperatingSystemCount | Should -BeTrue + $script:Details.Investigate | Should -BeTrue + $script:Details.Text | Should -BeLike '*| Computers with Unknown OS | 1 |*' + $script:Details.Text | Should -BeLike '*| Unknown OS | 1 | 33.33% of all computers |*' + } + + It 'escapes container cells and supplies a heading for the top five table' { + Test-MtAdComputerPerOUAverage | Should -BeTrue + $script:Details.Investigate | Should -BeTrue + $script:Details.Text | Should -Match '\| Container \| Computer Count \|' + $script:Details.Text | Should -Match 'OU=Servers\\\|Prod' + } + + It 'does not report missing CreatorSid collection as zero CreatorSids' { + Test-MtAdComputerCreatorSidCount | Should -BeFalse + $script:Details.Investigate | Should -BeTrue + $script:Details.Text | Should -BeLike '*CreatorSid is not collected*' + } + + It 'fails when an enabled computer is a child of the default Computers container' { + $script:AdComputerState.Computers[2].DistinguishedName = 'CN=client,CN=Computers,DC=example,DC=com' + Test-MtAdComputerInDefaultContainer | Should -BeFalse + $script:Details.Text | Should -BeLike '*| In Default Computers Container | 1 |*' + } + + It 'counts optional CreatorSid metadata rather than treating its presence as a security failure' { + foreach ($computer in $script:AdComputerState.Computers) { + $computer | Add-Member -NotePropertyName CreatorSid -NotePropertyValue $null + } + $script:AdComputerState.Computers[1].CreatorSid = 'S-1-5-21-1-2-3-1100' + Test-MtAdComputerCreatorSidCount | Should -BeTrue + $script:Details.Investigate | Should -BeTrue + $script:Details.Text | Should -BeLike '*| Computers with CreatorSid | 1 |*' + } + + It 'recognizes escaped commas in the computer name without counting an OU named Computers' { + $script:AdComputerState.Computers[1].DistinguishedName = 'CN=app\,one,CN=Computers,DC=example,DC=com' + $script:AdComputerState.Computers[2].DistinguishedName = 'CN=client,OU=Computers,DC=example,DC=com' + Test-MtAdComputerInDefaultContainer | Should -BeFalse + $script:Details.Text | Should -BeLike '*| In Default Computers Container | 1 |*' + } +} diff --git a/powershell/tests/functions/ActiveDirectoryIssues.Tests.ps1 b/powershell/tests/functions/ActiveDirectoryIssues.Tests.ps1 index eb336f1315..675582b495 100644 --- a/powershell/tests/functions/ActiveDirectoryIssues.Tests.ps1 +++ b/powershell/tests/functions/ActiveDirectoryIssues.Tests.ps1 @@ -7,7 +7,7 @@ BeforeDiscovery { } Describe 'AD-CFG-22: KDS root key count' { - It 'Skips when zero KDS root keys are found' { + It 'Fails when zero KDS root keys are found' { InModuleScope Maester { Mock Get-MtADDomainState -ModuleName Maester { return [ordered]@{ @@ -19,7 +19,7 @@ Describe 'AD-CFG-22: KDS root key count' { Mock Add-MtTestResultDetail -ModuleName Maester { } $result = Test-MtAdKdsRootKeysCount - $result | Should -Be $null + $result | Should -BeFalse } } @@ -55,7 +55,7 @@ Describe 'AD-CFG-22: KDS root key count' { Mock Add-MtTestResultDetail -ModuleName Maester { } $result = Test-MtAdKdsRootKeysCount - $result | Should -Be $null + $result | Should -BeTrue Assert-MockCalled Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate -eq $true } -Exactly 1 } } @@ -157,7 +157,7 @@ Describe 'AD-DCOMP-06: Stale enabled computers' { } } - It 'Returns Investigate when stale enabled computers exist' { + It 'Fails when stale enabled computers exist' { InModuleScope Maester { Mock Get-MtADDomainState -ModuleName Maester { return [ordered]@{ @@ -173,7 +173,7 @@ Describe 'AD-DCOMP-06: Stale enabled computers' { } $result = Test-MtAdComputerStaleEnabledCount - $result | Should -Be $null + $result | Should -BeFalse } } } diff --git a/tests/ad/computer/Test.AD-COMP-02.md b/tests/ad/computer/Test.AD-COMP-02.md deleted file mode 100644 index e7be546ea0..0000000000 --- a/tests/ad/computer/Test.AD-COMP-02.md +++ /dev/null @@ -1,34 +0,0 @@ -Dormant (stale) computer accounts—enabled accounts that haven't authenticated for more than the configured threshold (default 90 days)—pose significant security risks: - -- **Attack vector**: Attackers can exploit dormant accounts that may have weak or unchanged passwords -- **Shadow IT**: These may represent forgotten test systems, VMs, or decommissioned hardware still in the directory -- **Lateral movement**: Compromised dormant accounts can be used to move laterally within the network -- **Compliance issues**: Many security frameworks require identification and remediation of stale accounts - -#### Control Type - -**Detective** - -#### Security Recommendation - -Establish a process to: -1. Identify dormant computers (this test) -2. Investigate whether they represent legitimate systems -3. Disable accounts for systems that are truly decommissioned -4. Delete disabled accounts after a verification period - -#### How the Test Works - -This test examines all enabled computer accounts and identifies those where: -- The `lastLogonDate` property is older than `DormantThresholdDays` (default 90 days) -- The account remains enabled - -The default 90-day threshold is a common security baseline. Set `DormantThresholdDays` to adjust it based on your organization's requirements (e.g., seasonal systems, remote workstations). - -#### Related Tests - -- `Test-MtAdComputerDisabledCount` - Counts already-disabled computer accounts -- `Test-MtAdComputerInDefaultContainer` - Identifies computers that may be unmanaged - - -%TestResult% diff --git a/tests/ad/computer/Test.AD-COMP-02.ps1 b/tests/ad/computer/Test.AD-COMP-02.ps1 deleted file mode 100644 index 089d095016..0000000000 --- a/tests/ad/computer/Test.AD-COMP-02.ps1 +++ /dev/null @@ -1,111 +0,0 @@ -function Test-MtAdComputerDormantCount { - <# - .SYNOPSIS - Counts the number of dormant computer objects in Active Directory. - - .DESCRIPTION - This test identifies computer objects that have not logged on for more than the configured threshold. - Dormant computers can represent security risks if they are still enabled and can be - used for unauthorized access. This test provides visibility into stale computer accounts. - - .EXAMPLE - Test-MtAdComputerDormantCount - - Returns $true if computer object data is accessible, $false otherwise. - The test result includes counts of dormant computers since the configured threshold. - - .LINK - https://maester.dev/docs/commands/Test-MtAdComputerDormantCount - #> - [MaesterTest( - Id = 'AD-COMP-02', - Title = 'Computer dormant count should be retrievable', - Product = 'ad', - Feature = 'computers', - Area = 'identity-lifecycle', - ResourceType = 'Computer', - Severity = 'Info', - Mitre = 'T1078.002', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:computer:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param( - # Number of days without a logon before an enabled computer is considered dormant. - [ValidateRange(1, 3650)] - [int] $DormantThresholdDays = 90 - ) - - Write-Verbose "Starting Test-MtAdComputerDormantCount" - - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('Computers') - - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $computers = $adState.Computers - $thresholdDays = $DormantThresholdDays - $thresholdDate = (Get-Date).AddDays(-$thresholdDays) - - # Count dormant computers (last logon older than the configured threshold and still enabled) - $dormantComputers = $computers | Where-Object { - $_.Enabled -eq $true -and - $_.lastLogonDate -and - $_.lastLogonDate -lt $thresholdDate - } - - $dormantCount = ($dormantComputers | Measure-Object).Count - $enabledCount = ($computers | Where-Object { $_.Enabled -eq $true } | Measure-Object).Count - $totalCount = ($computers | Measure-Object).Count - - # Test passes if we successfully retrieved computer data - $testResult = $totalCount -gt 0 - - # Generate markdown results - if ($testResult) { - $percentage = if ($enabledCount -gt 0) { - [Math]::Round(($dormantCount / $enabledCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Computers | $totalCount |" + "`n" - $result += "| Enabled Computers | $enabledCount |" + "`n" - $result += "| Dormant Computers (>$thresholdDays days) | $dormantCount |" + "`n" - $result += "| Dormant Percentage (of enabled) | $percentage% |" + "`n" + "`n" - - $testResultMarkdown = "Active Directory computer objects have been analyzed. $dormantCount out of $enabledCount enabled computers ($percentage%) have not logged on for more than $thresholdDays days.`n`n%TestResult%" - if ($dormantCount -eq 0) { - $datedEnabledComputers = $computers | Where-Object { $_.Enabled -eq $true -and $null -ne $_.lastLogonDate } - $undatedEnabledCount = $enabledCount - $datedEnabledComputers.Count - $oldestLastLogonDate = $datedEnabledComputers | - Sort-Object -Property lastLogonDate | - Select-Object -First 1 -ExpandProperty lastLogonDate - - if ($null -eq $oldestLastLogonDate) { - $testResultMarkdown += "`n`nThere are $enabledCount enabled computers. None have a recorded last logon date, so dormant status cannot be determined from available data." - } else { - $oldestLastLogonDate = [datetime]$oldestLastLogonDate - $oldestLastLogon = $oldestLastLogonDate.ToString('yyyy-MM-dd') - $daysUntilThreshold = [Math]::Max(1, [Math]::Ceiling(($oldestLastLogonDate.AddDays($thresholdDays) - (Get-Date)).TotalDays)) - $undatedNote = if ($undatedEnabledCount -gt 0) { " $undatedEnabledCount enabled computer(s) have no recorded logon date and are not counted in this analysis." } else { "" } - $testResultMarkdown += "`n`nThere are $enabledCount enabled computers. The oldest last logon date is $oldestLastLogon. No computers currently exceed the dormant threshold of $thresholdDays days. The oldest computer would reach the threshold in $daysUntilThreshold days.$undatedNote" - } - } - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory computer objects. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult -} diff --git a/tests/ad/security/Test.AD-DCOMP-04.md b/tests/ad/security/Test.AD-DCOMP-04.md index ab61c58f05..b42a64caad 100644 --- a/tests/ad/security/Test.AD-DCOMP-04.md +++ b/tests/ad/security/Test.AD-DCOMP-04.md @@ -41,7 +41,7 @@ This test analyzes computer objects in Active Directory and: #### Related Tests -- `Test-MtAdComputerOperatingSystemDetails` - Detailed OS and service pack information +- Unknown OS values are counted explicitly; OS service pack and patch state are not available in the current collector. - `Test-MtAdComputerStaleEnabledCount` - Identifies stale computer accounts - `Test-MtAdDcOperatingSystemDetails` - Domain Controller OS distribution diff --git a/tests/ad/security/Test.AD-DCOMP-04.ps1 b/tests/ad/security/Test.AD-DCOMP-04.ps1 index dc1853d19f..ee5be2fdcd 100644 --- a/tests/ad/security/Test.AD-DCOMP-04.ps1 +++ b/tests/ad/security/Test.AD-DCOMP-04.ps1 @@ -44,9 +44,8 @@ $adState = Get-MtADDomainState -Categories @('Computers') Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $adState -or $null -eq $adState.Computers) { + throw 'Computer inventory is required to review operating systems.' } Write-Verbose "Filtering/counting computer operating system count" @@ -67,6 +66,7 @@ $result += "| Distinct Operating Systems | $osCount |" + "`n" $result += "| Computers with OS Data | $computersWithOs |" + "`n" $result += "| Computers without OS Data | $computersWithoutOs |" + "`n" + $result += "| Computers with Unknown OS | $computersWithoutOs |" + "`n" if ($osCount -gt 0) { $result += "`n**Operating Systems in Use:**" + "`n" + "`n" @@ -76,12 +76,17 @@ $sortedGroups = $osGroups | Sort-Object -Property Count -Descending foreach ($group in $sortedGroups) { $percentage = if ($computersWithOs -gt 0) { [Math]::Round(($group.Count / $computersWithOs) * 100, 2) } else { 0 } - $result += "| $($group.Name) | $($group.Count) | $percentage% |" + "`n" + $osName = [string]$group.Name -replace '\|', '\|' -replace '[\r\n]', ' ' + $result += "| $osName | $($group.Count) | $percentage% |" + "`n" } } + if ($computersWithoutOs -gt 0) { + $unknownPercentage = if ($totalComputers -gt 0) { [Math]::Round(($computersWithoutOs / $totalComputers) * 100, 2) } else { 0 } + $result += "| Unknown OS | $computersWithoutOs | $unknownPercentage% of all computers |`n" + } Write-Verbose "Counts computed" - $testResultMarkdown = "Domain computer operating system diversity has been analyzed.`n`n%TestResult%" + $testResultMarkdown = "Review the operating system inventory, including computers with unknown OS. OS service pack is not collected; this inventory cannot determine patch or support status.`n`n%TestResult%" $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result Add-MtTestResultDetail -Result $testResultMarkdown -Investigate diff --git a/tests/ad/security/Test.AD-DCOMP-05.md b/tests/ad/security/Test.AD-DCOMP-05.md deleted file mode 100644 index 6187f608a1..0000000000 --- a/tests/ad/security/Test.AD-DCOMP-05.md +++ /dev/null @@ -1,50 +0,0 @@ -- Detailed knowledge of operating system versions and service pack levels is essential for effective vulnerability management and security compliance. This information helps identify: - -**Security Risks:** -- **Missing Service Packs**: Systems without critical updates -- **End-of-Life Versions**: Operating systems no longer receiving security patches -- **Version Fragmentation**: Inconsistent patch levels across the environment -- **Unsupported Configurations**: OS versions that violate security policies - -**Compliance Requirements:** -- Many frameworks require specific OS versions -- Service pack levels may be mandated -- Documentation of OS landscape is often required - -#### Control Type - -**Operational** - -#### Security Recommendation - -1. **Maintain Current Service Packs**: - - Apply latest service packs and cumulative updates - - Test before deployment to production - - Maintain rollback procedures - -2. **Upgrade End-of-Life Systems**: - - Prioritize systems running unsupported OS versions - - Develop migration plans for legacy applications - - Consider virtualization for legacy requirements - -3. **Standardize Configurations**: - - Use standard OS images for new deployments - - Implement configuration management - - Regular compliance scanning - -#### How the Test Works - -This test provides detailed analysis including: -- Operating system names and versions -- Service pack levels -- Distribution counts and percentages -- Identification of systems without OS information - -#### Related Tests - -- `Test-MtAdComputerOperatingSystemCount` - Summary OS count -- `Test-MtAdComputerStaleEnabledCount` - Stale computer identification -- `Test-MtAdDcOperatingSystemDetails` - Domain Controller OS details - - -%TestResult% diff --git a/tests/ad/security/Test.AD-DCOMP-05.ps1 b/tests/ad/security/Test.AD-DCOMP-05.ps1 deleted file mode 100644 index dad3aff23a..0000000000 --- a/tests/ad/security/Test.AD-DCOMP-05.ps1 +++ /dev/null @@ -1,98 +0,0 @@ -function Test-MtAdComputerOperatingSystemDetails { - <# - .SYNOPSIS - Provides detailed breakdown of computers by operating system and service pack. - - .DESCRIPTION - This test provides a comprehensive view of the operating system landscape in the - domain, including OS versions and service pack levels. This helps identify - outdated systems, unsupported versions, and systems requiring security updates. - - Security Value: - - Identifies end-of-life operating systems - - Reveals systems missing critical service packs - - Supports vulnerability management programs - - Helps plan OS upgrade and standardization efforts - - .EXAMPLE - Test-MtAdComputerOperatingSystemDetails - - Returns $true if computer data is accessible. - - .LINK - https://maester.dev/docs/commands/Test-MtAdComputerOperatingSystemDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-DCOMP-05', - Title = 'Computer operating system details should be investigated', - Product = 'ad', - Feature = 'computers', - Area = 'devices', - ResourceType = 'Computer', - Severity = 'Info', - Mitre = 'None', - Control = 'nist-800-53-r5:CM-8', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:computer:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdComputerOperatingSystemDetails" - $adState = Get-MtADDomainState -Categories @('Computers') - Write-Verbose "Retrieved AD state" - - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting computer operating system details" - - $computers = $adState.Computers - - # Create detailed OS breakdown including service pack - $osDetails = $computers | Where-Object { $_.operatingSystem } | ForEach-Object { - $osName = $_.operatingSystem - $osServicePack = if ($_.operatingSystemServicePack) { $_.operatingSystemServicePack } else { "No Service Pack" } - "$osName $osServicePack" - } | Group-Object - - $totalComputers = ($computers | Measure-Object).Count - $computersWithOs = ($computers | Where-Object { $_.operatingSystem } | Measure-Object).Count - - $testResult = $true - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Computers | $totalComputers |" + "`n" - $result += "| Computers with OS Data | $computersWithOs |" + "`n" - $result += "| Distinct OS/Service Pack Combinations | $(($osDetails | Measure-Object).Count) |" + "`n" - - if ($osDetails.Count -gt 0) { - $result += "`n**Operating System Details (Top 15):**" + "`n" + "`n" - $result += "| Operating System | Count | Percentage |" + "`n" - $result += "| --- | --- | --- |" + "`n" - - $sortedDetails = $osDetails | Sort-Object -Property Count -Descending | Select-Object -First 15 - foreach ($detail in $sortedDetails) { - $percentage = if ($computersWithOs -gt 0) { [Math]::Round(($detail.Count / $computersWithOs) * 100, 2) } else { 0 } - $result += "| $($detail.Name) | $($detail.Count) | $percentage% |" + "`n" - } - - if ($osDetails.Count -gt 15) { - $result += "| ... and $($osDetails.Count - 15) more combinations | | |" + "`n" - } - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "Detailed operating system distribution has been analyzed. Review for unsupported or end-of-life systems.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdComputerOperatingSystemDetails" - - return $testResult -} diff --git a/tests/ad/security/Test.AD-DCOMP-06.md b/tests/ad/security/Test.AD-DCOMP-06.md index 1e401ef6e7..f881f3f009 100644 --- a/tests/ad/security/Test.AD-DCOMP-06.md +++ b/tests/ad/security/Test.AD-DCOMP-06.md @@ -44,7 +44,7 @@ Provides counts and lists affected computers. #### Related Tests -- `Test-MtAdComputerDormantCount` - Dormant computer identification +- This is the canonical stale enabled computer inventory; it reports Investigate rather than failing when stale accounts need owner review. - `Test-MtAdComputerDisabledCount` - Disabled computer analysis - `Test-MtAdUserDormantEnabledCount` - Stale user account check diff --git a/tests/ad/security/Test.AD-DCOMP-06.ps1 b/tests/ad/security/Test.AD-DCOMP-06.ps1 index 0603870c6f..d73743fd51 100644 --- a/tests/ad/security/Test.AD-DCOMP-06.ps1 +++ b/tests/ad/security/Test.AD-DCOMP-06.ps1 @@ -8,9 +8,8 @@ compromised and reactivated by attackers. This test identifies enabled computers that have not authenticated to the domain for the configured threshold or more. - Because nearly every domain has at least one stale enabled computer, this - test returns an Investigate result (rather than Pass/Fail) so the count - and details are surfaced for review without causing a failing audit. + An enabled computer with no recorded logon or a last logon before the threshold + is flagged for review. The result is Investigate when such computers exist. Security Risk: - Stale enabled accounts can be reactivated and used for lateral movement @@ -53,17 +52,12 @@ $adState = Get-MtADDomainState -Categories @('Computers') Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } + if ($null -eq $adState) { throw 'Computer inventory is required to assess stale accounts.' } Write-Verbose "Filtering/counting computer stale enabled count" $computers = $adState.Computers - if ($null -eq $computers) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } + if ($null -eq $computers) { throw 'Computer inventory is required to assess stale accounts.' } + if (@($computers).Count -eq 0) { throw 'Computer inventory is empty; stale accounts cannot be assessed.' } $staleThreshold = (Get-Date).AddDays(-$StaleThresholdDays) # Find enabled computers that haven't logged on for the configured threshold or more. @@ -105,7 +99,9 @@ $sortedStale = $staleEnabledComputers | Sort-Object -Property lastLogonDate | Select-Object -First 10 foreach ($comp in $sortedStale) { $lastLogon = if ($comp.lastLogonDate) { $comp.lastLogonDate.ToString('yyyy-MM-dd') } else { 'Never' } - $result += "| $($comp.Name) | $lastLogon | $($comp.operatingSystem) |" + "`n" + $name = [string]$comp.Name -replace '\|', '\|' -replace '[\r\n]', ' ' + $os = [string]$comp.OperatingSystem -replace '\|', '\|' -replace '[\r\n]', ' ' + $result += "| $name | $lastLogon | $os |" + "`n" } if ($staleCount -gt 10) { @@ -126,6 +122,6 @@ $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result Add-MtTestResultDetail -Result $testResultMarkdown -Investigate Write-Verbose "Completed Test-MtAdComputerStaleEnabledCount" - return $null + return $false } } diff --git a/tests/ad/security/Test.AD-DCOMP-07.md b/tests/ad/security/Test.AD-DCOMP-07.md index 0177ee703d..2b8a816c7b 100644 --- a/tests/ad/security/Test.AD-DCOMP-07.md +++ b/tests/ad/security/Test.AD-DCOMP-07.md @@ -44,7 +44,7 @@ This test counts computers with and without the `dNSHostName` attribute populate #### Related Tests - `Test-MtAdComputerDnsZoneCount` - DNS zone distribution -- `Test-MtAdComputerDnsZoneDetails` - Detailed DNS zone analysis +- `AD-DCOMP-08` - DNS suffix distribution and per-zone computer counts - `Test-MtAdComputerSpnSetCount` - SPN configuration check diff --git a/tests/ad/security/Test.AD-DCOMP-07.ps1 b/tests/ad/security/Test.AD-DCOMP-07.ps1 index 342b785915..d85ae9de82 100644 --- a/tests/ad/security/Test.AD-DCOMP-07.ps1 +++ b/tests/ad/security/Test.AD-DCOMP-07.ps1 @@ -43,9 +43,8 @@ $adState = Get-MtADDomainState -Categories @('Computers') Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $adState -or $null -eq $adState.Computers) { + throw 'Computer inventory is required to review DNS host names.' } Write-Verbose "Filtering/counting computer dns host name count" @@ -78,7 +77,9 @@ $result += "| --- | --- |" + "`n" foreach ($comp in $computersWithoutDns | Select-Object -First 10) { - $result += "| $($comp.Name) | $($comp.operatingSystem) |" + "`n" + $name = [string]$comp.Name -replace '\|', '\|' -replace '[\r\n]', ' ' + $os = [string]$comp.OperatingSystem -replace '\|', '\|' -replace '[\r\n]', ' ' + $result += "| $name | $os |`n" } if ($withoutDnsCount -gt 10) { diff --git a/tests/ad/security/Test.AD-DCOMP-08.md b/tests/ad/security/Test.AD-DCOMP-08.md index 4ed9d289bf..a5a666b65a 100644 --- a/tests/ad/security/Test.AD-DCOMP-08.md +++ b/tests/ad/security/Test.AD-DCOMP-08.md @@ -43,7 +43,7 @@ This test extracts DNS zones from computer `dNSHostName` attributes and: #### Related Tests - `Test-MtAdComputerDnsHostNameCount` - DNS host name coverage -- `Test-MtAdComputerDnsZoneDetails` - Detailed zone breakdown +- Zone counts and percentages are shown in this check; host names with no DNS suffix are counted separately. - `Test-MtAdDnsZoneCount` - DNS server zone analysis diff --git a/tests/ad/security/Test.AD-DCOMP-08.ps1 b/tests/ad/security/Test.AD-DCOMP-08.ps1 index c27dcb2e34..becce97ea5 100644 --- a/tests/ad/security/Test.AD-DCOMP-08.ps1 +++ b/tests/ad/security/Test.AD-DCOMP-08.ps1 @@ -43,30 +43,17 @@ $adState = Get-MtADDomainState -Categories @('Computers') Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $adState -or $null -eq $adState.Computers) { + throw 'Computer inventory is required to review DNS zones.' } Write-Verbose "Filtering/counting computer dns zone count" $computers = $adState.Computers - # Extract DNS zones from dNSHostName - $dnsZones = @() - foreach ($computer in $computers) { - if ($computer.dNSHostName) { - $dnsName = $computer.dNSHostName.ToString() - # Extract zone (everything after first dot) - if ($dnsName -match '\.') { - $zone = $dnsName.Substring($dnsName.IndexOf('.') + 1) - if ($zone -and $dnsZones -notcontains $zone) { - $dnsZones += $zone - } - } - } - } - - $zoneCount = $dnsZones.Count + # A host name without a suffix is not a DNS zone; report it separately. + $zoneGroups = @($computers | Where-Object { $_.dNSHostName -match '^[^.]+\..+' } | + Group-Object -Property { $_.dNSHostName.Substring($_.dNSHostName.IndexOf('.') + 1).TrimEnd('.').ToLowerInvariant() }) + $zoneCount = $zoneGroups.Count $computersWithDns = ($computers | Where-Object { $_.dNSHostName } | Measure-Object).Count $totalComputers = ($computers | Measure-Object).Count @@ -77,14 +64,17 @@ $result += "| Total Computers | $totalComputers |" + "`n" $result += "| Computers with DNS Host Name | $computersWithDns |" + "`n" $result += "| Unique DNS Zones | $zoneCount |" + "`n" + $result += "| Computers without DNS Host Name | $(@($computers | Where-Object { -not $_.dNSHostName }).Count) |`n" + $result += "| Host Names without DNS Suffix | $(@($computers | Where-Object { $_.dNSHostName -and $_.dNSHostName -notmatch '^[^.]+\..+' }).Count) |`n" if ($zoneCount -gt 0) { $result += "`n**DNS Zones in Use:**" + "`n" + "`n" - $result += "| DNS Zone |" + "`n" - $result += "| --- |" + "`n" + $result += "| DNS Zone | Computer Count | Percentage of Hosts with Zone |`n| --- | --- | --- |`n" - foreach ($zone in ($dnsZones | Sort-Object)) { - $result += "| $zone |" + "`n" + foreach ($group in ($zoneGroups | Sort-Object -Property Count -Descending)) { + $zone = [string]$group.Name -replace '\|', '\|' -replace '[\r\n]', ' ' + $percentage = [Math]::Round(100 * $group.Count / @($computers | Where-Object { $_.dNSHostName -match '^[^.]+\..+' }).Count, 2) + $result += "| $zone | $($group.Count) | $percentage% |`n" } } Write-Verbose "Counts computed" diff --git a/tests/ad/security/Test.AD-DCOMP-09.md b/tests/ad/security/Test.AD-DCOMP-09.md deleted file mode 100644 index 80dc50f15b..0000000000 --- a/tests/ad/security/Test.AD-DCOMP-09.md +++ /dev/null @@ -1,51 +0,0 @@ -- Detailed analysis of DNS zone distribution provides visibility into Active Directory topology and helps identify potential configuration issues or security concerns related to DNS. - -**Security and Operational Value:** -- **Topology Mapping**: Understand how computers are distributed across DNS domains -- **Disjoint Namespace Detection**: Identify computers in unexpected DNS zones -- **Configuration Validation**: Verify computers are in appropriate zones -- **Compliance Verification**: Ensure DNS configuration meets organizational standards - -**Potential Issues Identified:** -- Computers in incorrect DNS zones -- Disjoint namespace misconfigurations -- Orphaned computer accounts -- DNS registration failures - -#### Control Type - -**Operational** - -#### Security Recommendation - -1. **Zone Assignment Review**: - - Verify computers are in appropriate DNS zones - - Investigate computers in unexpected zones - - Document legitimate multi-zone scenarios - -2. **DNS Configuration Audit**: - - Regular review of DNS zone configuration - - Validate DNS delegation settings - - Check for stale or orphaned records - -3. **Remediation**: - - Move computers to correct zones if misconfigured - - Delete stale computer accounts - - Fix DNS registration issues - -#### How the Test Works - -This test provides detailed analysis: -- Breakdown of computers by DNS zone -- Counts per zone with percentages -- List of computers without DNS host names -- Distribution statistics - -#### Related Tests - -- `Test-MtAdComputerDnsZoneCount` - DNS zone count summary -- `Test-MtAdComputerDnsHostNameCount` - DNS host name coverage -- `Test-MtAdAllowedDnsSuffixesCount` - DNS suffix configuration - - -%TestResult% diff --git a/tests/ad/security/Test.AD-DCOMP-09.ps1 b/tests/ad/security/Test.AD-DCOMP-09.ps1 deleted file mode 100644 index ced5f6dc65..0000000000 --- a/tests/ad/security/Test.AD-DCOMP-09.ps1 +++ /dev/null @@ -1,122 +0,0 @@ -function Test-MtAdComputerDnsZoneDetails { - <# - .SYNOPSIS - Provides detailed breakdown of computers by DNS zone. - - .DESCRIPTION - This test provides a comprehensive view of how computers are distributed - across DNS zones in the domain. This helps identify disjoint namespaces, - multi-domain scenarios, and potential DNS configuration issues. - - Security Value: - - Identifies computers in unexpected DNS zones - - Supports disjoint namespace assessment - - Helps detect DNS misconfigurations - - Important for Kerberos realm configuration - - .EXAMPLE - Test-MtAdComputerDnsZoneDetails - - Returns $true if computer data is accessible. - - .LINK - https://maester.dev/docs/commands/Test-MtAdComputerDnsZoneDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-DCOMP-09', - Title = 'Computer DNS zone details should be investigated', - Product = 'ad', - Feature = 'computers', - Area = 'infrastructure', - ResourceType = 'DnsZone', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:computer:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdComputerDnsZoneDetails" - $adState = Get-MtADDomainState -Categories @('Computers') - Write-Verbose "Retrieved AD state" - - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting computer dns zone details" - - $computers = $adState.Computers - - # Group computers by DNS zone - $zoneGroups = $computers | Where-Object { $_.dNSHostName } | ForEach-Object { - $dnsName = $_.dNSHostName.ToString() - if ($dnsName -match '\.') { - $zone = $dnsName.Substring($dnsName.IndexOf('.') + 1) - [PSCustomObject]@{ - Computer = $_ - Zone = $zone - } - } else { - [PSCustomObject]@{ - Computer = $_ - Zone = "(No Zone)" - } - } - } | Group-Object -Property Zone - - $computersWithDns = ($computers | Where-Object { $_.dNSHostName } | Measure-Object).Count - $totalComputers = ($computers | Measure-Object).Count - $zoneCount = ($zoneGroups | Measure-Object).Count - - $testResult = $true - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Computers | $totalComputers |" + "`n" - $result += "| Computers with DNS Host Name | $computersWithDns |" + "`n" - $result += "| Unique DNS Zones | $zoneCount |" + "`n" - - if ($zoneCount -gt 0) { - $result += "`n**Computers by DNS Zone:**" + "`n" + "`n" - $result += "| DNS Zone | Computer Count | Percentage |" + "`n" - $result += "| --- | --- | --- |" + "`n" - - $sortedGroups = $zoneGroups | Sort-Object -Property Count -Descending - foreach ($group in $sortedGroups) { - $percentage = if ($computersWithDns -gt 0) { [Math]::Round(($group.Count / $computersWithDns) * 100, 2) } else { 0 } - $result += "| $($group.Name) | $($group.Count) | $percentage% |" + "`n" - } - } - - # List computers without DNS host name - $computersWithoutDns = $computers | Where-Object { -not $_.dNSHostName } - $withoutDnsCount = ($computersWithoutDns | Measure-Object).Count - - if ($withoutDnsCount -gt 0) { - $result += "`n**Computers without DNS Host Name:** $withoutDnsCount**" + "`n" + "`n" - $result += "| Computer Name | Operating System |" + "`n" - $result += "| --- | --- |" + "`n" - - foreach ($comp in $computersWithoutDns | Select-Object -First 10) { - $result += "| $($comp.Name) | $($comp.operatingSystem) |" + "`n" - } - - if ($withoutDnsCount -gt 10) { - $result += "| ... and $($withoutDnsCount - 10) more | |" + "`n" - } - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "Detailed DNS zone distribution has been analyzed.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdComputerDnsZoneDetails" - - return $testResult -} From 32c4852ae00d43006b13c4640f81995e532394a5 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 06:23:26 +0000 Subject: [PATCH 013/100] fix(ad): make computer inventory outcomes and placement checks accurate --- tests/ad/computer/Test.AD-COMP-01.md | 2 +- tests/ad/computer/Test.AD-COMP-01.ps1 | 9 +++------ tests/ad/computer/Test.AD-COMP-03.md | 2 +- tests/ad/computer/Test.AD-COMP-03.ps1 | 15 +++++++------- tests/ad/computer/Test.AD-COMP-04.ps1 | 29 ++++++++++++++++++--------- tests/ad/computer/Test.AD-COMP-05.md | 2 +- tests/ad/computer/Test.AD-COMP-05.ps1 | 11 ++++------ tests/ad/computer/Test.AD-COMP-06.ps1 | 26 +++++++++++++++--------- tests/ad/computer/Test.AD-COMP-07.ps1 | 7 ++----- tests/ad/computer/Test.AD-COMP-08.ps1 | 11 +++++----- 10 files changed, 62 insertions(+), 52 deletions(-) diff --git a/tests/ad/computer/Test.AD-COMP-01.md b/tests/ad/computer/Test.AD-COMP-01.md index 1222663687..a97f2a4a1c 100644 --- a/tests/ad/computer/Test.AD-COMP-01.md +++ b/tests/ad/computer/Test.AD-COMP-01.md @@ -24,7 +24,7 @@ The test returns informational results to help you assess the scope of disabled #### Related Tests -- `Test-MtAdComputerDormantCount` - Identifies enabled computers that haven't logged on recently +- `AD-DCOMP-06` - Identifies enabled computers that haven't logged on recently - `Test-MtAdComputerInDefaultContainer` - Finds computers in the default container (another hygiene indicator) diff --git a/tests/ad/computer/Test.AD-COMP-01.ps1 b/tests/ad/computer/Test.AD-COMP-01.ps1 index 9d38d1b29d..09e164eeec 100644 --- a/tests/ad/computer/Test.AD-COMP-01.ps1 +++ b/tests/ad/computer/Test.AD-COMP-01.ps1 @@ -39,10 +39,8 @@ # Get AD domain state data (uses cached data if available) $adState = Get-MtADDomainState -Categories @('Computers') - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $adState -or $null -eq $adState.Computers) { + throw 'Computer inventory is required to review disabled accounts.' } $computers = $adState.Computers @@ -53,7 +51,6 @@ $totalCount = ($computers | Measure-Object).Count $enabledCount = $totalCount - $disabledCount - # Test passes if we successfully retrieved computer data $testResult = $totalCount -gt 0 # Generate markdown results @@ -77,7 +74,7 @@ $testResultMarkdown = "Unable to retrieve Active Directory computer objects. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/computer/Test.AD-COMP-03.md b/tests/ad/computer/Test.AD-COMP-03.md index bfd313bed6..259240ee1c 100644 --- a/tests/ad/computer/Test.AD-COMP-03.md +++ b/tests/ad/computer/Test.AD-COMP-03.md @@ -19,7 +19,7 @@ Computer account creation should be tightly controlled: #### How the Test Works -This test counts computer objects that have the `ms-ds-CreatorSid` attribute populated. This attribute is typically set when: +The cached LDAP computer collector retrieves `mS-DS-CreatorSID` as `CreatorSid`. This check reports **Investigate** because a recorded creator is not proof of an unauthorized join. It does not report a zero count when the field was not collected. This test counts enabled computer objects that have the attribute populated. This attribute is typically set when: - A user or service account explicitly creates a computer account - The creating principal has been captured in the directory diff --git a/tests/ad/computer/Test.AD-COMP-03.ps1 b/tests/ad/computer/Test.AD-COMP-03.ps1 index 730ec182ff..bf42b360b7 100644 --- a/tests/ad/computer/Test.AD-COMP-03.ps1 +++ b/tests/ad/computer/Test.AD-COMP-03.ps1 @@ -39,20 +39,21 @@ # Get AD domain state data (uses cached data if available) $adState = Get-MtADDomainState -Categories @('Computers') - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + if ($null -eq $adState -or $null -eq $adState.Computers) { + throw 'Computer inventory is required to review CreatorSid.' } $computers = $adState.Computers + if (@($computers).Count -eq 0 -or @($computers | Where-Object { -not $_.PSObject.Properties['CreatorSid'] }).Count -gt 0) { + Add-MtTestResultDetail -Result 'CreatorSid is not collected in the cached computer inventory. This test cannot determine how many accounts have it.' -Investigate + return $false + } # Count enabled computers with CreatorSid attribute # CreatorSid is optional in the collected computer contract, so check whether it exists. $computersWithCreatorSid = $computers | Where-Object { $_.Enabled -eq $true -and - $_.PSObject.Properties['ms-ds-CreatorSid'] -and - $_.'ms-ds-CreatorSid' + $_.CreatorSid } $creatorSidCount = ($computersWithCreatorSid | Measure-Object).Count @@ -83,7 +84,7 @@ $testResultMarkdown = "Unable to retrieve Active Directory computer objects. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/computer/Test.AD-COMP-04.ps1 b/tests/ad/computer/Test.AD-COMP-04.ps1 index 7f2377e563..b644a8d2e3 100644 --- a/tests/ad/computer/Test.AD-COMP-04.ps1 +++ b/tests/ad/computer/Test.AD-COMP-04.ps1 @@ -24,12 +24,14 @@ #> [MaesterTest( Id = 'AD-COMP-04', - Title = 'Computer non-standard primary group count should be retrievable', + Title = 'Enabled computers should use standard primary groups', Product = 'ad', Feature = 'computers', Area = 'identity-lifecycle', ResourceType = 'Computer', - Severity = 'Info', + Severity = 'Low', + UserImpact = 'Low', + ImplementationCost = 'Medium', Mitre = 'None', Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:computer:ReadProperty'), @@ -48,17 +50,18 @@ $adState = Get-MtADDomainState -Categories @('Computers') # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } + if ($null -eq $adState -or $null -eq $adState.Computers) { throw 'Computer inventory is required to assess primary groups.' } $computers = $adState.Computers + if (@($computers).Count -eq 0) { throw 'Computer inventory is empty; primary groups cannot be assessed.' } + if (@($computers | Where-Object { $null -eq $_.Enabled }).Count -gt 0) { + throw 'Enabled state is missing for computers; primary groups cannot be assessed completely.' + } # Count enabled computers with non-standard primary group $nonStandardGroupComputers = $computers | Where-Object { $_.Enabled -eq $true -and - $_.primaryGroupId -and + $null -ne $_.primaryGroupId -and $_.primaryGroupId -notin $standardGroupIds } @@ -67,10 +70,13 @@ $totalCount = ($computers | Measure-Object).Count # Test passes if we successfully retrieved computer data - $testResult = $totalCount -gt 0 + if (@($computers | Where-Object { $_.Enabled -eq $true -and $null -eq $_.PrimaryGroupId }).Count -gt 0) { + throw 'PrimaryGroupId is missing for enabled computers; cannot assess all primary groups.' + } + $testResult = $nonStandardCount -eq 0 # Generate markdown results - if ($testResult) { + if ($totalCount -gt 0) { $percentage = if ($enabledCount -gt 0) { [Math]::Round(($nonStandardCount / $enabledCount) * 100, 2) } else { @@ -91,6 +97,11 @@ $testResultMarkdown = "Unable to retrieve Active Directory computer objects. Ensure you have appropriate permissions and the Active Directory module is installed." } + if ($testResult) { + $testResultMarkdown = "Well done. No enabled computers have a non-standard primary group.`n`n$result" + } else { + $testResultMarkdown = "Enabled computers have non-standard primary groups. Review and restore standard group assignments where appropriate.`n`n$result" + } Add-MtTestResultDetail -Result $testResultMarkdown return $testResult diff --git a/tests/ad/computer/Test.AD-COMP-05.md b/tests/ad/computer/Test.AD-COMP-05.md index 45afc8938e..25830e2cd8 100644 --- a/tests/ad/computer/Test.AD-COMP-05.md +++ b/tests/ad/computer/Test.AD-COMP-05.md @@ -23,7 +23,7 @@ This test counts computer objects where the `SIDHistory` attribute is populated. #### Related Tests - `Test-MtAdComputerNonStandardGroup` - Identifies other migration or configuration anomalies -- `Test-MtAdComputerDormantCount` - Finds stale accounts that may be migration remnants +- `AD-DCOMP-06` - Finds stale accounts that may be migration remnants #### Related links diff --git a/tests/ad/computer/Test.AD-COMP-05.ps1 b/tests/ad/computer/Test.AD-COMP-05.ps1 index a1c3f98036..066c82421f 100644 --- a/tests/ad/computer/Test.AD-COMP-05.ps1 +++ b/tests/ad/computer/Test.AD-COMP-05.ps1 @@ -43,10 +43,7 @@ $adState = Get-MtADDomainState -Categories @('Computers') # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } + if ($null -eq $adState -or $null -eq $adState.Computers) { throw 'Computer inventory is required to review SID history.' } $computers = $adState.Computers @@ -60,10 +57,10 @@ $totalCount = ($computers | Measure-Object).Count # Test passes if we successfully retrieved computer data - $testResult = $totalCount -gt 0 + $testResult = $sidHistoryCount -eq 0 # Generate markdown results - if ($testResult) { + if ($totalCount -gt 0) { $percentage = if ($totalCount -gt 0) { [Math]::Round(($sidHistoryCount / $totalCount) * 100, 2) } else { @@ -82,7 +79,7 @@ $testResultMarkdown = "Unable to retrieve Active Directory computer objects. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/computer/Test.AD-COMP-06.ps1 b/tests/ad/computer/Test.AD-COMP-06.ps1 index c67be42be8..6a1e721715 100644 --- a/tests/ad/computer/Test.AD-COMP-06.ps1 +++ b/tests/ad/computer/Test.AD-COMP-06.ps1 @@ -23,12 +23,14 @@ #> [MaesterTest( Id = 'AD-COMP-06', - Title = 'Computer default container count should be retrievable', + Title = 'Enabled computers should be moved out of the default Computers container', Product = 'ad', Feature = 'computers', Area = 'infrastructure', ResourceType = 'Computer', - Severity = 'Info', + Severity = 'Low', + UserImpact = 'Low', + ImplementationCost = 'Medium', Mitre = 'None', Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:computer:ReadProperty'), @@ -44,18 +46,19 @@ $adState = Get-MtADDomainState -Categories @('Computers') # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } + if ($null -eq $adState -or $null -eq $adState.Computers) { throw 'Computer inventory is required to review the default container.' } $computers = $adState.Computers + if (@($computers).Count -eq 0) { throw 'Computer inventory is empty; default container placement cannot be assessed.' } + if (@($computers | Where-Object { $null -eq $_.Enabled -or ($_.Enabled -eq $true -and -not $_.DistinguishedName) }).Count -gt 0) { + throw 'Computer enabled state or distinguished name is missing; container placement cannot be assessed completely.' + } # Count enabled computers in the default Computers container $defaultContainerComputers = $computers | Where-Object { $_.Enabled -eq $true -and $_.DistinguishedName -and - $_.DistinguishedName -like "CN=Computers,*" + $_.DistinguishedName -match '^CN=(?:\\.|[^,])+,CN=Computers,DC=' } $defaultContainerCount = ($defaultContainerComputers | Measure-Object).Count @@ -63,10 +66,10 @@ $totalCount = ($computers | Measure-Object).Count # Test passes if we successfully retrieved computer data - $testResult = $totalCount -gt 0 + $testResult = $defaultContainerCount -eq 0 # Generate markdown results - if ($testResult) { + if ($totalCount -gt 0) { $percentage = if ($enabledCount -gt 0) { [Math]::Round(($defaultContainerCount / $enabledCount) * 100, 2) } else { @@ -86,6 +89,11 @@ $testResultMarkdown = "Unable to retrieve Active Directory computer objects. Ensure you have appropriate permissions and the Active Directory module is installed." } + if ($testResult) { + $testResultMarkdown = "Well done. No enabled computers are in the default Computers container.`n`n$result" + } else { + $testResultMarkdown = "Enabled computers remain in the default Computers container. Move them to managed OUs so intended Group Policy applies.`n`n$result" + } Add-MtTestResultDetail -Result $testResultMarkdown return $testResult diff --git a/tests/ad/computer/Test.AD-COMP-07.ps1 b/tests/ad/computer/Test.AD-COMP-07.ps1 index 11036c2d29..8aa5efb664 100644 --- a/tests/ad/computer/Test.AD-COMP-07.ps1 +++ b/tests/ad/computer/Test.AD-COMP-07.ps1 @@ -42,10 +42,7 @@ $adState = Get-MtADDomainState -Categories @('Computers') # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } + if ($null -eq $adState -or $null -eq $adState.Computers) { throw 'Computer inventory is required to review containers.' } $computers = $adState.Computers @@ -92,7 +89,7 @@ $testResultMarkdown = "Unable to retrieve Active Directory computer objects. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/computer/Test.AD-COMP-08.ps1 b/tests/ad/computer/Test.AD-COMP-08.ps1 index e4c022ed7a..073153e173 100644 --- a/tests/ad/computer/Test.AD-COMP-08.ps1 +++ b/tests/ad/computer/Test.AD-COMP-08.ps1 @@ -41,10 +41,7 @@ $adState = Get-MtADDomainState -Categories @('Computers') # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } + if ($null -eq $adState -or $null -eq $adState.Computers) { throw 'Computer inventory is required to review container distribution.' } $computers = $adState.Computers @@ -99,11 +96,13 @@ if ($distinctOUCount -gt 0) { $result += "**Top 5 Containers by Computer Count:**" + "`n" + "`n" + $result += "| Container | Computer Count |`n| --- | --- |`n" $computersByContainer | Sort-Object -Property Count -Descending | Select-Object -First 5 | ForEach-Object { - $result += "| $($_.Name) | $($_.Count) |" + "`n" + $name = [string]$_.Name -replace '\|', '\|' -replace '[\r\n]', ' ' + $result += "| $name | $($_.Count) |" + "`n" } } @@ -113,7 +112,7 @@ $testResultMarkdown = "Unable to retrieve Active Directory computer objects. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } From ac946d4f5ec67ba06b8b5577f491c8a09aadef33 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 06:23:26 +0000 Subject: [PATCH 014/100] refactor(ad): consolidate complete group membership inventories --- tests/ad/group/Test.AD-GCHG-01.md | 4 +- tests/ad/group/Test.AD-GMC-01.md | 4 +- tests/ad/group/Test.AD-GMC-01.ps1 | 17 +--- tests/ad/group/Test.AD-GMC-02.md | 3 +- tests/ad/group/Test.AD-GMC-02.ps1 | 27 +++--- tests/ad/group/Test.AD-GMC-03.md | 34 ------- tests/ad/group/Test.AD-GMC-03.ps1 | 117 ----------------------- tests/ad/group/Test.AD-GMC-04.md | 5 +- tests/ad/group/Test.AD-GMC-04.ps1 | 40 ++++---- tests/ad/group/Test.AD-GMC-05.md | 35 ------- tests/ad/group/Test.AD-GMC-05.ps1 | 144 ---------------------------- tests/ad/group/Test.AD-GMC-06.md | 5 +- tests/ad/group/Test.AD-GMC-06.ps1 | 19 ++-- tests/ad/group/Test.AD-GMC-07.md | 31 ------ tests/ad/group/Test.AD-GMC-07.ps1 | 128 ------------------------- tests/ad/group/Test.AD-GMC-08.md | 2 +- tests/ad/group/Test.AD-GMC-08.ps1 | 17 ++-- tests/ad/group/Test.AD-GMC-09.md | 42 --------- tests/ad/group/Test.AD-GMC-09.ps1 | 107 --------------------- tests/ad/group/Test.AD-GMC-10.md | 2 +- tests/ad/group/Test.AD-GMC-10.ps1 | 14 ++- tests/ad/group/Test.AD-GMC-11.md | 47 --------- tests/ad/group/Test.AD-GMC-11.ps1 | 152 ------------------------------ tests/ad/ou/Test.AD-OU-05.md | 2 +- 24 files changed, 88 insertions(+), 910 deletions(-) delete mode 100644 tests/ad/group/Test.AD-GMC-03.md delete mode 100644 tests/ad/group/Test.AD-GMC-03.ps1 delete mode 100644 tests/ad/group/Test.AD-GMC-05.md delete mode 100644 tests/ad/group/Test.AD-GMC-05.ps1 delete mode 100644 tests/ad/group/Test.AD-GMC-07.md delete mode 100644 tests/ad/group/Test.AD-GMC-07.ps1 delete mode 100644 tests/ad/group/Test.AD-GMC-09.md delete mode 100644 tests/ad/group/Test.AD-GMC-09.ps1 delete mode 100644 tests/ad/group/Test.AD-GMC-11.md delete mode 100644 tests/ad/group/Test.AD-GMC-11.ps1 diff --git a/tests/ad/group/Test.AD-GCHG-01.md b/tests/ad/group/Test.AD-GCHG-01.md index 6d8732b0cf..f9f362e4d4 100644 --- a/tests/ad/group/Test.AD-GCHG-01.md +++ b/tests/ad/group/Test.AD-GCHG-01.md @@ -33,8 +33,8 @@ The analysis helps identify trends and patterns in group management activity. #### Related Tests -- `Test-MtAdGroupPrivilegedWithMembersDetails` - Reviews current privileged group state -- `Test-MtAdGroupEmptyNonPrivilegedDetails` - Identifies potentially stale groups +- `AD-GMC-02` - Reviews current privileged group membership counts and details +- `AD-GMC-10` - Identifies empty non-privileged groups %TestResult% diff --git a/tests/ad/group/Test.AD-GMC-01.md b/tests/ad/group/Test.AD-GMC-01.md index 9aca604c7a..f4062b5761 100644 --- a/tests/ad/group/Test.AD-GMC-01.md +++ b/tests/ad/group/Test.AD-GMC-01.md @@ -24,11 +24,11 @@ This test analyzes Active Directory groups and counts: - Percentage of groups with members - Empty groups (for cleanup candidates) -For performance reasons, the test analyzes the first 100 groups if there are many groups in the directory. +The check analyzes every collected group and reports the complete group count. #### Related Tests -- `Test-MtAdGroupMemberAccountTypeDetails` - Breaks down member types across groups +- `Test-MtAdGroupMemberAccountTypeCount` - Breaks down member types across groups - `Test-MtAdGroupMemberTrustCount` - Identifies cross-domain trust members diff --git a/tests/ad/group/Test.AD-GMC-01.ps1 b/tests/ad/group/Test.AD-GMC-01.ps1 index 3b7631feab..381c309945 100644 --- a/tests/ad/group/Test.AD-GMC-01.ps1 +++ b/tests/ad/group/Test.AD-GMC-01.ps1 @@ -44,25 +44,20 @@ } $groups = $adState.Groups + if ($null -eq $groups) { throw 'Group collection is unavailable.' } $totalGroupCount = ($groups | Measure-Object).Count $protocolConnection = New-MtAdProtocolConnection -ProtocolEvidence $adState.ProtocolEvidence # Query members for each group to find groups with members - # Limit to first 100 groups for performance if there are many - $groupsToCheck = $groups | Select-Object -First 100 + $groupsToCheck = @($groups) $groupsWithMembers = @() foreach ($group in $groupsToCheck) { - try { - $members = @(Get-MtLdapGroupMember -Connection $protocolConnection -GroupDistinguishedName $group.DistinguishedName) + $members = @(Get-MtLdapGroupMember -Connection $protocolConnection -GroupDistinguishedName $group.DistinguishedName) if ($members -and ($members | Measure-Object).Count -gt 0) { $groupsWithMembers += $group } - } - catch { - Write-Verbose "Could not retrieve members for group $($group.Name): $($_.Exception.Message)" - } } $protocolConnection.Dispose() @@ -88,9 +83,7 @@ $result += "| Empty Groups | $emptyGroupsCount |" + "`n" $result += "| Groups with Members % | $percentage% |" + "`n" - if ($groupsToCheck.Count -lt $totalGroupCount) { - $result += "| Note | Analyzed first $($groupsToCheck.Count) groups for performance |" + "`n" - } + $result += "| Groups Analyzed | $($groupsToCheck.Count) |" + "`n" $testResultMarkdown = "Active Directory groups have been analyzed. $groupsWithMembersCount out of $totalGroupCount groups ($percentage%) have at least one member.`n`n%TestResult%" $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result @@ -98,7 +91,7 @@ $testResultMarkdown = "Unable to retrieve Active Directory group objects. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/group/Test.AD-GMC-02.md b/tests/ad/group/Test.AD-GMC-02.md index 7fc4c943ad..9400a41ff8 100644 --- a/tests/ad/group/Test.AD-GMC-02.md +++ b/tests/ad/group/Test.AD-GMC-02.md @@ -22,11 +22,10 @@ - Counts unique account types (user, group, computer, foreignSecurityPrincipal) - Provides visibility into membership composition -For performance reasons, the test analyzes members from the first 50 groups and deduplicates by SID. +The test analyzes all collected groups, deduplicates members by SID (or distinguished name when SID is unavailable), and includes the account-type breakdown. #### Related Tests -- `Test-MtAdGroupMemberAccountTypeDetails` - Detailed breakdown of account types - `Test-MtAdGroupMemberForeignSidCount` - Identifies foreign security principals specifically diff --git a/tests/ad/group/Test.AD-GMC-02.ps1 b/tests/ad/group/Test.AD-GMC-02.ps1 index 202c70b4c8..ffd91f4296 100644 --- a/tests/ad/group/Test.AD-GMC-02.ps1 +++ b/tests/ad/group/Test.AD-GMC-02.ps1 @@ -45,29 +45,25 @@ } $groups = $adState.Groups + if ($null -eq $groups) { throw 'Group collection is unavailable.' } $protocolConnection = New-MtAdProtocolConnection -ProtocolEvidence $adState.ProtocolEvidence # Collect all unique member object classes - # Limit to first 50 groups for performance - $groupsToCheck = $groups | Select-Object -First 50 + $groupsToCheck = @($groups) $allMembers = @() $processedSids = @{} foreach ($group in $groupsToCheck) { - try { - $members = @(Get-MtLdapGroupMember -Connection $protocolConnection -GroupDistinguishedName $group.DistinguishedName) + $members = @(Get-MtLdapGroupMember -Connection $protocolConnection -GroupDistinguishedName $group.DistinguishedName) foreach ($member in $members) { # Avoid duplicates by SID - if (-not $processedSids.ContainsKey($member.SID.Value)) { - $processedSids[$member.SID.Value] = $true + $memberKey = if ($member.SID.Value) { [string]$member.SID.Value } else { [string]$member.DistinguishedName } + if (-not $processedSids.ContainsKey($memberKey)) { + $processedSids[$memberKey] = $true $allMembers += $member } } - } - catch { - Write-Verbose "Could not retrieve members for group $($group.Name): $($_.Exception.Message)" - } } $protocolConnection.Dispose() @@ -87,18 +83,21 @@ $result += "| Total Unique Members Analyzed | $totalUniqueMembers |" + "`n" $result += "| Distinct Account Types | $distinctTypeCount |" + "`n" $result += "| Account Types Found | $($distinctTypes -join ', ') |" + "`n" - - if ($groupsToCheck.Count -lt ($groups | Measure-Object).Count) { - $result += "| Note | Analyzed first $($groupsToCheck.Count) groups for performance |" + "`n" + $result += "`n| Account Type | Unique Members |" + "`n" + $result += "| --- | --- |" + "`n" + foreach ($type in @($allMembers | Group-Object objectClass | Sort-Object Count -Descending)) { + $result += "| $($type.Name) | $($type.Count) |" + "`n" } + $result += "| Groups Analyzed | $($groupsToCheck.Count) |" + "`n" + $testResultMarkdown = "Active Directory group member account types have been analyzed. Found $distinctTypeCount distinct account types across $totalUniqueMembers unique members.`n`n%TestResult%" $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result } else { $testResultMarkdown = "Unable to retrieve Active Directory group member data. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/group/Test.AD-GMC-03.md b/tests/ad/group/Test.AD-GMC-03.md deleted file mode 100644 index eaa04db3f9..0000000000 --- a/tests/ad/group/Test.AD-GMC-03.md +++ /dev/null @@ -1,34 +0,0 @@ -A detailed breakdown of account types across group membership provides comprehensive visibility: - -- **User Accounts**: Most common members - represent individual access -- **Group Nesting**: Groups within groups create hierarchical permissions -- **Computer Accounts**: Service accounts and system access requirements -- **Foreign Security Principals**: Cross-domain and cross-forest access - -#### Control Type - -**Operational** - -#### Security Recommendation - -Review account type distributions to identify: -- Over-reliance on group nesting that may create privilege escalation paths -- Unusual patterns (e.g., many computer accounts in privileged groups) -- External principals that may need periodic trust validation - -#### How the Test Works - -This test provides a detailed analysis of group membership composition: -- Categorizes all unique members by their object class -- Shows count and percentage for each account type -- Identifies the distribution of member types across groups - -For performance reasons, the test analyzes members from the first 50 groups and deduplicates by SID. - -#### Related Tests - -- `Test-MtAdGroupMemberAccountTypeCount` - Count of distinct account types -- `Test-MtAdGroupMemberTrustDetails` - Detailed view of trust members by group - - -%TestResult% diff --git a/tests/ad/group/Test.AD-GMC-03.ps1 b/tests/ad/group/Test.AD-GMC-03.ps1 deleted file mode 100644 index 5a84155a25..0000000000 --- a/tests/ad/group/Test.AD-GMC-03.ps1 +++ /dev/null @@ -1,117 +0,0 @@ -function Test-MtAdGroupMemberAccountTypeDetails { - <# - .SYNOPSIS - Provides detailed breakdown of member account types across Active Directory groups. - - .DESCRIPTION - This test provides a comprehensive analysis of group membership composition in - Active Directory. It categorizes members by their object class (user, group, - computer, foreignSecurityPrincipal) and provides counts for each type. This - detailed view helps administrators understand the structure and composition - of their group memberships. - - .EXAMPLE - Test-MtAdGroupMemberAccountTypeDetails - - Returns $true if group member data is accessible, $false otherwise. - The test result includes detailed breakdown of account types. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGroupMemberAccountTypeDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-GMC-03', - Title = 'Member account types breakdown should be retrievable', - Product = 'ad', - Feature = 'groups', - Area = 'identity-lifecycle', - ResourceType = 'Group', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:group:ReadProperty', 'ActiveDirectory:Ldap:group.member:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('Groups') - - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $groups = $adState.Groups - - $protocolConnection = New-MtAdProtocolConnection -ProtocolEvidence $adState.ProtocolEvidence - - # Collect all members and their types - # Limit to first 50 groups for performance - $groupsToCheck = $groups | Select-Object -First 50 - $allMembers = @() - $processedSids = @{} - - foreach ($group in $groupsToCheck) { - try { - $members = @(Get-MtLdapGroupMember -Connection $protocolConnection -GroupDistinguishedName $group.DistinguishedName) - foreach ($member in $members) { - # Avoid duplicates by SID - if (-not $processedSids.ContainsKey($member.SID.Value)) { - $processedSids[$member.SID.Value] = $true - $allMembers += $member - } - } - } catch { - Write-Verbose "Could not retrieve members for group $($group.Name): $($_.Exception.Message)" - } - } - - $protocolConnection.Dispose() - - # Group by object class and get counts - $typeBreakdown = $allMembers | Group-Object -Property objectClass | Sort-Object Count -Descending - $totalUniqueMembers = $allMembers.Count - $distinctTypeCount = $typeBreakdown.Count - - # Test passes if we successfully retrieved member data - $testResult = $totalUniqueMembers -ge 0 - - # Generate markdown results - if ($testResult) { - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Unique Members Analyzed | $totalUniqueMembers |" + "`n" - $result += "| Distinct Account Types | $distinctTypeCount |" + "`n" - - if ($groupsToCheck.Count -lt ($groups | Measure-Object).Count) { - $result += "| Groups Analyzed | $($groupsToCheck.Count) of $(($groups | Measure-Object).Count) |" + "`n" - } - - $result += "`n**Account Type Breakdown:**" + "`n" + "`n" - $result += "| Account Type | Count | Percentage |" + "`n" - $result += "| --- | --- | --- |" + "`n" - - foreach ($type in $typeBreakdown) { - $percentage = if ($totalUniqueMembers -gt 0) { - [Math]::Round(($type.Count / $totalUniqueMembers) * 100, 2) - } else { - 0 - } - $result += "| $($type.Name) | $($type.Count) | $percentage% |" + "`n" - } - - $testResultMarkdown = "Active Directory group member account types have been analyzed. Found $distinctTypeCount distinct account types across $totalUniqueMembers unique members.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory group member data. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult -} diff --git a/tests/ad/group/Test.AD-GMC-04.md b/tests/ad/group/Test.AD-GMC-04.md index 4f4337970d..07b97bea97 100644 --- a/tests/ad/group/Test.AD-GMC-04.md +++ b/tests/ad/group/Test.AD-GMC-04.md @@ -20,14 +20,13 @@ Regularly audit trust members: This test identifies trust members by: - Detecting foreignSecurityPrincipal object class -- Identifying SIDs that don't match the current domain SID pattern +- Identifying foreign domain-account SIDs (`S-1-5-21-…`) and foreign security principal objects; built-in `S-1-5-32` and NT AUTHORITY SIDs are not automatically foreign domains - Counting unique trust members across groups -For performance reasons, the test analyzes the first 50 groups. +The test analyzes all groups and includes the affected group names and member SIDs in its result. #### Related Tests -- `Test-MtAdGroupMemberTrustDetails` - Detailed breakdown by group - `Test-MtAdGroupMemberForeignSidCount` - Counts foreign SIDs specifically diff --git a/tests/ad/group/Test.AD-GMC-04.ps1 b/tests/ad/group/Test.AD-GMC-04.ps1 index d914e2ca34..e31150e0de 100644 --- a/tests/ad/group/Test.AD-GMC-04.ps1 +++ b/tests/ad/group/Test.AD-GMC-04.ps1 @@ -47,36 +47,41 @@ $groups = $adState.Groups $domain = $adState.Domain - $domainSid = $domain.DomainSID.Value + $domainSid = if ($domain.DomainSID.PSObject.Properties['Value']) { [string]$domain.DomainSID.Value } else { [string]$domain.DomainSID } + if ($null -eq $groups -or -not $domainSid) { throw 'Group or domain SID collection is unavailable.' } $protocolConnection = New-MtAdProtocolConnection -ProtocolEvidence $adState.ProtocolEvidence # Collect trust members - # Limit to first 50 groups for performance - $groupsToCheck = $groups | Select-Object -First 50 + # Assess every group; counts describe distinct SIDs and details retain all group memberships. + $groupsToCheck = @($groups) $trustMembers = @() $processedSids = @{} - foreach ($group in $groupsToCheck) { - try { + try { + foreach ($group in $groupsToCheck) { $members = @(Get-MtLdapGroupMember -Connection $protocolConnection -GroupDistinguishedName $group.DistinguishedName) foreach ($member in $members) { + $memberSid = if ($member.SID.PSObject.Properties['Value']) { [string]$member.SID.Value } else { [string]$member.SID } # Check if this is a trust member (foreignSecurityPrincipal or SID doesn't match domain) $isTrustMember = $false # Check by objectClass - if ($member.objectClass -eq 'foreignSecurityPrincipal') { + if (($member.IsForeignSecurityPrincipal -or $member.objectClass -eq 'foreignSecurityPrincipal') -and $memberSid -match '^S-1-5-21-') { $isTrustMember = $true } # Check by SID prefix (doesn't match current domain SID) - elseif ($member.SID.Value -and -not $member.SID.Value.StartsWith($domainSid)) { + elseif ($memberSid -match '^S-1-5-21-' -and -not $memberSid.StartsWith("$domainSid-")) { $isTrustMember = $true } - if ($isTrustMember -and -not $processedSids.ContainsKey($member.SID.Value)) { - $processedSids[$member.SID.Value] = $true + if (($member.IsForeignSecurityPrincipal -or $member.objectClass -eq 'foreignSecurityPrincipal') -and -not $memberSid) { + throw 'A foreign security principal has no SID; its domain cannot be assessed.' + } + if ($isTrustMember) { + $processedSids[$memberSid] = $true $trustMembers += [PSCustomObject]@{ - SID = $member.SID.Value + SID = $memberSid Name = $member.Name ObjectClass = $member.objectClass GroupName = $group.Name @@ -84,14 +89,10 @@ } } } - catch { - Write-Verbose "Could not retrieve members for group $($group.Name): $($_.Exception.Message)" - } } + finally { $protocolConnection.Dispose() } - $protocolConnection.Dispose() - - $trustMemberCount = $trustMembers.Count + $trustMemberCount = $processedSids.Count # Test passes if we successfully retrieved member data $testResult = $true @@ -101,7 +102,14 @@ $result = "| Metric | Value |" + "`n" $result += "| --- | --- |" + "`n" $result += "| Trust Members Found | $trustMemberCount |" + "`n" + $result += "| Foreign domain group memberships | $($trustMembers.Count) |" + "`n" $result += "| Groups Analyzed | $($groupsToCheck.Count) |" + "`n" + if ($trustMemberCount -gt 0) { + $result += "`n| Group | Member | SID |" + "`n| --- | --- | --- |" + "`n" + foreach ($member in $trustMembers) { + $result += "| $($member.GroupName) | $($member.Name) | $($member.SID) |" + "`n" + } + } if ($groupsToCheck.Count -lt ($groups | Measure-Object).Count) { $result += "| Note | Analyzed first $($groupsToCheck.Count) of $(($groups | Measure-Object).Count) groups |" + "`n" diff --git a/tests/ad/group/Test.AD-GMC-05.md b/tests/ad/group/Test.AD-GMC-05.md deleted file mode 100644 index b7b443fda3..0000000000 --- a/tests/ad/group/Test.AD-GMC-05.md +++ /dev/null @@ -1,35 +0,0 @@ -Understanding which specific groups contain trust members is critical for security management: - -- **Privileged Access**: Trust members in privileged groups (Administrators, Domain Admins) represent significant risk -- **Access Path Analysis**: Knowing which groups contain external members helps trace access paths -- **Trust Management**: Groups with many trust members may indicate over-reliance on external access -- **Compliance**: Some compliance frameworks require documentation of cross-domain access - -#### Control Type - -**Operational** - -#### Security Recommendation - -Perform detailed review of groups containing trust members: -- Prioritize review of privileged groups with external members -- Document the source domain and purpose of each trust member -- Establish processes to periodically validate continued need for external access -- Consider creating domain-local groups specifically for external access to maintain clear boundaries - -#### How the Test Works - -This test provides detailed analysis of trust membership: -- Identifies which groups contain trust members -- Lists trust members per group with their SIDs and types -- Shows the distribution of external access across groups - -For performance reasons, the test analyzes the first 50 groups and limits display to 10 members per group. - -#### Related Tests - -- `Test-MtAdGroupMemberTrustCount` - Overall count of trust members -- `Test-MtAdGroupMemberForeignSidCount` - Analysis of foreign SIDs - - -%TestResult% diff --git a/tests/ad/group/Test.AD-GMC-05.ps1 b/tests/ad/group/Test.AD-GMC-05.ps1 deleted file mode 100644 index f5fd4bbaf1..0000000000 --- a/tests/ad/group/Test.AD-GMC-05.ps1 +++ /dev/null @@ -1,144 +0,0 @@ -function Test-MtAdGroupMemberTrustDetails { - <# - .SYNOPSIS - Provides detailed breakdown of trust members by group in Active Directory. - - .DESCRIPTION - This test provides a detailed analysis of which Active Directory groups contain - members from trusted domains. It identifies groups with foreign security principals - or members with SIDs from external domains, showing the breakdown per group. - This helps administrators understand cross-domain access patterns and identify - which groups grant access to external users or groups. - - .EXAMPLE - Test-MtAdGroupMemberTrustDetails - - Returns $true if group member data is accessible, $false otherwise. - The test result includes detailed breakdown of trust members by group. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGroupMemberTrustDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-GMC-05', - Title = 'Trust members details by group should be investigated', - Product = 'ad', - Feature = 'groups', - Area = 'external-access', - ResourceType = 'Group', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:domainDNS:ReadProperty', 'ActiveDirectory:Ldap:group:ReadProperty', 'ActiveDirectory:Ldap:group.member:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('Domain', 'Groups') - - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $groups = $adState.Groups - $domain = $adState.Domain - $domainSid = $domain.DomainSID.Value - - $protocolConnection = New-MtAdProtocolConnection -ProtocolEvidence $adState.ProtocolEvidence - - # Collect trust members per group - # Limit to first 50 groups for performance - $groupsToCheck = $groups | Select-Object -First 50 - $groupsWithTrustMembers = @{} - $totalTrustMembers = 0 - - foreach ($group in $groupsToCheck) { - try { - $members = @(Get-MtLdapGroupMember -Connection $protocolConnection -GroupDistinguishedName $group.DistinguishedName) - $groupTrustMembers = @() - - foreach ($member in $members) { - # Check if this is a trust member - $isTrustMember = $false - - if ($member.objectClass -eq 'foreignSecurityPrincipal') { - $isTrustMember = $true - } elseif ($member.SID.Value -and -not $member.SID.Value.StartsWith($domainSid)) { - $isTrustMember = $true - } - - if ($isTrustMember) { - $groupTrustMembers += [PSCustomObject]@{ - SID = $member.SID.Value - Name = $member.Name - ObjectClass = $member.objectClass - } - $totalTrustMembers++ - } - } - - if ($groupTrustMembers.Count -gt 0) { - $groupsWithTrustMembers[$group.Name] = $groupTrustMembers - } - } catch { - Write-Verbose "Could not retrieve members for group $($group.Name): $($_.Exception.Message)" - } - } - - $protocolConnection.Dispose() - - $groupsWithTrustCount = $groupsWithTrustMembers.Count - - # Test passes if we successfully retrieved member data - $testResult = $true - - # Generate markdown results - if ($testResult) { - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Groups with Trust Members | $groupsWithTrustCount |" + "`n" - $result += "| Total Trust Members | $totalTrustMembers |" + "`n" - $result += "| Groups Analyzed | $($groupsToCheck.Count) |" + "`n" - - if ($groupsToCheck.Count -lt ($groups | Measure-Object).Count) { - $result += "| Note | Analyzed first $($groupsToCheck.Count) of $(($groups | Measure-Object).Count) groups |" + "`n" - } - - if ($groupsWithTrustCount -gt 0) { - $result += "`n**Groups Containing Trust Members:**" + "`n" + "`n" - - foreach ($groupName in ($groupsWithTrustMembers.Keys | Sort-Object)) { - $trustMembers = $groupsWithTrustMembers[$groupName] - $result += "**$groupName** ($($trustMembers.Count) trust members)" + "`n" + "`n" - $result += "| Name | SID | Type |" + "`n" - $result += "| --- | --- | --- |" + "`n" - - foreach ($member in $trustMembers | Select-Object -First 10) { - $result += "| $($member.Name) | $($member.SID) | $($member.ObjectClass) |" + "`n" - } - - if ($trustMembers.Count -gt 10) { - $result += "| ... | ... | ... ($($trustMembers.Count - 10) more) |" + "`n" - } - $result += "" + "`n" - } - } else { - $result += "`nNo groups with trust members found in analyzed groups." + "`n" - } - - $testResultMarkdown = "Active Directory group trust membership details have been analyzed. Found $totalTrustMembers trust members across $groupsWithTrustCount groups.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory group member data. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - - return $testResult -} diff --git a/tests/ad/group/Test.AD-GMC-06.md b/tests/ad/group/Test.AD-GMC-06.md index 472e27b2af..648762ab32 100644 --- a/tests/ad/group/Test.AD-GMC-06.md +++ b/tests/ad/group/Test.AD-GMC-06.md @@ -21,16 +21,15 @@ Monitor and audit foreign SIDs carefully: This test analyzes group membership for foreign SIDs by: - Comparing member SIDs against the current domain SID -- Identifying SIDs that don't match the local domain pattern +- Comparing domain-account SIDs in the `S-1-5-21` namespace; well-known `S-1-5-32` and NT AUTHORITY SIDs are not foreign domains - Grouping foreign SIDs by their domain of origin - Counting unique foreign SID principals -For performance reasons, the test analyzes the first 50 groups. +The test analyzes all groups and includes group, principal, and SID details. #### Related Tests - `Test-MtAdGroupMemberTrustCount` - Count of trust members overall -- `Test-MtAdGroupMemberTrustDetails` - Detailed view by group %TestResult% diff --git a/tests/ad/group/Test.AD-GMC-06.ps1 b/tests/ad/group/Test.AD-GMC-06.ps1 index 675e217372..c21e28f787 100644 --- a/tests/ad/group/Test.AD-GMC-06.ps1 +++ b/tests/ad/group/Test.AD-GMC-06.ps1 @@ -46,6 +46,7 @@ } $groups = $adState.Groups + if ($null -eq $groups -or -not $adState.Domain.DomainSID.Value) { throw 'Group or domain SID collection is unavailable.' } $domain = $adState.Domain $domainSid = $domain.DomainSID.Value @@ -53,7 +54,7 @@ # Collect foreign SID principals # Limit to first 50 groups for performance - $groupsToCheck = $groups | Select-Object -First 50 + $groupsToCheck = @($groups) $foreignSidPrincipals = @() $processedSids = @{} @@ -62,17 +63,13 @@ $members = @(Get-MtLdapGroupMember -Connection $protocolConnection -GroupDistinguishedName $group.DistinguishedName) foreach ($member in $members) { # Check if SID is foreign (doesn't start with domain SID) - if ($member.SID.Value -and -not $member.SID.Value.StartsWith($domainSid)) { + if ($member.SID.Value -match '^S-1-5-21-\d+-\d+-\d+-\d+$' -and -not $member.SID.Value.StartsWith("$domainSid-")) { if (-not $processedSids.ContainsKey($member.SID.Value)) { $processedSids[$member.SID.Value] = $true # Extract domain SID prefix $sidString = $member.SID.Value - $domainSidPrefix = if ($sidString -match '^S-\d+-\d+-\d+-\d+-\d+') { - $matches[0] - } else { - "Unknown" - } + $domainSidPrefix = $sidString -replace '-\d+$', '' $foreignSidPrincipals += [PSCustomObject]@{ SID = $member.SID.Value @@ -86,7 +83,7 @@ } } catch { - Write-Verbose "Could not retrieve members for group $($group.Name): $($_.Exception.Message)" + throw "Could not retrieve members for group $($group.Name): $($_.Exception.Message)" } } @@ -106,6 +103,12 @@ $result += "| Distinct External Domains | $distinctDomainSids |" + "`n" $result += "| Groups Analyzed | $($groupsToCheck.Count) |" + "`n" $result += "| Current Domain SID | $domainSid |" + "`n" + if ($foreignSidCount -gt 0) { + $result += "`n| Group | Principal | Foreign SID |" + "`n| --- | --- | --- |" + "`n" + foreach ($principal in $foreignSidPrincipals) { + $result += "| $($principal.GroupName) | $($principal.Name) | $($principal.SID) |" + "`n" + } + } if ($groupsToCheck.Count -lt ($groups | Measure-Object).Count) { $result += "| Note | Analyzed first $($groupsToCheck.Count) of $(($groups | Measure-Object).Count) groups |" + "`n" diff --git a/tests/ad/group/Test.AD-GMC-07.md b/tests/ad/group/Test.AD-GMC-07.md deleted file mode 100644 index 90c6d9fb2c..0000000000 --- a/tests/ad/group/Test.AD-GMC-07.md +++ /dev/null @@ -1,31 +0,0 @@ -Foreign security principals (FSPs) represent security principals from trusted external domains or forests. Understanding their distribution is important because: - -- **Trust visibility**: Identifies external trusts that may have been forgotten or are no longer needed -- **Security boundaries**: Helps assess the blast radius if an external domain is compromised -- **Access control**: Reveals who has access to resources from outside the domain -- **Cleanup opportunities**: May highlight groups that can be cleaned up after domain migrations - -#### Control Type - -**Operational** - -#### Security Recommendation - -Regularly review foreign security principals: -- Remove memberships from domains that are no longer trusted -- Audit groups containing external accounts for appropriate access levels -- Document all domain trusts and their business justifications -- Consider converting external access to local accounts where appropriate -- Monitor for unexpected foreign principal additions - -#### How the Test Works - -This test examines all group memberships in Active Directory and identifies security principals with SIDs that don't match the local domain SID. It groups these foreign principals by their domain SID and counts how many exist from each external domain. - -#### Related Tests - -- `Test-MtAdGroupMemberForeignSidCount` - Counts total foreign security principals -- `Test-MtAdGroupPrivilegedWithMembersDetails` - Reviews privileged group memberships - - -%TestResult% diff --git a/tests/ad/group/Test.AD-GMC-07.ps1 b/tests/ad/group/Test.AD-GMC-07.ps1 deleted file mode 100644 index aea7d437ae..0000000000 --- a/tests/ad/group/Test.AD-GMC-07.ps1 +++ /dev/null @@ -1,128 +0,0 @@ -function Test-MtAdGroupMemberForeignSidDetails { - <# - .SYNOPSIS - Details of foreign security principals by their domain of origin. - - .DESCRIPTION - This test analyzes group memberships containing foreign security principals (FSPs) - and breaks them down by their domain of origin. Foreign SIDs indicate trusts - with external domains or forests and may pose security risks if not properly managed. - - .EXAMPLE - Test-MtAdGroupMemberForeignSidDetails - - Returns $true if foreign SID data is retrievable. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGroupMemberForeignSidDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-GMC-07', - Title = 'Foreign SID details by domain should be investigated', - Product = 'ad', - Feature = 'groups', - Area = 'external-access', - ResourceType = 'Group', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:domainDNS:ReadProperty', 'ActiveDirectory:Ldap:group:ReadProperty', 'ActiveDirectory:Ldap:group.member:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - $adState = Get-MtADDomainState -Categories @('Domain', 'Groups') - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $groups = $adState.Groups - $domain = $adState.Domain - $domainSid = $domain.DomainSID.Value - - $protocolConnection = New-MtAdProtocolConnection -ProtocolEvidence $adState.ProtocolEvidence - - # Collect all foreign SIDs from group members - $foreignSidsByDomain = @{} - $totalForeignSids = 0 - - foreach ($group in $groups) { - try { - # Get group members - $members = @(Get-MtLdapGroupMember -Connection $protocolConnection -GroupDistinguishedName $group.DistinguishedName) - - foreach ($member in $members) { - if ($member.SID -and $member.SID.Value) { - $sidString = $member.SID.Value - - # Check if this is a foreign SID (does not start with domain SID) - if (-not $sidString.StartsWith($domainSid)) { - $totalForeignSids++ - - # Extract domain SID from the foreign SID - $foreignDomainSid = $sidString -replace '-\d+$', '' - - if (-not $foreignSidsByDomain.ContainsKey($foreignDomainSid)) { - $foreignSidsByDomain[$foreignDomainSid] = @{ - DomainSid = $foreignDomainSid - Count = 0 - Groups = @() - } - } - - $foreignSidsByDomain[$foreignDomainSid].Count++ - - if ($group.Name -notin $foreignSidsByDomain[$foreignDomainSid].Groups) { - $foreignSidsByDomain[$foreignDomainSid].Groups += $group.Name - } - } - } - } - } catch { - Write-Verbose "Could not retrieve members for group $($group.Name): $($_.Exception.Message)" - } - } - - $protocolConnection.Dispose() - - $testResult = $true - - if ($testResult) { - $result = "### Foreign Security Principals by Domain" + "`n" + "`n" - - if ($foreignSidsByDomain.Count -eq 0) { - $result += "> No foreign security principals found in group memberships." + "`n" + "`n" - $result += "This indicates all group members belong to the local domain." + "`n" + "`n" - } else { - $result += "| Domain SID | FSP Count | Groups Affected |" + "`n" - $result += "| --- | --- | --- |" + "`n" - - $sortedDomains = $foreignSidsByDomain.GetEnumerator() | Sort-Object { $_.Value.Count } -Descending - - foreach ($domainEntry in $sortedDomains) { - $sid = $domainEntry.Value.DomainSid - $count = $domainEntry.Value.Count - $affectedGroups = ($domainEntry.Value.Groups | Select-Object -First 5) -join ', ' - if ($domainEntry.Value.Groups.Count -gt 5) { - $affectedGroups += " (+$($domainEntry.Value.Groups.Count - 5) more)" - } - - $result += "| $sid | $count | $affectedGroups |" + "`n" - } - - $result += "`n**Total Foreign Security Principals:** $totalForeignSids" + "`n" - $result += "**External Domains:** $($foreignSidsByDomain.Count)" + "`n" - } - - $testResultMarkdown = $result - } else { - $testResultMarkdown = "Unable to retrieve foreign security principal data." - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - return $testResult -} diff --git a/tests/ad/group/Test.AD-GMC-08.md b/tests/ad/group/Test.AD-GMC-08.md index 698ccf3354..89c1e911af 100644 --- a/tests/ad/group/Test.AD-GMC-08.md +++ b/tests/ad/group/Test.AD-GMC-08.md @@ -29,7 +29,7 @@ The test categorizes groups by their status (empty privileged, empty non-privile #### Related Tests -- `Test-MtAdGroupEmptyNonPrivilegedDetails` - Lists specific empty non-privileged groups +- This check lists specific empty non-privileged groups alongside their count. - `Test-MtAdGroupPrivilegedWithMembersCount` - Reviews privileged groups with members diff --git a/tests/ad/group/Test.AD-GMC-08.ps1 b/tests/ad/group/Test.AD-GMC-08.ps1 index 23cd88adfc..c81b2d5938 100644 --- a/tests/ad/group/Test.AD-GMC-08.ps1 +++ b/tests/ad/group/Test.AD-GMC-08.ps1 @@ -40,12 +40,13 @@ } $groups = $adState.Groups + if ($null -eq $groups) { throw 'Group collection is unavailable.' } $totalGroups = ($groups | Measure-Object).Count $protocolConnection = New-MtAdProtocolConnection -ProtocolEvidence $adState.ProtocolEvidence # Count empty non-privileged groups - $emptyNonPrivilegedGroups = 0 + $emptyNonPrivilegedGroups = @() $emptyPrivilegedGroups = 0 $nonEmptyGroups = 0 @@ -59,14 +60,14 @@ if ($group.adminCount -eq 1) { $emptyPrivilegedGroups++ } else { - $emptyNonPrivilegedGroups++ + $emptyNonPrivilegedGroups += $group } } else { $nonEmptyGroups++ } } catch { - Write-Verbose "Could not check members for group $($group.Name): $($_.Exception.Message)" + throw "Could not check members for group $($group.Name): $($_.Exception.Message)" } } @@ -78,16 +79,20 @@ $result = "| Category | Count |" + "`n" $result += "| --- | --- |" + "`n" $result += "| Total Groups | $totalGroups |" + "`n" - $result += "| Empty Non-Privileged Groups | $emptyNonPrivilegedGroups |" + "`n" + $result += "| Empty Non-Privileged Groups | $($emptyNonPrivilegedGroups.Count) |" + "`n" $result += "| Empty Privileged Groups | $emptyPrivilegedGroups |" + "`n" $result += "| Groups with Members | $nonEmptyGroups |" + "`n" if ($totalGroups -gt 0) { - $emptyPercentage = [Math]::Round(($emptyNonPrivilegedGroups / $totalGroups) * 100, 2) + $emptyPercentage = [Math]::Round(($emptyNonPrivilegedGroups.Count / $totalGroups) * 100, 2) $result += "| Empty Non-Privileged Percentage | $emptyPercentage% |" + "`n" } - $testResultMarkdown = "Active Directory group analysis found **$emptyNonPrivilegedGroups** empty non-privileged groups out of **$totalGroups** total groups." + "`n" + "`n" + $result += "`n| Empty Non-Privileged Group | Scope | Category |" + "`n| --- | --- | --- |" + "`n" + foreach ($group in $emptyNonPrivilegedGroups) { + $result += "| $($group.Name) | $($group.GroupScope) | $($group.GroupCategory) |" + "`n" + } + $testResultMarkdown = "Active Directory group analysis found **$($emptyNonPrivilegedGroups.Count)** empty non-privileged groups out of **$totalGroups** total groups." + "`n" + "`n" $testResultMarkdown += "Empty non-privileged groups may be candidates for cleanup.`n`n%TestResult%" $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result } else { diff --git a/tests/ad/group/Test.AD-GMC-09.md b/tests/ad/group/Test.AD-GMC-09.md deleted file mode 100644 index a8a6ee9632..0000000000 --- a/tests/ad/group/Test.AD-GMC-09.md +++ /dev/null @@ -1,42 +0,0 @@ -Detailed visibility into empty non-privileged groups enables effective cleanup: - -- **Identification**: Lists specific groups that can be removed -- **Age assessment**: Shows creation and modification dates to determine staleness -- **Categorization**: Groups by type (security vs. distribution) and scope -- **Cleanup planning**: Provides data needed for maintenance windows -- **Audit trail**: Documents what was empty before cleanup - -#### Control Type - -**Operational** - -#### Security Recommendation - -Before removing empty groups: -- Verify groups are not referenced by applications or scripts -- Check if groups are used in Group Policy or Conditional Access -- Document groups before deletion for potential rollback -- Consider disabling groups first before permanent deletion -- Communicate with application owners about group dependencies -- Maintain a log of cleaned groups for compliance purposes - -#### How the Test Works - -This test identifies all Active Directory groups that: -1. Have no members -2. Do not have adminCount = 1 - -It then lists these groups with their: -- Name -- Group scope (DomainLocal, Global, Universal) -- Group category (Security, Distribution) -- Creation date -- Last modification date - -#### Related Tests - -- `Test-MtAdGroupEmptyNonPrivilegedCount` - Counts empty non-privileged groups -- `Test-MtAdGroupPrivilegedWithMembersDetails` - Reviews privileged group memberships - - -%TestResult% diff --git a/tests/ad/group/Test.AD-GMC-09.ps1 b/tests/ad/group/Test.AD-GMC-09.ps1 deleted file mode 100644 index a97ef791c1..0000000000 --- a/tests/ad/group/Test.AD-GMC-09.ps1 +++ /dev/null @@ -1,107 +0,0 @@ -function Test-MtAdGroupEmptyNonPrivilegedDetails { - <# - .SYNOPSIS - Details of empty non-privileged groups in Active Directory. - - .DESCRIPTION - This test lists groups that have no members and are not privileged - (do not have adminCount = 1). These groups may be candidates for cleanup - as they serve no purpose in access control and clutter the directory. - - .EXAMPLE - Test-MtAdGroupEmptyNonPrivilegedDetails - - Returns $true if data is retrievable. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGroupEmptyNonPrivilegedDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-GMC-09', - Title = 'Empty non-privileged group details should be investigated', - Product = 'ad', - Feature = 'groups', - Area = 'identity-lifecycle', - ResourceType = 'Group', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:group:ReadProperty', 'ActiveDirectory:Ldap:group.member:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - $adState = Get-MtADDomainState -Categories @('Groups') - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $groups = $adState.Groups - - $protocolConnection = $null - $emptyNonPrivilegedGroups = @() - - try { - $protocolConnection = New-MtAdProtocolConnection -ProtocolEvidence $adState.ProtocolEvidence - - foreach ($group in $groups) { - try { - $members = @(Get-MtLdapGroupMember -Connection $protocolConnection -GroupDistinguishedName $group.DistinguishedName) - $memberCount = ($members | Measure-Object).Count - - if ($memberCount -eq 0 -and $group.adminCount -ne 1) { - $emptyNonPrivilegedGroups += [PSCustomObject]@{ - Name = $group.Name - DistinguishedName = $group.DistinguishedName - GroupCategory = $group.GroupCategory - GroupScope = $group.GroupScope - Created = $group.createTimeStamp - Modified = $group.modifyTimeStamp - } - } - } catch { - Write-Verbose "Could not check members for group $($group.Name): $($_.Exception.Message)" - } - } - } finally { - if ($null -ne $protocolConnection) { - $protocolConnection.Dispose() - } - } - - $testResult = $true - - $result = "### Empty Non-Privileged Groups" + "`n" + "`n" - - if ($emptyNonPrivilegedGroups.Count -eq 0) { - $result += "> No empty non-privileged groups found." + "`n" + "`n" - $result += "All non-privileged groups have at least one member." + "`n" + "`n" - } else { - $result += "**Total Empty Non-Privileged Groups:** $($emptyNonPrivilegedGroups.Count)" + "`n" + "`n" - $result += "| Group Name | Scope | Category | Created | Last Modified |" + "`n" - $result += "| --- | --- | --- | --- | --- |" + "`n" - - $sortedGroups = $emptyNonPrivilegedGroups | Sort-Object Name - - foreach ($group in $sortedGroups | Select-Object -First 50) { - $created = if ($group.Created) { $group.Created.ToString('yyyy-MM-dd') } else { 'N/A' } - $modified = if ($group.Modified) { $group.Modified.ToString('yyyy-MM-dd') } else { 'N/A' } - - $result += "| $($group.Name) | $($group.GroupScope) | $($group.GroupCategory) | $created | $modified |" + "`n" - } - - if ($emptyNonPrivilegedGroups.Count -gt 50) { - $remaining = $emptyNonPrivilegedGroups.Count - 50 - $result += "`n> *... and $remaining more groups*" + "`n" - } - } - - $testResultMarkdown = $result - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - return $testResult -} diff --git a/tests/ad/group/Test.AD-GMC-10.md b/tests/ad/group/Test.AD-GMC-10.md index ad2cd22f51..f5747967d7 100644 --- a/tests/ad/group/Test.AD-GMC-10.md +++ b/tests/ad/group/Test.AD-GMC-10.md @@ -39,7 +39,7 @@ This test identifies privileged groups (those with adminCount = 1 or well-known #### Related Tests -- `Test-MtAdGroupPrivilegedWithMembersDetails` - Lists privileged groups with member details +- This check lists both well-known and other protected groups with members. - `Test-MtAdGroupEmptyNonPrivilegedCount` - Reviews non-privileged empty groups diff --git a/tests/ad/group/Test.AD-GMC-10.ps1 b/tests/ad/group/Test.AD-GMC-10.ps1 index 21ec0d93d0..fbdfca3152 100644 --- a/tests/ad/group/Test.AD-GMC-10.ps1 +++ b/tests/ad/group/Test.AD-GMC-10.ps1 @@ -49,6 +49,7 @@ } $groups = $adState.Groups + if ($null -eq $groups) { throw 'Group collection is unavailable.' } $protocolConnection = New-MtAdProtocolConnection -ProtocolEvidence $adState.ProtocolEvidence @@ -75,7 +76,11 @@ # Check if group is privileged (adminCount = 1 or well-known RID) $isPrivileged = $group.adminCount -eq 1 $rid = ($group.SID.Value -split '-')[-1] - $isWellKnown = $privilegedRIDs.ContainsKey($rid) + $sid = [string]$group.SID.Value + $isWellKnown = $privilegedRIDs.ContainsKey($rid) -and ( + ($sid -match '^S-1-5-21-\d+-\d+-\d+-(512|518|519)$') -or + ($sid -match '^S-1-5-32-(548|549|550|551)$') + ) if ($isPrivileged -or $isWellKnown) { $totalPrivileged++ @@ -101,7 +106,7 @@ } } catch { - Write-Verbose "Could not check members for group $($group.Name): $($_.Exception.Message)" + throw "Could not check members for group $($group.Name): $($_.Exception.Message)" } } } @@ -127,6 +132,11 @@ foreach ($group in $sortedWellKnown) { $result += "| $($group.Name) | $($group.RID) | $($group.MemberCount) |" + "`n" } + $result += "`n### Other AdminCount-Protected Groups with Members`n`n" + $result += "| Group | Member Count |" + "`n| --- | --- |" + "`n" + foreach ($group in @($privilegedGroupsWithMembers | Where-Object { -not $_.IsWellKnown } | Sort-Object MemberCount -Descending)) { + $result += "| $($group.Name) | $($group.MemberCount) |" + "`n" + } $testResultMarkdown = "Security audit found **$privilegedWithMembers** privileged groups with members out of **$totalPrivileged** total privileged groups." + "`n" + "`n" $testResultMarkdown += "These groups should be regularly audited for unauthorized membership changes.`n`n%TestResult%" diff --git a/tests/ad/group/Test.AD-GMC-11.md b/tests/ad/group/Test.AD-GMC-11.md deleted file mode 100644 index 3689585d30..0000000000 --- a/tests/ad/group/Test.AD-GMC-11.md +++ /dev/null @@ -1,47 +0,0 @@ -Understanding which privileged accounts have access is fundamental to Active Directory security: - -- **Identity management**: Know who has administrative access -- **Over-privilege detection**: Identify accounts with excessive permissions -- **Attack path analysis**: Understand potential lateral movement routes -- **Compliance evidence**: Document privileged access for audits -- **Access certification**: Support periodic access reviews - -Well-known privileged groups: -- **Domain Admins (RID 512)**: Full administrative control of the domain -- **Enterprise Admins (RID 519)**: Full administrative control of the forest -- **Schema Admins (RID 518)**: Can modify Active Directory schema -- **Account Operators (RID 548)**: Can manage user and group accounts -- **Server Operators (RID 549)**: Can manage domain servers -- **Print Operators (RID 550)**: Can manage print services -- **Backup Operators (RID 551)**: Can bypass file security for backup - -#### Control Type - -**Operational** - -#### Security Recommendation - -Review privileged group membership regularly: -- Document all members and their justifications -- Remove stale or unnecessary memberships -- Verify service accounts aren't in privileged groups unnecessarily -- Consider implementing privileged access management (PAM) solutions -- Use separate administrative accounts for privileged activities -- Implement time-bound access for privileged roles -- Monitor for new privileged group additions - -#### How the Test Works - -This test lists all privileged groups (those with adminCount = 1 or well-known RIDs) and provides: -- Group name and RID -- Member count for each group -- Categorization by well-known vs. AdminSDHolder protected groups -- Total members across all privileged groups - -#### Related Tests - -- `Test-MtAdGroupPrivilegedWithMembersCount` - Counts privileged groups with members -- `Test-MtAdGroupMemberForeignSidDetails` - Reviews foreign security principals in groups - - -%TestResult% diff --git a/tests/ad/group/Test.AD-GMC-11.ps1 b/tests/ad/group/Test.AD-GMC-11.ps1 deleted file mode 100644 index a58dd6bb88..0000000000 --- a/tests/ad/group/Test.AD-GMC-11.ps1 +++ /dev/null @@ -1,152 +0,0 @@ -function Test-MtAdGroupPrivilegedWithMembersDetails { - <# - .SYNOPSIS - Details of privileged groups with their member counts in Active Directory. - - .DESCRIPTION - This test lists all privileged groups (with adminCount = 1 or well-known RIDs) - along with their member counts. This information is crucial for security auditing - and identifying over-provisioned privileged access. - - Well-known privileged groups include: - - Domain Admins (RID 512) - - Enterprise Admins (RID 519) - - Schema Admins (RID 518) - - Account Operators (RID 548) - - Server Operators (RID 549) - - Print Operators (RID 550) - - Backup Operators (RID 551) - - .EXAMPLE - Test-MtAdGroupPrivilegedWithMembersDetails - - Returns $true if data is retrievable. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGroupPrivilegedWithMembersDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-GMC-11', - Title = 'Privileged groups with members details should be investigated', - Product = 'ad', - Feature = 'groups', - Area = 'privileged-access', - ResourceType = 'Group', - Severity = 'Info', - Mitre = ('T1098.007', 'T1078.002'), - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:group:ReadProperty', 'ActiveDirectory:Ldap:group.member:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - $adState = Get-MtADDomainState -Categories @('Groups') - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $groups = $adState.Groups - - $protocolConnection = New-MtAdProtocolConnection -ProtocolEvidence $adState.ProtocolEvidence - - # Well-known privileged group RIDs - $privilegedRIDs = @{ - '512' = 'Domain Admins' - '519' = 'Enterprise Admins' - '518' = 'Schema Admins' - '548' = 'Account Operators' - '549' = 'Server Operators' - '550' = 'Print Operators' - '551' = 'Backup Operators' - } - - # Collect privileged groups with members - $privilegedGroups = @() - - foreach ($group in $groups) { - # Check if group is privileged (adminCount = 1 or well-known RID) - $isPrivileged = $group.adminCount -eq 1 - $rid = ($group.SID.Value -split '-')[-1] - $isWellKnown = $privilegedRIDs.ContainsKey($rid) - - if ($isPrivileged -or $isWellKnown) { - try { - $members = @(Get-MtLdapGroupMember -Connection $protocolConnection -GroupDistinguishedName $group.DistinguishedName) - $memberCount = ($members | Measure-Object).Count - - $privilegedGroups += [PSCustomObject]@{ - Name = $group.Name - RID = $rid - IsWellKnown = $isWellKnown - WellKnownName = if ($isWellKnown) { $privilegedRIDs[$rid] } else { 'N/A' } - MemberCount = $memberCount - GroupScope = $group.GroupScope - GroupCategory = $group.GroupCategory - AdminCount = $group.adminCount - } - } catch { - Write-Verbose "Could not check members for group $($group.Name): $($_.Exception.Message)" - } - } - } - - $protocolConnection.Dispose() - - $testResult = $true - - if ($testResult) { - $result = "### Privileged Groups with Members" + "`n" + "`n" - - if ($privilegedGroups.Count -eq 0) { - $result += "> No privileged groups found." + "`n" + "`n" - } else { - # Sort by member count descending - $sortedGroups = $privilegedGroups | Sort-Object MemberCount -Descending - - $result += "**Total Privileged Groups:** $($privilegedGroups.Count)" + "`n" - $totalMembers = ($privilegedGroups | Measure-Object -Property MemberCount -Sum).Sum - $result += "**Total Members in Privileged Groups:** $totalMembers" + "`n" + "`n" - - # Well-known groups section - $result += "#### Well-Known Privileged Groups" + "`n" + "`n" - $result += "| Group Name | RID | Well-Known Name | Members |" + "`n" - $result += "| --- | --- | --- | --- |" + "`n" - - $wellKnownGroups = $sortedGroups | Where-Object { $_.IsWellKnown } - - foreach ($group in $wellKnownGroups) { - $result += "| **$($group.Name)** | $($group.RID) | $($group.WellKnownName) | $($group.MemberCount) |" + "`n" - } - - # AdminSDHolder protected groups section - $result += "`n#### AdminSDHolder Protected Groups (adminCount = 1)" + "`n" + "`n" - $result += "| Group Name | Members | Scope |" + "`n" - $result += "| --- | --- | --- |" + "`n" - - $adminSdHolderGroups = $sortedGroups | Where-Object { $_.AdminCount -eq 1 -and -not $_.IsWellKnown } - - if ($adminSdHolderGroups.Count -eq 0) { - $result += "| No additional AdminSDHolder groups found | - | - |" + "`n" - } else { - foreach ($group in ($adminSdHolderGroups | Select-Object -First 20)) { - $result += "| $($group.Name) | $($group.MemberCount) | $($group.GroupScope) |" + "`n" - } - - if ($adminSdHolderGroups.Count -gt 20) { - $result += "| ... and $($adminSdHolderGroups.Count - 20) more | - | - |" + "`n" - } - } - } - - $testResultMarkdown = $result - } else { - $testResultMarkdown = "Unable to retrieve group data." - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - return $testResult -} diff --git a/tests/ad/ou/Test.AD-OU-05.md b/tests/ad/ou/Test.AD-OU-05.md index 7b633ebcbc..57dd4fe94e 100644 --- a/tests/ad/ou/Test.AD-OU-05.md +++ b/tests/ad/ou/Test.AD-OU-05.md @@ -34,7 +34,7 @@ This test retrieves all Organizational Units from Active Directory and: - `Test-MtAdOuEmptyCount` - Provides count summary of empty OUs - `Test-MtAdOuStaleCount` - Identifies OUs not modified since before 2020 -- `Test-MtAdGroupEmptyNonPrivilegedDetails` - Lists empty non-privileged groups +- `AD-GMC-10` - Lists empty non-privileged groups %TestResult% From 22e334fccc06f0ea6d60ec4023d62096260ce48b Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 06:23:26 +0000 Subject: [PATCH 015/100] fix(ad): consolidate group reviews and configurable age thresholds --- tests/ad/group/Test.AD-GRP-01.ps1 | 2 +- tests/ad/group/Test.AD-GRP-02.md | 17 ++++--- tests/ad/group/Test.AD-GRP-02.ps1 | 2 +- tests/ad/group/Test.AD-GRP-03.md | 6 +-- tests/ad/group/Test.AD-GRP-03.ps1 | 29 +++++++---- tests/ad/group/Test.AD-GRP-04.ps1 | 2 +- tests/ad/group/Test.AD-GRP-05.ps1 | 2 +- tests/ad/group/Test.AD-GRP-06.md | 5 +- tests/ad/group/Test.AD-GRP-06.ps1 | 4 +- tests/ad/group/Test.AD-GRP-07.md | 39 -------------- tests/ad/group/Test.AD-GRP-07.ps1 | 83 ------------------------------ tests/ad/group/Test.AD-GRP-08.md | 5 +- tests/ad/group/Test.AD-GRP-08.ps1 | 6 ++- tests/ad/group/Test.AD-GRP-09.md | 40 --------------- tests/ad/group/Test.AD-GRP-09.ps1 | 83 ------------------------------ tests/ad/group/Test.AD-GRP-10.md | 42 ---------------- tests/ad/group/Test.AD-GRP-10.ps1 | 84 ------------------------------- 17 files changed, 44 insertions(+), 407 deletions(-) delete mode 100644 tests/ad/group/Test.AD-GRP-07.md delete mode 100644 tests/ad/group/Test.AD-GRP-07.ps1 delete mode 100644 tests/ad/group/Test.AD-GRP-09.md delete mode 100644 tests/ad/group/Test.AD-GRP-09.ps1 delete mode 100644 tests/ad/group/Test.AD-GRP-10.md delete mode 100644 tests/ad/group/Test.AD-GRP-10.ps1 diff --git a/tests/ad/group/Test.AD-GRP-01.ps1 b/tests/ad/group/Test.AD-GRP-01.ps1 index 234704a32c..d3e9c36f04 100644 --- a/tests/ad/group/Test.AD-GRP-01.ps1 +++ b/tests/ad/group/Test.AD-GRP-01.ps1 @@ -79,7 +79,7 @@ $testResultMarkdown = "Unable to retrieve Active Directory groups. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/group/Test.AD-GRP-02.md b/tests/ad/group/Test.AD-GRP-02.md index e461cd2848..a5cb547522 100644 --- a/tests/ad/group/Test.AD-GRP-02.md +++ b/tests/ad/group/Test.AD-GRP-02.md @@ -1,13 +1,14 @@ -- Active Directory supports two primary types of directory objects for storing other objects: Organizational Units (OUs) and Containers (CNs). While both can hold groups, they serve different purposes: -- **OUs (OU=)**: Designed for delegation, Group Policy application, and logical organization -- **Containers (CN=)**: System containers with limited flexibility (like CN=Users, CN=Computers) +Active Directory supports two primary types of directory objects for storing other objects: Organizational Units (OUs) and Containers (CNs). While both can hold groups, they serve different purposes: -- Storing groups in containers instead of OUs creates several issues: + - **OUs (OU=)**: Designed for delegation, Group Policy application, and logical organization + - **Containers (CN=)**: System containers with limited flexibility (like CN=Users, CN=Computers) -- **Delegation limitations**: Cannot easily delegate management of container contents -- **No Group Policy**: Cannot link Group Policy Objects to containers -- **Poor organization**: Containers lack the hierarchical flexibility of OUs -- **Security risks**: Default containers like CN=Users are well-known targets +Storing groups in containers instead of OUs creates several issues: + + - **Delegation limitations**: Cannot easily delegate management of container contents + - **No Group Policy**: Cannot link Group Policy Objects to containers + - **Poor organization**: Containers lack the hierarchical flexibility of OUs + - **Security risks**: Default containers like CN=Users are well-known targets #### Control Type diff --git a/tests/ad/group/Test.AD-GRP-02.ps1 b/tests/ad/group/Test.AD-GRP-02.ps1 index 280c251cbf..6c1bc1535c 100644 --- a/tests/ad/group/Test.AD-GRP-02.ps1 +++ b/tests/ad/group/Test.AD-GRP-02.ps1 @@ -81,7 +81,7 @@ $testResultMarkdown = "Unable to retrieve Active Directory groups. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/group/Test.AD-GRP-03.md b/tests/ad/group/Test.AD-GRP-03.md index 9c73009b88..43391090ba 100644 --- a/tests/ad/group/Test.AD-GRP-03.md +++ b/tests/ad/group/Test.AD-GRP-03.md @@ -1,4 +1,4 @@ -Groups that have not been modified for an extended period (in this case, before 2020) may represent: +Groups that have not been modified for longer than `MaximumAgeDays` (default 365 days) may warrant a membership and ownership review: - **Abandoned groups**: Created for projects or purposes that no longer exist - **Orphaned permissions**: Groups with memberships that haven't been reviewed @@ -21,13 +21,13 @@ Stale groups pose particular risks because: - Document all groups and their purposes - Consider implementing a group lifecycle policy with automatic expiration - Remove groups that are no longer needed after confirming they're not referenced -- Update the modifyTimeStamp by reviewing group membership periodically +- Do not make cosmetic changes merely to update the timestamp: investigate whether membership still grants appropriate access. #### How the Test Works This test retrieves all group objects from Active Directory and: - Examines the modifyTimeStamp property of each group -- Counts groups where modifyTimeStamp is before January 1, 2020 +- Fails if any group was last modified before the configurable cutoff (`MaximumAgeDays` days ago) - Calculates the percentage of stale groups in the environment #### Related Tests diff --git a/tests/ad/group/Test.AD-GRP-03.ps1 b/tests/ad/group/Test.AD-GRP-03.ps1 index 60cd79814b..31e9b59f35 100644 --- a/tests/ad/group/Test.AD-GRP-03.ps1 +++ b/tests/ad/group/Test.AD-GRP-03.ps1 @@ -1,7 +1,7 @@ function Test-MtAdGroupStaleCount { <# .SYNOPSIS - Counts groups that have not been modified since before 2020. + Checks whether groups have been modified within a configurable number of days. .DESCRIPTION This test identifies groups that have not been modified since before January 1, 2020. @@ -21,12 +21,14 @@ #> [MaesterTest( Id = 'AD-GRP-03', - Title = 'Stale groups count should be retrievable', + Title = 'Groups should be modified within the configured age', Product = 'ad', Feature = 'groups', Area = 'identity-lifecycle', ResourceType = 'Group', - Severity = 'Info', + Severity = 'Low', + UserImpact = 'Low', + ImplementationCost = 'Medium', Mitre = 'None', Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:group:ReadProperty'), @@ -34,7 +36,11 @@ )] [CmdletBinding()] [OutputType([bool])] - param() + param( + # Maximum number of days since a group's last modification. + [ValidateRange(1, 36500)] + [int] $MaximumAgeDays = 365 + ) Write-Verbose "Starting Test-MtAdGroupStaleCount" @@ -49,8 +55,9 @@ $groups = $adState.Groups - # Count groups last modified before 2020 - $cutoffDate = Get-Date -Year 2020 -Month 1 -Day 1 + if ($null -eq $adState.Groups) { throw 'Group collection is unavailable.' } + # Modification age is a hygiene indicator, not proof of actual group usage. + $cutoffDate = (Get-Date).AddDays(-$MaximumAgeDays) $staleGroups = $groups | Where-Object { $_.modifyTimeStamp -and $_.modifyTimeStamp -lt $cutoffDate } @@ -59,10 +66,10 @@ $totalCount = ($groups | Measure-Object).Count # Test passes if we successfully retrieved group data - $testResult = $totalCount -gt 0 + $testResult = $totalCount -gt 0 -and $staleCount -eq 0 # Generate markdown results - if ($testResult) { + if ($totalCount -gt 0) { $percentage = if ($totalCount -gt 0) { [Math]::Round(($staleCount / $totalCount) * 100, 2) } else { @@ -72,11 +79,11 @@ $result = "| Metric | Value |" + "`n" $result += "| --- | --- |" + "`n" $result += "| Total Groups | $totalCount |" + "`n" - $result += "| Groups Modified Before 2020 | $staleCount |" + "`n" + $result += "| Groups Modified Before Cutoff | $staleCount |" + "`n" $result += "| Stale Percentage | $percentage% |" + "`n" - $result += "| Cutoff Date | 2020-01-01 |" + "`n" + "`n" + $result += "| Cutoff Date | $($cutoffDate.ToString('yyyy-MM-dd')) |" + "`n" + "`n" - $testResultMarkdown = "Active Directory groups have been analyzed. $staleCount out of $totalCount groups ($percentage%) have not been modified since before 2020.`n`n%TestResult%" + $testResultMarkdown = "Active Directory groups have been analyzed. $staleCount out of $totalCount groups ($percentage%) have not been modified within $MaximumAgeDays days.`n`n%TestResult%" $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result } else { $testResultMarkdown = "Unable to retrieve Active Directory groups. Ensure you have appropriate permissions and the Active Directory module is installed." diff --git a/tests/ad/group/Test.AD-GRP-04.ps1 b/tests/ad/group/Test.AD-GRP-04.ps1 index 09b1153d0f..535be4e6fd 100644 --- a/tests/ad/group/Test.AD-GRP-04.ps1 +++ b/tests/ad/group/Test.AD-GRP-04.ps1 @@ -83,7 +83,7 @@ $testResultMarkdown = "Unable to retrieve Active Directory groups. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/group/Test.AD-GRP-05.ps1 b/tests/ad/group/Test.AD-GRP-05.ps1 index 9fa97f2833..3d0da37f3d 100644 --- a/tests/ad/group/Test.AD-GRP-05.ps1 +++ b/tests/ad/group/Test.AD-GRP-05.ps1 @@ -82,7 +82,7 @@ $testResultMarkdown = "Unable to retrieve Active Directory groups. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/group/Test.AD-GRP-06.md b/tests/ad/group/Test.AD-GRP-06.md index 3a5e8573c3..91e0ef22f3 100644 --- a/tests/ad/group/Test.AD-GRP-06.md +++ b/tests/ad/group/Test.AD-GRP-06.md @@ -25,14 +25,11 @@ This test examines all group objects and identifies those where: - The `GroupCategory` property equals "Distribution" - These groups are used solely for email distribution, not access control -The test provides counts and percentages to understand the distribution of group types in your environment. +The test provides security and distribution group counts and percentages to understand group categories in your environment. #### Related Tests -- `Test-MtAdGroupSecurityCount` - Counts security groups used for access control - `Test-MtAdGroupDomainLocalCount` - Counts domain local scope groups -- `Test-MtAdGroupGlobalCount` - Counts global scope groups -- `Test-MtAdGroupUniversalCount` - Counts universal scope groups %TestResult% diff --git a/tests/ad/group/Test.AD-GRP-06.ps1 b/tests/ad/group/Test.AD-GRP-06.ps1 index 6298758504..afe0b918f1 100644 --- a/tests/ad/group/Test.AD-GRP-06.ps1 +++ b/tests/ad/group/Test.AD-GRP-06.ps1 @@ -52,6 +52,7 @@ $distributionGroups = $groups | Where-Object { $_.GroupCategory -eq "Distribution" } $distributionCount = ($distributionGroups | Measure-Object).Count $totalCount = ($groups | Measure-Object).Count + $securityCount = @($groups | Where-Object { $_.GroupCategory -eq 'Security' }).Count # Test passes if we successfully retrieved group data $testResult = $totalCount -gt 0 @@ -67,6 +68,7 @@ $result = "| Metric | Value |" + "`n" $result += "| --- | --- |" + "`n" $result += "| Total Groups | $totalCount |" + "`n" + $result += "| Security Groups | $securityCount |" + "`n" $result += "| Distribution Groups | $distributionCount |" + "`n" $result += "| Distribution Percentage | $percentage% |" + "`n" + "`n" @@ -76,7 +78,7 @@ $testResultMarkdown = "Unable to retrieve Active Directory group objects. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/group/Test.AD-GRP-07.md b/tests/ad/group/Test.AD-GRP-07.md deleted file mode 100644 index d3480136c2..0000000000 --- a/tests/ad/group/Test.AD-GRP-07.md +++ /dev/null @@ -1,39 +0,0 @@ -Security groups are the foundation of access control in Active Directory. Understanding their count and distribution is critical for: - -- **Access management assessment**: High numbers of security groups may indicate complex or poorly managed permissions -- **Security auditing**: Security groups directly control who can access what resources -- **Privilege analysis**: Helps identify the scale of group-based access control to audit -- **Compliance requirements**: Many frameworks require documentation and regular review of security groups - -Security groups can be assigned permissions to resources, unlike distribution groups. - -#### Control Type - -**Operational** - -#### Security Recommendation - -Establish governance around security groups: -1. Implement a naming convention for security groups to improve manageability -2. Regularly audit security group memberships, especially for privileged groups -3. Document the purpose and owner of each security group -4. Remove unused or stale security groups to reduce attack surface -5. Consider implementing privileged access management for highly sensitive groups - -#### How the Test Works - -This test examines all group objects and identifies those where: -- The `GroupCategory` property equals "Security" -- These groups can be assigned permissions and used for access control - -The test provides counts and percentages to understand the proportion of security groups versus distribution groups. - -#### Related Tests - -- `Test-MtAdGroupDistributionCount` - Counts distribution groups (email-only) -- `Test-MtAdGroupDomainLocalCount` - Counts domain local scope groups -- `Test-MtAdGroupGlobalCount` - Counts global scope groups -- `Test-MtAdGroupUniversalCount` - Counts universal scope groups - - -%TestResult% diff --git a/tests/ad/group/Test.AD-GRP-07.ps1 b/tests/ad/group/Test.AD-GRP-07.ps1 deleted file mode 100644 index 852adff8f7..0000000000 --- a/tests/ad/group/Test.AD-GRP-07.ps1 +++ /dev/null @@ -1,83 +0,0 @@ -function Test-MtAdGroupSecurityCount { - <# - .SYNOPSIS - Counts the number of security groups in Active Directory. - - .DESCRIPTION - This test counts security groups in Active Directory, which are used for access control - and permissions management. Security groups can be assigned permissions to resources - and contain both users and computers. Understanding the number and distribution of - security groups is essential for assessing the security posture and access management - complexity of your Active Directory environment. - - .EXAMPLE - Test-MtAdGroupSecurityCount - - Returns $true if group data is accessible, $false otherwise. - The test result includes counts of security groups. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGroupSecurityCount - #> - [MaesterTest( - Id = 'AD-GRP-07', - Title = 'Security group count should be retrievable', - Product = 'ad', - Feature = 'groups', - Area = 'infrastructure', - ResourceType = 'Group', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:group:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdGroupSecurityCount" - - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('Groups') - - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $groups = $adState.Groups - - # Count security groups (GroupCategory = "Security") - $securityGroups = $groups | Where-Object { $_.GroupCategory -eq "Security" } - $securityCount = ($securityGroups | Measure-Object).Count - $totalCount = ($groups | Measure-Object).Count - - # Test passes if we successfully retrieved group data - $testResult = $totalCount -gt 0 - - # Generate markdown results - if ($testResult) { - $percentage = if ($totalCount -gt 0) { - [Math]::Round(($securityCount / $totalCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Groups | $totalCount |" + "`n" - $result += "| Security Groups | $securityCount |" + "`n" - $result += "| Security Percentage | $percentage% |" + "`n" + "`n" - - $testResultMarkdown = "Active Directory group objects have been analyzed. $securityCount out of $totalCount groups ($percentage%) are security groups (used for access control).`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory group objects. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult -} diff --git a/tests/ad/group/Test.AD-GRP-08.md b/tests/ad/group/Test.AD-GRP-08.md index 027a04bc87..fc6f5c9e12 100644 --- a/tests/ad/group/Test.AD-GRP-08.md +++ b/tests/ad/group/Test.AD-GRP-08.md @@ -26,14 +26,11 @@ This test examines all group objects and identifies those where: - The `GroupScope` property equals "DomainLocal" - These groups can only assign permissions to resources in their own domain -The test provides counts and percentages to understand the distribution of group scopes in your environment. +The test provides domain local, global and universal counts, plus domain local percentage, to understand the distribution of group scopes. #### Related Tests - `Test-MtAdGroupDistributionCount` - Counts distribution groups (email-only) -- `Test-MtAdGroupSecurityCount` - Counts security groups by category -- `Test-MtAdGroupGlobalCount` - Counts global scope groups -- `Test-MtAdGroupUniversalCount` - Counts universal scope groups %TestResult% diff --git a/tests/ad/group/Test.AD-GRP-08.ps1 b/tests/ad/group/Test.AD-GRP-08.ps1 index d86d0116d8..e634687786 100644 --- a/tests/ad/group/Test.AD-GRP-08.ps1 +++ b/tests/ad/group/Test.AD-GRP-08.ps1 @@ -53,6 +53,8 @@ $domainLocalGroups = $groups | Where-Object { $_.GroupScope -eq "DomainLocal" } $domainLocalCount = ($domainLocalGroups | Measure-Object).Count $totalCount = ($groups | Measure-Object).Count + $globalCount = @($groups | Where-Object { $_.GroupScope -eq 'Global' }).Count + $universalCount = @($groups | Where-Object { $_.GroupScope -eq 'Universal' }).Count # Test passes if we successfully retrieved group data $testResult = $totalCount -gt 0 @@ -69,6 +71,8 @@ $result += "| --- | --- |" + "`n" $result += "| Total Groups | $totalCount |" + "`n" $result += "| Domain Local Groups | $domainLocalCount |" + "`n" + $result += "| Global Groups | $globalCount |" + "`n" + $result += "| Universal Groups | $universalCount |" + "`n" $result += "| Domain Local Percentage | $percentage% |" + "`n" + "`n" $testResultMarkdown = "Active Directory group objects have been analyzed. $domainLocalCount out of $totalCount groups ($percentage%) are domain local groups (resources in local domain only).`n`n%TestResult%" @@ -77,7 +81,7 @@ $testResultMarkdown = "Unable to retrieve Active Directory group objects. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/group/Test.AD-GRP-09.md b/tests/ad/group/Test.AD-GRP-09.md deleted file mode 100644 index 5ddf98763f..0000000000 --- a/tests/ad/group/Test.AD-GRP-09.md +++ /dev/null @@ -1,40 +0,0 @@ -Global groups are the most commonly used group type for organizing users in Active Directory: - -- **User organization**: Used to organize users by role, department, or function -- **Forest-wide usage**: Can be used across the entire forest for access control -- **Domain replication**: Group membership only replicates within the domain, reducing replication traffic -- **AGDLP/AGUDLP strategy**: Accounts are placed into Global groups as the first step in the recommended group nesting strategy - -A high number of global groups typically indicates well-organized user role management. - -#### Control Type - -**Operational** - -#### Security Recommendation - -Optimize global group usage: -1. Use global groups to organize users by role, department, or business function -2. Keep global group membership relatively stable to minimize replication -3. Nest global groups into domain local or universal groups for resource access -4. Avoid assigning permissions directly to global groups—use them as user containers -5. Implement a naming convention that reflects the group's purpose (e.g., "G-Department-Finance") - -#### How the Test Works - -This test examines all group objects and identifies those where: -- The `GroupScope` property equals "Global" -- These groups can contain users and other global groups from the same domain -- Membership changes only replicate within the domain - -The test provides counts and percentages to understand the distribution of group scopes in your environment. - -#### Related Tests - -- `Test-MtAdGroupDistributionCount` - Counts distribution groups (email-only) -- `Test-MtAdGroupSecurityCount` - Counts security groups by category -- `Test-MtAdGroupDomainLocalCount` - Counts domain local scope groups -- `Test-MtAdGroupUniversalCount` - Counts universal scope groups - - -%TestResult% diff --git a/tests/ad/group/Test.AD-GRP-09.ps1 b/tests/ad/group/Test.AD-GRP-09.ps1 deleted file mode 100644 index 68e3bcf1f7..0000000000 --- a/tests/ad/group/Test.AD-GRP-09.ps1 +++ /dev/null @@ -1,83 +0,0 @@ -function Test-MtAdGroupGlobalCount { - <# - .SYNOPSIS - Counts the number of global groups in Active Directory. - - .DESCRIPTION - This test counts global groups in Active Directory. Global groups can be used across - the entire forest and can contain users and other global groups from the same domain. - They are typically used to organize users by role, department, or function and can - be placed into domain local groups for resource access. Global groups replicate - only within their domain and are the most commonly used group scope for user organization. - - .EXAMPLE - Test-MtAdGroupGlobalCount - - Returns $true if group data is accessible, $false otherwise. - The test result includes counts of global groups. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGroupGlobalCount - #> - [MaesterTest( - Id = 'AD-GRP-09', - Title = 'Global group count should be retrievable', - Product = 'ad', - Feature = 'groups', - Area = 'infrastructure', - ResourceType = 'Group', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:group:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdGroupGlobalCount" - - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('Groups') - - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $groups = $adState.Groups - - # Count global groups (GroupScope = "Global") - $globalGroups = $groups | Where-Object { $_.GroupScope -eq "Global" } - $globalCount = ($globalGroups | Measure-Object).Count - $totalCount = ($groups | Measure-Object).Count - - # Test passes if we successfully retrieved group data - $testResult = $totalCount -gt 0 - - # Generate markdown results - if ($testResult) { - $percentage = if ($totalCount -gt 0) { - [Math]::Round(($globalCount / $totalCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Groups | $totalCount |" + "`n" - $result += "| Global Groups | $globalCount |" + "`n" - $result += "| Global Percentage | $percentage% |" + "`n" + "`n" - - $testResultMarkdown = "Active Directory group objects have been analyzed. $globalCount out of $totalCount groups ($percentage%) are global groups (forest-wide usage).`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory group objects. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult -} diff --git a/tests/ad/group/Test.AD-GRP-10.md b/tests/ad/group/Test.AD-GRP-10.md deleted file mode 100644 index 6b68425712..0000000000 --- a/tests/ad/group/Test.AD-GRP-10.md +++ /dev/null @@ -1,42 +0,0 @@ -Universal groups play a specific role in multi-domain Active Directory environments: - -- **Cross-domain flexibility**: Can contain users and groups from any domain in the forest -- **Forest-wide access**: Can be used for access control across the entire forest -- **Global Catalog storage**: Group membership is stored in the Global Catalog -- **Replication impact**: Membership changes trigger forest-wide replication -- **Multi-domain consolidation**: Useful for nesting global groups from multiple domains - -High numbers of universal groups may indicate a complex multi-domain environment or potential replication optimization opportunities. - -#### Control Type - -**Operational** - -#### Security Recommendation - -Use universal groups strategically: -1. Minimize membership changes to universal groups to reduce replication traffic -2. Use universal groups primarily in multi-domain environments where cross-domain access is needed -3. Nest global groups (containing users) into universal groups rather than adding users directly -4. Consider the replication impact when designing universal group structure -5. Document the forest-wide access each universal group provides -6. In single-domain environments, prefer global and domain local groups - -#### How the Test Works - -This test examines all group objects and identifies those where: -- The `GroupScope` property equals "Universal" -- These groups can contain members from any domain in the forest -- Membership is stored in the Global Catalog - -The test provides counts and percentages to understand the distribution of group scopes in your environment. - -#### Related Tests - -- `Test-MtAdGroupDistributionCount` - Counts distribution groups (email-only) -- `Test-MtAdGroupSecurityCount` - Counts security groups by category -- `Test-MtAdGroupDomainLocalCount` - Counts domain local scope groups -- `Test-MtAdGroupGlobalCount` - Counts global scope groups - - -%TestResult% diff --git a/tests/ad/group/Test.AD-GRP-10.ps1 b/tests/ad/group/Test.AD-GRP-10.ps1 deleted file mode 100644 index d004710272..0000000000 --- a/tests/ad/group/Test.AD-GRP-10.ps1 +++ /dev/null @@ -1,84 +0,0 @@ -function Test-MtAdGroupUniversalCount { - <# - .SYNOPSIS - Counts the number of universal groups in Active Directory. - - .DESCRIPTION - This test counts universal groups in Active Directory. Universal groups can be used - across the entire forest and can contain users and other groups from any domain - in the forest. Unlike global groups, universal groups are stored in the Global - Catalog, which means membership changes trigger forest-wide replication. They are - typically used in multi-domain environments to provide consistent access across domains - or to nest global groups from multiple domains into a single group for resource access. - - .EXAMPLE - Test-MtAdGroupUniversalCount - - Returns $true if group data is accessible, $false otherwise. - The test result includes counts of universal groups. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGroupUniversalCount - #> - [MaesterTest( - Id = 'AD-GRP-10', - Title = 'Universal group count should be retrievable', - Product = 'ad', - Feature = 'groups', - Area = 'infrastructure', - ResourceType = 'Group', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:group:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdGroupUniversalCount" - - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('Groups') - - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $groups = $adState.Groups - - # Count universal groups (GroupScope = "Universal") - $universalGroups = $groups | Where-Object { $_.GroupScope -eq "Universal" } - $universalCount = ($universalGroups | Measure-Object).Count - $totalCount = ($groups | Measure-Object).Count - - # Test passes if we successfully retrieved group data - $testResult = $totalCount -gt 0 - - # Generate markdown results - if ($testResult) { - $percentage = if ($totalCount -gt 0) { - [Math]::Round(($universalCount / $totalCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Groups | $totalCount |" + "`n" - $result += "| Universal Groups | $universalCount |" + "`n" - $result += "| Universal Percentage | $percentage% |" + "`n" + "`n" - - $testResultMarkdown = "Active Directory group objects have been analyzed. $universalCount out of $totalCount groups ($percentage%) are universal groups (forest-wide, stored in Global Catalog).`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory group objects. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult -} From 9545e96452452502a3d82e319987a678e676c265 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 06:23:26 +0000 Subject: [PATCH 016/100] refactor(ad): consolidate SPN inventories and delegation details --- tests/ad/spn/Test.AD-SPN-01.md | 2 +- tests/ad/spn/Test.AD-SPN-01.ps1 | 11 ++- tests/ad/spn/Test.AD-SPN-02.md | 33 -------- tests/ad/spn/Test.AD-SPN-02.ps1 | 100 ---------------------- tests/ad/spn/Test.AD-SPN-03.md | 2 +- tests/ad/spn/Test.AD-SPN-03.ps1 | 11 ++- tests/ad/spn/Test.AD-SPN-04.md | 34 -------- tests/ad/spn/Test.AD-SPN-04.ps1 | 142 ------------------------------- tests/ad/spn/Test.AD-SPN-05.ps1 | 7 +- tests/ad/spn/Test.AD-SPN-07.md | 2 +- tests/ad/spn/Test.AD-SPN-07.ps1 | 7 +- tests/ad/spn/Test.AD-SPN-08.md | 33 -------- tests/ad/spn/Test.AD-SPN-08.ps1 | 102 ---------------------- tests/ad/spn/Test.AD-SPN-09.md | 2 +- tests/ad/spn/Test.AD-SPN-09.ps1 | 9 ++ tests/ad/spn/Test.AD-SPN-10.md | 34 -------- tests/ad/spn/Test.AD-SPN-10.ps1 | 146 -------------------------------- tests/ad/spn/Test.AD-SPN-11.ps1 | 7 +- 18 files changed, 47 insertions(+), 637 deletions(-) delete mode 100644 tests/ad/spn/Test.AD-SPN-02.md delete mode 100644 tests/ad/spn/Test.AD-SPN-02.ps1 delete mode 100644 tests/ad/spn/Test.AD-SPN-04.md delete mode 100644 tests/ad/spn/Test.AD-SPN-04.ps1 delete mode 100644 tests/ad/spn/Test.AD-SPN-08.md delete mode 100644 tests/ad/spn/Test.AD-SPN-08.ps1 delete mode 100644 tests/ad/spn/Test.AD-SPN-10.md delete mode 100644 tests/ad/spn/Test.AD-SPN-10.ps1 diff --git a/tests/ad/spn/Test.AD-SPN-01.md b/tests/ad/spn/Test.AD-SPN-01.md index b4d77da7f0..fce9f2801d 100644 --- a/tests/ad/spn/Test.AD-SPN-01.md +++ b/tests/ad/spn/Test.AD-SPN-01.md @@ -25,7 +25,7 @@ This test retrieves all computer objects from Active Directory, extracts their S #### Related Tests -- `Test-MtAdComputerSpnServiceClassUsage` - Shows usage breakdown of each service class +- This check includes a per-service-class usage breakdown. - `Test-MtAdComputerSpnUnknownCount` - Identifies unrecognized SPN service classes - `Test-MtAdUserSpnServiceClassCount` - Counts distinct service classes on user accounts diff --git a/tests/ad/spn/Test.AD-SPN-01.ps1 b/tests/ad/spn/Test.AD-SPN-01.ps1 index f7ec78fe4c..29f188be23 100644 --- a/tests/ad/spn/Test.AD-SPN-01.ps1 +++ b/tests/ad/spn/Test.AD-SPN-01.ps1 @@ -46,6 +46,7 @@ } $computers = $adState.Computers + if ($null -eq $computers) { throw 'Computer collection is unavailable.' } # Extract all SPNs from computer objects $allSpns = $computers | Where-Object { $null -ne $_.servicePrincipalName } | ForEach-Object { $_.servicePrincipalName } | ForEach-Object { $_ } @@ -61,7 +62,7 @@ $totalSpnCount = ($allSpns | Measure-Object).Count # Test passes if we successfully retrieved SPN data - $testResult = $totalSpnCount -ge 0 + $testResult = $null -ne $computers # Generate markdown results if ($testResult) { @@ -69,9 +70,13 @@ $result += "| --- | --- |" + "`n" $result += "| Total SPNs | $totalSpnCount |" + "`n" $result += "| Distinct Service Classes | $serviceClassCount |" + "`n" + $result += "`n| Service Class | SPN Count |" + "`n| --- | --- |" + "`n" + foreach ($class in @($allSpns | Where-Object { $_ -match '^[^/]+' } | ForEach-Object { ($_ -split '/')[0] } | Group-Object | Sort-Object Count -Descending)) { + $result += "| $($class.Name) | $($class.Count) |" + "`n" + } if ($serviceClassCount -gt 0) { - $result += "| Computers with SPNs | $(($computers | Where-Object { $null -ne $_.servicePrincipalName } | Measure-Object).Count) |" + "`n" + $result += "| Computers with SPNs | $(@($computers | Where-Object { @($_.servicePrincipalName | Where-Object { $_ }).Count -gt 0 }).Count) |" + "`n" } $testResultMarkdown = "Active Directory computer SPNs have been analyzed. $serviceClassCount distinct service classes found across $totalSpnCount SPNs.`n`n%TestResult%" @@ -80,7 +85,7 @@ $testResultMarkdown = "Unable to retrieve Active Directory computer SPN data. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/spn/Test.AD-SPN-02.md b/tests/ad/spn/Test.AD-SPN-02.md deleted file mode 100644 index 70adb0170f..0000000000 --- a/tests/ad/spn/Test.AD-SPN-02.md +++ /dev/null @@ -1,33 +0,0 @@ -Understanding the distribution of SPN service classes across your computer infrastructure provides valuable security insights: - -- **Service inventory**: See what services are deployed across your environment -- **Risk assessment**: Identify high-value targets (like database services with SPNs) -- **Compliance tracking**: Ensure only approved services are configured -- **Anomaly detection**: Spot unusual service classes that may indicate shadow IT or misconfigurations - -Services with SPNs are targets for Kerberoasting attacks, so knowing which services exist helps prioritize security efforts. - -#### Control Type - -**Operational** - -#### Security Recommendation - -Review the service class breakdown regularly: -- Validate that all services with SPNs are authorized -- Ensure sensitive services (MSSQLSvc, etc.) have additional protections -- Remove SPNs for decommissioned services -- Consider implementing SPN attribution monitoring for critical services - -#### How the Test Works - -This test analyzes all computer SPNs, groups them by service class, and provides a count and percentage for each service class. This gives you a clear view of your Kerberos-authenticated service landscape. - -#### Related Tests - -- `Test-MtAdComputerSpnServiceClassCount` - Counts distinct service classes -- `Test-MtAdComputerSpnUnknownCount` - Identifies unrecognized service classes -- `Test-MtAdUserSpnServiceClassUsage` - Shows user account SPN service class usage - - -%TestResult% diff --git a/tests/ad/spn/Test.AD-SPN-02.ps1 b/tests/ad/spn/Test.AD-SPN-02.ps1 deleted file mode 100644 index 5bd84cfb63..0000000000 --- a/tests/ad/spn/Test.AD-SPN-02.ps1 +++ /dev/null @@ -1,100 +0,0 @@ -function Test-MtAdComputerSpnServiceClassUsage { - <# - .SYNOPSIS - Provides a breakdown of SPN service class usage across computer accounts. - - .DESCRIPTION - This test retrieves all Service Principal Names (SPNs) configured on computer objects - and provides a detailed breakdown of how many computers use each service class. - This helps identify the service footprint and potential security risks. - - .EXAMPLE - Test-MtAdComputerSpnServiceClassUsage - - Returns $true if SPN data is accessible, $false otherwise. - The test result includes a breakdown of service classes with counts. - - .LINK - https://maester.dev/docs/commands/Test-MtAdComputerSpnServiceClassUsage - #> - [MaesterTest( - Id = 'AD-SPN-02', - Title = 'Computer SPN service class usage should be retrievable', - Product = 'ad', - Feature = 'service-principal-names', - Area = 'infrastructure', - ResourceType = 'Computer', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:computer:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdComputerSpnServiceClassUsage" - - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('Computers') - - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $computers = $adState.Computers - - # Extract all SPNs from computer objects with their service classes - $spnData = $computers | Where-Object { $null -ne $_.servicePrincipalName } | ForEach-Object { - $computer = $_ - $computer.servicePrincipalName | ForEach-Object { - if ($_ -match "^([^/]+)") { - [PSCustomObject]@{ - ServiceClass = $matches[1] - Computer = $computer.Name - SPN = $_ - } - } - } - } - - # Group by service class - $serviceClassGroups = $spnData | Group-Object ServiceClass | Sort-Object Count -Descending - - $serviceClassCount = ($serviceClassGroups | Measure-Object).Count - $totalSpnCount = ($spnData | Measure-Object).Count - - # Test passes if we successfully retrieved SPN data - $testResult = $totalSpnCount -ge 0 - - # Generate markdown results - if ($testResult) { - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total SPNs | $totalSpnCount |" + "`n" - $result += "| Distinct Service Classes | $serviceClassCount |" + "`n" + "`n" - - if ($serviceClassCount -gt 0) { - $result += "### Service Class Breakdown" + "`n" + "`n" - $result += "| Service Class | Count | Percentage |" + "`n" - $result += "| --- | --- | --- |" + "`n" - - foreach ($group in $serviceClassGroups) { - $percentage = [Math]::Round(($group.Count / $totalSpnCount) * 100, 2) - $result += "| $($group.Name) | $($group.Count) | $percentage% |" + "`n" - } - } - - $testResultMarkdown = "Active Directory computer SPN service class usage has been analyzed.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory computer SPN data. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult -} diff --git a/tests/ad/spn/Test.AD-SPN-03.md b/tests/ad/spn/Test.AD-SPN-03.md index 144265fdc1..096ba85665 100644 --- a/tests/ad/spn/Test.AD-SPN-03.md +++ b/tests/ad/spn/Test.AD-SPN-03.md @@ -26,7 +26,7 @@ This test compares discovered SPN service classes against a database of known SP #### Related Tests -- `Test-MtAdComputerSpnUnknownDetails` - Provides detailed information about unknown SPNs +- This check includes the computer and raw SPN for each unknown service class. - `Test-MtAdComputerSpnServiceClassCount` - Counts all distinct service classes - `Test-MtAdUserSpnUnknownCount` - Identifies unknown SPNs on user accounts diff --git a/tests/ad/spn/Test.AD-SPN-03.ps1 b/tests/ad/spn/Test.AD-SPN-03.ps1 index 34bfb23775..ffbdd2fe41 100644 --- a/tests/ad/spn/Test.AD-SPN-03.ps1 +++ b/tests/ad/spn/Test.AD-SPN-03.ps1 @@ -96,6 +96,7 @@ $unknownCount = ($unknownServiceClasses | Measure-Object).Count $totalServiceClasses = ($serviceClasses | Measure-Object).Count $totalSpnCount = ($allSpns | Measure-Object).Count + if ($null -eq $computers) { throw 'Computer collection is unavailable.' } # Test passes if we successfully retrieved SPN data $testResult = $totalSpnCount -ge 0 @@ -112,6 +113,14 @@ $percentage = [Math]::Round(($unknownCount / $totalServiceClasses) * 100, 2) $result += "| Unknown Percentage | $percentage% |" + "`n" $result += "| Unknown Classes | $($unknownServiceClasses -join ', ') |" + "`n" + $result += "`n| Computer | Unknown SPN |" + "`n| --- | --- |" + "`n" + foreach ($computer in $computers) { + foreach ($spn in @($computer.servicePrincipalName)) { + if (($spn -split '/')[0] -in $unknownServiceClasses) { + $result += "| $($computer.Name) | $spn |" + "`n" + } + } + } } $testResultMarkdown = "Active Directory computer SPN analysis found $unknownCount unknown service classes out of $totalServiceClasses total.`n`n%TestResult%" @@ -120,7 +129,7 @@ $testResultMarkdown = "Unable to retrieve Active Directory computer SPN data. Ensure you have appropriate permissions and the Active Directory module is installed." } - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate return $testResult } diff --git a/tests/ad/spn/Test.AD-SPN-04.md b/tests/ad/spn/Test.AD-SPN-04.md deleted file mode 100644 index 83a4762faa..0000000000 --- a/tests/ad/spn/Test.AD-SPN-04.md +++ /dev/null @@ -1,34 +0,0 @@ -Detailed information about unknown SPNs enables security teams to: - -- **Investigate effectively**: Know exactly which computers have unknown SPNs -- **Assess scope**: Understand how widespread an unknown service is -- **Track down owners**: Identify the computers to contact administrators -- **Document exceptions**: Build a list of authorized custom SPNs - -This granular visibility is essential for maintaining SPN hygiene and security. - -#### Control Type - -**Operational** - -#### Security Recommendation - -For each unknown SPN service class discovered: -1. Identify the service owner or application team -2. Determine if the service is legitimate and necessary -3. Verify the SPN is registered on the correct account (not a user account for a computer service) -4. Document approved custom SPNs in your security baseline -5. Remove or correct unauthorized SPNs - -#### How the Test Works - -This test analyzes all computer SPNs, compares service classes against a known database, and provides a detailed breakdown of unknown service classes including which computers have them and how many instances exist. - -#### Related Tests - -- `Test-MtAdComputerSpnUnknownCount` - Counts unknown service classes -- `Test-MtAdUserSpnUnknownDetails` - Details of unknown user account SPNs -- `Test-MtAdComputerSpnServiceClassUsage` - All service class usage breakdown - - -%TestResult% diff --git a/tests/ad/spn/Test.AD-SPN-04.ps1 b/tests/ad/spn/Test.AD-SPN-04.ps1 deleted file mode 100644 index 9144d72187..0000000000 --- a/tests/ad/spn/Test.AD-SPN-04.ps1 +++ /dev/null @@ -1,142 +0,0 @@ -function Test-MtAdComputerSpnUnknownDetails { - <# - .SYNOPSIS - Provides detailed information about unidentified SPN service classes on computer accounts. - - .DESCRIPTION - This test retrieves all Service Principal Names (SPNs) configured on computer objects - and provides detailed information about service classes that are not in the known SPN database. - This includes which computers have these SPNs and how many instances exist. - - .EXAMPLE - Test-MtAdComputerSpnUnknownDetails - - Returns $true if SPN data is accessible, $false otherwise. - The test result includes detailed information about unknown SPNs. - - .LINK - https://maester.dev/docs/commands/Test-MtAdComputerSpnUnknownDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-SPN-04', - Title = 'Computer SPN unknown service class details should be investigated', - Product = 'ad', - Feature = 'service-principal-names', - Area = 'infrastructure', - ResourceType = 'Computer', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:computer:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdComputerSpnUnknownDetails" - - # Known SPN service classes - $knownSpns = @( - 'HOST', 'HTTP', 'HTTPS', 'LDAP', 'GC', 'DNS', 'CIFS', 'RPC', 'SMB', - 'MSSQLSvc', 'SQLAgent', 'MSOLAPSvc', 'MSOLAPSvc.3', 'MSOLAPDisco.3', - 'exchangeAB', 'exchangeMDB', 'exchangeRFR', 'SMTP', 'SMTPSVC', 'POP', 'POP3', 'IMAP', 'IMAP4', - 'TERMSRV', 'TERMSERV', 'WSMAN', 'RestrictedKrbHost', 'nfs', 'iSCSITarget', - 'MSClusterVirtualServer', 'MSServerCluster', 'MSServerClusterMgmtAPI', - 'Hyper-V Replica Service', 'Microsoft Virtual Console Service', 'Microsoft Virtual System Migration Service', - 'VMMSvc', 'SCVMM', 'CmRcService', - 'FIMService', 'PCNSCLNT', 'AgpmServer', 'AdtServer', - 'MSOMHSvc', 'MSOMSdkSvc', 'LiveState Recovery Agent 6.x', - 'E3514235-4B06-11D1-AB04-00C04FC2DCD2', 'E3514235-4B06-11D1-AB04-00C04FC2DCD2-ADAM', - 'Dfsr-12F9A27C-BF97-4787-9364-D31B6C55EB04', 'NtFrs-88f5d2bd-b646-11d2-a6d3-00c04fc9b232', - 'kadmin', 'krbsvr400', 'oracle', 'postgres', 'mongod', 'mongos', - 'ftp', 'vnc', 'sip', 'xmpp', 'ipp', 'cvs', 'afpserver', 'pcast', 'xgrid', - 'hdb', 'hbase', 'hdfs', 'hive', 'impala', 'kafka', 'mapred', 'oozie', - 'solr', 'spark', 'yarn', 'zookeeper', 'sentry', 'flume', 'hue', 'boostfs', - 'SAP', 'SAPService', 'SAS', 'BOBJCentralMS', 'BOCMS', 'BOSSO', 'BICMS', - 'Cognos', 'DynamicsNAV', 'NAV2016', 'MSCRMAsyncService', 'MSCRMSandboxService', - 'M-Files', 'ImDmsSvc', 'SeapineLicenseSvr', 'PVSSoap', 'Norskale', - 'aradminsvc', 'CESREMOTE', 'CAXOsoftEngine', 'CAARCserveRHAEngine', - 'FileRepService', 'VProRecovery', 'Backup Exec System Recovery Agent 6.x', - 'LiveState Recovery Agent 6.x', 'SoftGrid', 'vssrvc', 'vmrc', - 'OA60', 'EDVR', 'iem', 'magfs', 'tapinego', 'tnetdgines', - 'CUSESSIONKEYSVR', 'ckp_pdp', 'secshd', 'informatica', - 'jboss', 'fcsvr', 'gateway', 'httpfs', 'JournalNode Server', - 'kafka_mirror_maker', 'kudu', 'mr2', 'Storm', 'Zeppelin', - 'PIAFServer', 'PIServer', 'AFServer', 'PowerBIReportServer', - 'AcronisAgent', 'NPPolicyEvaluator', 'NPRepository4(DEFAULT)', 'NPRepository4(*)', - 'Agent VProRecovery Norton Ghost 12.0', 'UPM_SPN_7DC3CE86', - '{14E52635-0A95-4a5c-BDB1-E0D0C703B6C8}', '{54094C05-F977-4987-BFC9-E8B90E088973}' - ) - - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('Computers') - - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $computers = $adState.Computers - - # Extract unknown SPNs from computer objects - $unknownSpnData = $computers | Where-Object { $null -ne $_.servicePrincipalName } | ForEach-Object { - $computer = $_ - $computer.servicePrincipalName | ForEach-Object { - if ($_ -match "^([^/]+)") { - $serviceClass = $matches[1] - if ($knownSpns -notcontains $serviceClass) { - [PSCustomObject]@{ - ServiceClass = $serviceClass - Computer = $computer.Name - SPN = $_ - } - } - } - } - } - - # Group by service class - $unknownGroups = $unknownSpnData | Group-Object ServiceClass | Sort-Object Count -Descending - - $unknownCount = ($unknownGroups | Measure-Object).Count - $totalUnknownInstances = ($unknownSpnData | Measure-Object).Count - - # Test passes if we successfully retrieved SPN data - $testResult = $true - - # Generate markdown results - if ($testResult) { - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Unknown Service Classes | $unknownCount |" + "`n" - $result += "| Total Unknown SPN Instances | $totalUnknownInstances |" + "`n" + "`n" - - if ($unknownCount -gt 0) { - $result += "### Unknown Service Class Details" + "`n" + "`n" - $result += "| Service Class | Count | Computers |" + "`n" - $result += "| --- | --- | --- |" + "`n" - - foreach ($group in $unknownGroups) { - $computersList = ($group.Group | Select-Object -ExpandProperty Computer -Unique) -join ', ' - if ($computersList.Length -gt 50) { - $computersList = $computersList.Substring(0, 47) + "..." - } - $result += "| $($group.Name) | $($group.Count) | $computersList |" + "`n" - } - } else { - $result += "No unknown SPN service classes found. All SPNs match the known service database." + "`n" - } - - $testResultMarkdown = "Active Directory computer SPN unknown service class details.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory computer SPN data. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - - return $testResult -} diff --git a/tests/ad/spn/Test.AD-SPN-05.ps1 b/tests/ad/spn/Test.AD-SPN-05.ps1 index 96d221b995..3510bb258d 100644 --- a/tests/ad/spn/Test.AD-SPN-05.ps1 +++ b/tests/ad/spn/Test.AD-SPN-05.ps1 @@ -73,10 +73,12 @@ } } - $totalSpns = ($spnData | Measure-Object).Count + if ($null -eq $computers) { throw 'Computer collection is unavailable.' } + $totalSpns = @($computers | ForEach-Object { $_.servicePrincipalName } | Where-Object { $_ }).Count + $parsedSpns = @($spnData).Count $nonFqdnSpns = $spnData | Where-Object { -not $_.IsFqdn } $nonFqdnCount = ($nonFqdnSpns | Measure-Object).Count - $fqdnCount = $totalSpns - $nonFqdnCount + $fqdnCount = $parsedSpns - $nonFqdnCount # Test passes if we successfully retrieved SPN data $testResult = $true @@ -86,6 +88,7 @@ $result = "| Metric | Value |" + "`n" $result += "| --- | --- |" + "`n" $result += "| Total SPNs | $totalSpns |" + "`n" + $result += "| SPNs with unparsed host format | $($totalSpns - $parsedSpns) |" + "`n" $result += "| FQDN Hosts | $fqdnCount |" + "`n" $result += "| Non-FQDN Hosts | $nonFqdnCount |" + "`n" diff --git a/tests/ad/spn/Test.AD-SPN-07.md b/tests/ad/spn/Test.AD-SPN-07.md index 4f774f02db..edcecc7835 100644 --- a/tests/ad/spn/Test.AD-SPN-07.md +++ b/tests/ad/spn/Test.AD-SPN-07.md @@ -25,7 +25,7 @@ This test retrieves all user objects with SPNs, extracts the service class from #### Related Tests -- `Test-MtAdUserSpnServiceClassUsage` - Detailed breakdown of service class usage +- This check includes a per-service-class usage breakdown. - `Test-MtAdUserSpnTotalCount` - Total count of user SPNs - `Test-MtAdComputerSpnServiceClassCount` - Computer account service classes diff --git a/tests/ad/spn/Test.AD-SPN-07.ps1 b/tests/ad/spn/Test.AD-SPN-07.ps1 index 4b3a7bbee7..53d4b6c54c 100644 --- a/tests/ad/spn/Test.AD-SPN-07.ps1 +++ b/tests/ad/spn/Test.AD-SPN-07.ps1 @@ -59,7 +59,8 @@ $serviceClassCount = ($serviceClasses | Measure-Object).Count $totalSpnCount = ($allSpns | Measure-Object).Count - $usersWithSpns = ($users | Where-Object { $null -ne $_.servicePrincipalName } | Measure-Object).Count + if ($null -eq $users) { throw 'User collection is unavailable.' } + $usersWithSpns = @($users | Where-Object { @($_.servicePrincipalName | Where-Object { $_ }).Count -gt 0 }).Count # Test passes if we successfully retrieved SPN data $testResult = $true @@ -74,6 +75,10 @@ if ($serviceClassCount -gt 0) { $result += "| Service Classes | $($serviceClasses -join ', ') |" + "`n" + $result += "`n| Service Class | SPN Count |" + "`n| --- | --- |" + "`n" + foreach ($class in @($allSpns | Where-Object { $_ -match '^[^/]+' } | ForEach-Object { ($_ -split '/')[0] } | Group-Object | Sort-Object Count -Descending)) { + $result += "| $($class.Name) | $($class.Count) |" + "`n" + } } $testResultMarkdown = "Active Directory user SPN service class analysis found $serviceClassCount distinct service classes across $totalSpnCount SPNs.`n`n%TestResult%" diff --git a/tests/ad/spn/Test.AD-SPN-08.md b/tests/ad/spn/Test.AD-SPN-08.md deleted file mode 100644 index bc36ba088f..0000000000 --- a/tests/ad/spn/Test.AD-SPN-08.md +++ /dev/null @@ -1,33 +0,0 @@ -A detailed breakdown of SPN service classes on user accounts enables: - -- **Risk prioritization**: Identify high-value targets like database services -- **Service inventory**: Understand what services run under user credentials -- **Compliance assessment**: Ensure services meet security standards -- **Migration planning**: Prioritize which services to move to gMSAs first - -Database and application services on user accounts pose the highest Kerberoasting risk. - -#### Control Type - -**Operational** - -#### Security Recommendation - -Based on service class usage: -- Prioritize migrating database services (MSSQLSvc, oracle) to gMSAs -- Audit HTTP/HTTPS services running under user accounts -- Investigate custom or unknown service classes -- Document legitimate service accounts and their purposes - -#### How the Test Works - -This test analyzes all user SPNs, groups them by service class, and provides a count and percentage for each service class, helping you understand your user service account landscape. - -#### Related Tests - -- `Test-MtAdUserSpnServiceClassCount` - Counts distinct service classes -- `Test-MtAdUserSpnUnknownCount` - Identifies unrecognized service classes -- `Test-MtAdComputerSpnServiceClassUsage` - Computer account service class usage - - -%TestResult% diff --git a/tests/ad/spn/Test.AD-SPN-08.ps1 b/tests/ad/spn/Test.AD-SPN-08.ps1 deleted file mode 100644 index b7bc4a43a2..0000000000 --- a/tests/ad/spn/Test.AD-SPN-08.ps1 +++ /dev/null @@ -1,102 +0,0 @@ -function Test-MtAdUserSpnServiceClassUsage { - <# - .SYNOPSIS - Provides a breakdown of SPN service class usage across user accounts. - - .DESCRIPTION - This test retrieves all Service Principal Names (SPNs) configured on user objects - and provides a detailed breakdown of how many users have each service class. - This helps identify the service footprint and potential security risks on user accounts. - - .EXAMPLE - Test-MtAdUserSpnServiceClassUsage - - Returns $true if SPN data is accessible, $false otherwise. - The test result includes a breakdown of service classes with counts. - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserSpnServiceClassUsage - #> - [MaesterTest( - Id = 'AD-SPN-08', - Title = 'User SPN service class usage should be investigated', - Product = 'ad', - Feature = 'service-principal-names', - Area = 'authentication', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'T1558.003', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserSpnServiceClassUsage" - - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('Users') - - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $users = $adState.Users - - # Extract all SPNs from user objects with their service classes - $spnData = $users | Where-Object { $null -ne $_.servicePrincipalName } | ForEach-Object { - $user = $_ - $user.servicePrincipalName | ForEach-Object { - if ($_ -match "^([^/]+)") { - [PSCustomObject]@{ - ServiceClass = $matches[1] - User = $user.SamAccountName - SPN = $_ - } - } - } - } - - # Group by service class - $serviceClassGroups = $spnData | Group-Object ServiceClass | Sort-Object Count -Descending - - $serviceClassCount = ($serviceClassGroups | Measure-Object).Count - $totalSpnCount = ($spnData | Measure-Object).Count - $usersWithSpns = ($users | Where-Object { $null -ne $_.servicePrincipalName } | Measure-Object).Count - - # Test passes if we successfully retrieved SPN data - $testResult = $true - - # Generate markdown results - if ($testResult) { - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total User SPNs | $totalSpnCount |" + "`n" - $result += "| Distinct Service Classes | $serviceClassCount |" + "`n" - $result += "| Users with SPNs | $usersWithSpns |" + "`n" + "`n" - - if ($serviceClassCount -gt 0) { - $result += "### Service Class Breakdown" + "`n" + "`n" - $result += "| Service Class | Count | Percentage |" + "`n" - $result += "| --- | --- | --- |" + "`n" - - foreach ($group in $serviceClassGroups) { - $percentage = [Math]::Round(($group.Count / $totalSpnCount) * 100, 2) - $result += "| $($group.Name) | $($group.Count) | $percentage% |" + "`n" - } - } - - $testResultMarkdown = "Active Directory user SPN service class usage has been analyzed.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory user SPN data. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - - return $testResult -} diff --git a/tests/ad/spn/Test.AD-SPN-09.md b/tests/ad/spn/Test.AD-SPN-09.md index 057df3a1b7..78d9ee5c1f 100644 --- a/tests/ad/spn/Test.AD-SPN-09.md +++ b/tests/ad/spn/Test.AD-SPN-09.md @@ -26,7 +26,7 @@ This test compares discovered user SPN service classes against a database of kno #### Related Tests -- `Test-MtAdUserSpnUnknownDetails` - Detailed information about unknown user SPNs +- This check includes the user and raw SPN for each unknown service class. - `Test-MtAdComputerSpnUnknownCount` - Unknown SPNs on computer accounts - `Test-MtAdUserSpnServiceClassCount` - All user SPN service classes diff --git a/tests/ad/spn/Test.AD-SPN-09.ps1 b/tests/ad/spn/Test.AD-SPN-09.ps1 index 1b6c4d5a51..18b6c7829f 100644 --- a/tests/ad/spn/Test.AD-SPN-09.ps1 +++ b/tests/ad/spn/Test.AD-SPN-09.ps1 @@ -97,6 +97,7 @@ $unknownCount = ($unknownServiceClasses | Measure-Object).Count $totalServiceClasses = ($serviceClasses | Measure-Object).Count $totalSpnCount = ($allSpns | Measure-Object).Count + if ($null -eq $users) { throw 'User collection is unavailable.' } # Test passes if we successfully retrieved SPN data $testResult = $true @@ -113,6 +114,14 @@ $percentage = [Math]::Round(($unknownCount / $totalServiceClasses) * 100, 2) $result += "| Unknown Percentage | $percentage% |" + "`n" $result += "| Unknown Classes | $($unknownServiceClasses -join ', ') |" + "`n" + $result += "`n| User | Unknown SPN |" + "`n| --- | --- |" + "`n" + foreach ($user in $users) { + foreach ($spn in @($user.servicePrincipalName)) { + if (($spn -split '/')[0] -in $unknownServiceClasses) { + $result += "| $($user.SamAccountName) | $spn |" + "`n" + } + } + } } $testResultMarkdown = "Active Directory user SPN analysis found $unknownCount unknown service classes out of $totalServiceClasses total.`n`n%TestResult%" diff --git a/tests/ad/spn/Test.AD-SPN-10.md b/tests/ad/spn/Test.AD-SPN-10.md deleted file mode 100644 index 902002d0ce..0000000000 --- a/tests/ad/spn/Test.AD-SPN-10.md +++ /dev/null @@ -1,34 +0,0 @@ -Detailed information about unknown user SPNs is critical for security: - -- **Immediate action required**: User SPNs are prime Kerberoasting targets -- **Accountability**: Know exactly which users have unknown SPNs -- **Investigation**: Track down service owners quickly -- **Risk assessment**: Determine if high-privilege users have unknown SPNs - -Unknown SPNs on privileged user accounts represent the highest risk. - -#### Control Type - -**Operational** - -#### Security Recommendation - -For each unknown user SPN: -1. Contact the user or their manager to understand the service -2. Verify if the service is legitimate and necessary -3. If legitimate, document it and consider migrating to gMSA -4. If unauthorized, remove the SPN immediately -5. Check if the account has been compromised - -#### How the Test Works - -This test analyzes all user SPNs, identifies unknown service classes, and provides detailed information about which users have these SPNs. - -#### Related Tests - -- `Test-MtAdUserSpnUnknownCount` - Counts unknown service classes on users -- `Test-MtAdUserSpnDomainAdminDetails` - Checks domain admin SPNs specifically -- `Test-MtAdComputerSpnUnknownDetails` - Unknown computer SPN details - - -%TestResult% diff --git a/tests/ad/spn/Test.AD-SPN-10.ps1 b/tests/ad/spn/Test.AD-SPN-10.ps1 deleted file mode 100644 index f23e55182a..0000000000 --- a/tests/ad/spn/Test.AD-SPN-10.ps1 +++ /dev/null @@ -1,146 +0,0 @@ -function Test-MtAdUserSpnUnknownDetails { - <# - .SYNOPSIS - Provides detailed information about unidentified SPN service classes on user accounts. - - .DESCRIPTION - This test retrieves all Service Principal Names (SPNs) configured on user objects - and provides detailed information about service classes that are not in the known SPN database. - This includes which users have these SPNs and how many instances exist. - - .EXAMPLE - Test-MtAdUserSpnUnknownDetails - - Returns $true if SPN data is accessible, $false otherwise. - The test result includes detailed information about unknown user SPNs. - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserSpnUnknownDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-SPN-10', - Title = 'User SPN unknown service class details should be investigated', - Product = 'ad', - Feature = 'service-principal-names', - Area = 'authentication', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'T1558.003', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserSpnUnknownDetails" - - # Known SPN service classes - $knownSpns = @( - 'HOST', 'HTTP', 'HTTPS', 'LDAP', 'GC', 'DNS', 'CIFS', 'RPC', 'SMB', - 'MSSQLSvc', 'SQLAgent', 'MSOLAPSvc', 'MSOLAPSvc.3', 'MSOLAPDisco.3', - 'exchangeAB', 'exchangeMDB', 'exchangeRFR', 'SMTP', 'SMTPSVC', 'POP', 'POP3', 'IMAP', 'IMAP4', - 'TERMSRV', 'TERMSERV', 'WSMAN', 'RestrictedKrbHost', 'nfs', 'iSCSITarget', - 'MSClusterVirtualServer', 'MSServerCluster', 'MSServerClusterMgmtAPI', - 'Hyper-V Replica Service', 'Microsoft Virtual Console Service', 'Microsoft Virtual System Migration Service', - 'VMMSvc', 'SCVMM', 'CmRcService', - 'FIMService', 'PCNSCLNT', 'AgpmServer', 'AdtServer', - 'MSOMHSvc', 'MSOMSdkSvc', 'LiveState Recovery Agent 6.x', - 'E3514235-4B06-11D1-AB04-00C04FC2DCD2', 'E3514235-4B06-11D1-AB04-00C04FC2DCD2-ADAM', - 'Dfsr-12F9A27C-BF97-4787-9364-D31B6C55EB04', 'NtFrs-88f5d2bd-b646-11d2-a6d3-00c04fc9b232', - 'kadmin', 'krbsvr400', 'oracle', 'postgres', 'mongod', 'mongos', - 'ftp', 'vnc', 'sip', 'xmpp', 'ipp', 'cvs', 'afpserver', 'pcast', 'xgrid', - 'hdb', 'hbase', 'hdfs', 'hive', 'impala', 'kafka', 'mapred', 'oozie', - 'solr', 'spark', 'yarn', 'zookeeper', 'sentry', 'flume', 'hue', 'boostfs', - 'SAP', 'SAPService', 'SAS', 'BOBJCentralMS', 'BOCMS', 'BOSSO', 'BICMS', - 'Cognos', 'DynamicsNAV', 'NAV2016', 'MSCRMAsyncService', 'MSCRMSandboxService', - 'M-Files', 'ImDmsSvc', 'SeapineLicenseSvr', 'PVSSoap', 'Norskale', - 'aradminsvc', 'CESREMOTE', 'CAXOsoftEngine', 'CAARCserveRHAEngine', - 'FileRepService', 'VProRecovery', 'Backup Exec System Recovery Agent 6.x', - 'LiveState Recovery Agent 6.x', 'SoftGrid', 'vssrvc', 'vmrc', - 'OA60', 'EDVR', 'iem', 'magfs', 'tapinego', 'tnetdgines', - 'CUSESSIONKEYSVR', 'ckp_pdp', 'secshd', 'informatica', - 'jboss', 'fcsvr', 'gateway', 'httpfs', 'JournalNode Server', - 'kafka_mirror_maker', 'kudu', 'mr2', 'Storm', 'Zeppelin', - 'PIAFServer', 'PIServer', 'AFServer', 'PowerBIReportServer', - 'AcronisAgent', 'NPPolicyEvaluator', 'NPRepository4(DEFAULT)', 'NPRepository4(*)', - 'Agent VProRecovery Norton Ghost 12.0', 'UPM_SPN_7DC3CE86', - '{14E52635-0A95-4a5c-BDB1-E0D0C703B6C8}', '{54094C05-F977-4987-BFC9-E8B90E088973}' - ) - - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('Users') - - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $users = $adState.Users - - # Extract unknown SPNs from user objects - $unknownSpnData = $users | Where-Object { $null -ne $_.servicePrincipalName } | ForEach-Object { - $user = $_ - $user.servicePrincipalName | ForEach-Object { - if ($_ -match "^([^/]+)") { - $serviceClass = $matches[1] - if ($knownSpns -notcontains $serviceClass) { - [PSCustomObject]@{ - ServiceClass = $serviceClass - User = $user.SamAccountName - SPN = $_ - } - } - } - } - } - - # Group by service class - $unknownGroups = $unknownSpnData | Group-Object ServiceClass | Sort-Object Count -Descending - - $unknownCount = ($unknownGroups | Measure-Object).Count - $totalUnknownInstances = ($unknownSpnData | Measure-Object).Count - - # Test passes if we successfully retrieved SPN data - $testResult = $true - - # Generate markdown results - if ($testResult) { - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Unknown Service Classes | $unknownCount |" + "`n" - $result += "| Total Unknown SPN Instances | $totalUnknownInstances |" + "`n" + "`n" - - if ($unknownCount -gt 0) { - $result += "### Unknown Service Class Details" + "`n" + "`n" - $result += "| Service Class | Count | Users |" + "`n" - $result += "| --- | --- | --- |" + "`n" - - foreach ($group in $unknownGroups) { - $usersList = ($group.Group | Select-Object -ExpandProperty User -Unique) -join ', ' - if ($usersList.Length -gt 50) { - $usersList = $usersList.Substring(0, 47) + "..." - } - $result += "| $($group.Name) | $($group.Count) | $usersList |" + "`n" - } - } else { - $result += "No unknown SPN service classes found on user accounts. All SPNs match the known service database." + "`n" - } - - $testResultMarkdown = "Active Directory user SPN unknown service class details.`n`n%TestResult%" - if ($unknownCount -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", "" - } - } else { - $testResultMarkdown = "Unable to retrieve Active Directory user SPN data. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - - return $testResult -} diff --git a/tests/ad/spn/Test.AD-SPN-11.ps1 b/tests/ad/spn/Test.AD-SPN-11.ps1 index dd4d747b6a..36f2e57e46 100644 --- a/tests/ad/spn/Test.AD-SPN-11.ps1 +++ b/tests/ad/spn/Test.AD-SPN-11.ps1 @@ -73,10 +73,12 @@ } } - $totalSpns = ($spnData | Measure-Object).Count + if ($null -eq $users) { throw 'User collection is unavailable.' } + $totalSpns = @($users | ForEach-Object { $_.servicePrincipalName } | Where-Object { $_ }).Count + $parsedSpns = @($spnData).Count $nonFqdnSpns = $spnData | Where-Object { -not $_.IsFqdn } $nonFqdnCount = ($nonFqdnSpns | Measure-Object).Count - $fqdnCount = $totalSpns - $nonFqdnCount + $fqdnCount = $parsedSpns - $nonFqdnCount # Test passes if we successfully retrieved SPN data $testResult = $true @@ -86,6 +88,7 @@ $result = "| Metric | Value |" + "`n" $result += "| --- | --- |" + "`n" $result += "| Total User SPNs | $totalSpns |" + "`n" + $result += "| SPNs with unparsed host format | $($totalSpns - $parsedSpns) |" + "`n" $result += "| FQDN Hosts | $fqdnCount |" + "`n" $result += "| Non-FQDN Hosts | $nonFqdnCount |" + "`n" From efb7654ce88a6a385790215ef4b9c0c9ea610fd7 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 06:23:26 +0000 Subject: [PATCH 017/100] fix(ad): assess SPNs on effective Domain Admins membership --- .../functions/ADGroupSpnChecks.Tests.ps1 | 137 +++++++++++++++++ tests/ad/spn/Test.AD-SPN-06.ps1 | 3 +- tests/ad/spn/Test.AD-SPN-12.md | 4 +- tests/ad/spn/Test.AD-SPN-12.ps1 | 92 +++++++++--- tests/ad/spn/Test.AD-SPN-13.md | 40 ----- tests/ad/spn/Test.AD-SPN-13.ps1 | 139 ------------------ tests/ad/user/Test.AD-USER-11.md | 2 +- tests/ad/user/Test.AD-USER-14.md | 27 ---- tests/ad/user/Test.AD-USER-14.ps1 | 81 ---------- tests/ad/user/Test.AD-USER-20.md | 2 +- 10 files changed, 216 insertions(+), 311 deletions(-) create mode 100644 powershell/tests/functions/ADGroupSpnChecks.Tests.ps1 delete mode 100644 tests/ad/spn/Test.AD-SPN-13.md delete mode 100644 tests/ad/spn/Test.AD-SPN-13.ps1 delete mode 100644 tests/ad/user/Test.AD-USER-14.md delete mode 100644 tests/ad/user/Test.AD-USER-14.ps1 diff --git a/powershell/tests/functions/ADGroupSpnChecks.Tests.ps1 b/powershell/tests/functions/ADGroupSpnChecks.Tests.ps1 new file mode 100644 index 0000000000..017f32961f --- /dev/null +++ b/powershell/tests/functions/ADGroupSpnChecks.Tests.ps1 @@ -0,0 +1,137 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name Test-MtAdGroupMemberDistinctGroupCount, Test-MtAdGroupMemberAccountTypeCount, + Test-MtAdGroupMemberTrustCount, Test-MtAdUserSpnTotalCount, Test-MtAdUserSpnServiceClassCount, + Test-MtAdUserSpnDomainAdminCount +} + +Describe 'AD group and SPN checks on a collected snapshot' { + BeforeEach { + InModuleScope Maester { + $script:adSpnDomainSid = 'S-1-5-21-111-222-333' + $script:adSpnAdminDn = 'CN=Domain Admins,DC=example,DC=com' + $script:adSpnState = [PSCustomObject]@{ + Domain = [PSCustomObject]@{ DomainSID = [PSCustomObject]@{ Value = $script:adSpnDomainSid } } + Groups = @([PSCustomObject]@{ DistinguishedName = $script:adSpnAdminDn; SID = [PSCustomObject]@{ Value = "$script:adSpnDomainSid-512" }; Name = 'Domain Admins' }) + Users = @([PSCustomObject]@{ DistinguishedName = 'CN=Ordinary,DC=example,DC=com'; SID = "$script:adSpnDomainSid-1100"; SamAccountName = 'ordinary'; PrimaryGroupId = 513; ServicePrincipalName = @() }) + ProtocolEvidence = [PSCustomObject]@{} + } + $script:adSpnMembers = @{ $script:adSpnAdminDn = @() } + $script:adSpnResult = '' + } + + Mock Get-MtADDomainState -ModuleName Maester { InModuleScope Maester { $script:adSpnState } } + Mock New-MtAdProtocolConnection -ModuleName Maester { + [PSCustomObject]@{} | Add-Member -MemberType ScriptMethod -Name Dispose -Value { } -PassThru + } + Mock Get-MtLdapGroupMember -ModuleName Maester -RemoveParameterType Connection { + InModuleScope Maester -Parameters @{ GroupDn = $GroupDistinguishedName } { + @($script:adSpnMembers[$GroupDn]) | Where-Object { $null -ne $_ } + } + } + Mock Add-MtTestResultDetail -ModuleName Maester { + InModuleScope Maester -Parameters @{ Detail = $Result } { $script:adSpnResult = $Detail } + } + } + + It 'counts members in group 51 instead of silently truncating at 50' { + InModuleScope Maester { + $script:adSpnState.Groups = @(1..51 | ForEach-Object { + [PSCustomObject]@{ DistinguishedName = "CN=G$_,DC=example,DC=com"; Name = "G$_"; SID = "$script:adSpnDomainSid-$_" } + }) + $script:adSpnMembers['CN=G51,DC=example,DC=com'] = @( + [PSCustomObject]@{ SID = "$script:adSpnDomainSid-1200"; DistinguishedName = 'CN=Member,DC=example,DC=com'; Name = 'Member'; ObjectClass = 'user' } + ) + Test-MtAdGroupMemberDistinctGroupCount | Should -BeTrue + $script:adSpnResult | Should -Match '1 out of 51 groups' + Test-MtAdGroupMemberAccountTypeCount | Should -BeTrue + $script:adSpnResult | Should -Match '1 distinct account types across 1 unique members' + } + } + + It 'counts trust principals from group 51 without classifying NT AUTHORITY SIDs as foreign domains' { + InModuleScope Maester { + $script:adSpnState.Groups = @(1..51 | ForEach-Object { + [PSCustomObject]@{ DistinguishedName = "CN=G$_,DC=example,DC=com"; Name = "G$_"; SID = "$script:adSpnDomainSid-$_" } + }) + $script:adSpnMembers['CN=G51,DC=example,DC=com'] = @( + [PSCustomObject]@{ SID = 'S-1-5-18'; DistinguishedName = 'CN=System,DC=example,DC=com'; Name = 'SYSTEM'; ObjectClass = 'user' }, + [PSCustomObject]@{ SID = 'S-1-5-21-444-555-666-1200'; DistinguishedName = 'CN=Foreign,DC=example,DC=com'; Name = 'Foreign'; ObjectClass = 'foreignSecurityPrincipal' } + ) + Test-MtAdGroupMemberTrustCount | Should -BeTrue + $script:adSpnResult | Should -Match 'Found 1 trust members' + $script:adSpnResult | Should -Match 'Groups Analyzed \| 51' + } + } + + It 'distinguishes two users with SPNs from seven raw SPNs' { + InModuleScope Maester { + $script:adSpnState.Users = @( + [PSCustomObject]@{ SamAccountName = 'one'; ServicePrincipalName = @('HTTP/a', 'HTTP/b', 'custom:value') }, + [PSCustomObject]@{ SamAccountName = 'two'; ServicePrincipalName = @('HTTP/c', 'HTTP/d', 'HTTP/e', 'HTTP/f') }, + [PSCustomObject]@{ SamAccountName = 'none'; ServicePrincipalName = @() } + ) + Test-MtAdUserSpnTotalCount | Should -BeTrue + $script:adSpnResult | Should -Match '7 SPNs across 2 user accounts' + Test-MtAdUserSpnServiceClassCount | Should -BeTrue + $script:adSpnResult | Should -Match 'Total User SPNs \| 7' + $script:adSpnResult | Should -Match 'Users with SPNs \| 2' + } + } + + It 'counts direct, nested and primary-group Domain Admins, including unparsed SPNs' { + InModuleScope Maester { + $nestedDn = 'CN=Nested,DC=example,DC=com' + $script:adSpnState.Groups += [PSCustomObject]@{ DistinguishedName = $nestedDn; SID = "$script:adSpnDomainSid-1400"; Name = 'Nested' } + $script:adSpnState.Users = @( + [PSCustomObject]@{ DistinguishedName = 'CN=Direct,DC=example,DC=com'; SID = [PSCustomObject]@{ Value = "$script:adSpnDomainSid-1101" }; SamAccountName = 'direct'; PrimaryGroupId = 513; ServicePrincipalName = @('HTTP/host', 'not-standard') }, + [PSCustomObject]@{ DistinguishedName = 'CN=Indirect,DC=example,DC=com'; SID = "$script:adSpnDomainSid-1102"; SamAccountName = 'indirect'; PrimaryGroupId = 513; ServicePrincipalName = @('HTTP/nested') }, + [PSCustomObject]@{ DistinguishedName = 'CN=Primary,DC=example,DC=com'; SID = "$script:adSpnDomainSid-1103"; SamAccountName = 'primary'; PrimaryGroupId = 512; ServicePrincipalName = @('opaque-spn') }, + [PSCustomObject]@{ DistinguishedName = 'CN=OtherDomain,DC=example,DC=com'; SID = 'S-1-5-21-444-555-666-1104'; SamAccountName = 'other'; PrimaryGroupId = 512; ServicePrincipalName = @('HTTP/foreign') } + ) + $script:adSpnMembers[$script:adSpnAdminDn] = @( + [PSCustomObject]@{ DistinguishedName = 'CN=Direct,DC=example,DC=com'; SID = "$script:adSpnDomainSid-1101" }, + [PSCustomObject]@{ DistinguishedName = $nestedDn; SID = "$script:adSpnDomainSid-1400" } + ) + $script:adSpnMembers[$nestedDn] = @( + [PSCustomObject]@{ DistinguishedName = 'CN=Indirect,DC=example,DC=com'; SID = "$script:adSpnDomainSid-1102" } + ) + Test-MtAdUserSpnDomainAdminCount | Should -BeFalse + $script:adSpnResult | Should -Match 'Domain Admin Accounts \| 3' + $script:adSpnResult | Should -Match 'Domain Admins with SPNs \| 3' + $script:adSpnResult | Should -Match 'Total SPNs on Domain Admins \| 4' + } + } + + It 'terminates on cyclic nested groups and deduplicates the same user' { + InModuleScope Maester { + $nestedDn = 'CN=Nested,DC=example,DC=com' + $script:adSpnState.Groups += [PSCustomObject]@{ DistinguishedName = $nestedDn; SID = "$script:adSpnDomainSid-1400"; Name = 'Nested' } + $script:adSpnState.Users = @([PSCustomObject]@{ + DistinguishedName = 'CN=Direct,DC=example,DC=com'; SID = "$script:adSpnDomainSid-1101" + SamAccountName = 'direct'; PrimaryGroupId = 512; ServicePrincipalName = @() + }) + $script:adSpnMembers[$script:adSpnAdminDn] = @( + [PSCustomObject]@{ DistinguishedName = $nestedDn; SID = "$script:adSpnDomainSid-1400" }, + [PSCustomObject]@{ DistinguishedName = 'CN=Direct,DC=example,DC=com'; SID = "$script:adSpnDomainSid-1101" } + ) + $script:adSpnMembers[$nestedDn] = @( + [PSCustomObject]@{ DistinguishedName = $script:adSpnAdminDn; SID = "$script:adSpnDomainSid-512" }, + [PSCustomObject]@{ DistinguishedName = 'CN=Direct,DC=example,DC=com'; SID = "$script:adSpnDomainSid-1101" } + ) + Test-MtAdUserSpnDomainAdminCount | Should -BeTrue + $script:adSpnResult | Should -Match 'Domain Admin Accounts \| 1' + } + } + + It 'errors instead of reporting a clean Domain Admins result when membership is unresolved' { + InModuleScope Maester { + $script:adSpnMembers[$script:adSpnAdminDn] = @( + [PSCustomObject]@{ DistinguishedName = 'CN=Missing,DC=example,DC=com'; SID = "$script:adSpnDomainSid-1999" } + ) + { Test-MtAdUserSpnDomainAdminCount } | Should -Throw '*Unresolved Domain Admins member*' + $script:adSpnResult | Should -BeNullOrEmpty + } + } +} diff --git a/tests/ad/spn/Test.AD-SPN-06.ps1 b/tests/ad/spn/Test.AD-SPN-06.ps1 index 2f5c43da0f..c1cb8ef552 100644 --- a/tests/ad/spn/Test.AD-SPN-06.ps1 +++ b/tests/ad/spn/Test.AD-SPN-06.ps1 @@ -52,8 +52,9 @@ $allSpns = $users | Where-Object { $null -ne $_.servicePrincipalName } | ForEach-Object { $_.servicePrincipalName } | ForEach-Object { $_ } $totalSpnCount = ($allSpns | Measure-Object).Count - $usersWithSpns = ($users | Where-Object { $null -ne $_.servicePrincipalName } | Measure-Object).Count + $usersWithSpns = @($users | Where-Object { @($_.servicePrincipalName | Where-Object { $_ }).Count -gt 0 }).Count $totalUsers = ($users | Measure-Object).Count + if ($null -eq $users) { throw 'User collection is unavailable.' } # Test passes if we successfully retrieved SPN data $testResult = $true diff --git a/tests/ad/spn/Test.AD-SPN-12.md b/tests/ad/spn/Test.AD-SPN-12.md index c621b36058..14faf7b907 100644 --- a/tests/ad/spn/Test.AD-SPN-12.md +++ b/tests/ad/spn/Test.AD-SPN-12.md @@ -22,11 +22,11 @@ If domain admin accounts have SPNs: #### How the Test Works -This test identifies domain administrator accounts (using the well-known RID 500) and checks if they have any SPNs configured. Any SPNs found on these accounts are flagged as critical security risks. +This test identifies the Domain Admins group by its domain SID and RID 512, resolves direct and nested user members plus users whose primary group ID is 512 (not represented by the group's `member` attribute), and checks all of their raw SPNs. RID 500 alone identifies the built-in Administrator account, not the Domain Admins group. An unresolved membership is an error, not a pass. #### Related Tests -- `Test-MtAdUserSpnDomainAdminDetails` - Detailed SPN information for domain admins +- This check includes account-level SPN counts for Domain Admins members. - `Test-MtAdUserSpnTotalCount` - Overall user SPN count - `Test-MtAdUserSpnServiceClassCount` - Service classes on user accounts diff --git a/tests/ad/spn/Test.AD-SPN-12.ps1 b/tests/ad/spn/Test.AD-SPN-12.ps1 index 5eb5f0dc8a..a53dc62f7d 100644 --- a/tests/ad/spn/Test.AD-SPN-12.ps1 +++ b/tests/ad/spn/Test.AD-SPN-12.ps1 @@ -1,4 +1,16 @@ -function Test-MtAdUserSpnDomainAdminCount { +function ConvertTo-MtAdSpnSidText { + [CmdletBinding()] + [OutputType([string])] + param([object] $Sid) + + if ($null -eq $Sid) { return '' } + if ($Sid.PSObject.Properties['Value'] -and $null -ne $Sid.Value) { + return [string]$Sid.Value + } + return [string]$Sid +} + +function Test-MtAdUserSpnDomainAdminCount { <# .SYNOPSIS Counts SPNs configured on domain administrator accounts. @@ -30,7 +42,7 @@ Mitre = 'T1558.003', Control = ('nist-800-53-r5:AC-6(5)', 'nist-800-53-r5:IA-5'), Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:domainDNS:ReadProperty', 'ActiveDirectory:Ldap:user:ReadProperty'), + Permission = ('ActiveDirectory:Ldap:domainDNS:ReadProperty', 'ActiveDirectory:Ldap:group:ReadProperty', 'ActiveDirectory:Ldap:group.member:ReadProperty', 'ActiveDirectory:Ldap:user:ReadProperty'), Author = 'soulemike' )] [CmdletBinding()] @@ -40,24 +52,68 @@ Write-Verbose "Starting Test-MtAdUserSpnDomainAdminCount" # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('Domain', 'Users') + $adState = Get-MtADDomainState -Categories @('Domain', 'Groups', 'Users') - # If unable to retrieve AD data, skip the test if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + throw 'Domain, groups and users are unavailable; cannot assess Domain Admins.' } $users = $adState.Users - $domain = $adState.Domain - - # Get domain admin SID (RID 500 is the built-in Administrator) - $domainAdminSid = "*$($domain.DomainSID.Value)-500" - - # Find domain admin accounts (built-in admin and users with RID 500 pattern) - $domainAdmins = $users | Where-Object { - $_.SID -like $domainAdminSid -or - $_.SID -like "S-1-5-*-500" + $domainSid = ConvertTo-MtAdSpnSidText -Sid $adState.Domain.DomainSID + if (-not $domainSid -or $null -eq $adState.Groups -or $null -eq $users -or @($users).Count -eq 0) { + throw 'Domain SID, groups or users are unavailable; cannot assess Domain Admins.' + } + $adminGroup = @($adState.Groups | Where-Object { (ConvertTo-MtAdSpnSidText -Sid $_.SID) -eq "$domainSid-512" }) + if ($adminGroup.Count -ne 1) { throw 'Unable to identify the Domain Admins group by its domain SID and RID 512.' } + $connection = New-MtAdProtocolConnection -ProtocolEvidence $adState.ProtocolEvidence + try { + $members = @(Get-MtLdapGroupMember -Connection $connection -GroupDistinguishedName $adminGroup[0].DistinguishedName) + } + finally { + $connection.Dispose() + } + # Expand nested groups from the cached domain group collection; unresolved or foreign members + # must not produce a clean result when their user SPNs cannot be assessed. + $pending = [System.Collections.Generic.Queue[object]]::new() + foreach ($member in $members) { $pending.Enqueue($member) } + $visitedGroups = @{ ([string]$adminGroup[0].DistinguishedName) = $true } + $memberSids = @{} + $userDns = @{} + foreach ($user in $users) { + $userSid = ConvertTo-MtAdSpnSidText -Sid $user.SID + if ([string]::IsNullOrWhiteSpace($userSid)) { + throw "User has no SID: $($user.DistinguishedName)" + } + $userDns[[string]$user.DistinguishedName] = $user + # AD primary-group membership is not recorded in the group's member attribute. + if ($user.PrimaryGroupId -eq 512 -and $userSid.StartsWith("$domainSid-")) { + $memberSids[$userSid] = $true + } + } + $connection = New-MtAdProtocolConnection -ProtocolEvidence $adState.ProtocolEvidence + try { + while ($pending.Count -gt 0) { + $member = $pending.Dequeue() + $memberSid = ConvertTo-MtAdSpnSidText -Sid $member.SID + $nestedGroup = @($adState.Groups | Where-Object { $_.DistinguishedName -eq $member.DistinguishedName }) + if ($nestedGroup.Count -gt 0) { + $dn = [string]$nestedGroup[0].DistinguishedName + if (-not $visitedGroups.ContainsKey($dn)) { + $visitedGroups[$dn] = $true + foreach ($child in @(Get-MtLdapGroupMember -Connection $connection -GroupDistinguishedName $dn)) { $pending.Enqueue($child) } + } + } + elseif ($userDns.ContainsKey([string]$member.DistinguishedName)) { + if (-not $memberSid) { throw "Domain Admins member has no SID: $($member.DistinguishedName)" } + $memberSids[$memberSid] = $true + } + else { throw "Unresolved Domain Admins member: $($member.DistinguishedName)" } + } + } + finally { $connection.Dispose() } + $domainAdmins = @($users | Where-Object { $memberSids.ContainsKey((ConvertTo-MtAdSpnSidText -Sid $_.SID)) }) + if ($domainAdmins.Count -eq 0) { + throw 'No Domain Admins users could be resolved from group membership or primary group ID 512.' } # Extract SPNs from domain admin accounts @@ -73,14 +129,14 @@ } $totalAdminSpns = ($adminSpns | Measure-Object).Count - $adminsWithSpns = ($domainAdmins | Where-Object { $null -ne $_.servicePrincipalName } | Measure-Object).Count + $adminsWithSpns = @($domainAdmins | Where-Object { @($_.servicePrincipalName | Where-Object { $_ }).Count -gt 0 }).Count $totalDomainAdmins = ($domainAdmins | Measure-Object).Count # Test passes if no domain admin accounts have SPNs configured $testResult = $totalAdminSpns -eq 0 # Generate markdown results - if ($testResult) { + if ($null -ne $domainAdmins) { $result = "| Metric | Value |" + "`n" $result += "| --- | --- |" + "`n" $result += "| Domain Admin Accounts | $totalDomainAdmins |" + "`n" @@ -108,8 +164,6 @@ $testResultMarkdown = "Active Directory domain administrator SPN analysis.`n`n%TestResult%" $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory user SPN data. Ensure you have appropriate permissions and the Active Directory module is installed." } Add-MtTestResultDetail -Result $testResultMarkdown diff --git a/tests/ad/spn/Test.AD-SPN-13.md b/tests/ad/spn/Test.AD-SPN-13.md deleted file mode 100644 index fbbb0d92f1..0000000000 --- a/tests/ad/spn/Test.AD-SPN-13.md +++ /dev/null @@ -1,40 +0,0 @@ -Detailed visibility into domain admin SPNs is critical for security incident response: - -- **Immediate remediation**: Know exactly which SPNs to remove -- **Service identification**: Understand what services were improperly configured -- **Attack surface assessment**: Evaluate the scope of exposure -- **Compliance violation**: Domain admins should never have SPNs - -Any SPN on a domain admin account is a critical finding requiring immediate action. - -#### Control Type - -**Preventive** - -#### Security Recommendation - -**Immediate actions required:** -1. Remove ALL SPNs from domain administrator accounts -2. Investigate how and why SPNs were configured -3. Create dedicated service accounts or gMSAs for the services -4. Review domain admin membership and remove unnecessary accounts -5. Implement monitoring for SPN changes to privileged accounts -6. Consider this a potential security incident requiring investigation - -#### How the Test Works - -This test identifies domain administrator accounts and provides detailed information about any SPNs configured on them, including service class, host, FQDN status, and full SPN value for remediation. - -#### Related Tests - -- `Test-MtAdUserSpnDomainAdminCount` - Counts SPNs on domain admins -- `Test-MtAdUserSpnTotalCount` - Overall user SPN analysis -- `Test-MtAdUserSpnUnknownDetails` - Unknown SPN details on all users - -#### Related links - -- [Microsoft Defender for Identity: Unsecure account attributes](https://learn.microsoft.com/defender-for-identity/security-posture-assessments/accounts#unsecure-account-attributes) -- [ANSSI Active Directory checkpoints: Privileged accounts with SPN](https://www.cert.ssi.gouv.fr/uploads/ad_checklist.html#vuln_spn_priv) - - -%TestResult% diff --git a/tests/ad/spn/Test.AD-SPN-13.ps1 b/tests/ad/spn/Test.AD-SPN-13.ps1 deleted file mode 100644 index 3d5595278d..0000000000 --- a/tests/ad/spn/Test.AD-SPN-13.ps1 +++ /dev/null @@ -1,139 +0,0 @@ -function Test-MtAdUserSpnDomainAdminDetails { - <# - .SYNOPSIS - Provides detailed information about SPNs configured on domain administrator accounts. - - .DESCRIPTION - This test retrieves all Service Principal Names (SPNs) configured on domain - administrator accounts and provides detailed information about each SPN. - This includes the service class, host, and full SPN value for investigation. - - .EXAMPLE - Test-MtAdUserSpnDomainAdminDetails - - Returns $true if SPN data is accessible, $false otherwise. - The test result includes detailed information about domain admin SPNs. - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserSpnDomainAdminDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-SPN-13', - Title = 'No domain admin accounts should have SPNs configured', - Product = 'ad', - Feature = 'service-principal-names', - Area = 'privileged-access', - ResourceType = 'User', - Severity = 'Critical', - UserImpact = 'Low', - ImplementationCost = 'Medium', - Mitre = 'T1558.003', - Control = ('nist-800-53-r5:AC-6(5)', 'nist-800-53-r5:IA-5'), - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:domainDNS:ReadProperty', 'ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserSpnDomainAdminDetails" - - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('Domain', 'Users') - - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $users = $adState.Users - $domain = $adState.Domain - - # Get domain admin SID (RID 500 is the built-in Administrator) - $domainAdminSid = "*$($domain.DomainSID.Value)-500" - - # Find domain admin accounts (built-in admin and users with RID 500 pattern) - $domainAdmins = $users | Where-Object { - $_.SID -like $domainAdminSid -or - $_.SID -like "S-1-5-*-500" - } - - # Extract detailed SPN information from domain admin accounts - $adminSpnDetails = $domainAdmins | Where-Object { $null -ne $_.servicePrincipalName } | ForEach-Object { - $admin = $_ - $admin.servicePrincipalName | ForEach-Object { - # Parse SPN to extract components - if ($_ -match "^([^/]+)/([^:]+)(?::(\d+))?$") { - $serviceClass = $matches[1] - $hostPart = $matches[2] - $port = $matches[3] - - [PSCustomObject]@{ - SPN = $_ - ServiceClass = $serviceClass - Host = $hostPart - Port = $port - IsFqdn = $hostPart -like "*.*" - AdminAccount = $admin.SamAccountName - AdminSID = $admin.SID - Enabled = $admin.Enabled - } - } - } - } - - $totalAdminSpns = ($adminSpnDetails | Measure-Object).Count - $adminsWithSpns = ($domainAdmins | Where-Object { $null -ne $_.servicePrincipalName } | Measure-Object).Count - $totalDomainAdmins = ($domainAdmins | Measure-Object).Count - - # Test passes if no domain admin accounts have SPNs configured - $testResult = $totalAdminSpns -eq 0 - - # Generate markdown results - if ($testResult) { - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Domain Admin Accounts | $totalDomainAdmins |" + "`n" - $result += "| Domain Admins with SPNs | $adminsWithSpns |" + "`n" - $result += "| Total SPNs on Domain Admins | $totalAdminSpns |" + "`n" - - if ($totalAdminSpns -gt 0) { - $result += "`n**⚠️ Critical**: Domain administrator accounts have SPNs configured. These must be removed immediately." + "`n" + "`n" - $result += "### Domain Admin SPN Details" + "`n" + "`n" - $result += "| Account | SPN | Service Class | Host | FQDN |" + "`n" - $result += "| --- | --- | --- | --- | --- |" + "`n" - - foreach ($spnDetail in $adminSpnDetails) { - $fqdnStatus = if ($spnDetail.IsFqdn) { "Yes" } else { "No" } - $result += "| $($spnDetail.AdminAccount) | $($spnDetail.SPN) | $($spnDetail.ServiceClass) | $($spnDetail.Host) | $fqdnStatus |" + "`n" - } - - # Service class breakdown - $serviceClassGroups = $adminSpnDetails | Group-Object ServiceClass | Sort-Object Count -Descending - $result += "`n### Service Class Breakdown" + "`n" + "`n" - $result += "| Service Class | Count |" + "`n" - $result += "| --- | --- |" + "`n" - foreach ($group in $serviceClassGroups) { - $result += "| $($group.Name) | $($group.Count) |" + "`n" - } - } else { - $result += "`n**✅ Good**: No domain administrator accounts have SPNs configured." + "`n" - } - - $testResultMarkdown = "Active Directory domain administrator SPN detailed analysis.`n`n%TestResult%" - if ($totalAdminSpns -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", "" - } - } else { - $testResultMarkdown = "Unable to retrieve Active Directory user SPN data. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult -} diff --git a/tests/ad/user/Test.AD-USER-11.md b/tests/ad/user/Test.AD-USER-11.md index 04155c7011..79af76b2a2 100644 --- a/tests/ad/user/Test.AD-USER-11.md +++ b/tests/ad/user/Test.AD-USER-11.md @@ -21,7 +21,7 @@ This test counts user objects where the `AdminCount` attribute equals `1`. #### Related Tests - `Test-MtAdUserNonStandardPrimaryGroupCount` - Finds users with unusual group membership baselines -- `Test-MtAdUserSpnSetCount` - Identifies potentially high-value service accounts +- `AD-SPN-06` - Identifies accounts with SPNs %TestResult% diff --git a/tests/ad/user/Test.AD-USER-14.md b/tests/ad/user/Test.AD-USER-14.md deleted file mode 100644 index 65a772ba4e..0000000000 --- a/tests/ad/user/Test.AD-USER-14.md +++ /dev/null @@ -1,27 +0,0 @@ -User accounts with `ServicePrincipalName` values are typically used as service accounts. These accounts are important because they may be susceptible to Kerberoasting and often have broad or persistent access. - -- **Kerberoasting exposure**: User SPNs are a common attack target -- **Service account discovery**: Helps inventory service identities in the domain -- **Hardening priority**: Supports review of password hygiene, delegation, and logon restrictions - -#### Control Type - -**Operational** - -#### Security Recommendation - -- Review every user account with an SPN and confirm it is a legitimate service account -- Prefer managed service account options where possible -- Ensure service accounts use strong credential and monitoring controls - -#### How the Test Works - -This test counts user objects where the `ServicePrincipalName` attribute contains one or more values. - -#### Related Tests - -- `Test-MtAdUserKnownServiceAccountCount` - Identifies service accounts by naming convention -- `Test-MtAdUserAdminCountCount` - Highlights protected user accounts that may need extra scrutiny - - -%TestResult% diff --git a/tests/ad/user/Test.AD-USER-14.ps1 b/tests/ad/user/Test.AD-USER-14.ps1 deleted file mode 100644 index ca33cd75bf..0000000000 --- a/tests/ad/user/Test.AD-USER-14.ps1 +++ /dev/null @@ -1,81 +0,0 @@ -function Test-MtAdUserSpnSetCount { - <# - .SYNOPSIS - Counts users with SPNs configured in Active Directory. - - .DESCRIPTION - This test identifies user objects with one or more Service Principal Names (SPNs) - configured. User-based SPNs often represent service accounts and can be high-value - targets for Kerberoasting. Tracking the volume of user accounts with SPNs helps - identify service account exposure and operational patterns that require review. - - .EXAMPLE - Test-MtAdUserSpnSetCount - - Returns $true if user data is accessible, $false otherwise. - The test result includes the count of users with SPNs configured. - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserSpnSetCount - #> - [MaesterTest( - Id = 'AD-USER-14', - Title = 'User SPN count should be retrievable', - Product = 'ad', - Feature = 'service-principal-names', - Area = 'authentication', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'T1558.003', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserSpnSetCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user spn set count" - - $users = $adState.Users - $usersWithSpn = $users | Where-Object { - $_.ServicePrincipalName -and - ($_.ServicePrincipalName | Measure-Object).Count -gt 0 - } - - $spnCount = ($usersWithSpn | Measure-Object).Count - $totalCount = ($users | Measure-Object).Count - $testResult = $totalCount -gt 0 - - if ($testResult) { - $percentage = if ($totalCount -gt 0) { - [Math]::Round(($spnCount / $totalCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users | $totalCount |" + "`n" - $result += "| Users with SPNs Configured | $spnCount |" + "`n" - $result += "| SPN Percentage | $percentage% |" + "`n" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory users have been analyzed. $spnCount out of $totalCount users ($percentage%) have one or more SPNs configured.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory users. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdUserSpnSetCount" - - return $testResult -} diff --git a/tests/ad/user/Test.AD-USER-20.md b/tests/ad/user/Test.AD-USER-20.md index 4e31f343f2..17f7bc5386 100644 --- a/tests/ad/user/Test.AD-USER-20.md +++ b/tests/ad/user/Test.AD-USER-20.md @@ -20,7 +20,7 @@ This test counts user objects whose `SamAccountName` or `Name` matches common se #### Related Tests -- `Test-MtAdUserSpnSetCount` - Identifies service accounts through SPN usage +- `AD-SPN-06` - Identifies service accounts through SPN usage - `Test-MtAdUserAdminCountCount` - Highlights service accounts that may also be protected or privileged From 9075c0a373dfc1a6decb6f9b67998b8327bfb2c4 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 06:23:26 +0000 Subject: [PATCH 018/100] fix(ad): consolidate schema SASL and managed service account checks --- .../functions/ADCollectorQueries.Tests.ps1 | 139 ++++++++++++++++++ tests/ad/replication/Test.AD-ROOTDSE-01.md | 31 +--- tests/ad/replication/Test.AD-ROOTDSE-01.ps1 | 20 ++- tests/ad/replication/Test.AD-ROOTDSE-02.md | 38 ----- tests/ad/replication/Test.AD-ROOTDSE-02.ps1 | 94 ------------ tests/ad/schema/Test.AD-SCH-01.md | 16 +- tests/ad/schema/Test.AD-SCH-01.ps1 | 71 ++++----- tests/ad/schema/Test.AD-SCH-02.md | 40 ----- tests/ad/schema/Test.AD-SCH-02.ps1 | 97 ------------ tests/ad/schema/Test.AD-SCH-03.md | 10 +- tests/ad/schema/Test.AD-SCH-03.ps1 | 87 +++++------ tests/ad/schema/Test.AD-SCH-04.md | 42 ------ tests/ad/schema/Test.AD-SCH-04.ps1 | 118 --------------- tests/ad/schema/Test.AD-SCH-05.md | 39 +---- tests/ad/schema/Test.AD-SCH-05.ps1 | 73 +++------ tests/ad/security/Test.AD-KRBTGT-01.md | 2 +- tests/ad/security/Test.AD-KRBTGT-01.ps1 | 5 +- tests/ad/security/Test.AD-MSA-01.md | 54 +------ tests/ad/security/Test.AD-MSA-01.ps1 | 29 ++-- 19 files changed, 290 insertions(+), 715 deletions(-) create mode 100644 powershell/tests/functions/ADCollectorQueries.Tests.ps1 delete mode 100644 tests/ad/replication/Test.AD-ROOTDSE-02.md delete mode 100644 tests/ad/replication/Test.AD-ROOTDSE-02.ps1 delete mode 100644 tests/ad/schema/Test.AD-SCH-02.md delete mode 100644 tests/ad/schema/Test.AD-SCH-02.ps1 delete mode 100644 tests/ad/schema/Test.AD-SCH-04.md delete mode 100644 tests/ad/schema/Test.AD-SCH-04.ps1 diff --git a/powershell/tests/functions/ADCollectorQueries.Tests.ps1 b/powershell/tests/functions/ADCollectorQueries.Tests.ps1 new file mode 100644 index 0000000000..c393081edb --- /dev/null +++ b/powershell/tests/functions/ADCollectorQueries.Tests.ps1 @@ -0,0 +1,139 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'AD query normalization for consolidated checks' { + BeforeEach { + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { } + } + + It 'uses schema LDAP display names rather than common names' { + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { + [pscustomobject]@{ name = 'ms-LAPS-Password'; lDAPDisplayName = 'msLAPS-Password'; objectClass = @('attributeSchema') } + } + InModuleScope Maester { + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') + try { + $objects = @(Get-MtLdapSchemaObject -Connection $connection -SchemaNamingContext 'CN=Schema,CN=Configuration,DC=example,DC=com') + $objects[0].Name | Should -Be 'ms-LAPS-Password' + $objects[0].LdapDisplayName | Should -Be 'msLAPS-Password' + } + finally { $connection.Dispose() } + } + Should -Invoke Invoke-MtLdapSearch -ModuleName Maester -ParameterFilter { $Attributes -contains 'lDAPDisplayName' } + } + + It 'collects all three managed service account classes without requesting passwords' { + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { + [pscustomobject]@{ name = 'Delegated'; objectClass = @('computer', 'msDS-DelegatedManagedServiceAccount'); 'msDS-DelegatedMSAState' = 2 } + } + InModuleScope Maester { + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') + try { + $accounts = @(Get-MtLdapServiceAccount -Connection $connection -SearchBase 'DC=example,DC=com') + $accounts[0].ObjectClass | Should -Contain 'msDS-DelegatedManagedServiceAccount' + $accounts[0].DelegatedMsaState | Should -Be 2 + } + finally { $connection.Dispose() } + } + Should -Invoke Invoke-MtLdapSearch -ModuleName Maester -ParameterFilter { + $Filter -match 'msDS-ManagedServiceAccount' -and $Filter -match 'msDS-GroupManagedServiceAccount' -and $Filter -match 'msDS-DelegatedManagedServiceAccount' -and + @($Attributes | Where-Object { $_ -match '^(msDS-ManagedPassword|msDS-ManagedPasswordId|msDS-ManagedPasswordPreviousId)$' }).Count -eq 0 + } + } + + It 'reports classic KCD targets and RBCD descriptor presence separately' { + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { + [pscustomobject]@{ name = 'Client'; userAccountControl = 4096; 'msDS-AllowedToDelegateTo' = @('HTTP/service.example.com'); 'msDS-AllowedToActOnBehalfOfOtherIdentity' = [byte[]]@(1, 2, 3) } + } + InModuleScope Maester { + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') + try { + $computers = @(Get-MtLdapComputer -Connection $connection -SearchBase 'DC=example,DC=com') + $computers[0].AllowedToDelegateTo | Should -Contain 'HTTP/service.example.com' + $computers[0].HasResourceBasedConstrainedDelegation | Should -BeTrue + $computers[0].PSObject.Properties.Name | Should -Not -Contain 'msDS-AllowedToActOnBehalfOfOtherIdentity' + } + finally { $connection.Dispose() } + } + } + + It 'retains enabled optional feature scopes' { + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { + [pscustomobject]@{ name = 'Recycle Bin Feature'; 'msDS-EnabledFeatureBL' = @('CN=Partitions,CN=Configuration,DC=example,DC=com') } + } + InModuleScope Maester { + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') + try { + $features = @(Get-MtLdapOptionalFeature -Connection $connection -ConfigurationNamingContext 'CN=Configuration,DC=example,DC=com') + $features[0].IsEnabled | Should -BeTrue + $features[0].EnabledScopes | Should -HaveCount 1 + } + finally { $connection.Dispose() } + } + } + + It 'normalizes binary CreatorSid as a SID rather than UTF-8 text' { + InModuleScope Maester { + $sid = ConvertFrom-MtLdapValue -AttributeName 'mS-DS-CreatorSID' -Value ([byte[]]@(1, 1, 0, 0, 0, 0, 0, 5, 11, 0, 0, 0)) + $sid.Value | Should -Be 'S-1-5-11' + } + } + + It 'distinguishes a missing Directory Service object from unset attributes' { + InModuleScope Maester { + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') + try { + $config = Get-MtLdapConfigurationContainer -Connection $connection -ConfigurationNamingContext 'CN=Configuration,DC=example,DC=com' + $config.DirectoryServiceRetrieved | Should -BeFalse + $config.SpnMappings | Should -BeNullOrEmpty + } + finally { $connection.Dispose() } + } + } + + It 'counts DHCP authorization values rather than dhcpClass container objects' { + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { + [pscustomobject]@{ name = 'DhcpRoot'; dhcpServers = @('i192.0.2.1$rcn=dhcp1.example.com$f0$sdhcp1.example.com$', 'i192.0.2.2$rcn=dhcp2.example.com$f0$sdhcp2.example.com$', 'unrecognized entry') } + } -ParameterFilter { $Filter -eq '(objectClass=dhcpClass)' } + InModuleScope Maester { + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') + try { + $config = Get-MtLdapConfigurationContainer -Connection $connection -ConfigurationNamingContext 'CN=Configuration,DC=example,DC=com' + $config.DhcpServers | Should -HaveCount 3 + @($config.DhcpServers | Where-Object RegistrationParsed) | Should -HaveCount 2 + $config.DhcpServers.DnsName | Should -Contain 'dhcp1.example.com' + $config.DhcpServers.IPAddress | Should -Contain '192.0.2.2' + } + finally { $connection.Dispose() } + } + } + + It 'requests the actual AD-based activation schema class' { + InModuleScope Maester { + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') + try { $null = Get-MtLdapConfigurationContainer -Connection $connection -ConfigurationNamingContext 'CN=Configuration,DC=example,DC=com' } + finally { $connection.Dispose() } + } + Should -Invoke Invoke-MtLdapSearch -ModuleName Maester -ParameterFilter { $Filter -eq '(objectClass=msSPP-ActivationObject)' } + } +} + +Describe 'Windows LAPS readiness accepts the production dictionary state' { + BeforeEach { + Mock -ModuleName Maester Get-MtADDomainState { + [ordered]@{ + WindowsLapsInstalled = $true + SchemaObjects = @( + [pscustomobject]@{ Name = 'ms-LAPS-Password'; LdapDisplayName = 'msLAPS-Password' } + [pscustomobject]@{ Name = 'ms-LAPS-Password-Expiration-Time'; LdapDisplayName = 'msLAPS-PasswordExpirationTime' } + ) + } + } + Mock -ModuleName Maester Add-MtTestResultDetail { } + } + + It 'passes with an ordered dictionary, not only a PSCustomObject fixture' { + InModuleScope Maester { Test-MtAdLapsInstalledStatus | Should -BeTrue } + } +} diff --git a/tests/ad/replication/Test.AD-ROOTDSE-01.md b/tests/ad/replication/Test.AD-ROOTDSE-01.md index 967d9e3b14..978bfd2ded 100644 --- a/tests/ad/replication/Test.AD-ROOTDSE-01.md +++ b/tests/ad/replication/Test.AD-ROOTDSE-01.md @@ -1,32 +1,15 @@ -SASL (Simple Authentication and Security Layer) mechanisms define the authentication protocols that Active Directory supports. Understanding these mechanisms is important for: +Inventories the **count and individual descriptions** of SASL mechanism names advertised by the connected domain controller's LDAP RootDSE. -- **Authentication Security**: Different mechanisms provide different security levels -- **Protocol Compatibility**: Ensuring clients can authenticate using appropriate methods -- **Security Baseline**: Tracking changes to supported mechanisms that could indicate misconfiguration +An advertised mechanism is not proof that a client successfully binds with it, that clients use it, or that a server policy enables a particular authentication path. DIGEST-MD5 may be advertised by Windows Server 2003 and later; its presence alone is not evidence of insecure use. -The default count is typically 4 mechanisms (GSSAPI, GSS-SPNEGO, EXTERNAL, DIGEST-MD5), though this may vary by configuration. +#### Remediation action -#### Control Type +1. Review the advertised mechanisms against the domain's authentication requirements. +2. To assess real authentication behavior, review domain controller policy and relevant authentication logs separately; do not infer bind success from this inventory. -**Operational** +#### Related links -#### Security Recommendation - -- Prefer Kerberos (GSSAPI) for authentication when possible -- Minimize use of less secure mechanisms like DIGEST-MD5 -- Monitor for unexpected changes to supported SASL mechanisms -- Disable mechanisms that are not required in your environment -- Ensure clients are configured to use the most secure available mechanism - -#### How the Test Works - -This test retrieves the Root DSE and counts: -- Number of supported SASL mechanisms -- List of mechanism names - -#### Related Tests - -- `Test-MtAdSupportedSaslMechanismDetails` - Provides detailed information about each mechanism +* [Microsoft ADTS: RootDSE supportedSASLMechanisms](https://learn.microsoft.com/openspecs/windows_protocols/ms-adts/96f7b086-1ca3-4764-9a08-33f8f7a543db) %TestResult% diff --git a/tests/ad/replication/Test.AD-ROOTDSE-01.ps1 b/tests/ad/replication/Test.AD-ROOTDSE-01.ps1 index c605d58971..2c03523c47 100644 --- a/tests/ad/replication/Test.AD-ROOTDSE-01.ps1 +++ b/tests/ad/replication/Test.AD-ROOTDSE-01.ps1 @@ -28,7 +28,7 @@ #> [MaesterTest( Id = 'AD-ROOTDSE-01', - Title = 'Supported SASL mechanism count should be investigated', + Title = 'Advertised SASL mechanism count and details should be investigated', Product = 'ad', Feature = 'directory-configuration', Area = 'authentication', @@ -48,11 +48,11 @@ $adState = Get-MtADDomainState -Categories @('Domain') if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + throw 'Active Directory domain state was not returned.' } $rootDse = $adState.RootDSE + if ($null -eq $rootDse) { throw 'LDAP RootDSE was not returned.' } $saslMechanisms = $rootDse.SupportedSASLMechanisms $mechanismCount = if ($saslMechanisms) { ($saslMechanisms | Measure-Object).Count } else { 0 } @@ -62,11 +62,19 @@ $result += "| --- | --- |" + "`n" $result += "| Supported SASL Mechanisms Count | $mechanismCount |" + "`n" - if ($mechanismCount -gt 0) { - $result += "| Mechanisms | $(($saslMechanisms -join ', ')) |" + "`n" + $result += "`n| Advertised mechanism | Description |`n| --- | --- |`n" + foreach ($mechanism in $saslMechanisms) { + $description = switch ($mechanism) { + 'GSSAPI' { 'Kerberos (GSSAPI)' } + 'GSS-SPNEGO' { 'Negotiation (Kerberos or NTLM)' } + 'EXTERNAL' { 'External authentication' } + 'DIGEST-MD5' { 'Digest; advertised by Windows Server 2003 and later' } + default { 'Mechanism advertised by this domain controller' } + } + $result += "| $mechanism | $description |`n" } - $testResultMarkdown = "Active Directory supported SASL mechanisms have been enumerated. These mechanisms define available authentication protocols.`n`n%TestResult%" + $testResultMarkdown = "The connected domain controller advertises these SASL mechanisms in RootDSE. Advertisement does not establish whether a bind succeeds or which clients use each mechanism.`n`n%TestResult%" $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result Add-MtTestResultDetail -Result $testResultMarkdown -Investigate diff --git a/tests/ad/replication/Test.AD-ROOTDSE-02.md b/tests/ad/replication/Test.AD-ROOTDSE-02.md deleted file mode 100644 index 5aea997ebe..0000000000 --- a/tests/ad/replication/Test.AD-ROOTDSE-02.md +++ /dev/null @@ -1,38 +0,0 @@ -Understanding the SASL (Simple Authentication and Security Layer) mechanisms supported by Active Directory is crucial for authentication security: - -- **Security Levels**: Different mechanisms offer varying levels of security -- **Protocol Selection**: Clients negotiate authentication based on available mechanisms -- **Attack Surface**: Unnecessary mechanisms increase the authentication attack surface -- **Compliance**: Some regulations may require specific authentication protocols - -Common mechanisms and their security levels: -- **GSSAPI (Kerberos)**: Highest security, mutual authentication -- **GSS-SPNEGO**: Negotiate between Kerberos and NTLM -- **EXTERNAL**: TLS client certificate authentication -- **DIGEST-MD5**: Less secure, often disabled in hardened environments - -#### Control Type - -**Operational** - -#### Security Recommendation - -- Use Kerberos (GSSAPI) as the primary authentication mechanism -- Disable DIGEST-MD5 if not explicitly required -- Enable EXTERNAL for certificate-based authentication scenarios -- Monitor authentication logs for mechanism usage patterns -- Document which mechanisms are required for your environment - -#### How the Test Works - -This test retrieves detailed information about each supported SASL mechanism: -- Mechanism name -- Description of the mechanism -- Security level assessment - -#### Related Tests - -- `Test-MtAdSupportedSaslMechanismCount` - Counts total supported mechanisms - - -%TestResult% diff --git a/tests/ad/replication/Test.AD-ROOTDSE-02.ps1 b/tests/ad/replication/Test.AD-ROOTDSE-02.ps1 deleted file mode 100644 index 541eef4c0f..0000000000 --- a/tests/ad/replication/Test.AD-ROOTDSE-02.ps1 +++ /dev/null @@ -1,94 +0,0 @@ -function Test-MtAdSupportedSaslMechanismDetails { - <# - .SYNOPSIS - Retrieves detailed information about supported SASL mechanisms. - - .DESCRIPTION - Simple Authentication and Security Layer (SASL) mechanisms define how - clients authenticate to Active Directory. This test provides detailed - information about each supported mechanism and its security implications. - - Key SASL Mechanisms: - - GSSAPI: Generic Security Services API (Kerberos) - Most secure - - GSS-SPNEGO: SPNEGO negotiation for Kerberos/NTLM - - EXTERNAL: Authentication via external means (TLS client certs) - - DIGEST-MD5: Digest authentication (less secure, often disabled) - - Security Best Practice: - - Prefer Kerberos (GSSAPI) for authentication - - Minimize use of less secure mechanisms - - Disable DIGEST-MD5 if not required - - .EXAMPLE - Test-MtAdSupportedSaslMechanismDetails - - Returns $true if Root DSE data is accessible. - - .LINK - https://maester.dev/docs/commands/Test-MtAdSupportedSaslMechanismDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-ROOTDSE-02', - Title = 'Supported SASL mechanism details should be investigated', - Product = 'ad', - Feature = 'directory-configuration', - Area = 'authentication', - ResourceType = 'Tenant', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:domainDNS:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdSupportedSaslMechanismDetails" - - $adState = Get-MtADDomainState -Categories @('Domain') - - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $rootDse = $adState.RootDSE - $saslMechanisms = $rootDse.SupportedSASLMechanisms - $mechanismCount = if ($saslMechanisms) { ($saslMechanisms | Measure-Object).Count } else { 0 } - - $testResult = $true - - $result = "| Property | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total SASL Mechanisms | $mechanismCount |" + "`n" - - if ($mechanismCount -gt 0) { - $result += "`n**Supported SASL Mechanisms:**" + "`n" + "`n" - $result += "| Mechanism | Description | Security Level |" + "`n" - $result += "| --- | --- | --- |" + "`n" - - foreach ($mechanism in $saslMechanisms) { - switch ($mechanism) { - 'GSSAPI' { $desc = 'Kerberos authentication'; $level = 'High' } - 'GSS-SPNEGO' { $desc = 'Negotiate (Kerberos/NTLM)'; $level = 'Medium-High' } - 'EXTERNAL' { $desc = 'External authentication (TLS certs)'; $level = 'High' } - 'DIGEST-MD5' { $desc = 'Digest authentication'; $level = 'Low' } - default { $desc = 'Unknown mechanism'; $level = 'Unknown' } - } - $result += "| $mechanism | $desc | $level |" + "`n" - } - } - - $testResultMarkdown = "Active Directory SASL mechanism details have been retrieved. These mechanisms determine available authentication protocols.`n`n%TestResult%" - if ($mechanismCount -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", "" - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - - return $testResult -} diff --git a/tests/ad/schema/Test.AD-SCH-01.md b/tests/ad/schema/Test.AD-SCH-01.md index bc1300f4e6..535e554729 100644 --- a/tests/ad/schema/Test.AD-SCH-01.md +++ b/tests/ad/schema/Test.AD-SCH-01.md @@ -1,14 +1,14 @@ -Understanding when your Active Directory schema has been modified provides important visibility into the evolution of your directory infrastructure. Schema modifications typically occur during: +Understanding when Active Directory schema objects were created provides visibility into the evolution of your directory infrastructure. This inventory groups objects by `whenCreated`, not by a modification date; it does not establish an audit history of subsequent changes. Schema extensions typically occur during: - **Domain upgrades**: When upgrading to newer Windows Server versions - **Application installations**: Products like Exchange, Skype for Business, and third-party applications extend the schema - **Custom developments**: Organizations may add custom attributes or classes -Tracking schema modification years helps: -- **Audit trail**: Understand when major changes occurred +Tracking schema object creation years helps: +- **Inventory**: Understand when extensions first appeared (not later edits) - **Compliance**: Document directory evolution for compliance purposes - **Troubleshooting**: Correlate issues with schema change timeframes -- **Planning**: Identify when the directory was last updated +- **Planning**: Identify when objects were first created #### Control Type @@ -25,15 +25,13 @@ While schema modifications are normal and necessary, they should be: #### How the Test Works This test retrieves all schema objects and analyzes their creation dates to identify: -- How many different years have had schema modifications +- How many different years had schema objects created - The total number of schema objects -- The first and most recent schema changes +- A count for each year and details of every schema object with a creation date #### Related Tests -- `Test-MtAdSchemaModificationYearDetails` - Provides detailed breakdown by year -- `Test-MtAdSchemaVersionEntryCount` - Shows the current schema version -- `Test-MtAdSchemaVersionDetails` - Provides comprehensive schema information +- `Test-MtAdSchemaVersionEntryCount` (AD-SCH-03) - Shows the current schema version and every classSchema definition %TestResult% diff --git a/tests/ad/schema/Test.AD-SCH-01.ps1 b/tests/ad/schema/Test.AD-SCH-01.ps1 index 67994d597e..52f5e8df79 100644 --- a/tests/ad/schema/Test.AD-SCH-01.ps1 +++ b/tests/ad/schema/Test.AD-SCH-01.ps1 @@ -1,26 +1,23 @@ function Test-MtAdSchemaModificationYearCount { <# .SYNOPSIS - Counts the number of years with Active Directory schema modifications. + Counts the number of years with Active Directory schema object creation. .DESCRIPTION - This test analyzes the Active Directory schema to identify how many different years - have had schema modifications. Schema changes indicate when the directory has been - extended with new object classes or attributes, which is typically done during - domain upgrades or application installations. + This test groups schema objects by whenCreated. It describes creation years, + not subsequent schema object edits or an audit history of changes. .EXAMPLE Test-MtAdSchemaModificationYearCount - Returns $true if schema data is accessible, $false otherwise. - The test result includes the count of years with schema modifications. + Reports creation-year counts and schema objects grouped by creation year. .LINK https://maester.dev/docs/commands/Test-MtAdSchemaModificationYearCount #> [MaesterTest( Id = 'AD-SCH-01', - Title = 'Schema modification year count should be retrievable', + Title = 'Schema creation years and objects should be investigated', Product = 'ad', Feature = 'schema', Area = 'infrastructure', @@ -42,45 +39,29 @@ # If unable to retrieve AD data, skip the test if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + throw 'Active Directory schema inventory was not returned.' } $schemaObjects = $adState.SchemaObjects - - # Count unique years with schema modifications - $yearsWithModifications = $schemaObjects | Where-Object { $_.whenCreated } | - ForEach-Object { $_.whenCreated.Year } | - Sort-Object -Unique - - $yearCount = ($yearsWithModifications | Measure-Object).Count - - # Test passes if we successfully retrieved schema data - $testResult = $null -ne $schemaObjects - - # Generate markdown results - if ($testResult) { - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Schema Objects | $(($schemaObjects | Measure-Object).Count) |" + "`n" - $result += "| Years with Modifications | $yearCount |" + "`n" - $result += "| First Schema Change | $(($yearsWithModifications | Sort-Object | Select-Object -First 1)) |" + "`n" - $result += "| Most Recent Schema Change | $(($yearsWithModifications | Sort-Object | Select-Object -Last 1)) |" + "`n" + "`n" - - $result += "**Years with Schema Modifications:**" + "`n" + "`n" - $result += "| Year |" + "`n" - $result += "| --- |" + "`n" - foreach ($year in ($yearsWithModifications | Sort-Object)) { - $result += "| $year |" + "`n" - } - - $testResultMarkdown = "Active Directory schema has been modified across $yearCount different years.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory schema information. Ensure you have appropriate permissions and the Active Directory module is installed." + if ($null -eq $schemaObjects) { throw 'Active Directory schema objects were not returned.' } + + $datedObjects = @($schemaObjects | Where-Object { $null -ne $_.WhenCreated }) + $years = @($datedObjects | Group-Object { $_.WhenCreated.Year } | Sort-Object Name) + $result = "| Metric | Value |`n| --- | --- |`n" + $result += "| Total schema objects | $(@($schemaObjects).Count) |`n" + $result += "| Objects with creation date | $($datedObjects.Count) |`n" + $result += "| Creation years | $($years.Count) |`n`n" + $result += "| Year | Object count |`n| --- | --- |`n" + foreach ($year in $years) { + $result += "| $($year.Name) | $($year.Count) |`n" } - - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult + $result += "`n**Schema objects by creation year:**`n`n| Year | Object name | Distinguished name |`n| --- | --- | --- |`n" + foreach ($object in ($datedObjects | Sort-Object WhenCreated, Name)) { + $result += "| $($object.WhenCreated.Year) | $($object.Name) | $($object.DistinguishedName) |`n" + } + if ($datedObjects.Count -lt @($schemaObjects).Count) { + $result += "`n$(@($schemaObjects).Count - $datedObjects.Count) object(s) lack a creation date and are excluded from the year breakdown." + } + Add-MtTestResultDetail -Result "Schema object creation dates span $($years.Count) year(s). Creation dates do not reveal subsequent schema edits.`n`n$result" -Investigate + return $true } diff --git a/tests/ad/schema/Test.AD-SCH-02.md b/tests/ad/schema/Test.AD-SCH-02.md deleted file mode 100644 index f8226a17fc..0000000000 --- a/tests/ad/schema/Test.AD-SCH-02.md +++ /dev/null @@ -1,40 +0,0 @@ -Detailed visibility into schema modifications by year provides a comprehensive timeline of your Active Directory's evolution. This information is valuable for: - -- **Capacity planning**: Understanding growth patterns of the directory -- **Change management**: Tracking when major applications were deployed -- **Security auditing**: Identifying unauthorized or unexpected schema changes -- **Compliance reporting**: Documenting directory modifications for auditors - -Unexpected spikes in schema modifications may indicate: -- Unauthorized application deployments -- Malicious schema extensions -- Improper testing procedures -- Lack of change control - -#### Control Type - -**Operational** - -#### Security Recommendation - -Establish monitoring for schema changes: -- **Alert on schema modifications**: Configure alerts when schema changes occur -- **Regular reviews**: Periodically review schema modification history -- **Access controls**: Limit Schema Admins group membership -- **Audit logging**: Enable auditing for schema changes - -#### How the Test Works - -This test analyzes schema objects and groups them by creation year, providing: -- Count of schema objects created per year -- Percentage distribution across years -- Timeline of directory evolution - -#### Related Tests - -- `Test-MtAdSchemaModificationYearCount` - Shows count of years with modifications -- `Test-MtAdSchemaVersionEntryCount` - Shows current schema version -- `Test-MtAdSchemaVersionDetails` - Provides comprehensive schema details - - -%TestResult% diff --git a/tests/ad/schema/Test.AD-SCH-02.ps1 b/tests/ad/schema/Test.AD-SCH-02.ps1 deleted file mode 100644 index 3a52333f9a..0000000000 --- a/tests/ad/schema/Test.AD-SCH-02.ps1 +++ /dev/null @@ -1,97 +0,0 @@ -function Test-MtAdSchemaModificationYearDetails { - <# - .SYNOPSIS - Provides detailed breakdown of Active Directory schema modifications by year. - - .DESCRIPTION - This test analyzes the Active Directory schema to provide a detailed breakdown - of schema modifications organized by year. It shows how many schema objects - were created each year, helping identify periods of significant directory - changes such as domain upgrades or application installations. - - .EXAMPLE - Test-MtAdSchemaModificationYearDetails - - Returns $true if schema data is accessible, $false otherwise. - The test result includes a breakdown of schema modifications per year. - - .LINK - https://maester.dev/docs/commands/Test-MtAdSchemaModificationYearDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-SCH-02', - Title = 'Schema modification year details should be retrievable', - Product = 'ad', - Feature = 'schema', - Area = 'infrastructure', - ResourceType = 'Tenant', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:Schema/*:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdSchemaModificationYearDetails" - - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('Schema') - - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $schemaObjects = $adState.SchemaObjects - - # Group schema objects by year and count modifications per year - $modificationsByYear = $schemaObjects | Where-Object { $_.whenCreated } | - Group-Object { $_.whenCreated.Year } | - Select-Object Name, Count | - Sort-Object Name - - $yearCount = ($modificationsByYear | Measure-Object).Count - - # Test passes if we successfully retrieved schema data - $testResult = $null -ne $schemaObjects - - # Generate markdown results - if ($testResult) { - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Schema Objects | $(($schemaObjects | Measure-Object).Count) |" + "`n" - $result += "| Years with Modifications | $yearCount |" + "`n" + "`n" - - $result += "**Schema Modifications by Year:**" + "`n" + "`n" - $result += "| Year | Object Count | Percentage |" + "`n" - $result += "| --- | --- | --- |" + "`n" - - $totalObjects = ($schemaObjects | Measure-Object).Count - foreach ($yearData in $modificationsByYear) { - $percentage = if ($totalObjects -gt 0) { - [Math]::Round(($yearData.Count / $totalObjects) * 100, 2) - } else { - 0 - } - $result += "| $($yearData.Name) | $($yearData.Count) | $percentage% |" + "`n" - } - - $testResultMarkdown = "Active Directory schema modification details by year. Schema changes occurred across $yearCount different years.`n`n%TestResult%" - if ($yearCount -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", "" - } - } else { - $testResultMarkdown = "Unable to retrieve Active Directory schema information. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult -} diff --git a/tests/ad/schema/Test.AD-SCH-03.md b/tests/ad/schema/Test.AD-SCH-03.md index f46d941ec1..9402540000 100644 --- a/tests/ad/schema/Test.AD-SCH-03.md +++ b/tests/ad/schema/Test.AD-SCH-03.md @@ -1,4 +1,4 @@ -The Active Directory schema version indicates the functional level and capabilities of your directory. Different schema versions correspond to different Windows Server releases: +The Active Directory schema version tracks schema updates, not the domain or forest functional level. Different schema versions correspond to different Windows Server releases: | Schema Version | Windows Server Version | |----------------|----------------------| @@ -10,6 +10,7 @@ The Active Directory schema version indicates the functional level and capabilit | 69 | Windows Server 2012 R2 | | 87 | Windows Server 2016 | | 88 | Windows Server 2019/2022 | +| 91 | Windows Server 2025 | Knowing your schema version is important for: - **Compatibility**: Ensuring applications support your schema version @@ -23,19 +24,18 @@ Knowing your schema version is important for: #### Security Recommendation -Keep your schema version current with your domain functional level: +Plan schema updates separately from domain functional-level changes: - **Regular updates**: Update schema when upgrading domain controllers - **Feature enablement**: Newer schemas enable security features like Authentication Policies - **Application support**: Modern applications may require newer schema versions #### How the Test Works -This test retrieves the objectVersion attribute from the schema container to determine the current schema version and maps it to the corresponding Windows Server version. +This test retrieves `objectVersion` from the schema container, maps it to a Windows Server release, and lists **all** schema objects whose `objectClass` includes `classSchema` (name and distinguished name). It does not arbitrarily truncate the class list or claim a domain functional level. #### Related Tests -- `Test-MtAdSchemaVersionDetails` - Provides comprehensive schema details -- `Test-MtAdSchemaModificationYearCount` - Shows schema modification timeline +- `Test-MtAdSchemaModificationYearCount` (AD-SCH-01) - Shows schema object creation years and details - `Test-MtAdDomainFunctionalLevel` - Shows domain functional level diff --git a/tests/ad/schema/Test.AD-SCH-03.ps1 b/tests/ad/schema/Test.AD-SCH-03.ps1 index b2236fb1d0..8c93beb7ef 100644 --- a/tests/ad/schema/Test.AD-SCH-03.ps1 +++ b/tests/ad/schema/Test.AD-SCH-03.ps1 @@ -1,26 +1,25 @@ function Test-MtAdSchemaVersionEntryCount { <# .SYNOPSIS - Counts the number of schema version entries in Active Directory. + Reports the Active Directory schema version and all classSchema definitions. .DESCRIPTION This test retrieves the schema version information from the Active Directory - schema container. The schema version indicates the functional level and - extensions applied to the directory, with each major Windows Server version - typically introducing a new schema version. + schema container and inventories every classSchema object. The schema version + is not the domain or forest functional level. .EXAMPLE Test-MtAdSchemaVersionEntryCount Returns $true if schema version data is accessible, $false otherwise. - The test result includes the schema version number. + The test result includes the schema version and all classSchema definitions. .LINK https://maester.dev/docs/commands/Test-MtAdSchemaVersionEntryCount #> [MaesterTest( Id = 'AD-SCH-03', - Title = 'Schema version entry count should be retrievable', + Title = 'Schema version and class definitions should be investigated', Product = 'ad', Feature = 'schema', Area = 'infrastructure', @@ -42,11 +41,12 @@ # If unable to retrieve AD data, skip the test if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + throw 'Active Directory schema inventory was not returned.' } $schemaContainer = $adState.SchemaContainer + $schemaObjects = $adState.SchemaObjects + if ($null -eq $schemaObjects) { throw 'Active Directory schema objects were not returned.' } # Get schema version $schemaVersion = if ($schemaContainer -and $schemaContainer.objectVersion) { @@ -55,47 +55,34 @@ $null } - # Test passes if we successfully retrieved schema version - $testResult = $null -ne $schemaVersion - - # Generate markdown results - if ($testResult) { - # Map schema versions to Windows Server versions - $versionMap = @{ - 13 = "Windows Server 2000" - 30 = "Windows Server 2003" - 31 = "Windows Server 2003 R2" - 44 = "Windows Server 2008" - 47 = "Windows Server 2008 R2" - 56 = "Windows Server 2012" - 69 = "Windows Server 2012 R2" - 87 = "Windows Server 2016" - 88 = "Windows Server 2019/2022" - } - - $osVersion = $versionMap[$schemaVersion] - if (-not $osVersion) { - $osVersion = "Unknown/Custom Schema" - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Schema Version | $schemaVersion |" + "`n" - $result += "| Corresponding OS | $osVersion |" + "`n" - if ($schemaContainer.whenCreated) { - $result += "| Schema Created | $($schemaContainer.whenCreated) |" + "`n" - } - if ($schemaContainer.whenChanged) { - $result += "| Last Modified | $($schemaContainer.whenChanged) |" + "`n" - } - - $testResultMarkdown = "Active Directory schema version is $schemaVersion ($osVersion).`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory schema version information. Ensure you have appropriate permissions and the Active Directory module is installed." + if ($null -eq $schemaVersion) { throw 'Schema container version was not returned.' } + $versionMap = @{ + 13 = 'Windows 2000' + 30 = 'Windows Server 2003' + 31 = 'Windows Server 2003 R2' + 44 = 'Windows Server 2008' + 47 = 'Windows Server 2008 R2' + 56 = 'Windows Server 2012' + 69 = 'Windows Server 2012 R2' + 87 = 'Windows Server 2016' + 88 = 'Windows Server 2019/2022' + 91 = 'Windows Server 2025' } - - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult + $osVersion = $versionMap[$schemaVersion] + if (-not $osVersion) { $osVersion = 'Unknown/custom schema' } + + $classSchemas = @($schemaObjects | Where-Object { $_.ObjectClass -contains 'classSchema' } | Sort-Object Name) + $result = "| Property | Value |`n| --- | --- |`n" + $result += "| Schema version | $schemaVersion |`n" + $result += "| Corresponding Windows Server release | $osVersion |`n" + $result += "| Schema naming context | $($schemaContainer.DistinguishedName) |`n" + $result += "| Total schema objects | $(@($schemaObjects).Count) |`n" + $result += "| classSchema definitions | $($classSchemas.Count) |`n" + if ($schemaContainer.WhenCreated) { $result += "| Schema created | $($schemaContainer.WhenCreated) |`n" } + $result += "`n**All classSchema definitions:**`n`n| Name | Distinguished name |`n| --- | --- |`n" + foreach ($class in $classSchemas) { + $result += "| $($class.Name) | $($class.DistinguishedName) |`n" + } + Add-MtTestResultDetail -Result "Schema version $schemaVersion ($osVersion) and all $($classSchemas.Count) classSchema definitions are shown below. Schema version does not establish functional level.`n`n$result" -Investigate + return $true } diff --git a/tests/ad/schema/Test.AD-SCH-04.md b/tests/ad/schema/Test.AD-SCH-04.md deleted file mode 100644 index ed6b38ed02..0000000000 --- a/tests/ad/schema/Test.AD-SCH-04.md +++ /dev/null @@ -1,42 +0,0 @@ -Comprehensive schema information provides the foundation for understanding your Active Directory infrastructure. The schema defines: - -- **Object classes**: What types of objects can exist (users, computers, groups) -- **Attributes**: What properties objects can have -- **Constraints**: Rules for object creation and modification - -Understanding schema details helps with: -- **Troubleshooting**: Identifying schema-related issues -- **Planning**: Preparing for application deployments -- **Documentation**: Maintaining accurate AD documentation -- **Security**: Detecting unauthorized schema modifications - -#### Control Type - -**Operational** - -#### Security Recommendation - -Protect your schema with these practices: -- **Schema Admins group**: Keep membership minimal and monitored -- **Change control**: Require approval for all schema modifications -- **Documentation**: Maintain records of all schema extensions -- **Backup**: Regularly backup the schema NC (naming context) -- **Monitoring**: Alert on any schema modifications - -#### How the Test Works - -This test retrieves detailed information from the schema container including: -- Schema version number -- Corresponding Windows Server version -- Schema creation and modification dates -- Distribution of object classes -- Total schema object count - -#### Related Tests - -- `Test-MtAdSchemaVersionEntryCount` - Shows schema version number -- `Test-MtAdSchemaModificationYearCount` - Shows modification timeline -- `Test-MtAdSchemaModificationYearDetails` - Detailed modification breakdown - - -%TestResult% diff --git a/tests/ad/schema/Test.AD-SCH-04.ps1 b/tests/ad/schema/Test.AD-SCH-04.ps1 deleted file mode 100644 index fc155ef3e8..0000000000 --- a/tests/ad/schema/Test.AD-SCH-04.ps1 +++ /dev/null @@ -1,118 +0,0 @@ -function Test-MtAdSchemaVersionDetails { - <# - .SYNOPSIS - Provides detailed Active Directory schema version information. - - .DESCRIPTION - This test retrieves comprehensive schema version details from the Active Directory - schema container, including the object version number, creation date, and last - modification date. This information helps identify the directory's schema level - and track when schema updates occurred. - - .EXAMPLE - Test-MtAdSchemaVersionDetails - - Returns $true if schema version data is accessible, $false otherwise. - The test result includes detailed schema version information. - - .LINK - https://maester.dev/docs/commands/Test-MtAdSchemaVersionDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-SCH-04', - Title = 'Schema version details should be retrievable', - Product = 'ad', - Feature = 'schema', - Area = 'infrastructure', - ResourceType = 'Tenant', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:Schema/*.objectVersion:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdSchemaVersionDetails" - - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('Schema') - - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $schemaContainer = $adState.SchemaContainer - $schemaObjects = $adState.SchemaObjects - - # Get schema version - $schemaVersion = if ($schemaContainer -and $schemaContainer.objectVersion) { - $schemaContainer.objectVersion - } else { - $null - } - - # Test passes if we successfully retrieved schema version - $testResult = $null -ne $schemaVersion - - # Generate markdown results - if ($testResult) { - # Map schema versions to Windows Server versions - $versionMap = @{ - 13 = "Windows Server 2000" - 30 = "Windows Server 2003" - 31 = "Windows Server 2003 R2" - 44 = "Windows Server 2008" - 47 = "Windows Server 2008 R2" - 56 = "Windows Server 2012" - 69 = "Windows Server 2012 R2" - 87 = "Windows Server 2016" - 88 = "Windows Server 2019/2022" - } - - $osVersion = $versionMap[$schemaVersion] - if (-not $osVersion) { - $osVersion = "Unknown/Custom Schema" - } - - # Calculate object class distribution - $classDistribution = $schemaObjects | Group-Object objectClass | Select-Object Name, Count | Sort-Object Count -Descending - - $result = "| Property | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Schema Version | $schemaVersion |" + "`n" - $result += "| Corresponding OS | $osVersion |" + "`n" - $result += "| Schema Naming Context | $($schemaContainer.DistinguishedName) |" + "`n" - if ($schemaContainer.whenCreated) { - $result += "| Schema Created | $($schemaContainer.whenCreated) |" + "`n" - } - if ($schemaContainer.whenChanged) { - $result += "| Last Modified | $($schemaContainer.whenChanged) |" + "`n" - } - if ($schemaContainer.ObjectGUID) { - $result += "| Object GUID | $($schemaContainer.ObjectGUID) |" + "`n" - } - $result += "| Total Schema Objects | $(($schemaObjects | Measure-Object).Count) |" + "`n" + "`n" - - $result += "**Schema Object Classes:**" + "`n" + "`n" - $result += "| Object Class | Count |" + "`n" - $result += "| --- | --- |" + "`n" - foreach ($class in ($classDistribution | Select-Object -First 10)) { - $result += "| $($class.Name) | $($class.Count) |" + "`n" - } - - $testResultMarkdown = "Active Directory schema version details. The directory is running schema version $schemaVersion ($osVersion).`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory schema version information. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult -} diff --git a/tests/ad/schema/Test.AD-SCH-05.md b/tests/ad/schema/Test.AD-SCH-05.md index 6e22925c93..671fe21830 100644 --- a/tests/ad/schema/Test.AD-SCH-05.md +++ b/tests/ad/schema/Test.AD-SCH-05.md @@ -1,40 +1,11 @@ -The Local Administrator Password Solution (LAPS) is a critical security tool that: +Checks whether both Windows LAPS schema attributes are present: `msLAPS-Password` and `msLAPS-PasswordExpirationTime`. The verdict uses the top-level `WindowsLapsInstalled` state, derived from schema `lDAPDisplayName`; the result shows individual schema-name evidence. -- **Manages local admin passwords**: Automatically rotates passwords on domain-joined computers -- **Prevents lateral movement**: Eliminates shared local administrator passwords -- **Secure storage**: Stores passwords securely in Active Directory attributes -- **Access control**: Controls who can retrieve local administrator passwords -- **Audit trail**: Logs password access for compliance +Legacy LAPS (`ms-Mcs-AdmPwd`) uses a different schema and alone does not establish Windows LAPS readiness. Schema presence is not evidence that password rotation is configured or operating. This check reads schema *names* only, never password values; `msLAPS-Password` contains a cleartext secret and must not be collected. -Without LAPS, organizations commonly face these risks: -- **Pass-the-hash attacks**: Attackers use shared local credentials to move laterally -- **Persistent access**: Compromised local accounts provide ongoing access -- **Credential stuffing**: Shared passwords reused across multiple systems -- **Compliance failures**: Many frameworks require unique local admin passwords +#### Remediation action -#### Control Type - -**Preventive** - -#### Security Recommendation - -Deploy LAPS across your entire domain: - -1. **Install LAPS**: Download from Microsoft and extend the AD schema -2. **Group Policy**: Configure password rotation policies (recommended: every 30 days) -3. **Access controls**: Limit who can read the ms-Mcs-AdmPwd attribute -4. **Monitoring**: Alert on password retrieval events -5. **Legacy LAPS**: Consider upgrading to Windows LAPS (built into Windows 11/Server 2022) - -#### How the Test Works - -This test checks for the presence of LAPS schema attributes (ms-Mcs-AdmPwd) to determine if LAPS has been installed and configured in the Active Directory environment. - -#### Related Tests - -- `Test-MtAdComputerUnconstrainedDelegationCount` - Check for delegation risks -- `Test-MtAdUserPasswordNeverExpiresCount` - Identify password policy gaps -- `Test-MtAdPasswordComplexityRequired` - Verify password policies +1. [Extend the Active Directory schema for Windows LAPS](https://learn.microsoft.com/windows-server/identity/laps/laps-scenarios-windows-server-active-directory#update-the-windows-server-active-directory-schema). +2. Verify both schema attribute names are present, then separately deploy Windows LAPS policy, permissions, and password rotation to applicable devices. %TestResult% diff --git a/tests/ad/schema/Test.AD-SCH-05.ps1 b/tests/ad/schema/Test.AD-SCH-05.ps1 index d0d42d6cf5..1df89a84d2 100644 --- a/tests/ad/schema/Test.AD-SCH-05.ps1 +++ b/tests/ad/schema/Test.AD-SCH-05.ps1 @@ -1,19 +1,17 @@ function Test-MtAdLapsInstalledStatus { <# .SYNOPSIS - Checks whether Local Administrator Password Solution (LAPS) is installed in Active Directory. + Checks whether Windows LAPS schema attributes are present in Active Directory. .DESCRIPTION - This test checks if the Local Administrator Password Solution (LAPS) schema extensions - are present in Active Directory. LAPS is a Microsoft solution that manages local - administrator passwords on domain-joined computers, storing them securely in AD - and automatically rotating them on a scheduled basis. + This test checks for both msLAPS-Password and msLAPS-PasswordExpirationTime schema + attributes. Legacy LAPS ms-Mcs-AdmPwd alone does not demonstrate Windows LAPS readiness. + Schema presence does not prove deployment, permissions, policy or rotation. .EXAMPLE Test-MtAdLapsInstalledStatus - Returns $true if LAPS is installed, $false if not installed or unable to determine. - The test result includes LAPS installation status. + Returns $true when both Windows LAPS schema attributes are present. .LINK https://maester.dev/docs/commands/Test-MtAdLapsInstalledStatus @@ -21,7 +19,7 @@ [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] [MaesterTest( Id = 'AD-SCH-05', - Title = 'LAPS should be installed in Active Directory', + Title = 'Windows LAPS schema should be ready in Active Directory', Product = 'ad', Feature = 'schema', Area = 'privileged-access', @@ -30,7 +28,6 @@ UserImpact = 'Low', ImplementationCost = 'Medium', Mitre = ('T1078.003', 'T1550.002'), - Control = ('nist-800-53-r5:IA-5', 'nist-800-53-r5:AC-6(2)'), Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:Schema/*:ReadProperty'), Author = 'soulemike' @@ -41,50 +38,26 @@ Write-Verbose "Starting Test-MtAdLapsInstalledStatus" - # Get AD domain state data (uses cached data if available) $adState = Get-MtADDomainState -Categories @('Schema') - - # If unable to retrieve AD data, skip the test if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + throw 'Active Directory schema inventory was not returned.' } - - # Check LAPS installation status - $lapsInstalled = $adState.LapsInstalled - - # Test passes if LAPS is installed (compliance test) - $testResult = $lapsInstalled -eq $true - - # Generate markdown results - $result = "| Property | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| LAPS Installed | $(if ($lapsInstalled) { "Yes" } else { "No" }) |" + "`n" - $result += "| Status | $(if ($lapsInstalled) { "✅ Compliant" } else { "❌ Not Installed" }) |" + "`n" + "`n" - - if ($lapsInstalled) { - $result += "**LAPS Schema Attributes:**" + "`n" + "`n" - $result += "The following LAPS attributes are present in the schema:" + "`n" + "`n" - $result += "| Attribute | Description |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| ms-Mcs-AdmPwd | Stores the local administrator password |" + "`n" - $result += "| ms-Mcs-AdmPwdExpirationTime | Stores the password expiration timestamp |" + "`n" - - $testResultMarkdown = "✅ Local Administrator Password Solution (LAPS) is installed and configured in Active Directory. Local administrator passwords are being managed and rotated automatically.`n`n%TestResult%" - } else { - $result += "**Recommendation:**" + "`n" + "`n" - $result += "LAPS is not installed. Consider deploying LAPS to improve security by:" + "`n" - $result += "- Automatically rotating local administrator passwords" + "`n" - $result += "- Storing passwords securely in Active Directory" + "`n" - $result += "- Preventing lateral movement using shared local credentials" + "`n" + "`n" - $result += "Download LAPS from: https://www.microsoft.com/download/details.aspx?id=46899" - - $testResultMarkdown = "❌ Local Administrator Password Solution (LAPS) is not installed. Local administrator passwords may be shared across multiple systems, creating a security risk.`n`n%TestResult%" + if ($null -eq $adState.SchemaObjects) { throw 'Active Directory schema objects were not returned.' } + if ($null -eq $adState.WindowsLapsInstalled) { throw 'Windows LAPS schema readiness was not returned.' } + $names = @($adState.SchemaObjects | ForEach-Object { $_.LdapDisplayName }) + $passwordPresent = $names -contains 'msLAPS-Password' + $expirationPresent = $names -contains 'msLAPS-PasswordExpirationTime' + $legacyPresent = $names -contains 'ms-Mcs-AdmPwd' + + $result = "| Schema attribute | Present |`n| --- | --- |`n" + $result += "| msLAPS-Password | $passwordPresent |`n" + $result += "| msLAPS-PasswordExpirationTime | $expirationPresent |`n" + $result += "| Legacy ms-Mcs-AdmPwd | $legacyPresent |" + if ($adState.WindowsLapsInstalled -eq $true) { + Add-MtTestResultDetail -Result "Well done. Both Windows LAPS schema attributes are present. This does not establish that password management is enabled or rotating.`n`n$result" + return $true } - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult + Add-MtTestResultDetail -Result "Windows LAPS schema readiness could not be established: one or both required attributes are absent. Legacy LAPS presence alone is insufficient. Verify schema deployment; this check does not read password values.`n`n$result" + return $false } diff --git a/tests/ad/security/Test.AD-KRBTGT-01.md b/tests/ad/security/Test.AD-KRBTGT-01.md index 9436086ea6..e3cd6df0e0 100644 --- a/tests/ad/security/Test.AD-KRBTGT-01.md +++ b/tests/ad/security/Test.AD-KRBTGT-01.md @@ -31,7 +31,7 @@ This test retrieves the KRBTGT account from Active Directory and checks: - Password last set date - Days since last password change - Whether password age exceeds `MaxPasswordAgeDays` (default 180) -- Account status (should be disabled) +- Account status (reported for context; this check only evaluates password age) #### Related Tests diff --git a/tests/ad/security/Test.AD-KRBTGT-01.ps1 b/tests/ad/security/Test.AD-KRBTGT-01.ps1 index bca57ece2b..4eec962d7b 100644 --- a/tests/ad/security/Test.AD-KRBTGT-01.ps1 +++ b/tests/ad/security/Test.AD-KRBTGT-01.ps1 @@ -49,8 +49,7 @@ Write-Verbose "Retrieved AD state" if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + throw 'Active Directory user inventory was not returned.' } Write-Verbose "Filtering/counting krbtgt password last set" @@ -59,7 +58,7 @@ if ($null -eq $krbtgt) { Add-MtTestResultDetail -Result "KRBTGT account not found in Active Directory." - return $null + return $false } $passwordLastSet = $krbtgt.PasswordLastSet diff --git a/tests/ad/security/Test.AD-MSA-01.md b/tests/ad/security/Test.AD-MSA-01.md index d37ca6f1df..a2751f66ce 100644 --- a/tests/ad/security/Test.AD-MSA-01.md +++ b/tests/ad/security/Test.AD-MSA-01.md @@ -1,55 +1,15 @@ -- Managed Service Accounts (MSAs) and Group Managed Service Accounts (gMSAs) provide significant security improvements over traditional service accounts by automating password management and simplifying service principal name (SPN) management. +Inventories standalone managed service accounts (sMSA), group managed service accounts (gMSA), and delegated managed service accounts (dMSA). -**Security Benefits:** -- **Automatic Password Rotation**: Passwords change automatically (every 30 days for gMSAs) -- **Eliminates Manual Management**: No need for administrators to manage service account passwords -- **No Interactive Logon**: Cannot be used for interactive logon, reducing attack surface -- **Reduced Credential Theft Risk**: Passwords are complex and regularly changed -- **Simplified Administration**: No manual password changes or coordination required +dMSAs were first implemented in Windows Server 2025 and are subclasses of computer objects. The inventory reports `DelegatedMsaState` when available, but does not infer dMSA support from functional level or establish effective service-account password rotation. The count is for review, not a security pass/fail threshold. -**Types of Managed Service Accounts:** -- **Standalone MSA**: For use on a single computer (legacy, largely replaced by gMSA) -- **Group MSA (gMSA)**: Can be used across multiple computers, preferred solution +#### Remediation action -#### Control Type +1. Review the accounts and their service owners; evaluate whether conventional service identities can migrate to managed accounts. +2. Validate hosting, authorization, and lifecycle arrangements before migrating services. -**Operational** +#### Related links -#### Security Recommendation - -1. **Use gMSAs Where Possible**: - - Replace traditional service accounts with gMSAs - - Prioritize high-privilege service accounts - - Plan migration for legacy applications - -2. **Implementation Requirements**: - - At least one Windows Server 2012 or later domain controller - - KDS root key must be created (one-time operation) - - Applications must support gMSA authentication - -3. **Best Practices**: - - Use gMSAs for all new service deployments - - Create separate gMSAs for different services - - Document gMSA usage and permissions - - Regular audit of gMSA deployments - -#### How the Test Works - -This test counts managed service accounts in Active Directory and categorizes them by: -- Total MSAs and gMSAs -- Group vs. standalone MSAs -- Account details and status - -#### Related Tests - -- `Test-MtAdUserKnownServiceAccountCount` - Traditional service account identification -- `Test-MtAdKdsRootKeysCount` - KDS root key requirement for gMSAs -- `Test-MtAdUserPasswordNeverExpiresCount` - Traditional accounts with non-expiring passwords - -#### References - -- [Microsoft: Group Managed Service Accounts Overview](https://docs.microsoft.com/windows-server/security/group-managed-service-accounts/group-managed-service-accounts-overview) -- [Microsoft: Getting Started with gMSAs](https://docs.microsoft.com/windows-server/security/group-managed-service-accounts/getting-started-with-group-managed-service-accounts) +* [Microsoft Learn: Managed service accounts overview](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/understand-service-accounts) %TestResult% diff --git a/tests/ad/security/Test.AD-MSA-01.ps1 b/tests/ad/security/Test.AD-MSA-01.ps1 index d891358543..ef5903195f 100644 --- a/tests/ad/security/Test.AD-MSA-01.ps1 +++ b/tests/ad/security/Test.AD-MSA-01.ps1 @@ -7,7 +7,9 @@ Managed Service Accounts (MSAs) and Group Managed Service Accounts (gMSAs) provide automatic password management and simplified service principal name (SPN) management for services running on domain-joined computers. This test counts the number of - MSAs and gMSAs in the domain. + sMSAs, gMSAs and delegated MSAs (dMSAs) in the domain. dMSA schema and + setup support were introduced with Windows Server 2025; inventory presence + alone does not demonstrate successful password management or migration. Security Benefits of MSAs: - Automatic password rotation (every 30 days for gMSAs) @@ -34,7 +36,7 @@ Severity = 'Info', Mitre = 'None', Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:msDS-GroupManagedServiceAccount:ReadProperty'), + Permission = ('ActiveDirectory:Ldap:msDS-ManagedServiceAccount:ReadProperty', 'ActiveDirectory:Ldap:msDS-GroupManagedServiceAccount:ReadProperty', 'ActiveDirectory:Ldap:msDS-DelegatedManagedServiceAccount:ReadProperty'), Author = 'soulemike' )] [CmdletBinding()] @@ -46,22 +48,24 @@ Write-Verbose "Retrieved AD state" if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + throw 'Active Directory service account inventory was not returned.' } Write-Verbose "Filtering/counting managed service account count" $serviceAccounts = $adState.ServiceAccounts - $msaCount = ($serviceAccounts | Measure-Object).Count + if ($null -eq $serviceAccounts) { throw 'Active Directory service accounts were not returned.' } + $msaCount = @($serviceAccounts).Count # Distinguish between MSA and gMSA if possible - $groupMSAs = $serviceAccounts | Where-Object { $_.ObjectClass -contains 'msDS-GroupManagedServiceAccount' -or $_.ServiceAccountType -eq 'GroupManagedServiceAccount' } - $standaloneMSAs = $serviceAccounts | Where-Object { $_.ObjectClass -contains 'msDS-ManagedServiceAccount' -or $_.ServiceAccountType -eq 'ManagedServiceAccount' } + $delegatedMSAs = @($serviceAccounts | Where-Object { $_.ObjectClass -contains 'msDS-DelegatedManagedServiceAccount' }) + $groupMSAs = @($serviceAccounts | Where-Object { $_.ObjectClass -contains 'msDS-GroupManagedServiceAccount' -and $_.ObjectClass -notcontains 'msDS-DelegatedManagedServiceAccount' }) + $standaloneMSAs = @($serviceAccounts | Where-Object { $_.ObjectClass -contains 'msDS-ManagedServiceAccount' -and $_.ObjectClass -notcontains 'msDS-GroupManagedServiceAccount' -and $_.ObjectClass -notcontains 'msDS-DelegatedManagedServiceAccount' }) $gmsaCount = ($groupMSAs | Measure-Object).Count $standaloneCount = ($standaloneMSAs | Measure-Object).Count - $undeterminedCount = $msaCount - $gmsaCount - $standaloneCount + $delegatedCount = $delegatedMSAs.Count + $undeterminedCount = $msaCount - $gmsaCount - $standaloneCount - $delegatedCount $testResult = $true @@ -70,19 +74,20 @@ $result += "| Total Managed Service Accounts | $msaCount |" + "`n" $result += "| Group Managed Service Accounts (gMSA) | $gmsaCount |" + "`n" $result += "| Standalone Managed Service Accounts | $standaloneCount |" + "`n" + $result += "| Delegated Managed Service Accounts (dMSA) | $delegatedCount |" + "`n" if ($undeterminedCount -gt 0) { $result += "| Undetermined Type | $undeterminedCount |" + "`n" } if ($msaCount -gt 0) { $result += "`n**Managed Service Accounts:**" + "`n" + "`n" - $result += "| Account Name | Type | Enabled |" + "`n" + $result += "| Account Name | Type | Delegated MSA state |" + "`n" $result += "| --- | --- | --- |" + "`n" foreach ($msa in $serviceAccounts | Select-Object -First 20) { - $type = if ($groupMSAs -contains $msa) { 'gMSA' } elseif ($standaloneMSAs -contains $msa) { 'MSA' } else { 'Unknown' } - $enabled = if ($null -ne $msa.Enabled) { $msa.Enabled } else { 'N/A' } - $result += "| $($msa.Name) | $type | $enabled |" + "`n" + $type = if ($delegatedMSAs -contains $msa) { 'dMSA' } elseif ($groupMSAs -contains $msa) { 'gMSA' } elseif ($standaloneMSAs -contains $msa) { 'sMSA' } else { 'Unknown' } + $state = if ($type -eq 'dMSA' -and $null -ne $msa.DelegatedMsaState) { $msa.DelegatedMsaState } else { 'N/A' } + $result += "| $($msa.Name) | $type | $state |" + "`n" } if ($msaCount -gt 20) { From 12775a0f0f1d90785e32e0864ef25bde991544b1 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 06:23:26 +0000 Subject: [PATCH 019/100] fix(ad): consolidate trust filtering and validation reviews --- .../functions/ADSchemaTrustChecks.Tests.ps1 | 129 +++++++++++++++ tests/ad/domain/Test.AD-FORS-04.md | 2 +- tests/ad/trust/Test.AD-TRUST-01.md | 7 +- tests/ad/trust/Test.AD-TRUST-01.ps1 | 17 +- tests/ad/trust/Test.AD-TRUST-02.md | 6 +- tests/ad/trust/Test.AD-TRUST-02.ps1 | 11 +- tests/ad/trust/Test.AD-TRUST-03.md | 47 +----- tests/ad/trust/Test.AD-TRUST-03.ps1 | 84 ++++++---- tests/ad/trust/Test.AD-TRUST-04.md | 69 -------- tests/ad/trust/Test.AD-TRUST-04.ps1 | 150 ------------------ tests/ad/trust/Test.AD-TRUST-05.md | 58 ------- tests/ad/trust/Test.AD-TRUST-05.ps1 | 137 ---------------- tests/ad/trust/Test.AD-TRUST-06.md | 56 +------ tests/ad/trust/Test.AD-TRUST-06.ps1 | 43 +++-- tests/ad/trust/Test.AD-TRUST-07.md | 66 -------- tests/ad/trust/Test.AD-TRUST-07.ps1 | 129 --------------- 16 files changed, 247 insertions(+), 764 deletions(-) create mode 100644 powershell/tests/functions/ADSchemaTrustChecks.Tests.ps1 delete mode 100644 tests/ad/trust/Test.AD-TRUST-04.md delete mode 100644 tests/ad/trust/Test.AD-TRUST-04.ps1 delete mode 100644 tests/ad/trust/Test.AD-TRUST-05.md delete mode 100644 tests/ad/trust/Test.AD-TRUST-05.ps1 delete mode 100644 tests/ad/trust/Test.AD-TRUST-07.md delete mode 100644 tests/ad/trust/Test.AD-TRUST-07.ps1 diff --git a/powershell/tests/functions/ADSchemaTrustChecks.Tests.ps1 b/powershell/tests/functions/ADSchemaTrustChecks.Tests.ps1 new file mode 100644 index 0000000000..a86b27d477 --- /dev/null +++ b/powershell/tests/functions/ADSchemaTrustChecks.Tests.ps1 @@ -0,0 +1,129 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name @( + 'Test-MtAdSchemaModificationYearCount' + 'Test-MtAdSchemaVersionEntryCount' + 'Test-MtAdLapsInstalledStatus' + 'Test-MtAdSupportedSaslMechanismCount' + 'Test-MtAdManagedServiceAccountCount' + 'Test-MtAdKrbtgtPasswordLastSet' + 'Test-MtAdTrustTotalCount' + 'Test-MtAdTrustQuarantinedCount' + 'Test-MtAdTrustStaleCount' + ) +} + +Describe 'Merged AD schema, RootDSE, service-account and trust checks' { + BeforeEach { + $script:detail = $null + $script:state = [PSCustomObject]@{ + SchemaObjects = @( + [PSCustomObject]@{ Name = 'classOne'; DistinguishedName = 'CN=classOne,CN=Schema'; ObjectClass = @('top', 'classSchema'); WhenCreated = [datetime]'2020-01-01'; LdapDisplayName = 'classOne' } + [PSCustomObject]@{ Name = 'classTwo'; DistinguishedName = 'CN=classTwo,CN=Schema'; ObjectClass = @('top', 'classSchema'); WhenCreated = [datetime]'2022-01-01'; LdapDisplayName = 'classTwo' } + [PSCustomObject]@{ Name = 'attrOne'; DistinguishedName = 'CN=attrOne,CN=Schema'; ObjectClass = @('top', 'attributeSchema'); WhenCreated = [datetime]'2022-01-01'; LdapDisplayName = 'ms-Mcs-AdmPwd' } + ) + SchemaContainer = [PSCustomObject]@{ ObjectVersion = 91; DistinguishedName = 'CN=Schema'; WhenCreated = [datetime]'2020-01-01' } + WindowsLapsInstalled = $false + RootDSE = [PSCustomObject]@{ SupportedSaslMechanisms = @('GSSAPI', 'DIGEST-MD5') } + ServiceAccounts = @( + [PSCustomObject]@{ Name = 'standalone'; ObjectClass = @('top', 'msDS-ManagedServiceAccount') } + [PSCustomObject]@{ Name = 'group'; ObjectClass = @('top', 'msDS-GroupManagedServiceAccount') } + [PSCustomObject]@{ Name = 'delegated'; ObjectClass = @('top', 'computer', 'msDS-DelegatedManagedServiceAccount'); DelegatedMsaState = 2 } + ) + Users = @([PSCustomObject]@{ SamAccountName = 'krbtgt'; PasswordLastSet = (Get-Date).AddDays(-200); Enabled = $false }) + Trusts = @( + [PSCustomObject]@{ TrustPartner = 'external.example'; Direction = 'Inbound'; TrustTypeName = 'Domain Uplevel'; TrustType = 2; TrustAttributes = 0; LastValidated = $null; Modified = [datetime]'2025-01-01' } + [PSCustomObject]@{ TrustPartner = 'forest.example'; Direction = 'Outbound'; TrustTypeName = 'Domain Uplevel'; TrustType = 2; TrustAttributes = 8; LastValidated = $null; Modified = [datetime]'2025-01-01' } + ) + } + Mock Get-MtADDomainState -ModuleName Maester { $script:state } + Mock Add-MtTestResultDetail -ModuleName Maester { param($Result, [switch] $Investigate) $script:detail = [PSCustomObject]@{ Text = $Result; Investigate = $Investigate.IsPresent } } + } + + It 'merges schema creation-year counts with all dated object details' { + Test-MtAdSchemaModificationYearCount | Should -BeTrue + $script:detail.Investigate | Should -BeTrue + $script:detail.Text | Should -Match 'Creation years \| 2' + $script:detail.Text | Should -Match '2022 \| 2' + $script:detail.Text | Should -Match '2020 \| classOne \| CN=classOne' + $script:detail.Text | Should -Match '2022 \| attrOne \| CN=attrOne' + } + + It 'merges schema version and all classSchema definitions without listing attributes as classes' { + Test-MtAdSchemaVersionEntryCount | Should -BeTrue + $script:detail.Investigate | Should -BeTrue + $script:detail.Text | Should -Match 'Schema version \| 91' + $script:detail.Text | Should -Match 'classSchema definitions \| 2' + $script:detail.Text | Should -Match 'classOne \| CN=classOne' + $script:detail.Text | Should -Match 'classTwo \| CN=classTwo' + $script:detail.Text | Should -Not -Match '\| attrOne \| CN=attrOne' + } + + It 'requires the collected Windows LAPS flag and does not accept legacy schema alone' { + Test-MtAdLapsInstalledStatus | Should -BeFalse + $script:detail.Text | Should -Match 'Legacy LAPS presence alone is insufficient' + $script:state.WindowsLapsInstalled = $true + $script:state.SchemaObjects += [PSCustomObject]@{ Name = 'ms-LAPS-Password'; LdapDisplayName = 'msLAPS-Password' } + $script:state.SchemaObjects += [PSCustomObject]@{ Name = 'ms-LAPS-PasswordExpirationTime'; LdapDisplayName = 'msLAPS-PasswordExpirationTime' } + Test-MtAdLapsInstalledStatus | Should -BeTrue + $script:detail.Text | Should -Match 'Both Windows LAPS schema attributes are present' + } + + It 'shows DIGEST-MD5 as advertised, not as a successful authentication' { + Test-MtAdSupportedSaslMechanismCount | Should -BeTrue + $script:detail.Investigate | Should -BeTrue + $script:detail.Text | Should -Match 'Mechanisms Count \| 2' + $script:detail.Text | Should -Match 'DIGEST-MD5 \| Digest; advertised' + $script:detail.Text | Should -Match 'does not establish whether a bind succeeds' + } + + It 'counts standalone, group and delegated MSAs without double counting' { + Test-MtAdManagedServiceAccountCount | Should -BeTrue + $script:detail.Investigate | Should -BeTrue + $script:detail.Text | Should -Match 'Total Managed Service Accounts \| 3' + $script:detail.Text | Should -Match 'gMSA\) \| 1' + $script:detail.Text | Should -Match 'dMSA\) \| 1' + $script:detail.Text | Should -Match 'Standalone Managed Service Accounts \| 1' + $script:detail.Text | Should -Match 'delegated \| dMSA \| 2' + } + + It 'fails on a missing KRBTGT account and respects a configured password-age threshold' { + Test-MtAdKrbtgtPasswordLastSet | Should -BeFalse + Test-MtAdKrbtgtPasswordLastSet -MaxPasswordAgeDays 240 | Should -BeTrue + $script:state.Users = @() + Test-MtAdKrbtgtPasswordLastSet | Should -BeFalse + $script:detail.Text | Should -Match 'KRBTGT account not found' + } + + It 'merges trust count and all configuration details as investigation' { + Test-MtAdTrustTotalCount | Should -BeTrue + $script:detail.Investigate | Should -BeTrue + $script:detail.Text | Should -Match 'Total Trusts \| 2' + $script:detail.Text | Should -Match 'external.example \| Inbound \| Domain Uplevel' + $script:detail.Text | Should -Match 'forest.example \| Outbound \| Domain Uplevel' + } + + It 'fails weak SID filtering and lists each finding in the count check' { + Test-MtAdTrustQuarantinedCount | Should -BeFalse + $script:detail.Text | Should -Match 'Weak SID Filtering \| 1' + $script:detail.Text | Should -Match 'external.example \| Inbound \| Domain Uplevel \| External trust:' + $script:state.Trusts[0].TrustAttributes = 4 + Test-MtAdTrustQuarantinedCount | Should -BeTrue + } + + It 'investigates unknown trust validation without claiming no stale trusts' { + Test-MtAdTrustStaleCount | Should -BeTrue + $script:detail.Investigate | Should -BeTrue + $script:detail.Text | Should -Match 'Unknown Validation Status \| 2' + $script:detail.Text | Should -Match 'external.example \| Inbound \| Domain Uplevel \| Unknown' + $script:detail.Text | Should -Match 'forest.example \| Outbound \| Domain Uplevel \| Unknown' + $script:detail.Text | Should -Match 'no stale-trust assertion can be made' + $script:detail.Text | Should -Not -Match 'No stale trusts detected' + $script:state.Trusts[0] | Add-Member -NotePropertyName LastValidated -NotePropertyValue (Get-Date).AddDays(-90) -Force + Test-MtAdTrustStaleCount -StaleThresholdDays 60 | Should -BeTrue + $script:detail.Text | Should -Match 'Stale Trusts \(>60 days\) \| 1' + $script:detail.Text | Should -Match 'Unknown Validation Status \| 1' + $script:detail.Text | Should -Match 'external.example \| Inbound \| Domain Uplevel \| [0-9]{4}-' + } +} diff --git a/tests/ad/domain/Test.AD-FORS-04.md b/tests/ad/domain/Test.AD-FORS-04.md index 1b3586599b..ee35163fb2 100644 --- a/tests/ad/domain/Test.AD-FORS-04.md +++ b/tests/ad/domain/Test.AD-FORS-04.md @@ -27,7 +27,7 @@ This test retrieves cross-forest reference information from the forest configura #### Related Tests - `Test-MtAdTrustTotalCount` - Checks for configured domain trusts -- `Test-MtAdTrustDetails` - Provides detailed trust configuration information +- `AD-TRUST-01` - Provides trust counts and detailed configuration information %TestResult% diff --git a/tests/ad/trust/Test.AD-TRUST-01.md b/tests/ad/trust/Test.AD-TRUST-01.md index c9e299a555..4bf2814a02 100644 --- a/tests/ad/trust/Test.AD-TRUST-01.md +++ b/tests/ad/trust/Test.AD-TRUST-01.md @@ -21,17 +21,16 @@ Trusts allow users from one domain to access resources in another. While necessa #### How the Test Works -This test retrieves all trust objects from Active Directory using `Get-ADTrust` and counts the total number of configured trusts. The test returns: +This test retrieves the cached LDAP trusted-domain inventory and counts the configured trusts. The test returns: -- Total count of trusts +- Total count of trusts and each trust's target, direction, type, within-forest status, quarantine bit, and selective authentication bit - Informational result (no pass/fail criteria) #### Related Tests - `Test-MtAdTrustInterForestCount` - Identifies external/inter-forest trusts - `Test-MtAdTrustQuarantinedCount` - Checks for SID filtering on trusts -- `Test-MtAdTrustStaleCount` - Identifies trusts not validated recently -- `Test-MtAdTrustDetails` - Provides detailed trust configuration information +- `Test-MtAdTrustStaleCount` (AD-TRUST-06) - Inventories known and unknown validation dates; safe LDAP cannot establish staleness %TestResult% diff --git a/tests/ad/trust/Test.AD-TRUST-01.ps1 b/tests/ad/trust/Test.AD-TRUST-01.ps1 index aa1c572cfb..9c9469384a 100644 --- a/tests/ad/trust/Test.AD-TRUST-01.ps1 +++ b/tests/ad/trust/Test.AD-TRUST-01.ps1 @@ -19,7 +19,7 @@ #> [MaesterTest( Id = 'AD-TRUST-01', - Title = 'Trust total count should be investigated', + Title = 'Trust count and configuration should be investigated', Product = 'ad', Feature = 'trusts', Area = 'external-access', @@ -41,11 +41,11 @@ # If unable to retrieve AD data, skip the test if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + throw 'Active Directory trust inventory was not returned.' } $trusts = $adState.Trusts + if ($null -eq $trusts) { throw 'Active Directory trusts were not returned.' } # Count total trusts $totalCount = ($trusts | Measure-Object).Count @@ -57,6 +57,17 @@ $result = "| Metric | Value |" + "`n" $result += "| --- | --- |" + "`n" $result += "| Total Trusts | $totalCount |" + "`n" + "`n" + if ($totalCount -gt 0) { + $result += "| Target | Direction | Type | Within forest | Quarantined | Selective authentication |`n" + $result += "| --- | --- | --- | --- | --- | --- |`n" + foreach ($trust in $trusts) { + $bits = $trust.TrustAttributes + $withinForest = if ($null -eq $bits) { 'Unknown' } elseif (([int]$bits -band 0x20) -ne 0) { 'Yes' } else { 'No' } + $quarantined = if ($null -eq $bits) { 'Unknown' } elseif (([int]$bits -band 0x4) -ne 0) { 'Yes' } else { 'No' } + $selective = if ($null -eq $bits) { 'Unknown' } elseif (([int]$bits -band 0x10) -ne 0) { 'Yes' } else { 'No' } + $result += "| $($trust.TrustPartner) | $($trust.Direction) | $($trust.TrustTypeName) | $withinForest | $quarantined | $selective |`n" + } + } if ($totalCount -eq 0) { $testResultMarkdown = "No Active Directory trusts are configured in this domain. This is typical for single-domain environments.`n`n%TestResult%" diff --git a/tests/ad/trust/Test.AD-TRUST-02.md b/tests/ad/trust/Test.AD-TRUST-02.md index 6de361aad1..1f6c0a8b8c 100644 --- a/tests/ad/trust/Test.AD-TRUST-02.md +++ b/tests/ad/trust/Test.AD-TRUST-02.md @@ -22,7 +22,7 @@ Intra-forest trusts (within the same forest) generally have stronger security gu #### How the Test Works -This test analyzes all trust objects and identifies those where `IntraForest` is `$false`. The test returns: +This test analyzes all LDAP trust objects and identifies those where `WITHIN_FOREST` (`0x20`) is absent. It distinguishes unknown bitmasks; this outside-forest count can include non-AD realm trusts and is not equivalent to forest trust classification. The test returns: - Total count of trusts - Count of inter-forest trusts @@ -31,9 +31,9 @@ This test analyzes all trust objects and identifies those where `IntraForest` is #### Related Tests - `Test-MtAdTrustQuarantinedCount` - Checks if external trusts have SID filtering enabled -- `Test-MtAdTrustNonQuarantinedDetails` - Lists external trusts without SID filtering +- `Test-MtAdTrustQuarantinedCount` (AD-TRUST-03) - Counts and lists weak SID-filtering findings - `Test-MtAdTrustTotalCount` - Overall trust count -- `Test-MtAdTrustDetails` - Detailed trust configuration +- `Test-MtAdTrustTotalCount` (AD-TRUST-01) - Trust count and full configuration inventory %TestResult% diff --git a/tests/ad/trust/Test.AD-TRUST-02.ps1 b/tests/ad/trust/Test.AD-TRUST-02.ps1 index 6f00ea493c..d49f256ca8 100644 --- a/tests/ad/trust/Test.AD-TRUST-02.ps1 +++ b/tests/ad/trust/Test.AD-TRUST-02.ps1 @@ -41,14 +41,14 @@ # If unable to retrieve AD data, skip the test if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + throw 'Active Directory trust inventory was not returned.' } $trusts = $adState.Trusts + if ($null -eq $trusts) { throw 'Active Directory trusts were not returned.' } # Count inter-forest trusts - $interForestTrusts = $trusts | Where-Object { $_.IntraForest -eq $false } + $interForestTrusts = $trusts | Where-Object { $null -ne $_.TrustAttributes -and (([int]$_.TrustAttributes -band 0x20) -eq 0) } $interForestCount = ($interForestTrusts | Measure-Object).Count $totalCount = ($trusts | Measure-Object).Count @@ -60,10 +60,11 @@ $result += "| --- | --- |" + "`n" $result += "| Total Trusts | $totalCount |" + "`n" $result += "| Inter-Forest Trusts | $interForestCount |" + "`n" - $result += "| Intra-Forest Trusts | $($totalCount - $interForestCount) |" + "`n" + "`n" + $result += "| Within-Forest Trusts | $(($trusts | Where-Object { $null -ne $_.TrustAttributes -and ([int]$_.TrustAttributes -band 0x20) -ne 0 } | Measure-Object).Count) |" + "`n" + $result += "| Unknown classification | $(($trusts | Where-Object { $null -eq $_.TrustAttributes } | Measure-Object).Count) |" + "`n" + "`n" if ($interForestCount -eq 0) { - $testResultMarkdown = "No inter-forest trusts are configured. All trusts (if any) are within the same forest.`n`n%TestResult%" + $testResultMarkdown = "No outside-forest trusts were identified from available trust attributes. Review unknown classifications separately.`n`n%TestResult%" } else { $testResultMarkdown = "There are $interForestCount inter-forest trust(s) configured. Inter-forest trusts connect to external forests and should be carefully monitored for security.`n`n%TestResult%" } diff --git a/tests/ad/trust/Test.AD-TRUST-03.md b/tests/ad/trust/Test.AD-TRUST-03.md index ecd2777328..805cda7faf 100644 --- a/tests/ad/trust/Test.AD-TRUST-03.md +++ b/tests/ad/trust/Test.AD-TRUST-03.md @@ -1,50 +1,17 @@ -Strong SID filtering is a critical security control for inter-forest trusts: +Checks applicable external and forest trusts for SID filtering using their LDAP `trustAttributes` flags. -- **Prevents Privilege Escalation**: Blocks malicious SID history from being honored across trust boundaries -- **Limits Blast Radius**: Contains the impact of a compromised external domain -- **Security Best Practice**: Microsoft recommends SID filtering for all external trusts -- **Compliance Requirement**: Many security frameworks require SID filtering on external trusts +External downlevel and uplevel trusts without `WITHIN_FOREST` or `FOREST_TRANSITIVE` are checked for `QUARANTINED_DOMAIN` (`0x4`). Forest trusts are checked for `TREAT_AS_EXTERNAL` (`0x40`), which relaxes cross-forest filtering to external-trust rules. Within-forest and MIT realm trusts are excluded. PIM trusts (`0x400`) are counted for manual review rather than failed on this general-purpose rule; they have distinct filtering rules. A missing trust type or bitmask does not count as a pass; investigate configurations and documented exceptions before changing any trust. -Without strong SID filtering, an attacker who compromises a domain in a trusting forest could inject SIDs from the trusted forest's privileged groups (like Domain Admins or Enterprise Admins) into their own account, effectively gaining privileged access across the trust boundary. +The result includes total, evaluated, strong, weak, unknown, and excluded counts, plus details of **every weak or unknown trust**. Selective authentication is a separate control and is not forced as a universal SID-filtering baseline. -#### Control Type +#### Remediation action -**Operational** - -#### Security Recommendation - -- **Enable SID Filtering**: Enable SID filtering (quarantine) on ALL external trusts -- **Disable SID History**: Disable SID history on ALL forest trusts -- **Audit Regularly**: Regularly verify that external trusts remain quarantined and forest trusts do not have SID history enabled -- **Document Exceptions**: If strong SID filtering cannot be enabled, document the risk and compensating controls -- **Use Forest Trusts**: When possible, use forest trusts instead of external trusts as they provide better security controls -- **Monitor Changes**: Alert on any changes to trust SID filtering status - -#### How the Test Works - -This test derives trust classification and SID filtering status from the `trustAttributes` LDAP attribute and `trustType`: - -- **External trusts**: `trustType` in `1,2` and `trustAttributes` does not have `FOREST_TRANSITIVE` (`0x8`) or `WITHIN_FOREST` (`0x20`) -- **Forest trusts**: `trustAttributes` has `FOREST_TRANSITIVE` (`0x8`) -- **Strong external trusts**: `QUARANTINED_DOMAIN` (`0x4`) is set -- **Strong forest trusts**: `TREAT_AS_EXTERNAL` (`0x40`) is not set (SID history disabled) - -The test returns: -- Total count of trusts -- Count of external/forest trusts evaluated -- Count of trusts with strong SID filtering -- Count of trusts with weak SID filtering - -#### Related Tests - -- `Test-MtAdTrustNonQuarantinedDetails` - Lists specific trusts without SID filtering -- `Test-MtAdTrustInterForestCount` - Identifies external trusts that should be quarantined -- `Test-MtAdTrustDetails` - Shows quarantine status for all trusts +1. Review affected trust directions and business requirements with domain administrators. +2. Verify SID filtering behavior and SID-history migration needs before changing trust flags; pilot any change to avoid breaking cross-domain access. #### Related links -- [Microsoft Learn: Security considerations for trusts](https://learn.microsoft.com/previous-versions/windows/it-pro/windows-server-2003/cc755321%28v=ws.10%29) -- [ANSSI Active Directory checkpoints: Unfiltered outbound domain trust relationship](https://www.cert.ssi.gouv.fr/uploads/ad_checklist.html#vuln_trusts_domain_notfiltered) +* [Microsoft MS-ADTS trust attribute flags](https://learn.microsoft.com/openspecs/windows_protocols/ms-adts/e9a2d23c-c31e-4a6f-88a0-6646fdb51a3c) %TestResult% diff --git a/tests/ad/trust/Test.AD-TRUST-03.ps1 b/tests/ad/trust/Test.AD-TRUST-03.ps1 index db4feda14d..b3547c3eab 100644 --- a/tests/ad/trust/Test.AD-TRUST-03.ps1 +++ b/tests/ad/trust/Test.AD-TRUST-03.ps1 @@ -23,13 +23,16 @@ #> [MaesterTest( Id = 'AD-TRUST-03', - Title = 'Trust quarantined count should be investigated', + Title = 'Applicable trusts should have strong SID filtering with no weak findings', Product = 'ad', Feature = 'trusts', Area = 'external-access', ResourceType = 'Trust', - Severity = 'Info', + Severity = 'High', + UserImpact = 'Medium', + ImplementationCost = 'Medium', Mitre = 'T1134.005', + Control = ('nist-800-53-r5:AC-4', 'nist-800-53-r5:SC-7'), Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:trustedDomain:ReadProperty'), Author = 'soulemike' @@ -45,11 +48,11 @@ # If unable to retrieve AD data, skip the test if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + throw 'Active Directory trust inventory was not returned.' } $trusts = $adState.Trusts + if ($null -eq $trusts) { throw 'Active Directory trusts were not returned.' } # Derive trust classification and SID filtering status from trustAttributes bitmask # trustAttributes bits: @@ -62,37 +65,25 @@ # 2 = UPLEVEL (Windows 2000+ AD domain) # 3 = MIT (Kerberos realm) — SID filtering does not apply # 4 = DCE - foreach ($trust in $trusts) { - $trustAttributes = [int]$trust.TrustAttributes - $trustType = [int]$trust.TrustType - - $isForest = ($trustAttributes -band 0x8) -ne 0 - $isExternal = -not $isForest -and -not ($trustAttributes -band 0x20) -and ($trustType -in 1,2) - $isMit = ($trustType -eq 3) - - # SID filtering weakness: - # - External trusts: weak if QUARANTINED_DOMAIN (0x4) is NOT set - # - Forest trusts: weak if TREAT_AS_EXTERNAL (0x40) IS set (SID history enabled) - # - MIT trusts: excluded from evaluation - $sidFilteringWeak = ($isExternal -and -not ($trustAttributes -band 0x4)) -or - ($isForest -and ($trustAttributes -band 0x40)) - - $trust | Add-Member -NotePropertyName IsForest -NotePropertyValue $isForest -Force - $trust | Add-Member -NotePropertyName IsExternal -NotePropertyValue $isExternal -Force - $trust | Add-Member -NotePropertyName IsMit -NotePropertyValue $isMit -Force - $trust | Add-Member -NotePropertyName SidFilteringWeak -NotePropertyValue $sidFilteringWeak -Force - } - - # Only evaluate external/forest trusts for SID filtering weakness - # Intra-forest trusts do not support quarantine; MIT trusts are excluded - $evaluatedTrusts = $trusts | Where-Object { $_.IsExternal -or $_.IsForest } - $strongTrusts = $evaluatedTrusts | Where-Object { -not $_.SidFilteringWeak } + # Only external Windows trusts and forest trusts have applicable flags. + $evaluatedTrusts = @($trusts | Where-Object { + $bits = [int]$_.TrustAttributes + $null -ne $_.TrustAttributes -and $null -ne $_.TrustType -and ($bits -band 0x400) -eq 0 -and + ((($bits -band 0x8) -ne 0) -or (($bits -band 0x20) -eq 0 -and [int]$_.TrustType -in 1, 2)) + }) + $strongTrusts = @($evaluatedTrusts | Where-Object { + $bits = [int]$_.TrustAttributes + if (($bits -band 0x8) -ne 0) { ($bits -band 0x40) -eq 0 } + else { ($bits -band 0x4) -ne 0 } + }) $strongCount = ($strongTrusts | Measure-Object).Count $evaluatedCount = ($evaluatedTrusts | Measure-Object).Count $totalCount = ($trusts | Measure-Object).Count - # Test passes if we successfully retrieved trust data - $testResult = $true + # A missing bitmask is not evidence of a protected trust. + $unknownCount = @($trusts | Where-Object { $null -eq $_.TrustAttributes -or $null -eq $_.TrustType }).Count + $pimCount = @($trusts | Where-Object { $null -ne $_.TrustAttributes -and ([int]$_.TrustAttributes -band 0x400) -ne 0 }).Count + $testResult = $strongCount -eq $evaluatedCount -and $unknownCount -eq 0 # Generate markdown results $result = "| Metric | Value |" + "`n" @@ -101,20 +92,43 @@ $result += "| Evaluated Trusts (External/Forest) | $evaluatedCount |" + "`n" $result += "| Strong SID Filtering | $strongCount |" + "`n" $result += "| Weak SID Filtering | $($evaluatedCount - $strongCount) |" + "`n" + "`n" + $result += "| Unknown Trust Attributes or Type | $unknownCount |" + "`n" + $result += "| PIM Trusts Excluded (manual review) | $pimCount |" + "`n" + $weakTrusts = @($evaluatedTrusts | Where-Object { + $bits = [int]$_.TrustAttributes + if (($bits -band 0x8) -ne 0) { ($bits -band 0x40) -ne 0 } + else { ($bits -band 0x4) -eq 0 } + }) + if ($weakTrusts.Count -gt 0) { + $result += "`n**Trusts with weak SID filtering:**`n`n" + $result += "| Target | Direction | Type | Reason |`n| --- | --- | --- | --- |`n" + foreach ($trust in $weakTrusts) { + $reason = if (([int]$trust.TrustAttributes -band 0x8) -ne 0) { 'Forest trust: TREAT_AS_EXTERNAL set (SID history permitted)' } else { 'External trust: QUARANTINED_DOMAIN not set' } + $result += "| $($trust.TrustPartner) | $($trust.Direction) | $($trust.TrustTypeName) | $reason |`n" + } + } + if ($unknownCount -gt 0) { + $result += "`n**Trusts with unknown configuration:**`n`n| Target | Direction |`n| --- | --- |`n" + foreach ($trust in ($trusts | Where-Object { $null -eq $_.TrustAttributes -or $null -eq $_.TrustType })) { + $result += "| $($trust.TrustPartner) | $($trust.Direction) |`n" + } + } if ($totalCount -eq 0) { $testResultMarkdown = "No trusts are configured in this domain.`n`n%TestResult%" + } elseif ($unknownCount -gt 0) { + $testResultMarkdown = "Trust SID filtering cannot be confirmed: $unknownCount trust(s) lack trust attributes or type. Review the missing data and any weak trusts listed in the count.`n`n%TestResult%" } elseif ($evaluatedCount -eq 0) { - $testResultMarkdown = "No external or forest trusts are configured. Only intra-forest or MIT trusts exist, which are not evaluated for SID filtering.`n`n%TestResult%" - } elseif ($strongCount -eq 0) { + $testResultMarkdown = "No non-PIM external or forest trusts are eligible for this SID-filtering check. Within-forest and MIT trusts are excluded; review $pimCount PIM trust(s) under their separate filtering rules.`n`n%TestResult%" + } elseif ($strongCount -eq 0 -and $evaluatedCount -gt 0) { $testResultMarkdown = "No external/forest trusts have strong SID filtering. Consider enabling SID filtering on external trusts and disabling SID history on forest trusts to prevent privilege escalation attacks.`n`n%TestResult%" } else { - $testResultMarkdown = "$strongCount external/forest trust(s) have strong SID filtering. This helps prevent privilege escalation attacks across trust boundaries.`n`n%TestResult%" + $testResultMarkdown = "$(if ($testResult) { 'Well done.' } else { 'Review weak filtering.' }) $strongCount of $evaluatedCount external/forest trust(s) have strong SID filtering.`n`n%TestResult%" } $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate + Add-MtTestResultDetail -Result $testResultMarkdown return $testResult } diff --git a/tests/ad/trust/Test.AD-TRUST-04.md b/tests/ad/trust/Test.AD-TRUST-04.md deleted file mode 100644 index 9d43ab7f73..0000000000 --- a/tests/ad/trust/Test.AD-TRUST-04.md +++ /dev/null @@ -1,69 +0,0 @@ -Trusts with weak SID filtering are a significant security risk: - -- **SID History Vulnerability**: Attackers can exploit SID history to elevate privileges across trust boundaries -- **Privilege Escalation Path**: Compromised external accounts can gain access to privileged resources -- **Audit Finding**: Most security audits flag weak SID filtering on inter-forest trusts as high-risk -- **Compliance Gap**: Fails compliance requirements for many security frameworks - -This test identifies external and forest trusts with weak SID filtering, enabling targeted remediation: -- **External trusts** are weak when the `QUARANTINED_DOMAIN` bit (`0x4`) is not set -- **Forest trusts** are weak when the `TREAT_AS_EXTERNAL` bit (`0x40`) is set (SID history enabled) -- **Intra-forest** (parent-child) trusts are excluded because they do not support quarantine -- **MIT Kerberos realm** trusts are excluded as SID filtering does not apply to them - -#### Control Type - -**Detective** - -#### Security Recommendation - -**Immediate Actions:** -- Review each trust with weak SID filtering to determine if it can be strengthened -- For external trusts: enable SID filtering (`netdom trust /quarantine:yes`) -- For forest trusts: disable SID history (`netdom trust /enablesidhistory:no`) -- Test applications that rely on cross-trust authentication before making changes - -**Long-term Strategy:** -- Replace external trusts with forest trusts where possible -- Implement selective authentication for sensitive resources -- Regularly audit trust configurations -- Document any trusts that must remain weak with business justification - -**Commands to Strengthen SID Filtering:** -```powershell -# External trust — enable quarantine (SID filtering) -netdom trust /domain: /quarantine:yes - -# Forest trust — disable SID history -netdom trust /domain: /enablesidhistory:no -``` - -#### How the Test Works - -This test derives trust classification and SID filtering status from the `trustAttributes` LDAP attribute and `trustType`: - -- **External trusts**: `trustType` in `1,2` and `trustAttributes` does not have `FOREST_TRANSITIVE` (`0x8`) or `WITHIN_FOREST` (`0x20`) -- **Forest trusts**: `trustAttributes` has `FOREST_TRANSITIVE` (`0x8`) -- **Weak external trusts**: `QUARANTINED_DOMAIN` (`0x4`) is **not** set -- **Weak forest trusts**: `TREAT_AS_EXTERNAL` (`0x40`) **is** set (SID history enabled) - -The test displays: -- Target domain of the trust -- Trust direction (Inbound, Outbound, or Bidirectional) -- Trust type (External Downlevel, Domain Uplevel, MIT Kerberos, or DCE) -- Whether the trust is a forest or external trust -- The reason for weak SID filtering - -#### Related Tests - -- `Test-MtAdTrustQuarantinedCount` - Count of quarantined vs non-quarantined external/forest trusts -- `Test-MtAdTrustInterForestCount` - Identifies external trusts that should be quarantined -- `Test-MtAdTrustDetails` - Complete trust configuration details - -#### Related links - -- [Microsoft Learn: Security considerations for trusts](https://learn.microsoft.com/previous-versions/windows/it-pro/windows-server-2003/cc755321%28v=ws.10%29) -- [ANSSI Active Directory checkpoints: Unfiltered outbound domain trust relationship](https://www.cert.ssi.gouv.fr/uploads/ad_checklist.html#vuln_trusts_domain_notfiltered) - - -%TestResult% diff --git a/tests/ad/trust/Test.AD-TRUST-04.ps1 b/tests/ad/trust/Test.AD-TRUST-04.ps1 deleted file mode 100644 index 0e46426671..0000000000 --- a/tests/ad/trust/Test.AD-TRUST-04.ps1 +++ /dev/null @@ -1,150 +0,0 @@ -function Test-MtAdTrustNonQuarantinedDetails { - <# - .SYNOPSIS - Lists details of trusts with weak SID filtering in Active Directory. - - .DESCRIPTION - This test retrieves detailed information about external and forest trusts that have weak - SID filtering. For external trusts, weakness means the QUARANTINED_DOMAIN bit (0x4) is not set. - For forest trusts, weakness means the TREAT_AS_EXTERNAL bit (0x40) is set (SID history enabled). - Intra-forest (parent-child) trusts are excluded because they do not support quarantine. - MIT Kerberos realm trusts are also excluded as SID filtering does not apply to them. - - Trust classification is derived from the trustAttributes LDAP attribute and trustType. - - .EXAMPLE - Test-MtAdTrustNonQuarantinedDetails - - Returns $true if all evaluated trusts have strong SID filtering, $false if any are weak. - The test result includes details of trusts with weak SID filtering. - - .LINK - https://maester.dev/docs/commands/Test-MtAdTrustNonQuarantinedDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-TRUST-04', - Title = 'No trusts should lack SID filtering (quarantine)', - Product = 'ad', - Feature = 'trusts', - Area = 'external-access', - ResourceType = 'Trust', - Severity = 'High', - UserImpact = 'Medium', - ImplementationCost = 'Medium', - Mitre = 'T1134.005', - Control = ('nist-800-53-r5:AC-4', 'nist-800-53-r5:SC-7'), - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:trustedDomain:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdTrustNonQuarantinedDetails" - - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('Trusts') - - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $trusts = $adState.Trusts - - # Derive trust classification and SID filtering status from trustAttributes bitmask - # trustAttributes bits: - # 0x4 = QUARANTINED_DOMAIN (SID filtering enabled on external trusts) - # 0x8 = FOREST_TRANSITIVE (forest trust) - # 0x20 = WITHIN_FOREST (parent-child intra-forest trust) - # 0x40 = TREAT_AS_EXTERNAL (SID history enabled on forest trusts) - # trustType values: - # 1 = DOWNLEVEL (Windows NT 4 external) - # 2 = UPLEVEL (Windows 2000+ AD domain) - # 3 = MIT (Kerberos realm) — SID filtering does not apply - # 4 = DCE - foreach ($trust in $trusts) { - $trustAttributes = [int]$trust.TrustAttributes - $trustType = [int]$trust.TrustType - - $isForest = ($trustAttributes -band 0x8) -ne 0 - $isExternal = -not $isForest -and -not ($trustAttributes -band 0x20) -and ($trustType -in 1,2) - $isMit = ($trustType -eq 3) - - # SID filtering weakness: - # - External trusts: weak if QUARANTINED_DOMAIN (0x4) is NOT set - # - Forest trusts: weak if TREAT_AS_EXTERNAL (0x40) IS set (SID history enabled) - # - MIT trusts: excluded from evaluation - $sidFilteringWeak = ($isExternal -and -not ($trustAttributes -band 0x4)) -or - ($isForest -and ($trustAttributes -band 0x40)) - - $trust | Add-Member -NotePropertyName IsForest -NotePropertyValue $isForest -Force - $trust | Add-Member -NotePropertyName IsExternal -NotePropertyValue $isExternal -Force - $trust | Add-Member -NotePropertyName IsMit -NotePropertyValue $isMit -Force - $trust | Add-Member -NotePropertyName SidFilteringWeak -NotePropertyValue $sidFilteringWeak -Force - } - - # Only evaluate external/forest trusts for SID filtering weakness - # Intra-forest trusts do not support quarantine; MIT trusts are excluded - $evaluatedTrusts = $trusts | Where-Object { $_.IsExternal -or $_.IsForest } - $weakTrusts = $evaluatedTrusts | Where-Object { $_.SidFilteringWeak } - $weakCount = ($weakTrusts | Measure-Object).Count - $evaluatedCount = ($evaluatedTrusts | Measure-Object).Count - $totalCount = ($trusts | Measure-Object).Count - - # Test fails if any evaluated trusts have weak SID filtering - $testResult = ($weakCount -eq 0) - - # Generate markdown results - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Trusts | $totalCount |" + "`n" - $result += "| Evaluated Trusts (External/Forest) | $evaluatedCount |" + "`n" - $result += "| Trusts with Weak SID Filtering | $weakCount |" + "`n" + "`n" - - if ($weakCount -gt 0) { - $result += "### Trusts with Weak SID Filtering" + "`n" + "`n" - $result += "| Target | Direction | Type | Forest | External | Weak Reason |" + "`n" - $result += "| --- | --- | --- | --- | --- | --- |" + "`n" - - foreach ($trust in $weakTrusts) { - $target = $trust.TrustPartner - $direction = switch ([int]$trust.TrustDirection) { - 1 { "Inbound" } - 2 { "Outbound" } - 3 { "Bidirectional" } - default { $trust.TrustDirection } - } - $trustType = switch ([int]$trust.TrustType) { - 1 { "External (Downlevel)" } - 2 { "Domain (Uplevel)" } - 3 { "MIT (Kerberos)" } - 4 { "DCE" } - default { "Type $($trust.TrustType)" } - } - $isForestStr = if ($trust.IsForest) { "Yes" } else { "No" } - $isExternalStr = if ($trust.IsExternal) { "Yes" } else { "No" } - $weakReason = if ($trust.IsForest) { "TREAT_AS_EXTERNAL (SID history enabled)" } else { "QUARANTINED_DOMAIN not set" } - $result += "| $target | $direction | $trustType | $isForestStr | $isExternalStr | $weakReason |" + "`n" - } - } - - if ($totalCount -eq 0) { - $testResultMarkdown = "No trusts are configured in this domain.`n`n%TestResult%" - } elseif ($evaluatedCount -eq 0) { - $testResultMarkdown = "No external or forest trusts are configured. Only intra-forest or MIT trusts exist, which are not evaluated for SID filtering.`n`n%TestResult%" - } elseif ($weakCount -eq 0) { - $testResultMarkdown = "All external/forest trusts have strong SID filtering. Good security posture!`n`n%TestResult%" - } else { - $testResultMarkdown = "Found $weakCount trust(s) with weak SID filtering. External trusts lacking quarantine or forest trusts with SID history enabled may be vulnerable to privilege escalation.`n`n%TestResult%" - } - - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult -} diff --git a/tests/ad/trust/Test.AD-TRUST-05.md b/tests/ad/trust/Test.AD-TRUST-05.md deleted file mode 100644 index 24d1225145..0000000000 --- a/tests/ad/trust/Test.AD-TRUST-05.md +++ /dev/null @@ -1,58 +0,0 @@ -Comprehensive trust documentation is essential for security operations: - -- **Security Audits**: Auditors require detailed trust configuration information -- **Incident Response**: Understanding trust relationships helps during security incidents -- **Change Management**: Tracking trust configurations supports change control processes -- **Risk Assessment**: Detailed trust information enables proper risk evaluation -- **Compliance**: Many frameworks require documentation of trust relationships - -Trust details reveal critical security properties including: -- **Direction**: Who can access whose resources -- **Type**: External vs Forest trust (different security models) -- **SID Filtering**: Whether the trust has strong SID filtering -- **Selective Authentication**: Whether authentication is restricted -- **Trust Classification**: Derived `IsForest`, `IsExternal`, and `SidFilteringWeak` properties - -#### Control Type - -**Operational** - -#### Security Recommendation - -**Configuration Best Practices:** - -1. **Use Forest Trusts**: Prefer forest trusts over external trusts for better security -2. **Enable SID Filtering**: Always enable SID filtering on external trusts -3. **Selective Authentication**: Use selective authentication when possible -4. **Inbound Only**: Prefer inbound trusts over bidirectional when possible -5. **Document Everything**: Maintain detailed documentation of each trust's purpose - -**Trust Properties to Monitor:** -- `Quarantined`: Should be `$true` for external trusts (SID filtering enabled) -- `SidFilteringWeak`: Should be `$false` for both external and forest trusts -- `SelectiveAuthentication`: Consider enabling for sensitive environments -- `Direction`: Bidirectional trusts have higher risk -- `IsForest` / `IsExternal`: Helps identify which SID filtering rules apply - -#### How the Test Works - -This test retrieves all trust properties from LDAP and derives display values: - -- **Quarantined**: Derived from `trustAttributes` bit `0x4` (`QUARANTINED_DOMAIN`) -- **Selective Authentication**: Derived from `trustAttributes` bit `0x10` (`CROSS_ORGANIZATION`) -- **Intra-Forest**: Derived from `trustAttributes` bit `0x20` (`WITHIN_FOREST`) -- **IsForest**: Derived from `trustAttributes` bit `0x8` (`FOREST_TRANSITIVE`) -- **IsExternal**: Derived from `trustType` in `1,2` and absence of `FOREST_TRANSITIVE` / `WITHIN_FOREST` -- **SidFilteringWeak**: External trusts weak when `QUARANTINED_DOMAIN` not set; forest trusts weak when `TREAT_AS_EXTERNAL` (`0x40`) is set -- **Trust Type**: Mapped from numeric `trustType` (1=External Downlevel, 2=Domain Uplevel, 3=MIT Kerberos, 4=DCE) -- **Direction**: Mapped from numeric `trustDirection` (1=Inbound, 2=Outbound, 3=Bidirectional) - -#### Related Tests - -- `Test-MtAdTrustTotalCount` - Overall trust count -- `Test-MtAdTrustInterForestCount` - External trust identification -- `Test-MtAdTrustQuarantinedCount` - SID filtering status -- `Test-MtAdTrustStaleCount` - Trust validation status - - -%TestResult% diff --git a/tests/ad/trust/Test.AD-TRUST-05.ps1 b/tests/ad/trust/Test.AD-TRUST-05.ps1 deleted file mode 100644 index 36aa90b74e..0000000000 --- a/tests/ad/trust/Test.AD-TRUST-05.ps1 +++ /dev/null @@ -1,137 +0,0 @@ -function Test-MtAdTrustDetails { - <# - .SYNOPSIS - Lists detailed information about all Active Directory trusts. - - .DESCRIPTION - This test retrieves comprehensive details about all domain trusts configured - in Active Directory. Trust details include target domain, trust direction, - trust type, SID filtering status, and whether the trust is within the same - forest. Properties are derived from the LDAP trustAttributes bitmask and - trustType numeric values. - - .EXAMPLE - Test-MtAdTrustDetails - - Returns $true if trust data is accessible, $false otherwise. - The test result includes detailed trust configuration information with SID filtering classification. - - .LINK - https://maester.dev/docs/commands/Test-MtAdTrustDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-TRUST-05', - Title = 'Trust configuration details should be investigated', - Product = 'ad', - Feature = 'trusts', - Area = 'external-access', - ResourceType = 'Trust', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:trustedDomain:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdTrustDetails" - - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('Trusts') - - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $trusts = $adState.Trusts - $totalCount = ($trusts | Measure-Object).Count - - # Derive properties from trustAttributes bitmask and trustType - # trustAttributes bits: - # 0x4 = QUARANTINED_DOMAIN (SID filtering enabled on external trusts) - # 0x8 = FOREST_TRANSITIVE (forest trust) - # 0x10 = CROSS_ORGANIZATION (selective authentication) - # 0x20 = WITHIN_FOREST (parent-child intra-forest trust) - # 0x40 = TREAT_AS_EXTERNAL (SID history enabled on forest trusts) - # trustType values: - # 1 = DOWNLEVEL (Windows NT 4 external) - # 2 = UPLEVEL (Windows 2000+ AD domain) - # 3 = MIT (Kerberos realm) - # 4 = DCE - foreach ($trust in $trusts) { - $trustAttributes = [int]$trust.TrustAttributes - $trustType = [int]$trust.TrustType - - $isForest = ($trustAttributes -band 0x8) -ne 0 - $isExternal = -not $isForest -and -not ($trustAttributes -band 0x20) -and ($trustType -in 1,2) - $isMit = ($trustType -eq 3) - $sidFilteringWeak = ($isExternal -and -not ($trustAttributes -band 0x4)) -or - ($isForest -and ($trustAttributes -band 0x40)) - - $trust | Add-Member -NotePropertyName Quarantined -NotePropertyValue (($trustAttributes -band 0x4) -ne 0) -Force - $trust | Add-Member -NotePropertyName IntraForest -NotePropertyValue (($trustAttributes -band 0x20) -ne 0) -Force - $trust | Add-Member -NotePropertyName SelectiveAuthentication -NotePropertyValue (($trustAttributes -band 0x10) -ne 0) -Force - $trust | Add-Member -NotePropertyName IsForest -NotePropertyValue $isForest -Force - $trust | Add-Member -NotePropertyName IsExternal -NotePropertyValue $isExternal -Force - $trust | Add-Member -NotePropertyName IsMit -NotePropertyValue $isMit -Force - $trust | Add-Member -NotePropertyName SidFilteringWeak -NotePropertyValue $sidFilteringWeak -Force - } - - # Test passes if we successfully retrieved trust data - $testResult = $true - - # Generate markdown results - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Trusts | $totalCount |" + "`n" + "`n" - - if ($totalCount -gt 0) { - $result += "### Trust Configuration Details" + "`n" + "`n" - $result += "| Target | Direction | Type | Intra-Forest | Quarantined | Selective Auth |" + "`n" - $result += "| --- | --- | --- | --- | --- | --- |" + "`n" - - foreach ($trust in $trusts) { - $target = $trust.TrustPartner - $direction = switch ([int]$trust.TrustDirection) { - 1 { "Inbound" } - 2 { "Outbound" } - 3 { "Bidirectional" } - default { $trust.TrustDirection } - } - $trustType = switch ([int]$trust.TrustType) { - 1 { "External (Downlevel)" } - 2 { "Domain (Uplevel)" } - 3 { "MIT (Kerberos)" } - 4 { "DCE" } - default { "Type $($trust.TrustType)" } - } - $intraForest = if ($trust.IntraForest) { "Yes" } else { "No" } - $quarantined = if ($trust.Quarantined) { "Yes" } else { "No" } - $selectiveAuth = if ($trust.SelectiveAuthentication) { "Yes" } else { "No" } - $result += "| $target | $direction | $trustType | $intraForest | $quarantined | $selectiveAuth |" + "`n" - } - } - - if ($totalCount -eq 0) { - $testResultMarkdown = "No Active Directory trusts are configured in this domain.`n`n%TestResult%" - } else { - $testResultMarkdown = "Active Directory trust configuration details are listed below.`n`n%TestResult%" - } - - # Only include the table content when findings exist. If there are zero findings, - # omit the table entirely by replacing the placeholder with an empty string. - if ($totalCount -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", "" - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - - return $testResult -} diff --git a/tests/ad/trust/Test.AD-TRUST-06.md b/tests/ad/trust/Test.AD-TRUST-06.md index d1941ff30b..b807cd47e2 100644 --- a/tests/ad/trust/Test.AD-TRUST-06.md +++ b/tests/ad/trust/Test.AD-TRUST-06.md @@ -1,57 +1,11 @@ -Stale trusts (those not validated for extended periods) indicate potential issues: +Inventories **all trusts** with targets, directions, types, validation date/age (or Unknown), and counts known dates older than `StaleThresholdDays` (default 60), unknown dates, and known dates within threshold. -- **Decommissioned Domains**: The target domain may no longer exist -- **Connectivity Issues**: Network problems preventing trust validation -- **Orphaned Trusts**: Trusts created for temporary purposes that were never removed -- **Security Hygiene**: Unused trusts increase attack surface unnecessarily -- **Operational Risk**: Stale trusts may fail unexpectedly when needed +The safe LDAP trust inventory does **not** return `LastValidated`; it has no official persisted last-validation timestamp. Consequently typical runs show unknown status for all trusts. `whenChanged`/`Modified` records object updates, **not** validation. This remains an investigation result, never a pass/fail stale-trust assertion, until a viable trustworthy validation data source exists. Known timestamps, if supplied by a future verified source, are compared against the configured threshold. -Trust validation occurs when the trusting domain attempts to verify the trust relationship with the trusted domain. If this hasn't happened within `StaleThresholdDays` (default 60), it suggests the trust is not actively used. +#### Remediation action -#### Control Type - -**Operational** - -#### Security Recommendation - -**Immediate Actions:** -- Review all stale trusts to determine if they are still needed -- Test connectivity to the target domain -- Verify the target domain still exists - -**Remediation Steps:** -1. **Verify Need**: Confirm if the trust serves a business purpose -2. **Test Connectivity**: Attempt to validate the trust manually -3. **Remove if Unused**: Delete trusts that are no longer needed -4. **Document Exceptions**: For trusts that must remain, document why - -**Command to Validate a Trust:** -```powershell -Test-ADTrust -Target -``` - -**Command to Remove a Trust:** -```powershell -Remove-ADTrust -Target -``` - -#### How the Test Works - -This test checks the `LastValidated` property of each trust. Trusts are considered stale if: -- `LastValidated` is not null -- `LastValidated` is older than `StaleThresholdDays` (default 60) - -The test returns: -- Total trust count -- Count of stale trusts -- Count of trusts with unknown validation status -- Count of valid trusts - -#### Related Tests - -- `Test-MtAdTrustStaleDetails` - Lists specific stale trusts with details -- `Test-MtAdTrustTotalCount` - Overall trust count -- `Test-MtAdTrustDetails` - Complete trust configuration including last validated date +1. Review trust ownership, necessity, and connectivity with domain administrators. +2. Use an independently approved validation procedure to evaluate reachability and document any results; do not substitute trust object modification time or read trust secrets. %TestResult% diff --git a/tests/ad/trust/Test.AD-TRUST-06.ps1 b/tests/ad/trust/Test.AD-TRUST-06.ps1 index 53bd6da540..61523bc44d 100644 --- a/tests/ad/trust/Test.AD-TRUST-06.ps1 +++ b/tests/ad/trust/Test.AD-TRUST-06.ps1 @@ -21,7 +21,7 @@ #> [MaesterTest( Id = 'AD-TRUST-06', - Title = 'Trust stale count should be investigated', + Title = 'Trust validation age and unknown dates should be investigated', Product = 'ad', Feature = 'trusts', Area = 'external-access', @@ -46,24 +46,24 @@ # If unable to retrieve AD data, skip the test if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null + throw 'Active Directory trust inventory was not returned.' } $trusts = $adState.Trusts + if ($null -eq $trusts) { throw 'Active Directory trusts were not returned.' } $totalCount = ($trusts | Measure-Object).Count # Define stale threshold $staleThreshold = (Get-Date).AddDays(-$StaleThresholdDays) # Count stale trusts (those not validated within the configured threshold) - $staleTrusts = $trusts | Where-Object { - $null -ne $_.LastValidated -and $_.LastValidated -lt $staleThreshold - } + $staleTrusts = @($trusts | Where-Object { + $null -ne $_.LastValidated -and [datetime]$_.LastValidated -lt $staleThreshold + }) $staleCount = ($staleTrusts | Measure-Object).Count # Count trusts with unknown validation status (null LastValidated) - $unknownTrusts = $trusts | Where-Object { $null -eq $_.LastValidated } + $unknownTrusts = @($trusts | Where-Object { $null -eq $_.LastValidated }) $unknownCount = ($unknownTrusts | Measure-Object).Count $mostRecentValidation = $trusts | Where-Object { $null -ne $_.LastValidated } | @@ -75,7 +75,7 @@ $mostRecentValidation = $mostRecentValidation.ToString('yyyy-MM-dd') } - # Test passes if we successfully retrieved trust data + # The safe LDAP inventory has no LastValidated field. Never infer validation from whenChanged. $testResult = $true # Generate markdown results @@ -84,18 +84,35 @@ $result += "| Total Trusts | $totalCount |" + "`n" $result += "| Stale Trusts (>$StaleThresholdDays days) | $staleCount |" + "`n" $result += "| Unknown Validation Status | $unknownCount |" + "`n" - $result += "| Valid Trusts | $($totalCount - $staleCount - $unknownCount) |" + "`n" + "`n" + $result += "| Known dates within threshold | $($totalCount - $staleCount - $unknownCount) |" + "`n" + "`n" + if ($totalCount -gt 0) { + $result += "| Target | Direction | Type | Last validated | Days since validation | Assessment |`n" + $result += "| --- | --- | --- | --- | --- | --- |`n" + foreach ($trust in ($trusts | Sort-Object TrustPartner)) { + if ($null -eq $trust.LastValidated) { + $date = 'Unknown' + $days = 'Unknown' + $assessment = 'Cannot assess from LDAP inventory' + } else { + $validated = [datetime]$trust.LastValidated + $date = $validated.ToString('yyyy-MM-dd') + $days = [Math]::Floor(((Get-Date) - $validated).TotalDays) + $assessment = if ($validated -lt $staleThreshold) { 'Older than threshold' } else { 'Within threshold' } + } + $result += "| $($trust.TrustPartner) | $($trust.Direction) | $($trust.TrustTypeName) | $date | $days | $assessment |`n" + } + } if ($totalCount -eq 0) { $testResultMarkdown = "No trusts are configured in this domain. The analysis would change if one or more trusts were created.`n`n%TestResult%" } elseif ($staleCount -eq 0 -and $unknownCount -eq $totalCount) { - $testResultMarkdown = "No stale trusts detected. None of the $totalCount configured trusts has a recorded validation date, so staleness cannot be determined from available data.`n`n%TestResult%" + $testResultMarkdown = "Validation age is unknown for all $totalCount configured trusts. The safe LDAP inventory has no persisted last-validation timestamp; no stale-trust assertion can be made. Do not substitute trust object modification time.`n`n%TestResult%" } elseif ($staleCount -eq 0 -and $unknownCount -gt 0) { - $testResultMarkdown = "No stale trusts detected. $unknownCount trust(s) have an unknown validation status. The remaining $($totalCount - $unknownCount) configured trust(s) have been validated within the last $StaleThresholdDays days. The most recent validation was on $mostRecentValidation.`n`n%TestResult%" + $testResultMarkdown = "No dated trust exceeds $StaleThresholdDays days, but $unknownCount trust(s) have no recorded validation date and cannot be assessed. The most recent known validation date was $mostRecentValidation.`n`n%TestResult%" } elseif ($staleCount -eq 0) { - $testResultMarkdown = "All $totalCount configured trusts have been validated within the last $StaleThresholdDays days. The most recent validation was on $mostRecentValidation.`n`n%TestResult%" + $testResultMarkdown = "All $totalCount trusts with known validation dates fall within $StaleThresholdDays days. The most recent recorded date was $mostRecentValidation.`n`n%TestResult%" } else { - $testResultMarkdown = "Found $staleCount stale trust(s) that have not been validated for more than $StaleThresholdDays days. These trusts should be reviewed and removed if no longer needed.`n`n%TestResult%" + $testResultMarkdown = "Found $staleCount trust(s) with a recorded validation date older than $StaleThresholdDays days; $unknownCount trust(s) remain unassessable. Review the dated records and verify trusts independently.`n`n%TestResult%" } $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result diff --git a/tests/ad/trust/Test.AD-TRUST-07.md b/tests/ad/trust/Test.AD-TRUST-07.md deleted file mode 100644 index 4ffadd6dcf..0000000000 --- a/tests/ad/trust/Test.AD-TRUST-07.md +++ /dev/null @@ -1,66 +0,0 @@ -Identifying specific stale trusts enables targeted remediation: - -- **Prioritization**: Focus cleanup efforts on the oldest, most likely unused trusts -- **Investigation**: Specific target domains can be investigated for existence and need -- **Risk Assessment**: Older trusts may represent higher security risks -- **Documentation**: Detailed stale trust information supports decision-making -- **Compliance**: Demonstrates active trust management for audits - -Stale trusts often accumulate over time as: -- Temporary project trusts are forgotten -- Acquired company domains are decommissioned -- Network restructuring leaves orphaned connections -- Test environments are removed without cleanup - -#### Control Type - -**Operational** - -#### Security Recommendation - -**Investigation Process:** - -1. **Identify Target Domain**: Determine if the target domain still exists -2. **Check Business Need**: Verify if any systems still require the trust -3. **Test Validation**: Attempt manual trust validation -4. **Plan Removal**: Schedule removal if trust is confirmed unused -5. **Document**: Record removal rationale for audit purposes - -**Sample Investigation Commands:** -```powershell -#### Test if the trust can be validated -Test-ADTrust -Target - -#### Check when the trust was created -Get-ADTrust -Filter {Target -eq ""} -Properties Created - -#### View detailed trust information -Get-ADTrust -Filter {Target -eq ""} -Properties * -``` - -**Removal Process:** -- Notify stakeholders before removing production trusts -- Remove during maintenance windows -- Document removal in change management system -- Monitor for any authentication failures after removal - -#### How the Test Works - -This test identifies trusts where `LastValidated` is older than `StaleThresholdDays` (default 60) and displays: - -- Target domain name -- Trust direction -- Last validation date -- Days since last validation -- Trust type - -Results are sorted by last validation date (oldest first). - -#### Related Tests - -- `Test-MtAdTrustStaleCount` - Count of stale trusts -- `Test-MtAdTrustTotalCount` - Overall trust count -- `Test-MtAdTrustDetails` - Complete trust configuration information - - -%TestResult% diff --git a/tests/ad/trust/Test.AD-TRUST-07.ps1 b/tests/ad/trust/Test.AD-TRUST-07.ps1 deleted file mode 100644 index 953b263241..0000000000 --- a/tests/ad/trust/Test.AD-TRUST-07.ps1 +++ /dev/null @@ -1,129 +0,0 @@ -function Test-MtAdTrustStaleDetails { - <# - .SYNOPSIS - Lists detailed information about stale trusts in Active Directory. - - .DESCRIPTION - This test retrieves detailed information about trusts that have not been validated - beyond the configured threshold (default 60 days). Stale trusts may indicate connectivity issues, decommissioned - domains, or trusts that are no longer needed. This test helps identify specific - trusts that should be reviewed and potentially removed to reduce the attack surface. - - .EXAMPLE - Test-MtAdTrustStaleDetails - - Returns $true if trust data is accessible, $false otherwise. - The test result includes details of stale trusts. - - .LINK - https://maester.dev/docs/commands/Test-MtAdTrustStaleDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-TRUST-07', - Title = 'Trust stale details should be investigated', - Product = 'ad', - Feature = 'trusts', - Area = 'external-access', - ResourceType = 'Trust', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:trustedDomain:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param( - # Age, in days, after which a trust is considered stale. - [ValidateRange(1, 3650)] [int] $StaleThresholdDays = 60 - ) - - Write-Verbose "Starting Test-MtAdTrustStaleDetails" - - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('Trusts') - - # If unable to retrieve AD data, skip the test - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $trusts = $adState.Trusts - $totalCount = ($trusts | Measure-Object).Count - - # Define stale threshold - $staleThreshold = (Get-Date).AddDays(-$StaleThresholdDays) - - # Get stale trusts (those not validated within the configured threshold) - $staleTrusts = $trusts | Where-Object { - $null -ne $_.LastValidated -and $_.LastValidated -lt $staleThreshold - } | Sort-Object LastValidated - - $staleCount = ($staleTrusts | Measure-Object).Count - $mostRecentValidation = $trusts | - Where-Object { $null -ne $_.LastValidated } | - Sort-Object LastValidated -Descending | - Select-Object -First 1 -ExpandProperty LastValidated - if ($null -eq $mostRecentValidation) { - $mostRecentValidation = 'unknown' - } else { - $mostRecentValidation = $mostRecentValidation.ToString('yyyy-MM-dd') - } - - # Test passes if we successfully retrieved trust data - $testResult = $true - - # Generate markdown results - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Trusts | $totalCount |" + "`n" - $result += "| Stale Trusts (>$StaleThresholdDays days) | $staleCount |" + "`n" + "`n" - - if ($staleCount -gt 0) { - $result += "### Stale Trust Details" + "`n" + "`n" - $result += "| Target | Direction | Last Validated | Days Since Validation | Type |" + "`n" - $result += "| --- | --- | --- | --- | --- |" + "`n" - - foreach ($trust in $staleTrusts) { - $target = $trust.Target - $direction = $trust.Direction - $lastValidated = $trust.LastValidated - $daysSince = [Math]::Floor(((Get-Date) - $lastValidated).TotalDays) - $trustType = switch ($trust.TrustType) { - "External" { "External" } - "Forest" { "Forest" } - "Kerberos" { "Kerberos" } - default { $trust.TrustType } - } - $result += "| $target | $direction | $($lastValidated.ToString('yyyy-MM-dd')) | $daysSince | $trustType |" + "`n" - } - } - - if ($totalCount -eq 0) { - $testResultMarkdown = "No trusts are configured in this domain. The analysis would change if one or more trusts were created.`n`n%TestResult%" - } elseif ($staleCount -eq 0) { - $knownValidationCount = ($trusts | Where-Object { $null -ne $_.LastValidated } | Measure-Object).Count - if ($knownValidationCount -eq 0) { - $testResultMarkdown = "No stale trusts detected. None of the $totalCount configured trusts has a recorded validation date, so staleness cannot be determined from available data.`n`n%TestResult%" - } elseif ($knownValidationCount -lt $totalCount) { - $unknownCount = $totalCount - $knownValidationCount - $testResultMarkdown = "No stale trusts detected. $unknownCount trust(s) have an unknown validation status. The remaining $knownValidationCount configured trust(s) have been validated within the last $StaleThresholdDays days. The most recent validation was on $mostRecentValidation.`n`n%TestResult%" - } else { - $testResultMarkdown = "All $totalCount configured trusts have been validated within the last $StaleThresholdDays days. The most recent validation was on $mostRecentValidation.`n`n%TestResult%" - } - } else { - $testResultMarkdown = "Found $staleCount stale trust(s) that have not been validated for more than $StaleThresholdDays days. These trusts should be reviewed and removed if the target domain is no longer accessible or needed.`n`n%TestResult%" - } - - if ($totalCount -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", "" - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - - return $testResult -} From ab5001dd266c77c00624add8c4ae597eccad3e02 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 06:23:26 +0000 Subject: [PATCH 020/100] fix(ad): regenerate legacy tag mappings for consolidated checks --- build/golden/Export-MtLegacyTagTable.ps1 | 14 +- build/golden/native-test-replacements.psd1 | 54 +++ powershell/assets/Maester.LegacyTags.json | 425 +++++++++++++----- .../tests/functions/golden/Golden.Tests.ps1 | 9 +- 4 files changed, 381 insertions(+), 121 deletions(-) create mode 100644 build/golden/native-test-replacements.psd1 diff --git a/build/golden/Export-MtLegacyTagTable.ps1 b/build/golden/Export-MtLegacyTagTable.ps1 index 33da8e4eff..4609761d1e 100644 --- a/build/golden/Export-MtLegacyTagTable.ps1 +++ b/build/golden/Export-MtLegacyTagTable.ps1 @@ -8,10 +8,11 @@ -Tag CA, -Tag CIS, -ExcludeTag MS.AAD.3.5 and every other 2.x tag keep selecting the same tests, the module ships a table that maps each 2.x tag to the IDs of the built-in tests that carried it. - The table is derived from two frozen files and nothing else, so the output never changes with tests/: + The table is derived from two frozen files and explicit native test replacements: powershell/tests/fixtures/golden/tags-and-blocks.json the tags of every built-in test in 2.x - powershell/tests/fixtures/golden/tags-3.0-preview.json tags the 3.0 previews added (for example AI) + powershell/tests/fixtures/golden/tags-3.0-preview.json tags the 3.0 previews added (for example AI) + build/golden/native-test-replacements.psd1 intentional renames and consolidations Rules: - A tag is matched case-insensitively; the table keeps the first spelling of the snapshot. @@ -22,7 +23,8 @@ obvious one ($Replacements below, and -Severity for Severity:). The engine names it in the warning it writes when a run selects through the tag. - Tests added after 3.0 are not in the table. The file is generated once and is not edited by hand; + Tests added after 3.0 are not in the table unless they explicitly replace a historical check. + The file is regenerated when native replacements change and is never edited by hand; powershell/tests/functions/golden/Golden.Tests.ps1 checks that it is what this script produces. .EXAMPLE @@ -49,10 +51,8 @@ $ErrorActionPreference = 'Stop' $RepoRoot = (Resolve-Path -Path $RepoRoot).Path $fixtures = Join-Path $RepoRoot 'powershell/tests/fixtures/golden' -# 2.x IDs that have another ID in 3.0. -$RenamedIds = @{ - 'MT1060' = 'MT.1060' # The drift family: four Its per folder in 2.x, one native family in 3.0. -} +# Explicit replacements, never a dynamic filter that could hide an accidental test deletion. +$RenamedIds = Import-PowerShellDataFile -LiteralPath (Join-Path $RepoRoot 'build/golden/native-test-replacements.psd1') # The typed selector that takes the place of a tag. Only tags with an obvious one are listed. $Replacements = [ordered]@{ diff --git a/build/golden/native-test-replacements.psd1 b/build/golden/native-test-replacements.psd1 new file mode 100644 index 0000000000..969a96f8f0 --- /dev/null +++ b/build/golden/native-test-replacements.psd1 @@ -0,0 +1,54 @@ +@{ + # Explicit native test consolidations. Frozen 2.x tags select these surviving checks. + 'MT1060' = 'MT.1060' + 'AD-CFG-01' = 'AD-FOR-03' + 'AD-CFG-04' = 'AD-FEAT-01' + 'AD-CFG-05' = 'AD-FOR-04' + 'AD-COMP-02' = 'AD-DCOMP-06' + 'AD-COMP-09' = 'AD-DCOMP-01' + 'AD-COMP-10' = 'AD-DCOMP-03' + 'AD-DACL-04' = 'AD-DACL-03' + 'AD-DACL-06' = 'AD-DACL-05' + 'AD-DACL-08' = 'AD-DACL-07' + 'AD-DACL-10' = 'AD-DACL-09' + 'AD-DACL-12' = 'AD-DACL-11' + 'AD-DACL-13' = 'AD-DACL-11' + 'AD-DACL-16' = 'AD-DACL-15' + 'AD-DACL-18' = 'AD-DACL-17' + 'AD-DCOMP-02' = 'AD-DCOMP-01' + 'AD-DCOMP-05' = 'AD-DCOMP-04' + 'AD-DCOMP-09' = 'AD-DCOMP-08' + 'AD-FEAT-02' = 'AD-FEAT-01' + 'AD-GMC-03' = 'AD-GMC-02' + 'AD-GMC-05' = 'AD-GMC-04' + 'AD-GMC-07' = 'AD-GMC-06' + 'AD-GMC-09' = 'AD-GMC-08' + 'AD-GMC-11' = 'AD-GMC-10' + 'AD-GPO-03' = 'AD-GPO-02' + 'AD-GPO-05' = 'AD-GPO-04' + 'AD-GPOL-06' = 'AD-GPOL-03' + 'AD-GPOREP-02' = 'AD-GPOREP-01' + 'AD-GPOREP-04' = 'AD-GPOREP-03' + 'AD-GPOREP-08' = 'AD-GPOREP-07' + 'AD-GPOREP-11' = 'AD-GPOREP-10' + 'AD-GPOREP-13' = 'AD-GPOREP-12' + 'AD-GPOREP-16' = 'AD-GPOREP-15' + 'AD-GPOREP-18' = 'AD-GPOREP-17' + 'AD-GPOREP-19' = 'AD-GPOREP-17' + 'AD-GPOREP-20' = 'AD-GPOREP-17' + 'AD-GRP-07' = 'AD-GRP-06' + 'AD-GRP-09' = 'AD-GRP-08' + 'AD-GRP-10' = 'AD-GRP-08' + 'AD-ROOTDSE-02' = 'AD-ROOTDSE-01' + 'AD-SCH-02' = 'AD-SCH-01' + 'AD-SCH-04' = 'AD-SCH-03' + 'AD-SPN-02' = 'AD-SPN-01' + 'AD-SPN-04' = 'AD-SPN-03' + 'AD-SPN-08' = 'AD-SPN-07' + 'AD-SPN-10' = 'AD-SPN-09' + 'AD-SPN-13' = 'AD-SPN-12' + 'AD-TRUST-04' = 'AD-TRUST-03' + 'AD-TRUST-05' = 'AD-TRUST-01' + 'AD-TRUST-07' = 'AD-TRUST-06' + 'AD-USER-14' = 'AD-SPN-06' +} diff --git a/powershell/assets/Maester.LegacyTags.json b/powershell/assets/Maester.LegacyTags.json index 2ba8db3c4b..1ea37aa45f 100644 --- a/powershell/assets/Maester.LegacyTags.json +++ b/powershell/assets/Maester.LegacyTags.json @@ -16,11 +16,8 @@ "Tag": "AD", "Replacement": "-Product ad", "Tests": [ - "AD-CFG-01", "AD-CFG-02", "AD-CFG-03", - "AD-CFG-04", - "AD-CFG-05", "AD-CFG-06", "AD-CFG-07", "AD-CFG-08", @@ -41,33 +38,22 @@ "AD-CFG-23", "AD-CFG-24", "AD-COMP-01", - "AD-COMP-02", "AD-COMP-03", "AD-COMP-04", "AD-COMP-05", "AD-COMP-06", "AD-COMP-07", "AD-COMP-08", - "AD-COMP-09", - "AD-COMP-10", "AD-DACL-01", "AD-DACL-02", "AD-DACL-03", - "AD-DACL-04", "AD-DACL-05", - "AD-DACL-06", "AD-DACL-07", - "AD-DACL-08", "AD-DACL-09", - "AD-DACL-10", "AD-DACL-11", - "AD-DACL-12", - "AD-DACL-13", "AD-DACL-14", "AD-DACL-15", - "AD-DACL-16", "AD-DACL-17", - "AD-DACL-18", "AD-DC-01", "AD-DC-02", "AD-DC-03", @@ -81,14 +67,11 @@ "AD-DCD-03", "AD-DCD-04", "AD-DCOMP-01", - "AD-DCOMP-02", "AD-DCOMP-03", "AD-DCOMP-04", - "AD-DCOMP-05", "AD-DCOMP-06", "AD-DCOMP-07", "AD-DCOMP-08", - "AD-DCOMP-09", "AD-DFSR-01", "AD-DNS-01", "AD-DNS-02", @@ -119,7 +102,6 @@ "AD-DOM-08", "AD-DOMS-01", "AD-FEAT-01", - "AD-FEAT-02", "AD-FGPP-01", "AD-FGPP-02", "AD-FGPP-03", @@ -135,46 +117,29 @@ "AD-GCHG-01", "AD-GMC-01", "AD-GMC-02", - "AD-GMC-03", "AD-GMC-04", - "AD-GMC-05", "AD-GMC-06", - "AD-GMC-07", "AD-GMC-08", - "AD-GMC-09", "AD-GMC-10", - "AD-GMC-11", "AD-GPO-01", "AD-GPO-02", - "AD-GPO-03", "AD-GPO-04", - "AD-GPO-05", "AD-GPOL-01", "AD-GPOL-02", "AD-GPOL-03", "AD-GPOL-04", "AD-GPOL-05", - "AD-GPOL-06", "AD-GPOREP-01", - "AD-GPOREP-02", "AD-GPOREP-03", - "AD-GPOREP-04", "AD-GPOREP-05", "AD-GPOREP-06", "AD-GPOREP-07", - "AD-GPOREP-08", "AD-GPOREP-09", "AD-GPOREP-10", - "AD-GPOREP-11", "AD-GPOREP-12", - "AD-GPOREP-13", "AD-GPOREP-14", "AD-GPOREP-15", - "AD-GPOREP-16", "AD-GPOREP-17", - "AD-GPOREP-18", - "AD-GPOREP-19", - "AD-GPOREP-20", "AD-GPOS-01", "AD-GPOS-02", "AD-GPOS-03", @@ -190,10 +155,7 @@ "AD-GRP-04", "AD-GRP-05", "AD-GRP-06", - "AD-GRP-07", "AD-GRP-08", - "AD-GRP-09", - "AD-GRP-10", "AD-KRBTGT-01", "AD-KRBTGT-02", "AD-KRBTGT-03", @@ -214,12 +176,9 @@ "AD-REPL-01", "AD-REPL-02", "AD-ROOTDSE-01", - "AD-ROOTDSE-02", "AD-ROOTDSE-03", "AD-SCH-01", - "AD-SCH-02", "AD-SCH-03", - "AD-SCH-04", "AD-SCH-05", "AD-SITE-01", "AD-SITE-02", @@ -227,18 +186,13 @@ "AD-SITE-04", "AD-SITE-05", "AD-SPN-01", - "AD-SPN-02", "AD-SPN-03", - "AD-SPN-04", "AD-SPN-05", "AD-SPN-06", "AD-SPN-07", - "AD-SPN-08", "AD-SPN-09", - "AD-SPN-10", "AD-SPN-11", "AD-SPN-12", - "AD-SPN-13", "AD-SUB-01", "AD-SUB-02", "AD-SUB-03", @@ -253,10 +207,7 @@ "AD-TRUST-01", "AD-TRUST-02", "AD-TRUST-03", - "AD-TRUST-04", - "AD-TRUST-05", "AD-TRUST-06", - "AD-TRUST-07", "AD-USER-01", "AD-USER-02", "AD-USER-03", @@ -270,7 +221,6 @@ "AD-USER-11", "AD-USER-12", "AD-USER-13", - "AD-USER-14", "AD-USER-15", "AD-USER-16", "AD-USER-17", @@ -288,29 +238,326 @@ "AD-USER-29" ] }, + { + "Tag": "AD-CFG-01", + "Tests": [ + "AD-FOR-03" + ] + }, + { + "Tag": "AD-CFG-04", + "Tests": [ + "AD-FEAT-01" + ] + }, + { + "Tag": "AD-CFG-05", + "Tests": [ + "AD-FOR-04" + ] + }, + { + "Tag": "AD-COMP-02", + "Tests": [ + "AD-DCOMP-06" + ] + }, + { + "Tag": "AD-COMP-09", + "Tests": [ + "AD-DCOMP-01" + ] + }, + { + "Tag": "AD-COMP-10", + "Tests": [ + "AD-DCOMP-03" + ] + }, + { + "Tag": "AD-DACL-04", + "Tests": [ + "AD-DACL-03" + ] + }, + { + "Tag": "AD-DACL-06", + "Tests": [ + "AD-DACL-05" + ] + }, + { + "Tag": "AD-DACL-08", + "Tests": [ + "AD-DACL-07" + ] + }, + { + "Tag": "AD-DACL-10", + "Tests": [ + "AD-DACL-09" + ] + }, + { + "Tag": "AD-DACL-12", + "Tests": [ + "AD-DACL-11" + ] + }, + { + "Tag": "AD-DACL-13", + "Tests": [ + "AD-DACL-11" + ] + }, + { + "Tag": "AD-DACL-16", + "Tests": [ + "AD-DACL-15" + ] + }, + { + "Tag": "AD-DACL-18", + "Tests": [ + "AD-DACL-17" + ] + }, + { + "Tag": "AD-DCOMP-02", + "Tests": [ + "AD-DCOMP-01" + ] + }, + { + "Tag": "AD-DCOMP-05", + "Tests": [ + "AD-DCOMP-04" + ] + }, + { + "Tag": "AD-DCOMP-09", + "Tests": [ + "AD-DCOMP-08" + ] + }, + { + "Tag": "AD-FEAT-02", + "Tests": [ + "AD-FEAT-01" + ] + }, + { + "Tag": "AD-GMC-03", + "Tests": [ + "AD-GMC-02" + ] + }, + { + "Tag": "AD-GMC-05", + "Tests": [ + "AD-GMC-04" + ] + }, + { + "Tag": "AD-GMC-07", + "Tests": [ + "AD-GMC-06" + ] + }, + { + "Tag": "AD-GMC-09", + "Tests": [ + "AD-GMC-08" + ] + }, + { + "Tag": "AD-GMC-11", + "Tests": [ + "AD-GMC-10" + ] + }, + { + "Tag": "AD-GPO-03", + "Tests": [ + "AD-GPO-02" + ] + }, + { + "Tag": "AD-GPO-05", + "Tests": [ + "AD-GPO-04" + ] + }, + { + "Tag": "AD-GPOL-06", + "Tests": [ + "AD-GPOL-03" + ] + }, + { + "Tag": "AD-GPOREP-02", + "Tests": [ + "AD-GPOREP-01" + ] + }, + { + "Tag": "AD-GPOREP-04", + "Tests": [ + "AD-GPOREP-03" + ] + }, + { + "Tag": "AD-GPOREP-08", + "Tests": [ + "AD-GPOREP-07" + ] + }, + { + "Tag": "AD-GPOREP-11", + "Tests": [ + "AD-GPOREP-10" + ] + }, + { + "Tag": "AD-GPOREP-13", + "Tests": [ + "AD-GPOREP-12" + ] + }, + { + "Tag": "AD-GPOREP-16", + "Tests": [ + "AD-GPOREP-15" + ] + }, + { + "Tag": "AD-GPOREP-18", + "Tests": [ + "AD-GPOREP-17" + ] + }, + { + "Tag": "AD-GPOREP-19", + "Tests": [ + "AD-GPOREP-17" + ] + }, + { + "Tag": "AD-GPOREP-20", + "Tests": [ + "AD-GPOREP-17" + ] + }, + { + "Tag": "AD-GRP-07", + "Tests": [ + "AD-GRP-06" + ] + }, + { + "Tag": "AD-GRP-09", + "Tests": [ + "AD-GRP-08" + ] + }, + { + "Tag": "AD-GRP-10", + "Tests": [ + "AD-GRP-08" + ] + }, + { + "Tag": "AD-ROOTDSE-02", + "Tests": [ + "AD-ROOTDSE-01" + ] + }, + { + "Tag": "AD-SCH-02", + "Tests": [ + "AD-SCH-01" + ] + }, + { + "Tag": "AD-SCH-04", + "Tests": [ + "AD-SCH-03" + ] + }, + { + "Tag": "AD-SPN-02", + "Tests": [ + "AD-SPN-01" + ] + }, + { + "Tag": "AD-SPN-04", + "Tests": [ + "AD-SPN-03" + ] + }, + { + "Tag": "AD-SPN-08", + "Tests": [ + "AD-SPN-07" + ] + }, + { + "Tag": "AD-SPN-10", + "Tests": [ + "AD-SPN-09" + ] + }, + { + "Tag": "AD-SPN-13", + "Tests": [ + "AD-SPN-12" + ] + }, + { + "Tag": "AD-TRUST-04", + "Tests": [ + "AD-TRUST-03" + ] + }, + { + "Tag": "AD-TRUST-05", + "Tests": [ + "AD-TRUST-01" + ] + }, + { + "Tag": "AD-TRUST-07", + "Tests": [ + "AD-TRUST-06" + ] + }, + { + "Tag": "AD-USER-14", + "Tests": [ + "AD-SPN-06" + ] + }, { "Tag": "AD.Computer", "Tests": [ "AD-COMP-01", - "AD-COMP-02", "AD-COMP-03", "AD-COMP-04", "AD-COMP-05", "AD-COMP-06", "AD-COMP-07", "AD-COMP-08", - "AD-COMP-09", - "AD-COMP-10" + "AD-DCOMP-01", + "AD-DCOMP-03", + "AD-DCOMP-06" ] }, { "Tag": "AD.Config", "Tests": [ - "AD-CFG-01", "AD-CFG-02", "AD-CFG-03", - "AD-CFG-04", - "AD-CFG-05", "AD-CFG-06", "AD-CFG-07", "AD-CFG-08", @@ -329,7 +576,10 @@ "AD-CFG-21", "AD-CFG-22", "AD-CFG-23", - "AD-CFG-24" + "AD-CFG-24", + "AD-FEAT-01", + "AD-FOR-03", + "AD-FOR-04" ] }, { @@ -338,21 +588,13 @@ "AD-DACL-01", "AD-DACL-02", "AD-DACL-03", - "AD-DACL-04", "AD-DACL-05", - "AD-DACL-06", "AD-DACL-07", - "AD-DACL-08", "AD-DACL-09", - "AD-DACL-10", "AD-DACL-11", - "AD-DACL-12", - "AD-DACL-13", "AD-DACL-14", "AD-DACL-15", - "AD-DACL-16", - "AD-DACL-17", - "AD-DACL-18" + "AD-DACL-17" ] }, { @@ -432,11 +674,9 @@ { "Tag": "AD.GMC", "Tests": [ - "AD-GMC-07", + "AD-GMC-06", "AD-GMC-08", - "AD-GMC-09", - "AD-GMC-10", - "AD-GMC-11" + "AD-GMC-10" ] }, { @@ -444,40 +684,28 @@ "Tests": [ "AD-GPO-01", "AD-GPO-02", - "AD-GPO-03", "AD-GPO-04", - "AD-GPO-05", "AD-GPOL-01", "AD-GPOL-02", "AD-GPOL-03", "AD-GPOL-04", - "AD-GPOL-05", - "AD-GPOL-06" + "AD-GPOL-05" ] }, { "Tag": "AD.GPOState", "Tests": [ "AD-GPOREP-01", - "AD-GPOREP-02", "AD-GPOREP-03", - "AD-GPOREP-04", "AD-GPOREP-05", "AD-GPOREP-06", "AD-GPOREP-07", - "AD-GPOREP-08", "AD-GPOREP-09", "AD-GPOREP-10", - "AD-GPOREP-11", "AD-GPOREP-12", - "AD-GPOREP-13", "AD-GPOREP-14", "AD-GPOREP-15", - "AD-GPOREP-16", "AD-GPOREP-17", - "AD-GPOREP-18", - "AD-GPOREP-19", - "AD-GPOREP-20", "AD-GPOS-01", "AD-GPOS-02", "AD-GPOS-03", @@ -495,25 +723,17 @@ "AD-GCHG-01", "AD-GMC-01", "AD-GMC-02", - "AD-GMC-03", "AD-GMC-04", - "AD-GMC-05", "AD-GMC-06", - "AD-GMC-07", "AD-GMC-08", - "AD-GMC-09", "AD-GMC-10", - "AD-GMC-11", "AD-GRP-01", "AD-GRP-02", "AD-GRP-03", "AD-GRP-04", "AD-GRP-05", "AD-GRP-06", - "AD-GRP-07", - "AD-GRP-08", - "AD-GRP-09", - "AD-GRP-10" + "AD-GRP-08" ] }, { @@ -553,11 +773,9 @@ "Tests": [ "AD-DFSR-01", "AD-FEAT-01", - "AD-FEAT-02", "AD-REPL-01", "AD-REPL-02", "AD-ROOTDSE-01", - "AD-ROOTDSE-02", "AD-ROOTDSE-03" ] }, @@ -565,9 +783,7 @@ "Tag": "AD.Schema", "Tests": [ "AD-SCH-01", - "AD-SCH-02", "AD-SCH-03", - "AD-SCH-04", "AD-SCH-05" ] }, @@ -575,14 +791,11 @@ "Tag": "AD.Security", "Tests": [ "AD-DCOMP-01", - "AD-DCOMP-02", "AD-DCOMP-03", "AD-DCOMP-04", - "AD-DCOMP-05", "AD-DCOMP-06", "AD-DCOMP-07", "AD-DCOMP-08", - "AD-DCOMP-09", "AD-KRBTGT-01", "AD-KRBTGT-02", "AD-KRBTGT-03", @@ -614,18 +827,13 @@ "Tag": "AD.SPN", "Tests": [ "AD-SPN-01", - "AD-SPN-02", "AD-SPN-03", - "AD-SPN-04", "AD-SPN-05", "AD-SPN-06", "AD-SPN-07", - "AD-SPN-08", "AD-SPN-09", - "AD-SPN-10", "AD-SPN-11", - "AD-SPN-12", - "AD-SPN-13" + "AD-SPN-12" ] }, { @@ -634,15 +842,13 @@ "AD-TRUST-01", "AD-TRUST-02", "AD-TRUST-03", - "AD-TRUST-04", - "AD-TRUST-05", - "AD-TRUST-06", - "AD-TRUST-07" + "AD-TRUST-06" ] }, { "Tag": "AD.User", "Tests": [ + "AD-SPN-06", "AD-USER-01", "AD-USER-02", "AD-USER-03", @@ -656,7 +862,6 @@ "AD-USER-11", "AD-USER-12", "AD-USER-13", - "AD-USER-14", "AD-USER-15", "AD-USER-16", "AD-USER-17", diff --git a/powershell/tests/functions/golden/Golden.Tests.ps1 b/powershell/tests/functions/golden/Golden.Tests.ps1 index 744d5aebe5..eeb60326ba 100644 --- a/powershell/tests/functions/golden/Golden.Tests.ps1 +++ b/powershell/tests/functions/golden/Golden.Tests.ps1 @@ -56,10 +56,9 @@ Describe 'Maester 2.x golden fixtures' -Tag 'Golden' { BeforeAll { # tags-and-blocks.json is the frozen 2.x snapshot. In 3.0 the built-in tests carry no taxonomy # tags, and Block and the tags on a result row changed on purpose, so neither is compared any - # more. What must hold is that every 2.x tag still selects exactly the tests it selected: not - # fewer, and not more, so a new test must not take a 2.x tag as one of its own tags. - # MT1060 (drift) became the native family MT.1060: its four 2.x Its are one test. - $script:renamedIds = @{ 'MT1060' = 'MT.1060' } + # more. Every 2.x tag selects the same tests, except for explicit native replacements. + # This registry preserves consolidation intent without filtering out accidental deletions. + $script:renamedIds = Import-PowerShellDataFile -LiteralPath (Join-Path $repoRoot 'build/golden/native-test-replacements.psd1') $toSet = { param($entries) $byTag = [System.Collections.Generic.Dictionary[string, System.Collections.Generic.SortedSet[string]]]::new([System.StringComparer]::OrdinalIgnoreCase) @@ -125,6 +124,8 @@ Describe 'Maester 2.x golden fixtures' -Tag 'Golden' { $ids = [System.Collections.Generic.HashSet[string]]::new([string[]]@($script:fresh | ForEach-Object { $_.Id }), [System.StringComparer]::OrdinalIgnoreCase) $missing = @($table.Tags | ForEach-Object { $_.Tests } | Where-Object { -not $ids.Contains($_) } | Select-Object -Unique) $missing | Should -BeNullOrEmpty + @($script:renamedIds.Values | Where-Object { -not $ids.Contains($_) }) | Should -BeNullOrEmpty -Because 'each explicit replacement must have a surviving native test' + @($script:renamedIds.Keys | Where-Object { $ids.Contains($_) }) | Should -BeNullOrEmpty -Because 'a replaced ID must no longer have its own test' $replacement = @{} foreach ($entry in $table.Tags) { if ($entry.PSObject.Properties['Replacement']) { $replacement[$entry.Tag] = $entry.Replacement } } $replacement['CA'] | Should -Be '-Feature conditional-access' From 56ca3818e3f446c5bdc9c87e90a4d7f3d1a01074 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 14:26:36 +0000 Subject: [PATCH 021/100] fix(ad): restore managed account delegation and verify DC identities --- .../ad/Test-MtAdDomainControllerAccount.ps1 | 38 +++++++++++ .../ad/queries/Get-MtLdapServiceAccount.ps1 | 14 ++++- .../functions/ADCollectorQueries.Tests.ps1 | 6 +- .../functions/ADComputerChecks.Tests.ps1 | 63 ++++++++++++++++--- tests/ad/computer/Test.AD-COMP-04.md | 2 +- tests/ad/computer/Test.AD-COMP-04.ps1 | 28 ++++++--- tests/ad/security/Test.AD-DCOMP-01.md | 6 +- tests/ad/security/Test.AD-DCOMP-01.ps1 | 41 ++++++------ tests/ad/security/Test.AD-DCOMP-03.md | 4 +- tests/ad/security/Test.AD-DCOMP-03.ps1 | 59 ++++++++--------- 10 files changed, 182 insertions(+), 79 deletions(-) create mode 100644 powershell/internal/services/ad/Test-MtAdDomainControllerAccount.ps1 diff --git a/powershell/internal/services/ad/Test-MtAdDomainControllerAccount.ps1 b/powershell/internal/services/ad/Test-MtAdDomainControllerAccount.ps1 new file mode 100644 index 0000000000..9648e13ac3 --- /dev/null +++ b/powershell/internal/services/ad/Test-MtAdDomainControllerAccount.ps1 @@ -0,0 +1,38 @@ +function Test-MtAdDomainControllerAccount { + <# + .SYNOPSIS + Identifies a DC account from the collected directory server inventory. + + .DESCRIPTION + Uses serverReference distinguished names, with DNS fallback only for inventory + entries lacking serverReference. A claimed DC primary group is not DC evidence. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [object] $Account, + + [Parameter(Mandatory)] + [object[]] $DomainControllers + ) + + if ([string]::IsNullOrWhiteSpace([string]$Account.DistinguishedName)) { + throw 'Account distinguished name is unavailable; DC identity cannot be verified.' + } + if (@($Account.ObjectClass | Where-Object { $_ -in 'msDS-ManagedServiceAccount', 'msDS-GroupManagedServiceAccount', 'msDS-DelegatedManagedServiceAccount' }).Count -gt 0) { + return $false + } + foreach ($dc in $DomainControllers) { + if (-not $dc.ServerReference -and -not $dc.DnsHostName) { + throw 'DC inventory lacks serverReference and DNS identity; DC exclusions cannot be verified.' + } + if ($dc.ServerReference) { + if ([string]$dc.ServerReference -eq [string]$Account.DistinguishedName) { return $true } + } + elseif ($Account.DnsHostName -and ([string]$dc.DnsHostName).TrimEnd('.') -eq ([string]$Account.DnsHostName).TrimEnd('.')) { + return $true + } + } + return $false +} diff --git a/powershell/internal/services/ad/queries/Get-MtLdapServiceAccount.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapServiceAccount.ps1 index 42a12bbe96..01870d6947 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapServiceAccount.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapServiceAccount.ps1 @@ -9,7 +9,17 @@ ) if ([string]::IsNullOrWhiteSpace($SearchBase)) { $SearchBase = (Get-MtLdapRootDse -Connection $Connection).DefaultNamingContext } - $attributes = @('distinguishedName', 'name', 'sAMAccountName', 'dNSHostName', 'whenCreated', 'whenChanged', 'objectSid', 'objectClass', 'msDS-DelegatedMSAState') + $attributes = @('distinguishedName', 'name', 'sAMAccountName', 'dNSHostName', 'whenCreated', 'whenChanged', 'objectSid', 'objectClass', 'msDS-DelegatedMSAState', 'userAccountControl', 'msDS-AllowedToDelegateTo', 'msDS-AllowedToActOnBehalfOfOtherIdentity') $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter '(|(objectClass=msDS-ManagedServiceAccount)(objectClass=msDS-GroupManagedServiceAccount)(objectClass=msDS-DelegatedManagedServiceAccount))' -Attributes $attributes) - return @($entries | ForEach-Object { [PSCustomObject]@{ DistinguishedName = [string]$_.DistinguishedName; Name = [string]$_.name; SamAccountName = [string]$_.sAMAccountName; DnsHostName = [string]$_.dNSHostName; Created = $_.whenCreated; Modified = $_.whenChanged; Sid = $_.objectSid; ObjectClass = @($_.objectClass); DelegatedMsaState = $_.'msDS-DelegatedMSAState' } }) + return @($entries | ForEach-Object { + $uac = if ($null -ne $_.userAccountControl) { ConvertFrom-MtLdapUserAccountControl -UserAccountControl ([int]$_.userAccountControl) } else { $null } + [PSCustomObject]@{ + DistinguishedName = [string]$_.DistinguishedName; Name = [string]$_.name; SamAccountName = [string]$_.sAMAccountName; DnsHostName = [string]$_.dNSHostName + Created = $_.whenCreated; Modified = $_.whenChanged; Sid = $_.objectSid; ObjectClass = @($_.objectClass); DelegatedMsaState = $_.'msDS-DelegatedMSAState' + TrustedForDelegation = if ($null -ne $uac) { $uac.TrustedForDelegation } else { $null } + TrustedToAuthForDelegation = if ($null -ne $uac) { $uac.TrustedToAuthForDelegation } else { $null } + AllowedToDelegateTo = [string[]]@($_.'msDS-AllowedToDelegateTo' | Where-Object { $null -ne $_ }) + HasResourceBasedConstrainedDelegation = $null -ne $_.'msDS-AllowedToActOnBehalfOfOtherIdentity' + } + }) } diff --git a/powershell/tests/functions/ADCollectorQueries.Tests.ps1 b/powershell/tests/functions/ADCollectorQueries.Tests.ps1 index c393081edb..d93b2af2de 100644 --- a/powershell/tests/functions/ADCollectorQueries.Tests.ps1 +++ b/powershell/tests/functions/ADCollectorQueries.Tests.ps1 @@ -25,7 +25,7 @@ Describe 'AD query normalization for consolidated checks' { It 'collects all three managed service account classes without requesting passwords' { Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { - [pscustomobject]@{ name = 'Delegated'; objectClass = @('computer', 'msDS-DelegatedManagedServiceAccount'); 'msDS-DelegatedMSAState' = 2 } + [pscustomobject]@{ name = 'Delegated'; objectClass = @('computer', 'msDS-DelegatedManagedServiceAccount'); 'msDS-DelegatedMSAState' = 2; userAccountControl = 17301504; 'msDS-AllowedToDelegateTo' = @('HTTP/managed'); 'msDS-AllowedToActOnBehalfOfOtherIdentity' = [byte[]]@(1, 2, 3) } } InModuleScope Maester { $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') @@ -33,6 +33,10 @@ Describe 'AD query normalization for consolidated checks' { $accounts = @(Get-MtLdapServiceAccount -Connection $connection -SearchBase 'DC=example,DC=com') $accounts[0].ObjectClass | Should -Contain 'msDS-DelegatedManagedServiceAccount' $accounts[0].DelegatedMsaState | Should -Be 2 + $accounts[0].TrustedForDelegation | Should -BeTrue + $accounts[0].TrustedToAuthForDelegation | Should -BeTrue + $accounts[0].AllowedToDelegateTo | Should -Contain 'HTTP/managed' + $accounts[0].HasResourceBasedConstrainedDelegation | Should -BeTrue } finally { $connection.Dispose() } } diff --git a/powershell/tests/functions/ADComputerChecks.Tests.ps1 b/powershell/tests/functions/ADComputerChecks.Tests.ps1 index a8344ea29b..7a58ad243f 100644 --- a/powershell/tests/functions/ADComputerChecks.Tests.ps1 +++ b/powershell/tests/functions/ADComputerChecks.Tests.ps1 @@ -9,6 +9,7 @@ 'Test-MtAdComputerPerOUAverage' 'Test-MtAdComputerCreatorSidCount' 'Test-MtAdComputerInDefaultContainer' + 'Test-MtAdComputerNonStandardGroup' ) } @@ -21,6 +22,7 @@ [PSCustomObject]@{ Name = 'client'; DistinguishedName = 'CN=client,OU=Clients,DC=example,DC=com'; DnsHostName = 'client.example.com'; PrimaryGroupId = 515; Enabled = $true; TrustedForDelegation = $false; TrustedToAuthForDelegation = $false; AllowedToDelegateTo = @(); HasResourceBasedConstrainedDelegation = $false; OperatingSystem = 'Client' } ) DomainControllers = @([PSCustomObject]@{ Name = 'dc1'; ServerReference = 'CN=dc1,OU=Domain Controllers,DC=example,DC=com'; DnsHostName = 'dc1.example.com' }) + ServiceAccounts = @() } Mock -ModuleName Maester Get-MtADDomainState { $script:AdComputerState } Mock -ModuleName Maester Add-MtTestResultDetail { param($Result, [switch] $Investigate) $script:Details = [PSCustomObject]@{ Text = $Result; Investigate = $Investigate.IsPresent } } @@ -40,19 +42,19 @@ It 'inventories classic KCD, protocol transition, and RBCD descriptor presence independently' { Test-MtAdComputerNonDcConstrainedDelegationCount | Should -BeTrue $script:Details.Investigate | Should -BeTrue - $script:Details.Text | Should -BeLike '*| Non-DC Computers with Classic KCD Target SPNs | 1 |*' - $script:Details.Text | Should -BeLike '*| Non-DC Computers with Protocol Transition Flag | 1 |*' - $script:Details.Text | Should -BeLike '*| Non-DC Computers with RBCD Descriptor Present | 1 |*' - $script:Details.Text | Should -BeLike '*| Distinct Non-DC Computers with One or More Indicators | 1 |*' + $script:Details.Text | Should -BeLike '*| Non-DC Accounts with Classic KCD Target SPNs | 1 |*' + $script:Details.Text | Should -BeLike '*| Non-DC Accounts with Protocol Transition Flag | 1 |*' + $script:Details.Text | Should -BeLike '*| Non-DC Accounts with RBCD Descriptor Present | 1 |*' + $script:Details.Text | Should -BeLike '*| Distinct Non-DC Accounts with One or More Indicators | 1 |*' $script:Details.Text | Should -Match 'HTTP/backend\\\|one' $script:AdComputerState.Computers[1].TrustedToAuthForDelegation = $false $script:AdComputerState.Computers[2].HasResourceBasedConstrainedDelegation = $true Test-MtAdComputerNonDcConstrainedDelegationCount | Should -BeTrue - $script:Details.Text | Should -BeLike '*| Non-DC Computers with Classic KCD Target SPNs | 1 |*' - $script:Details.Text | Should -BeLike '*| Non-DC Computers with Protocol Transition Flag | 0 |*' - $script:Details.Text | Should -BeLike '*| Non-DC Computers with RBCD Descriptor Present | 2 |*' - $script:Details.Text | Should -BeLike '*| Distinct Non-DC Computers with One or More Indicators | 2 |*' + $script:Details.Text | Should -BeLike '*| Non-DC Accounts with Classic KCD Target SPNs | 1 |*' + $script:Details.Text | Should -BeLike '*| Non-DC Accounts with Protocol Transition Flag | 0 |*' + $script:Details.Text | Should -BeLike '*| Non-DC Accounts with RBCD Descriptor Present | 2 |*' + $script:Details.Text | Should -BeLike '*| Distinct Non-DC Accounts with One or More Indicators | 2 |*' } It 'does not treat missing delegation metadata as a clean result' { @@ -67,10 +69,11 @@ { Test-MtAdComputerNonDcConstrainedDelegationCount } | Should -Throw '*Required delegation fields*' } - It 'excludes RODCs by primary group and DCs by DNS identity rather than a matching short name' { + It 'excludes RODCs by server inventory and DCs by DNS fallback, not a claimed primary group' { $script:AdComputerState.Computers += [PSCustomObject]@{ Name = 'rodc-other'; DistinguishedName = 'CN=rodc-other,DC=example,DC=com'; DnsHostName = 'rodc-other.example.com'; PrimaryGroupId = 521; TrustedForDelegation = $true; TrustedToAuthForDelegation = $true; AllowedToDelegateTo = @('HTTP/dc'); HasResourceBasedConstrainedDelegation = $true } $script:AdComputerState.Computers += [PSCustomObject]@{ Name = 'dc-alias'; DistinguishedName = 'CN=dc-alias,DC=example,DC=com'; DnsHostName = 'SECOND.example.com'; PrimaryGroupId = 515; TrustedForDelegation = $true; TrustedToAuthForDelegation = $true; AllowedToDelegateTo = @('HTTP/dc'); HasResourceBasedConstrainedDelegation = $true } $script:AdComputerState.DomainControllers += [PSCustomObject]@{ Name = 'different-short-name'; ServerReference = ''; DnsHostName = 'second.EXAMPLE.com' } + $script:AdComputerState.DomainControllers += [PSCustomObject]@{ Name = 'rodc-other'; ServerReference = 'CN=rodc-other,DC=example,DC=com'; DnsHostName = 'rodc-other.example.com' } Test-MtAdComputerUnconstrainedDelegationCount | Should -BeTrue $script:Details.Text | Should -BeLike '*| Total Non-DC Computers | 2 |*' @@ -120,4 +123,46 @@ Test-MtAdComputerInDefaultContainer | Should -BeFalse $script:Details.Text | Should -BeLike '*| In Default Computers Container | 1 |*' } + + It 'does not exclude a non-DC account claiming primary group ' -ForEach @(@{ Group = 516 }, @{ Group = 521 }) { + $script:AdComputerState.Computers[2].PrimaryGroupId = $Group + $script:AdComputerState.Computers[2].TrustedForDelegation = $true + Test-MtAdComputerUnconstrainedDelegationCount | Should -BeFalse + $script:Details.Text | Should -BeLike '*| Total Non-DC Computers | 2 |*' + $script:Details.Text | Should -BeLike '*| Non-DC Computers Claiming DC Primary Groups | 1 |*' + Test-MtAdComputerNonStandardGroup | Should -BeFalse + $script:Details.Text | Should -Match 'client' + } + + It 'does not accept a forged DNS name when the DC inventory has serverReference' { + $script:AdComputerState.Computers[2].DnsHostName = 'dc1.example.com' + $script:AdComputerState.Computers[2].TrustedForDelegation = $true + Test-MtAdComputerUnconstrainedDelegationCount | Should -BeFalse + } + + It 'includes delegation on without adding it to device percentages' -ForEach @( + @{ Class = 'msDS-ManagedServiceAccount' } + @{ Class = 'msDS-GroupManagedServiceAccount' } + @{ Class = 'msDS-DelegatedManagedServiceAccount' } + ) { + $script:AdComputerState.ServiceAccounts = @([PSCustomObject]@{ + Name = 'Managed service'; DistinguishedName = 'CN=Managed,DC=example,DC=com' + ObjectClass = @('computer', $Class); TrustedForDelegation = $true + TrustedToAuthForDelegation = $true; AllowedToDelegateTo = @('HTTP/managed') + HasResourceBasedConstrainedDelegation = $true + }) + Test-MtAdComputerUnconstrainedDelegationCount | Should -BeFalse + $script:Details.Text | Should -BeLike '*| Managed Service Accounts with Unconstrained Delegation | 1 |*' + $script:Details.Text | Should -BeLike '*| Non-DC Percentage with Unconstrained Delegation | 0% |*' + Test-MtAdComputerNonDcConstrainedDelegationCount | Should -BeTrue + $script:Details.Text | Should -BeLike '*| Non-DC Accounts with Classic KCD Target SPNs | 2 |*' + $script:Details.Text | Should -Match 'Managed service' + } + + It 'errors when the managed account inventory or delegation flags are unavailable' { + $script:AdComputerState.ServiceAccounts = $null + { Test-MtAdComputerUnconstrainedDelegationCount } | Should -Throw '*inventories*' + $script:AdComputerState.ServiceAccounts = @([PSCustomObject]@{ Name = 'Unknown'; TrustedForDelegation = $null }) + { Test-MtAdComputerUnconstrainedDelegationCount } | Should -Throw '*flag is missing*' + } } diff --git a/tests/ad/computer/Test.AD-COMP-04.md b/tests/ad/computer/Test.AD-COMP-04.md index 5a4738eaf3..b48a0d61f4 100644 --- a/tests/ad/computer/Test.AD-COMP-04.md +++ b/tests/ad/computer/Test.AD-COMP-04.md @@ -23,7 +23,7 @@ The standard primary groups for computers are: #### How the Test Works -This test examines the `primaryGroupId` attribute of all enabled computer accounts and identifies those where the value is not 515, 516, or 521. +This test examines the `primaryGroupId` attribute of all enabled computer accounts. Non-DC devices must use 515. Groups 516 and 521 are accepted only for accounts identified in the collected DC server inventory, never because the account claims that group. A non-DC device claiming a DC group is listed as a finding; missing inventory or primary-group data produces Error. #### Related Tests diff --git a/tests/ad/computer/Test.AD-COMP-04.ps1 b/tests/ad/computer/Test.AD-COMP-04.ps1 index b644a8d2e3..a8088994e6 100644 --- a/tests/ad/computer/Test.AD-COMP-04.ps1 +++ b/tests/ad/computer/Test.AD-COMP-04.ps1 @@ -10,7 +10,8 @@ - 516: Domain Controllers - 521: Read-only Domain Controllers - Computers with non-standard primary groups may indicate misconfiguration or + Only accounts verified in the DC inventory may use primary group 516 or 521. + Other enabled computer accounts must use 515. Computers with non-standard primary groups may indicate misconfiguration or custom security configurations that should be reviewed. .EXAMPLE @@ -34,7 +35,7 @@ ImplementationCost = 'Medium', Mitre = 'None', Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:computer:ReadProperty'), + Permission = ('ActiveDirectory:Ldap:computer:ReadProperty', 'ActiveDirectory:Ldap:nTDSDSA:ReadProperty'), Author = 'soulemike' )] [CmdletBinding()] @@ -43,14 +44,13 @@ Write-Verbose "Starting Test-MtAdComputerNonStandardGroup" - # Standard computer primary group IDs - $standardGroupIds = @(515, 516, 521) - # Get AD domain state data (uses cached data if available) - $adState = Get-MtADDomainState -Categories @('Computers') + $adState = Get-MtADDomainState -Categories @('Computers', 'DomainControllers') # If unable to retrieve AD data, skip the test - if ($null -eq $adState -or $null -eq $adState.Computers) { throw 'Computer inventory is required to assess primary groups.' } + if ($null -eq $adState -or $null -eq $adState.Computers -or $null -eq $adState.DomainControllers) { throw 'Computer and DC inventories are required to assess primary groups.' } + $domainControllers = @($adState.DomainControllers) + if ($domainControllers.Count -eq 0) { throw 'DC inventory is empty; primary group assignments cannot be verified.' } $computers = $adState.Computers if (@($computers).Count -eq 0) { throw 'Computer inventory is empty; primary groups cannot be assessed.' } @@ -60,9 +60,11 @@ # Count enabled computers with non-standard primary group $nonStandardGroupComputers = $computers | Where-Object { - $_.Enabled -eq $true -and - $null -ne $_.primaryGroupId -and - $_.primaryGroupId -notin $standardGroupIds + if ($_.Enabled -eq $true -and $null -ne $_.PrimaryGroupId) { + $isDc = Test-MtAdDomainControllerAccount -Account $_ -DomainControllers $domainControllers + if ($isDc) { $_.PrimaryGroupId -notin 516, 521 } + else { $_.PrimaryGroupId -ne 515 } + } } $nonStandardCount = ($nonStandardGroupComputers | Measure-Object).Count @@ -90,6 +92,12 @@ $result += "| Non-Standard Primary Group | $nonStandardCount |" + "`n" $result += "| Non-Standard Percentage | $percentage% |" + "`n" + "`n" $result += "**Standard Primary Group IDs:** 515 (Domain Computers), 516 (Domain Controllers), 521 (Read-only Domain Controllers)" + "`n" + "`n" + $result += "DC groups are accepted only for accounts verified in the DC inventory.`n`n| Computer | Primary group | Distinguished name |`n| --- | --- | --- |`n" + foreach ($computer in $nonStandardGroupComputers) { + $name = ([string]$computer.Name).Replace('|', '|') -replace '[\r\n]+', ' ' + $dn = ([string]$computer.DistinguishedName).Replace('|', '|') -replace '[\r\n]+', ' ' + $result += "| $name | $($computer.PrimaryGroupId) | $dn |`n" + } $testResultMarkdown = "Active Directory computer objects have been analyzed. $nonStandardCount out of $enabledCount enabled computers ($percentage%) have non-standard primary group IDs.`n`n%TestResult%" $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result diff --git a/tests/ad/security/Test.AD-DCOMP-01.md b/tests/ad/security/Test.AD-DCOMP-01.md index 7cc00b0047..93b2997f7a 100644 --- a/tests/ad/security/Test.AD-DCOMP-01.md +++ b/tests/ad/security/Test.AD-DCOMP-01.md @@ -1,4 +1,6 @@ -Unconstrained delegation on non-domain-controller computers exposes users' Kerberos tickets to any attacker who compromises the computer. This check fails when one or more non-DC computers have the `TrustedForDelegation` flag. DCs are counted separately but do not cause failure; percentages use only non-DC computers as the denominator. +Unconstrained delegation on non-domain-controller computers or managed service accounts exposes users' Kerberos tickets. This check fails when a non-DC computer, sMSA, gMSA or dMSA has the `TrustedForDelegation` flag. Managed accounts are reported separately; the device percentage still uses only non-DC computers as its denominator. + +Only the collected DC server inventory establishes DC identity: `serverReference` DN, or DNS fallback when that reference is unavailable. Primary groups 516 and 521 alone never exclude a computer. Unexpected DC primary-group claims are counted for review under AD-COMP-04. **Security Risks:** - **Complete Impersonation**: Attackers can impersonate any user who authenticates to the computer @@ -35,7 +37,7 @@ This test counts computers with the `TrustedForDelegation` flag enabled and cate #### Related Tests -- `AD-DCOMP-03` - Reviews protocol transition on non-DC computers +- `AD-DCOMP-03` - Reviews KCD, protocol transition and RBCD descriptor presence on non-DC computers and managed accounts - `Test-MtAdUserDelegationConfiguredCount` - Reviews user account delegation #### Related links diff --git a/tests/ad/security/Test.AD-DCOMP-01.ps1 b/tests/ad/security/Test.AD-DCOMP-01.ps1 index 4300de37bc..1c3c0e197b 100644 --- a/tests/ad/security/Test.AD-DCOMP-01.ps1 +++ b/tests/ad/security/Test.AD-DCOMP-01.ps1 @@ -7,6 +7,7 @@ Unconstrained delegation allows a service to impersonate a user to any other service. This is a high-risk configuration on non-domain-controller computers. Domain controllers are reported separately but excluded from the assessed population. + Managed service accounts are also assessed and reported separately from device percentages. Security Risk: - Unconstrained delegation allows full impersonation of authenticated users @@ -24,7 +25,7 @@ #> [MaesterTest( Id = 'AD-DCOMP-01', - Title = 'Non-DC computers should not have unconstrained delegation', + Title = 'Non-DC computers and managed service accounts should not have unconstrained delegation', Product = 'ad', Feature = 'computers', Area = 'authentication', @@ -35,7 +36,7 @@ Mitre = ('T1558', 'T1550.003'), Control = 'nist-800-53-r5:AC-6', Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:computer:ReadProperty', 'ActiveDirectory:Ldap:nTDSDSA:ReadProperty'), + Permission = ('ActiveDirectory:Ldap:computer:ReadProperty', 'ActiveDirectory:Ldap:nTDSDSA:ReadProperty', 'ActiveDirectory:Ldap:msDS-ManagedServiceAccount:ReadProperty', 'ActiveDirectory:Ldap:msDS-GroupManagedServiceAccount:ReadProperty', 'ActiveDirectory:Ldap:msDS-DelegatedManagedServiceAccount:ReadProperty'), Author = 'soulemike' )] [CmdletBinding()] @@ -43,10 +44,10 @@ param() Write-Verbose "Starting Test-MtAdComputerUnconstrainedDelegationCount" - $adState = Get-MtADDomainState -Categories @('Computers', 'DomainControllers') + $adState = Get-MtADDomainState -Categories @('Computers', 'DomainControllers', 'ServiceAccounts') Write-Verbose "Retrieved AD state" - if ($null -eq $adState -or $null -eq $adState.Computers -or $null -eq $adState.DomainControllers) { + if ($null -eq $adState -or $null -eq $adState.Computers -or $null -eq $adState.DomainControllers -or $null -eq $adState.ServiceAccounts) { throw 'Computer and domain controller inventories are required to assess unconstrained delegation.' } Write-Verbose "Filtering/counting computer unconstrained delegation count" @@ -57,21 +58,12 @@ throw 'Computer and domain controller inventories must not be empty when assessing delegation.' } - # DCs are identified by primary group, serverReference DN or matching DNS - # host name. Name alone is used only when the DC has neither reference nor DNS. - $dcReferences = @($domainControllers | Where-Object { $_.ServerReference } | ForEach-Object { $_.ServerReference }) - $dcDnsNames = @($domainControllers | Where-Object { $_.DnsHostName } | ForEach-Object { $_.DnsHostName }) - $dcWithoutReference = @($domainControllers | Where-Object { -not $_.ServerReference }) + # Only the collected server inventory establishes DC identity, never a claimed primary group. $nonDcComputers = @($computers | Where-Object { - $computer = $_ - $isDc = $computer.PrimaryGroupId -in @(516, 521) -or $dcReferences -contains $computer.DistinguishedName - if (-not $isDc -and $computer.DnsHostName) { $isDc = $dcDnsNames -contains $computer.DnsHostName } - if (-not $isDc -and -not $computer.DnsHostName -and $computer.Name) { - $isDc = @($dcWithoutReference | Where-Object { -not $_.DnsHostName -and $_.Name -eq $computer.Name }).Count -gt 0 - } - -not $isDc + -not (Test-MtAdDomainControllerAccount -Account $_ -DomainControllers $domainControllers) }) - if (@($nonDcComputers | Where-Object { $null -eq $_.TrustedForDelegation }).Count -gt 0) { + $managedAccounts = @($adState.ServiceAccounts) + if (@(@($nonDcComputers) + @($managedAccounts) | Where-Object { $null -eq $_.TrustedForDelegation }).Count -gt 0) { throw 'Unconstrained delegation flag is missing for non-DC computers.' } @@ -83,10 +75,12 @@ $nonDcUnconstrained = @($nonDcComputers | Where-Object { $_.TrustedForDelegation -eq $true }) $dcUnconstrainedCount = $unconstrainedCount - $nonDcUnconstrained.Count $nonDcUnconstrainedCount = $nonDcUnconstrained.Count + $managedUnconstrained = @($managedAccounts | Where-Object { $_.TrustedForDelegation -eq $true }) + $unverifiedDcGroups = @($nonDcComputers | Where-Object { $_.PrimaryGroupId -in 516, 521 }) $totalComputers = @($computers).Count $totalNonDcComputers = $nonDcComputers.Count - $testResult = $nonDcUnconstrainedCount -eq 0 + $testResult = $nonDcUnconstrainedCount -eq 0 -and $managedUnconstrained.Count -eq 0 $result = "| Metric | Value |" + "`n" $result += "| --- | --- |" + "`n" @@ -95,6 +89,9 @@ $result += "| Domain Controllers with Unconstrained Delegation | $dcUnconstrainedCount |" + "`n" $result += "| Non-DC Computers with Unconstrained Delegation | $nonDcUnconstrainedCount |" + "`n" $result += "| Total Non-DC Computers | $totalNonDcComputers |" + "`n" + $result += "| Managed Service Accounts | $($managedAccounts.Count) |`n" + $result += "| Managed Service Accounts with Unconstrained Delegation | $($managedUnconstrained.Count) |`n" + $result += "| Non-DC Computers Claiming DC Primary Groups | $($unverifiedDcGroups.Count) |`n" $percentage = if ($totalNonDcComputers -gt 0) { [Math]::Round(($nonDcUnconstrainedCount / $totalNonDcComputers) * 100, 2) } else { 0 } $result += "| Non-DC Percentage with Unconstrained Delegation | $percentage% |" + "`n" if (-not $testResult) { @@ -104,10 +101,16 @@ $os = [string]$computer.OperatingSystem -replace '\|', '\|' -replace '[\r\n]', ' ' $result += "| $name | $os |`n" } + $result += "`n| Managed Account with Unconstrained Delegation |`n| --- |`n" + foreach ($account in $managedUnconstrained) { + $name = ([string]$account.Name).Replace('|', '|') -replace '[\r\n]+', ' ' + $result += "| $name |`n" + } } Write-Verbose "Counts computed" - $summary = if ($testResult) { 'Well done. No non-DC computers have unconstrained delegation.' } else { 'Non-DC computers with unconstrained delegation were found. Migrate their services to constrained delegation and remove unconstrained delegation.' } + $summary = if ($testResult) { 'Well done. No non-DC computers or managed service accounts have unconstrained delegation.' } else { 'Non-DC computers or managed service accounts with unconstrained delegation were found. Migrate their services to constrained delegation and remove unconstrained delegation.' } + if ($unverifiedDcGroups.Count -gt 0) { $summary += " $($unverifiedDcGroups.Count) computer(s) claim a DC primary group without inventory evidence; review AD-COMP-04. They were not excluded." } $testResultMarkdown = "$summary`n`n%TestResult%" $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result diff --git a/tests/ad/security/Test.AD-DCOMP-03.md b/tests/ad/security/Test.AD-DCOMP-03.md index 0acfe0b134..2e1c869de7 100644 --- a/tests/ad/security/Test.AD-DCOMP-03.md +++ b/tests/ad/security/Test.AD-DCOMP-03.md @@ -1,4 +1,4 @@ -This check inventories three separate indicators on non-domain-controller computer accounts: classic Kerberos constrained delegation (KCD) target SPNs from `msDS-AllowedToDelegateTo`, the `TrustedToAuthForDelegation` protocol-transition flag, and **presence** of an `msDS-AllowedToActOnBehalfOfOtherIdentity` resource-based constrained delegation (RBCD) descriptor. One computer can have multiple indicators. Descriptor presence neither identifies allowed principals nor proves effective delegation permissions. +This check inventories three separate indicators on non-domain-controller computers and sMSA, gMSA and dMSA accounts: classic Kerberos constrained delegation (KCD) target SPNs from `msDS-AllowedToDelegateTo`, the `TrustedToAuthForDelegation` protocol-transition flag, and **presence** of an `msDS-AllowedToActOnBehalfOfOtherIdentity` resource-based constrained delegation (RBCD) descriptor. One account can have multiple indicators. Descriptor presence neither identifies allowed principals nor proves effective delegation permissions. **Security Considerations:** - **Limited Scope**: Safer than unconstrained but still enables impersonation @@ -29,7 +29,7 @@ This check inventories three separate indicators on non-domain-controller comput #### How the Test Works -The test reports separate non-DC counts for KCD target SPNs, protocol transition and RBCD descriptor presence, plus a deduplicated count and a sample of computers and KCD targets for review. A protocol-transition flag alone does not prove that a classic KCD target is configured. A present RBCD descriptor needs a separate permissions review; this test cannot resolve principals or effective access. Delegation on user or managed service accounts is outside this computer inventory. +The test reports device and managed-account populations separately, then combined non-DC account counts for KCD targets, protocol transition and RBCD descriptor presence. Indicator percentages use this combined population. DC identity comes from the DC inventory, not a claimed primary group. A present RBCD descriptor needs a separate permissions review; this test cannot resolve principals or effective access. Delegation on ordinary user accounts remains outside this inventory. #### Related Tests diff --git a/tests/ad/security/Test.AD-DCOMP-03.ps1 b/tests/ad/security/Test.AD-DCOMP-03.ps1 index e91440cdab..0b76c568b7 100644 --- a/tests/ad/security/Test.AD-DCOMP-03.ps1 +++ b/tests/ad/security/Test.AD-DCOMP-03.ps1 @@ -6,7 +6,7 @@ .DESCRIPTION Inventories classic Kerberos constrained delegation target SPNs, the TrustedToAuthForDelegation protocol-transition flag, and presence of an RBCD - security descriptor on non-DC computer objects. RBCD presence does not + security descriptor on non-DC computers and sMSA, gMSA and dMSA objects. RBCD presence does not identify allowed principals or establish effective access. These categories can overlap and do not include delegation configured on user accounts. @@ -26,7 +26,7 @@ #> [MaesterTest( Id = 'AD-DCOMP-03', - Title = 'Non-DC computer constrained delegation should be investigated', + Title = 'Non-DC computer and managed account constrained delegation should be investigated', Product = 'ad', Feature = 'computers', Area = 'authentication', @@ -34,7 +34,7 @@ Severity = 'Info', Mitre = ('T1558', 'T1550.003'), Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:computer:ReadProperty', 'ActiveDirectory:Ldap:nTDSDSA:ReadProperty'), + Permission = ('ActiveDirectory:Ldap:computer:ReadProperty', 'ActiveDirectory:Ldap:nTDSDSA:ReadProperty', 'ActiveDirectory:Ldap:msDS-ManagedServiceAccount:ReadProperty', 'ActiveDirectory:Ldap:msDS-GroupManagedServiceAccount:ReadProperty', 'ActiveDirectory:Ldap:msDS-DelegatedManagedServiceAccount:ReadProperty'), Author = 'soulemike' )] [CmdletBinding()] @@ -42,10 +42,10 @@ param() Write-Verbose "Starting Test-MtAdComputerNonDcConstrainedDelegationCount" - $adState = Get-MtADDomainState -Categories @('Computers', 'DomainControllers') + $adState = Get-MtADDomainState -Categories @('Computers', 'DomainControllers', 'ServiceAccounts') Write-Verbose "Retrieved AD state" - if ($null -eq $adState -or $null -eq $adState.Computers -or $null -eq $adState.DomainControllers) { + if ($null -eq $adState -or $null -eq $adState.Computers -or $null -eq $adState.DomainControllers -or $null -eq $adState.ServiceAccounts) { throw 'Computer and domain controller inventories are required to review constrained delegation.' } Write-Verbose "Filtering/counting computer non dc constrained delegation count" @@ -56,22 +56,13 @@ throw 'Computer and domain controller inventories must not be empty when reviewing constrained delegation.' } - # Match DC computer DNs to serverReference first. The primary group also - # identifies writable DCs (516) and RODCs (521). DNS names also identify - # DCs; a name alone is used only when the DC has no reference or DNS name. - $dcReferences = @($domainControllers | Where-Object { $_.ServerReference } | ForEach-Object { $_.ServerReference }) - $dcDnsNames = @($domainControllers | Where-Object { $_.DnsHostName } | ForEach-Object { $_.DnsHostName }) - $dcWithoutReference = @($domainControllers | Where-Object { -not $_.ServerReference }) + # Device inventory stays separate from managed accounts; both are assessed for delegation. $nonDcComputers = @($computers | Where-Object { - $computer = $_ - $isDc = $computer.PrimaryGroupId -in @(516, 521) -or $dcReferences -contains $computer.DistinguishedName - if (-not $isDc -and $computer.DnsHostName) { $isDc = $dcDnsNames -contains $computer.DnsHostName } - if (-not $isDc -and -not $computer.DnsHostName -and $computer.Name) { - $isDc = @($dcWithoutReference | Where-Object { -not $_.DnsHostName -and $_.Name -eq $computer.Name }).Count -gt 0 - } - -not $isDc + -not (Test-MtAdDomainControllerAccount -Account $_ -DomainControllers $domainControllers) }) - if (@($nonDcComputers | Where-Object { + $managedAccounts = @($adState.ServiceAccounts) + $nonDcAccounts = @($nonDcComputers) + @($managedAccounts) + if (@($nonDcAccounts | Where-Object { -not $_.PSObject.Properties['AllowedToDelegateTo'] -or $null -eq $_.AllowedToDelegateTo -or -not $_.PSObject.Properties['HasResourceBasedConstrainedDelegation'] -or $null -eq $_.HasResourceBasedConstrainedDelegation -or -not $_.PSObject.Properties['TrustedToAuthForDelegation'] -or $null -eq $_.TrustedToAuthForDelegation @@ -79,29 +70,31 @@ throw 'Required delegation fields are missing from the non-DC computer inventory; a zero count cannot be trusted.' } - $classicKcd = @($nonDcComputers | Where-Object { @($_.AllowedToDelegateTo).Count -gt 0 }) - $protocolTransition = @($nonDcComputers | Where-Object { $_.TrustedToAuthForDelegation -eq $true }) - $rbcdPresent = @($nonDcComputers | Where-Object { $_.HasResourceBasedConstrainedDelegation -eq $true }) - $reviewComputers = @($nonDcComputers | Where-Object { + $classicKcd = @($nonDcAccounts | Where-Object { @($_.AllowedToDelegateTo).Count -gt 0 }) + $protocolTransition = @($nonDcAccounts | Where-Object { $_.TrustedToAuthForDelegation -eq $true }) + $rbcdPresent = @($nonDcAccounts | Where-Object { $_.HasResourceBasedConstrainedDelegation -eq $true }) + $reviewComputers = @($nonDcAccounts | Where-Object { @($_.AllowedToDelegateTo).Count -gt 0 -or $_.TrustedToAuthForDelegation -eq $true -or $_.HasResourceBasedConstrainedDelegation -eq $true }) $totalNonDcComputers = $nonDcComputers.Count + $totalNonDcAccounts = $nonDcAccounts.Count $result = "| Metric | Value |" + "`n" $result += "| --- | --- |" + "`n" $result += "| Total Non-DC Computers | $totalNonDcComputers |" + "`n" - $result += "| Non-DC Computers with Classic KCD Target SPNs | $($classicKcd.Count) |`n" - $result += "| Non-DC Computers with Protocol Transition Flag | $($protocolTransition.Count) |`n" - $result += "| Non-DC Computers with RBCD Descriptor Present | $($rbcdPresent.Count) |`n" - $result += "| Distinct Non-DC Computers with One or More Indicators | $($reviewComputers.Count) |`n" - if ($totalNonDcComputers -gt 0) { - $percentage = [Math]::Round(($reviewComputers.Count / $totalNonDcComputers) * 100, 2) - $result += "| Percentage of Non-DC Computers with an Indicator | $percentage% |`n" + $result += "| Managed Service Accounts | $($managedAccounts.Count) |`n" + $result += "| Non-DC Accounts with Classic KCD Target SPNs | $($classicKcd.Count) |`n" + $result += "| Non-DC Accounts with Protocol Transition Flag | $($protocolTransition.Count) |`n" + $result += "| Non-DC Accounts with RBCD Descriptor Present | $($rbcdPresent.Count) |`n" + $result += "| Distinct Non-DC Accounts with One or More Indicators | $($reviewComputers.Count) |`n" + if ($totalNonDcAccounts -gt 0) { + $percentage = [Math]::Round(($reviewComputers.Count / $totalNonDcAccounts) * 100, 2) + $result += "| Percentage of Non-DC Accounts with an Indicator | $percentage% |`n" } if ($reviewComputers.Count -gt 0) { - $result += "`n**Non-DC Computers to Review (Top 10):**`n`n" - $result += "| Computer | Classic KCD Target SPNs | Protocol Transition Flag | RBCD Descriptor Present |`n| --- | --- | --- | --- |`n" + $result += "`n**Non-DC Accounts to Review (Top 10):**`n`n" + $result += "| Account | Classic KCD Target SPNs | Protocol Transition Flag | RBCD Descriptor Present |`n| --- | --- | --- | --- |`n" foreach ($computer in $reviewComputers | Select-Object -First 10) { $name = [string]$computer.Name -replace '\|', '\|' -replace '[\r\n]', ' ' $spns = [string](@($computer.AllowedToDelegateTo) -join ', ') -replace '\|', '\|' -replace '[\r\n]', ' ' @@ -114,7 +107,7 @@ } Write-Verbose "Counts computed" - $testResultMarkdown = "Review non-DC classic KCD target SPNs, protocol transition and RBCD descriptor presence. RBCD presence does not identify allowed principals or prove effective access; categories can overlap.`n`n%TestResult%" + $testResultMarkdown = "Review non-DC computer and managed service account classic KCD target SPNs, protocol transition and RBCD descriptor presence. RBCD presence does not identify allowed principals or prove effective access; categories can overlap.`n`n%TestResult%" $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result Add-MtTestResultDetail -Result $testResultMarkdown -Investigate From 4efd5ca0d959ee8afdb29522893b9f79e1de76e9 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 14:26:36 +0000 Subject: [PATCH 022/100] fix(ad): distinguish hidden KDS keys from missing inventory --- .../functions/ADConfigurationChecks.Tests.ps1 | 19 ++++++++++++++++-- .../functions/ActiveDirectoryIssues.Tests.ps1 | 6 +++--- tests/ad/config/Test.AD-CFG-22.md | 14 ++++++++----- tests/ad/config/Test.AD-CFG-22.ps1 | 20 +++++++++++++++---- website/docs/upgrading-from-2x.md | 8 ++++++++ 5 files changed, 53 insertions(+), 14 deletions(-) diff --git a/powershell/tests/functions/ADConfigurationChecks.Tests.ps1 b/powershell/tests/functions/ADConfigurationChecks.Tests.ps1 index e3b05647e8..1fd1b1b2bc 100644 --- a/powershell/tests/functions/ADConfigurationChecks.Tests.ps1 +++ b/powershell/tests/functions/ADConfigurationChecks.Tests.ps1 @@ -76,13 +76,13 @@ Describe 'AD configuration, forest and optional-feature checks' { It 'fails for zero KDS root keys rather than assuming gMSAs are unused' { $script:state.Configuration.KdsRootKeys = @() - Test-MtAdKdsRootKeysCount | Should -BeFalse + Test-MtAdKdsRootKeysCount -KeyInventoryReadAccessConfirmed $true | Should -BeFalse $script:detail | Should -Match 'No KDS root keys' } It 'investigates the documented two-key case with a single boolean return' { $script:state.Configuration.KdsRootKeys += [PSCustomObject]@{ 'msKds-CreateTime' = [datetime]'2025-01-01' } - Test-MtAdKdsRootKeysCount | Should -BeTrue + Test-MtAdKdsRootKeysCount -KeyInventoryReadAccessConfirmed $true | Should -BeTrue Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Exactly 1 -ParameterFilter { $Investigate } $script:detail | Should -Not -Match 'Recommended Count' } @@ -91,4 +91,19 @@ Describe 'AD configuration, forest and optional-feature checks' { $script:state.Configuration.KdsRootKeys += [PSCustomObject]@{ Name = 'Unreadable metadata' } { Test-MtAdKdsRootKeysCount } | Should -Throw '*inventory is incomplete*' } + + It 'investigates zero visible keys unless complete read access was confirmed' { + $script:state.Configuration.KdsRootKeys = @() + Test-MtAdKdsRootKeysCount | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Exactly 1 -ParameterFilter { $Investigate } + $script:detail | Should -Match 'not proof that keys are missing' + $script:detail | Should -Not -Match 'create a third' + } + + It 'does not recommend another key from an unconfirmed two-key inventory' { + $script:state.Configuration.KdsRootKeys += [PSCustomObject]@{ 'msKds-CreateTime' = [datetime]'2025-01-01' } + Test-MtAdKdsRootKeysCount | Should -BeTrue + $script:detail | Should -Match 'complete inventory is not confirmed' + $script:detail | Should -Not -Match 'create a third' + } } diff --git a/powershell/tests/functions/ActiveDirectoryIssues.Tests.ps1 b/powershell/tests/functions/ActiveDirectoryIssues.Tests.ps1 index 675582b495..88ebbfa981 100644 --- a/powershell/tests/functions/ActiveDirectoryIssues.Tests.ps1 +++ b/powershell/tests/functions/ActiveDirectoryIssues.Tests.ps1 @@ -18,7 +18,7 @@ Describe 'AD-CFG-22: KDS root key count' { } Mock Add-MtTestResultDetail -ModuleName Maester { } - $result = Test-MtAdKdsRootKeysCount + $result = Test-MtAdKdsRootKeysCount -KeyInventoryReadAccessConfirmed $true $result | Should -BeFalse } } @@ -35,7 +35,7 @@ Describe 'AD-CFG-22: KDS root key count' { } } - $result = Test-MtAdKdsRootKeysCount + $result = Test-MtAdKdsRootKeysCount -KeyInventoryReadAccessConfirmed $true $result | Should -Be $true } } @@ -54,7 +54,7 @@ Describe 'AD-CFG-22: KDS root key count' { } Mock Add-MtTestResultDetail -ModuleName Maester { } - $result = Test-MtAdKdsRootKeysCount + $result = Test-MtAdKdsRootKeysCount -KeyInventoryReadAccessConfirmed $true $result | Should -BeTrue Assert-MockCalled Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate -eq $true } -Exactly 1 } diff --git a/tests/ad/config/Test.AD-CFG-22.md b/tests/ad/config/Test.AD-CFG-22.md index 6605a0d4ea..a56e11869d 100644 --- a/tests/ad/config/Test.AD-CFG-22.md +++ b/tests/ad/config/Test.AD-CFG-22.md @@ -10,22 +10,26 @@ Monitoring the *count* of KDS root keys helps identify: **Operational** -#### Security Recommendation -- At least one KDS root key is required to provision gMSAs. Exactly two keys can cause gMSA authentication failures in some sorting scenarios; multiple keys are not inherently invalid. -- If exactly two keys exist, Microsoft's recommended workaround is to create a third key. Do not remove existing keys. +#### Remediation action +- Verify that the assessment identity can list the Master Root Keys container and read every key's metadata. Default key ACLs restrict visibility to privileged identities; a successful LDAP search with zero results does not establish absence. +- `KeyInventoryReadAccessConfirmed` defaults to `false`. Set it to `true` in this check's `TestSettings[].Parameters` only after independently auditing complete read/list access for the identity and target used by this run. This is operator confirmation, not an automated permission probe. Never assume completeness solely from a group name or a successful connection. +- At least one KDS root key is required to provision gMSAs. Exactly two confirmed keys can cause gMSA authentication failures in some sorting scenarios; multiple keys are not inherently invalid. +- Only after confirming that exactly two keys actually exist should an administrator consider Microsoft's documented third-key workaround. Do not create another key based on a partial visible inventory. Do not remove existing keys. - Validate the expected number of keys for your environment and alert on deviations. - Restrict administrative access to actions that can modify KDS root keys. #### How the Test Works The test enumerates KDS root keys present in Active Directory and evaluates the count: -- **0 keys**: gMSA provisioning is unavailable; the test fails. This does not prove whether gMSAs are in use. +- **0 visible keys, access unconfirmed**: Investigate. Keys may be hidden; no missing-key or provisioning-unavailable claim is made. +- **0 keys, complete access operator-confirmed**: Failed. This does not prove whether gMSAs are in use. - **1 key**: The test passes. -- **2 keys**: Can cause gMSA authentication failures in some scenarios; the test returns Investigate. +- **2 visible keys**: Investigate. With unconfirmed access, verify the complete count before taking action; with confirmed access, evaluate the documented two-key issue. - **3+ keys**: The test passes; Microsoft's workaround for the two-key sorting issue is to add a third key. #### References - [Microsoft: gMSA authentication failures with multiple KDS root keys](https://learn.microsoft.com/troubleshoot/windows-server/active-directory/gmsa-auth-failures-multiple-keys) +- [Microsoft: KDS root-key class and default security descriptor](https://learn.microsoft.com/windows/win32/adschema/c-mskds-provrootkey) %TestResult% diff --git a/tests/ad/config/Test.AD-CFG-22.ps1 b/tests/ad/config/Test.AD-CFG-22.ps1 index 28fba4b4d8..58f95cc98e 100644 --- a/tests/ad/config/Test.AD-CFG-22.ps1 +++ b/tests/ad/config/Test.AD-CFG-22.ps1 @@ -7,7 +7,8 @@ KDS root keys are required for Group Managed Service Accounts (gMSA). This test checks the number of KDS root keys configured in the domain. - - Zero keys means gMSA provisioning cannot work; the test fails. + - Zero visible keys fails only when inventory read access is operator-confirmed; + otherwise it needs investigation because keys may be hidden by directory ACLs. - One key supports gMSA operations; the test passes. - Exactly two keys can cause gMSA authentication failures in some scenarios; the test returns Investigate per Microsoft guidance. @@ -39,7 +40,10 @@ )] [CmdletBinding()] [OutputType([bool])] - param() + param( + # Confirm that this run's identity has audited read/list access to the complete KDS key inventory. + [bool] $KeyInventoryReadAccessConfirmed = $false + ) Write-Verbose "Starting Test-MtAdKdsRootKeysCount" @@ -70,9 +74,13 @@ # Build the metric table once so both result paths can include it $result = "| Metric | Value |" + "`n" $result += "| --- | --- |" + "`n" - $result += "| KDS Root Keys (gMSA) | $kdsRootKeysCount |" + "`n" - # No keys means gMSA provisioning is unavailable; this does not prove gMSAs are unused. + $result += "| Visible KDS Root Keys (gMSA) | $kdsRootKeysCount |" + "`n" + $result += "| Complete inventory read access confirmed by operator | $KeyInventoryReadAccessConfirmed |" + "`n" if ($kdsRootKeysCount -eq 0) { + if (-not $KeyInventoryReadAccessConfirmed) { + Add-MtTestResultDetail -Result "No KDS root keys are visible to this identity. Directory ACLs can hide existing keys; this is not proof that keys are missing. Verify read/list access before provisioning any key.`n`n$result" -Investigate + return $true + } Add-MtTestResultDetail -Result "No KDS root keys were found. gMSA provisioning requires a KDS root key; review whether gMSAs are planned or already in use.`n`n$result" return $false } @@ -80,6 +88,10 @@ # A nonzero count establishes presence, not a universal recommended key count. # Two keys triggers an Investigate result per the Microsoft article if ($kdsRootKeysCount -eq 2) { + if (-not $KeyInventoryReadAccessConfirmed) { + Add-MtTestResultDetail -Result "Two KDS root keys are visible, but the complete inventory is not confirmed. Verify access and the actual key count before considering the documented two-key issue; do not create another key based on a partial inventory.`n`n$result" -Investigate + return $true + } $testResultMarkdown = "⚠️ Exactly two KDS root keys exist. In some scenarios this can cause gMSA authentication failures. Microsoft's recommended workaround is to create a third KDS root key. Do not remove existing keys. See [Microsoft documentation](https://learn.microsoft.com/troubleshoot/windows-server/active-directory/gmsa-auth-failures-multiple-keys) for details.`n`n%TestResult%" $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result Add-MtTestResultDetail -Result $testResultMarkdown -Investigate diff --git a/website/docs/upgrading-from-2x.md b/website/docs/upgrading-from-2x.md index 61428c6452..8f6d8d4a0a 100644 --- a/website/docs/upgrading-from-2x.md +++ b/website/docs/upgrading-from-2x.md @@ -11,6 +11,14 @@ Maester 3.0 gives Maester its own test engine. The built-in tests are no longer folder: they ship inside the module and run from there. Most runs need no change at all, but the way tests are installed, selected, configured and written has moved on. This page lists every change that can affect you. +## Active Directory check consolidation + +Overlapping AD count/detail checks now produce one combined result. Historical inclusion **and exclusion** tags map to the surviving check. This preserves exclusion mapping but can broaden what an old exclusion suppresses: `-ExcludeTag AD-GPOREP-19` now excludes Critical **AD-GPOREP-17**, including both the `cpassword` and default-password checks. Audit existing exclusions and retain them only when excluding the entire merged control is intended. The native replacements are recorded in `build/golden/native-test-replacements.psd1`; this does not automatically migrate ID-based `TestSettings` rows. + +Existing exported AD collectors also distinguish collection failure from an empty inventory. The `GPOs` or `GPOReports` fields returned by `Get-MtADGpoState` can be `$null` when collection fails; an empty array is not an equivalent error signal. Custom tests must check for `$null` before calculating a clean result. Device inventory excludes managed service account classes; managed-account delegation remains covered by AD-DCOMP-01 and AD-DCOMP-03 through the separate ServiceAccounts collection. + +AD-CFG-22 treats zero **visible** KDS keys as Investigate unless complete key-inventory access has been independently confirmed with `KeyInventoryReadAccessConfirmed`. Do not create keys solely because a restricted identity returned an empty inventory. + ## Requirements - **PowerShell 7.4 or later** (the `Core` edition) on Linux, macOS, or Windows. The module no longer loads in Windows PowerShell 5.1. From f931ddb8298f078d3df0841c40f3a40b775d4e62 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 14:26:36 +0000 Subject: [PATCH 023/100] fix(ad): gate GPO parsing and reject incomplete group age data --- .../functions/ADGroupSpnChecks.Tests.ps1 | 7 ++- tests/ad/gpo-state/Test.AD-GPOREP-10.md | 2 +- tests/ad/gpo-state/Test.AD-GPOREP-10.ps1 | 1 + tests/ad/group/Test.AD-GRP-03.ps1 | 5 +- website/docs/advanced/active-directory.md | 56 ++++++++++--------- 5 files changed, 42 insertions(+), 29 deletions(-) diff --git a/powershell/tests/functions/ADGroupSpnChecks.Tests.ps1 b/powershell/tests/functions/ADGroupSpnChecks.Tests.ps1 index 017f32961f..6b50f2dfda 100644 --- a/powershell/tests/functions/ADGroupSpnChecks.Tests.ps1 +++ b/powershell/tests/functions/ADGroupSpnChecks.Tests.ps1 @@ -3,10 +3,15 @@ . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" Use-MtModuleFunction -Name Test-MtAdGroupMemberDistinctGroupCount, Test-MtAdGroupMemberAccountTypeCount, Test-MtAdGroupMemberTrustCount, Test-MtAdUserSpnTotalCount, Test-MtAdUserSpnServiceClassCount, - Test-MtAdUserSpnDomainAdminCount + Test-MtAdUserSpnDomainAdminCount, Test-MtAdGroupStaleCount } Describe 'AD group and SPN checks on a collected snapshot' { + It 'errors rather than treating missing group modification timestamps as recent' { + InModuleScope Maester { + { Test-MtAdGroupStaleCount } | Should -Throw '*modification timestamps are missing*' + } + } BeforeEach { InModuleScope Maester { $script:adSpnDomainSid = 'S-1-5-21-111-222-333' diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-10.md b/tests/ad/gpo-state/Test.AD-GPOREP-10.md index 994bd99b02..84eab3b03c 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-10.md +++ b/tests/ad/gpo-state/Test.AD-GPOREP-10.md @@ -1,6 +1,6 @@ Checks that every GPO has an allow entry for the Apply Group Policy right. A policy without application rights cannot deliver its intended settings through that right. This is a policy-health check, not a calculation of effective permissions for every user or computer. -The check fails when an application entry is absent and errors when permissions are unreadable. Intentionally unused policies require review before granting access; archive or remove them if they are no longer needed. +This check requires Windows for security-descriptor parsing; the engine skips it on Linux and macOS. On Windows, it fails when an application entry is absent and errors when permissions are unreadable. Intentionally unused policies require review before granting access; archive or remove them if they are no longer needed. #### Remediation action diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-10.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-10.ps1 index f0d6744d3b..65ce9972fb 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-10.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOREP-10.ps1 @@ -11,6 +11,7 @@ Product = 'ad', Feature = 'group-policy', Area = 'access-control', ResourceType = 'GroupPolicy', Severity = 'Low', UserImpact = 'Low', ImplementationCost = 'Medium', Mitre = 'None', Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), + Platform = 'Windows', Author = 'soulemike' )] [CmdletBinding()] diff --git a/tests/ad/group/Test.AD-GRP-03.ps1 b/tests/ad/group/Test.AD-GRP-03.ps1 index 31e9b59f35..80fcdeead3 100644 --- a/tests/ad/group/Test.AD-GRP-03.ps1 +++ b/tests/ad/group/Test.AD-GRP-03.ps1 @@ -4,7 +4,7 @@ Checks whether groups have been modified within a configurable number of days. .DESCRIPTION - This test identifies groups that have not been modified since before January 1, 2020. + This test identifies groups whose modification date exceeds MaximumAgeDays. Groups that haven't been modified for an extended period may represent: - Unused or obsolete groups that should be reviewed for deletion - Legacy configurations that may no longer be needed @@ -56,6 +56,9 @@ $groups = $adState.Groups if ($null -eq $adState.Groups) { throw 'Group collection is unavailable.' } + if (@($groups | Where-Object { $null -eq $_.modifyTimeStamp }).Count -gt 0) { + throw 'Group modification timestamps are missing; modification age cannot be assessed completely.' + } # Modification age is a hygiene indicator, not proof of actual group usage. $cutoffDate = (Get-Date).AddDays(-$MaximumAgeDays) $staleGroups = $groups | Where-Object { diff --git a/website/docs/advanced/active-directory.md b/website/docs/advanced/active-directory.md index 234ff2d34e..e4928b63ac 100644 --- a/website/docs/advanced/active-directory.md +++ b/website/docs/advanced/active-directory.md @@ -103,13 +103,13 @@ For LDAP, the optional partition is `Configuration` or `Schema`; omitted means t ## Tests Requiring Elevated Privileges -A standard **authenticated user** (Domain User) can read most LDAP attributes on most objects via the default security descriptor. The following tests require privileges **beyond** what a standard Domain User holds by default. +A standard **authenticated user** (Domain User) can read many LDAP attributes through default object ACLs. The following collection paths have additional access or platform requirements; whether a particular identity needs elevation depends on the effective ACLs and transport permissions. -### DACL Tests (18 tests) +### DACL checks | Tests | Required Permission | Why It Requires Elevation | |---|---|---| -| AD-DACL-01 through AD-DACL-18 | `ActiveDirectory:Ldap:*.ntSecurityDescriptor:ReadControl` | Reading the DACL portion of `ntSecurityDescriptor` is restricted. Standard users can read the owner and group, but not the full DACL. | +| AD-DACL-01, 02, 03, 05, 07, 09, 11, 14, 15, 17 | `ActiveDirectory:Ldap:*.ntSecurityDescriptor:ReadControl` | Reading a DACL requires READ_CONTROL access, which can be restricted by object ACLs. Do not infer effective access from a group name. DACL parsing also requires Windows. | ### DNS Tests (19 tests) @@ -123,52 +123,56 @@ A standard **authenticated user** (Domain User) can read most LDAP attributes on |---|---|---| | AD-DC-02, AD-DC-03, AD-DC-04 | `ActiveDirectory:Cim:root\Microsoft\Windows\SMB:MSFT_SmbServerConfiguration:Read`, `ActiveDirectory:Remoting:Microsoft.PowerShell` | Remote CIM access for SMB server configuration and PowerShell remoting execution require elevated access. | -### GPO Tests (40 tests) +### GPO checks | Tests | Required Permission | Why It May Require Elevation | |---|---|---| -| AD-GPO-01 through AD-GPO-05, AD-GPOL-01 through AD-GPOL-06, AD-GPOREP-01 through AD-GPOREP-20, AD-GPOS-01 through AD-GPOS-09 | `ActiveDirectory:File:SYSVOL:Read` | Reading files from the `\\domain\SYSVOL` share. While Authenticated Users typically receive read access to SYSVOL, this is filesystem access separate from LDAP and may be restricted in hardened environments. | +| AD-GPO-*, AD-GPOL-*, AD-GPOREP-*, AD-GPOS-* | `ActiveDirectory:File:SYSVOL:Read` | Reading files from the `\\domain\SYSVOL` share. While Authenticated Users typically receive read access to SYSVOL, this is filesystem access separate from LDAP and may be restricted in hardened environments. Only surviving IDs in the catalog are available; merged count/detail checks no longer have separate rows. | -**Summary:** 80 of 270 AD tests (30%) require privileges beyond a standard authenticated user. The remaining 190 tests can run with standard Domain User LDAP read access. +### KDS root-key visibility + +AD-CFG-22 reads key metadata, never `msKds-RootKeyData`. Default key ACLs restrict visibility to privileged identities. Zero visible keys therefore reports Investigate unless complete read/list access was independently confirmed using `KeyInventoryReadAccessConfirmed`. Do not add a key based only on an empty search by a restricted reader. + +Use `Get-MtTest -Product ad` for the current catalog and each check's declared permissions. Static test counts or membership in a named group do not establish effective read access. ## Category Summary | Category | Tests | Required permissions | |---|---|---| -| `cfg` | AD-CFG-01 through AD-CFG-24 | `ActiveDirectory:Ldap:Configuration/*:ReadProperty` | -| `comp` | AD-COMP-01 through AD-COMP-10 | `ActiveDirectory:Ldap:computer:ReadProperty` | -| `dacl` | AD-DACL-01 through AD-DACL-18 | `ActiveDirectory:Ldap:*.ntSecurityDescriptor:ReadControl` | +| `cfg` | AD-CFG-02, 03, 06–24 | `ActiveDirectory:Ldap:Configuration/*:ReadProperty`; CFG-22 additionally needs confirmed inventory visibility for a zero-key failure | +| `comp` | AD-COMP-01, 03–08 | `ActiveDirectory:Ldap:computer:ReadProperty`; COMP-04 also uses the DC inventory | +| `dacl` | AD-DACL-01, 02, 03, 05, 07, 09, 11, 14, 15, 17 | `ActiveDirectory:Ldap:*.ntSecurityDescriptor:ReadControl` | | `dc` | AD-DC-01 through AD-DC-08 | `ActiveDirectory:Ldap:nTDSDSA:ReadProperty`; AD-DC-02 through AD-DC-04 also need `ActiveDirectory:Cim:root\Microsoft\Windows\SMB:MSFT_SmbServerConfiguration:Read` and `ActiveDirectory:Remoting:Microsoft.PowerShell` | | `dcd` | AD-DCD-01 through AD-DCD-04 | `ActiveDirectory:Ldap:nTDSDSA:ReadProperty` | -| `dcomp` | AD-DCOMP-01 through AD-DCOMP-09 | `ActiveDirectory:Ldap:computer:ReadProperty` | +| `dcomp` | AD-DCOMP-01, 03, 04, 06, 07, 08 | Computer and DC inventory permissions; DCOMP-01/03 also read sMSA, gMSA and dMSA delegation metadata | | `dfsr` | AD-DFSR-01 | `ActiveDirectory:Ldap:domainDNS.distinguishedName:ReadProperty` | | `dns` | AD-DNS-01 through AD-DNS-19 | `ActiveDirectory:Cim:root\MicrosoftDNS:MicrosoftDNS_Zone:Read`, `ActiveDirectory:Remoting:Microsoft.PowerShell` | | `dom` | AD-DOM-01 through AD-DOM-08 | `ActiveDirectory:Ldap:domainDNS:ReadProperty` | | `doms` | AD-DOMS-01 | `ActiveDirectory:Ldap:domainDNS:ReadProperty` | -| `feat` | AD-FEAT-01 through AD-FEAT-02 | `ActiveDirectory:Ldap:msDS-OptionalFeature:ReadProperty` | +| `feat` | AD-FEAT-01 | `ActiveDirectory:Ldap:msDS-OptionalFeature:ReadProperty` | | `fgpp` | AD-FGPP-01 through AD-FGPP-04 | `ActiveDirectory:Ldap:msDS-PasswordSettings:ReadProperty` | | `for` | AD-FOR-01 through AD-FOR-04 | `ActiveDirectory:Ldap:crossRef:ReadProperty` | | `fors` | AD-FORS-01 through AD-FORS-04 | `ActiveDirectory:Ldap:crossRef:ReadProperty` | | `gchg` | AD-GCHG-01 | `ActiveDirectory:Ldap:group:ReadProperty` | -| `gmc` | AD-GMC-01 through AD-GMC-11 | `ActiveDirectory:Ldap:group:ReadProperty`; GMC-01 also needs `ActiveDirectory:Ldap:group.member:ReadProperty` | -| `gpo` | AD-GPO-01 through AD-GPO-05 | `ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty`, `ActiveDirectory:File:SYSVOL:Read` | -| `gpol` | AD-GPOL-01 through AD-GPOL-06 | `ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty`, `ActiveDirectory:File:SYSVOL:Read` | -| `gporep` | AD-GPOREP-01 through AD-GPOREP-20 | `ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty`, `ActiveDirectory:File:SYSVOL:Read` | +| `gmc` | AD-GMC-01, 02, 04, 06, 08, 10 | `ActiveDirectory:Ldap:group:ReadProperty`; membership checks also need `ActiveDirectory:Ldap:group.member:ReadProperty` | +| `gpo` | AD-GPO-01, 02, 04 | `ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty`, `ActiveDirectory:File:SYSVOL:Read` | +| `gpol` | AD-GPOL-01–05 | `ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty`, `ActiveDirectory:File:SYSVOL:Read` | +| `gporep` | AD-GPOREP-01, 03, 05, 06, 07, 09, 10, 12, 14, 15, 17 | `ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty`, `ActiveDirectory:File:SYSVOL:Read`; ACL-dependent checks need readable security descriptors | | `gpos` | AD-GPOS-01 through AD-GPOS-09 | `ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty`, `ActiveDirectory:File:SYSVOL:Read` | -| `grp` | AD-GRP-01 through AD-GRP-10 | `ActiveDirectory:Ldap:group:ReadProperty` | +| `grp` | AD-GRP-01–06, 08 | `ActiveDirectory:Ldap:group:ReadProperty` | | `krbtgt` | AD-KRBTGT-01 through AD-KRBTGT-03 | `ActiveDirectory:Ldap:user:ReadProperty` | -| `msa` | AD-MSA-01 | `ActiveDirectory:Ldap:msDS-GroupManagedServiceAccount:ReadProperty` | +| `msa` | AD-MSA-01 | `ActiveDirectory:Ldap:msDS-ManagedServiceAccount:ReadProperty`, `ActiveDirectory:Ldap:msDS-GroupManagedServiceAccount:ReadProperty`, `ActiveDirectory:Ldap:msDS-DelegatedManagedServiceAccount:ReadProperty` | | `ou` | AD-OU-01 through AD-OU-05 | `ActiveDirectory:Ldap:organizationalUnit:ReadProperty` | | `print` | AD-PRINT-01 | `ActiveDirectory:Ldap:printQueue:ReadProperty` | | `pwdpol` | AD-PWDPOL-01 through AD-PWDPOL-07 | `ActiveDirectory:Ldap:domainDNS:ReadProperty` | | `repl` | AD-REPL-01 through AD-REPL-02 | `ActiveDirectory:Ldap:nTDSConnection:ReadProperty` | -| `rootdse` | AD-ROOTDSE-01 through AD-ROOTDSE-03 | `ActiveDirectory:Ldap:domainDNS:ReadProperty` | -| `sch` | AD-SCH-01 through AD-SCH-05 | `ActiveDirectory:Ldap:attributeSchema:ReadProperty` | +| `rootdse` | AD-ROOTDSE-01, 03 | `ActiveDirectory:Ldap:domainDNS:ReadProperty` | +| `sch` | AD-SCH-01, 03, 05 | `ActiveDirectory:Ldap:Schema/*:ReadProperty`; SCH-05 distinguishes Windows LAPS schema from legacy LAPS | | `site` | AD-SITE-01 through AD-SITE-05 | `ActiveDirectory:Ldap:site:ReadProperty` | -| `spn` | AD-SPN-01 through AD-SPN-13 | `ActiveDirectory:Ldap:computer:ReadProperty`, `ActiveDirectory:Ldap:user:ReadProperty` | +| `spn` | AD-SPN-01, 03, 05, 06, 07, 09, 11, 12 | Computer/user permissions; SPN-12 also reads domain SID, groups and group membership | | `sub` | AD-SUB-01 through AD-SUB-11 | `ActiveDirectory:Ldap:subnet:ReadProperty` | -| `trust` | AD-TRUST-01 through AD-TRUST-07 | `ActiveDirectory:Ldap:trustedDomain:ReadProperty` | -| `user` | AD-USER-01 through AD-USER-29 | `ActiveDirectory:Ldap:user:ReadProperty` | +| `trust` | AD-TRUST-01, 02, 03, 06 | `ActiveDirectory:Ldap:trustedDomain:ReadProperty`; TRUST-06 cannot infer validation age from LDAP modification dates | +| `user` | AD-USER-01–13, 15–29 | `ActiveDirectory:Ldap:user:ReadProperty`; USER-14 was consolidated into SPN-06 | ## Known Misleading Outcomes @@ -176,19 +180,19 @@ The following behaviors can hide incomplete access. They are documented here so ### DACL tests (AD-DACL-*) -`Get-MtLdapDacl` delegates to `Invoke-MtLdapSearch` and returns an empty array when no entries match. An empty result is indistinguishable from insufficient access. Tests set `$testResult = $true` even when the array is empty, so a pass does not prove the DACL was fully read. +Merged DACL checks reject missing or empty collected entries rather than reporting a clean inventory. A nonempty response still does not prove that every object's DACL was readable. Confirm read access to the intended scope; DACL parsing requires Windows. ### GPO tests (AD-GPO-*, AD-GPOL-*, AD-GPOREP-*, AD-GPOS-*) -`Get-MtADGpoState` can return a non-null state with an empty GPO array. A non-null check therefore does not establish that GPO data was retrieved. GPO reads also depend on SMB/SYSVOL file access; an LDAP probe alone does not prove policy files were read. +`Get-MtADGpoState` uses `$null` for failed metadata or report collection, distinct from an empty inventory. The merged version and exposed-password checks reject incomplete reports or scans, including unreadable/malformed XML. GPOREP-10 skips off Windows because its permission parsing is Windows-only. An LDAP probe alone does not prove SYSVOL access or complete collection. ### DNS tests (AD-DNS-*) -If `Invoke-MtADManagementCommand` fails, the DNS category collector throws. `Get-MtADDomainState` catches the failure and leaves DNS arrays empty. The helper then skips with `NotConnectedActiveDirectoryDNS`, which does not distinguish "server has no data" from "query could not retrieve data." +If DNS management collection fails, the category is unavailable: scoped calls return null properties, and legacy unscoped calls may omit DNS keys. Do not interpret missing DNS data as an empty, healthy inventory. ### Configuration tests (AD-CFG-*) -`Get-MtLdapConfigurationContainer` catches individual query errors. The state object survives with empty arrays or null properties even when subqueries did not return data. +Configuration searches tolerate absent optional containers, but propagate genuine query failures so the category is unavailable. The Directory Service retrieval flag distinguishes an unreadable/missing object from unset attributes. LDAP ACL filtering can still hide objects without a query error, particularly KDS keys; zero visible results alone cannot establish absence. ### Transport and cache From fc6a5281b240a38d53489803b57f6897370ffc42 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 18:47:00 +0000 Subject: [PATCH 024/100] fix(ad): normalize cached AD collector evidence --- .../ad/protocol/ConvertFrom-MtLdapValue.ps1 | 6 +- .../Get-MtLdapConfigurationContainer.ps1 | 2 + .../services/ad/queries/Get-MtLdapDomain.ps1 | 20 ++- .../ad/queries/Get-MtLdapDomainController.ps1 | 54 ++++++-- .../Get-MtLdapFineGrainedPasswordPolicy.ps1 | 6 +- .../services/ad/queries/Get-MtLdapForest.ps1 | 9 +- .../services/ad/queries/Get-MtLdapPrinter.ps1 | 4 +- .../ad/queries/Get-MtLdapReplicationSite.ps1 | 2 +- .../services/ad/queries/Get-MtLdapUser.ps1 | 9 +- .../ADSecondBatchCollectors.Tests.ps1 | 128 ++++++++++++++++++ 10 files changed, 212 insertions(+), 28 deletions(-) create mode 100644 powershell/tests/functions/ADSecondBatchCollectors.Tests.ps1 diff --git a/powershell/internal/services/ad/protocol/ConvertFrom-MtLdapValue.ps1 b/powershell/internal/services/ad/protocol/ConvertFrom-MtLdapValue.ps1 index 3384d6305f..065a94b11f 100644 --- a/powershell/internal/services/ad/protocol/ConvertFrom-MtLdapValue.ps1 +++ b/powershell/internal/services/ad/protocol/ConvertFrom-MtLdapValue.ps1 @@ -58,6 +58,8 @@ 'minpwdage', 'lockoutduration', 'msds-lockoutduration', + 'lockoutobservationwindow', + 'msds-lockoutobservationwindow', 'msds-maximumpasswordage', 'msds-minimumpasswordage' ) @@ -107,7 +109,7 @@ } } - if ($NormalizedAttributeName -in @('iscriticalsystemobject', 'enabledconnection', 'msds-passwordcomplexityenabled', 'msds-isrodc')) { + if ($NormalizedAttributeName -in @('iscriticalsystemobject', 'enabledconnection', 'msds-passwordcomplexityenabled', 'msds-passwordreversibleencryptionenabled', 'msds-isrodc')) { $convertedBoolean = $false if ([bool]::TryParse($InputValue, [ref]$convertedBoolean)) { return $convertedBoolean @@ -225,7 +227,7 @@ return [int]$Value } - if ($normalizedAttributeName -in @('maxpwdage', 'minpwdage', 'lockoutduration', 'msds-lockoutduration', 'msds-maximumpasswordage', 'msds-minimumpasswordage')) { + if ($normalizedAttributeName -in @('maxpwdage', 'minpwdage', 'lockoutduration', 'lockoutobservationwindow', 'msds-lockoutduration', 'msds-lockoutobservationwindow', 'msds-maximumpasswordage', 'msds-minimumpasswordage')) { $intervalValue = [long]$Value if ($intervalValue -eq [long]::MinValue) { return [timespan]::Zero diff --git a/powershell/internal/services/ad/queries/Get-MtLdapConfigurationContainer.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapConfigurationContainer.ps1 index 710e8b156f..800aa0a2db 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapConfigurationContainer.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapConfigurationContainer.ps1 @@ -55,6 +55,8 @@ $siteLinks = @($rawSiteLinks | ForEach-Object { $replInterval = if ($null -ne $_.replInterval) { [int]$_.replInterval } else { $null } $_ | Add-Member -NotePropertyName ReplicationFrequencyInMinutes -NotePropertyValue $replInterval -Force + $transport = if ([string]$_.DistinguishedName -match '(?i),CN=(IP|SMTP),CN=Inter-Site Transports,') { $matches[1].ToUpperInvariant() } else { $null } + $_ | Add-Member -NotePropertyName TransportName -NotePropertyValue $transport -Force $_ }) diff --git a/powershell/internal/services/ad/queries/Get-MtLdapDomain.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapDomain.ps1 index 16d6130788..0d394ac3db 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapDomain.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapDomain.ps1 @@ -36,7 +36,7 @@ $SearchBase = $rootDse.DefaultNamingContext } - $attributes = @('distinguishedName', 'name', 'objectSid', 'lockoutDuration', 'lockoutThreshold', 'maxPwdAge', 'minPwdAge', 'minPwdLength', 'ms-DS-MachineAccountQuota', 'pwdProperties', 'pwdHistoryLength', 'rIDAvailablePool', 'objectVersion', 'whenCreated', 'whenChanged', 'msDS-Behavior-Version', 'fSMORoleOwner', 'msDS-AllowedDNSSuffixes') + $attributes = @('distinguishedName', 'name', 'objectSid', 'lockoutDuration', 'lockoutThreshold', 'lockOutObservationWindow', 'maxPwdAge', 'minPwdAge', 'minPwdLength', 'ms-DS-MachineAccountQuota', 'pwdProperties', 'pwdHistoryLength', 'objectVersion', 'whenCreated', 'whenChanged', 'msDS-Behavior-Version', 'fSMORoleOwner', 'msDS-AllowedDNSSuffixes', 'msDS-LogonTimeSyncInterval') $entry = Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Base -Filter '(objectClass=domainDNS)' -Attributes $attributes -PageSize 0 | Select-Object -First 1 if ($null -eq $entry) { return $null @@ -46,9 +46,9 @@ $crossRef = $crossRefs | Where-Object { $_.nCName -eq $SearchBase } | Select-Object -First 1 $infrastructure = Invoke-MtLdapSearch -Connection $Connection -SearchBase "CN=Infrastructure,$SearchBase" -Scope Base -Filter '(objectClass=infrastructureUpdate)' -Attributes @('fSMORoleOwner') -PageSize 0 | Select-Object -First 1 - $ridManager = Invoke-MtLdapSearch -Connection $Connection -SearchBase ('CN=RID Manager$,CN=System,' + $SearchBase) -Scope Base -Filter '(objectClass=rIDManager)' -Attributes @('fSMORoleOwner') -PageSize 0 | Select-Object -First 1 + $ridManager = Invoke-MtLdapSearch -Connection $Connection -SearchBase ('CN=RID Manager$,CN=System,' + $SearchBase) -Scope Base -Filter '(objectClass=rIDManager)' -Attributes @('fSMORoleOwner', 'rIDAvailablePool') -PageSize 0 | Select-Object -First 1 $domainModeNames = @('Windows2000Domain', 'Windows2003InterimDomain', 'Windows2003Domain', 'Windows2008Domain', 'Windows2008R2Domain', 'Windows2012Domain', 'Windows2012R2Domain', 'Windows2016Domain') - $domainModeValue = [int]$entry.'msDS-Behavior-Version' + $domainModeValue = if ($null -ne $entry.'msDS-Behavior-Version') { [int]$entry.'msDS-Behavior-Version' } else { $null } return [PSCustomObject]@{ DistinguishedName = [string]$entry.DistinguishedName @@ -57,19 +57,29 @@ DomainSID = $entry.objectSid LockoutDuration = $entry.lockoutDuration LockoutThreshold = $entry.lockoutThreshold + LockoutObservationWindow = $entry.lockOutObservationWindow MaxPwdAge = $entry.maxPwdAge MinPwdAge = $entry.minPwdAge MinPwdLength = $entry.minPwdLength MsDsMachineAccountQuota = $entry.'ms-DS-MachineAccountQuota' PwdProperties = $entry.pwdProperties + ComplexityEnabled = if ($null -ne $entry.pwdProperties) { ([int]$entry.pwdProperties -band 1) -ne 0 } else { $null } + ReversibleEncryptionEnabled = if ($null -ne $entry.pwdProperties) { ([int]$entry.pwdProperties -band 16) -ne 0 } else { $null } + PasswordExpirationDisabled = if ($null -ne $entry.maxPwdAge) { $entry.maxPwdAge -eq [timespan]::Zero } else { $null } + LockoutRequiresAdminUnlock = if ($null -ne $entry.lockoutDuration) { $entry.lockoutDuration -eq [timespan]::Zero } else { $null } PwdHistoryLength = $entry.pwdHistoryLength - RIDAvailablePool = $entry.rIDAvailablePool + RIDAvailablePool = $ridManager.rIDAvailablePool ObjectVersion = $entry.objectVersion WhenCreated = $entry.whenCreated WhenChanged = $entry.whenChanged DnsRoot = ConvertFrom-DomainDistinguishedName -DistinguishedName $SearchBase Forest = ConvertFrom-DomainDistinguishedName -DistinguishedName $rootDse.RootDomainNamingContext - DomainMode = if ($domainModeValue -ge 0 -and $domainModeValue -lt $domainModeNames.Count) { $domainModeNames[$domainModeValue] } else { $domainModeValue } + DomainMode = if ($domainModeValue -eq 10) { 'Windows2025Domain' } elseif ($null -ne $domainModeValue -and $domainModeValue -ge 0 -and $domainModeValue -lt $domainModeNames.Count) { $domainModeNames[$domainModeValue] } else { $domainModeValue } + DomainLevelValue = $domainModeValue + PdcOwnerDistinguishedName = [string]$entry.fSMORoleOwner + RidOwnerDistinguishedName = [string]$ridManager.fSMORoleOwner + InfrastructureOwnerDistinguishedName = [string]$infrastructure.fSMORoleOwner + LogonTimeSyncIntervalDays = $entry.'msDS-LogonTimeSyncInterval' InfrastructureMaster = Resolve-FsmoOwner -OwnerDistinguishedName ([string]$infrastructure.fSMORoleOwner) PDCEmulator = Resolve-FsmoOwner -OwnerDistinguishedName ([string]$entry.fSMORoleOwner) RIDMaster = Resolve-FsmoOwner -OwnerDistinguishedName ([string]$ridManager.fSMORoleOwner) diff --git a/powershell/internal/services/ad/queries/Get-MtLdapDomainController.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapDomainController.ps1 index 97f417105c..f83c7c0479 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapDomainController.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapDomainController.ps1 @@ -10,30 +10,51 @@ ) $searchBase = "CN=Sites,$ConfigurationNamingContext" - $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $searchBase -Scope Subtree -Filter '(objectClass=nTDSDSA)' -Attributes @('distinguishedName', 'name', 'options', 'invocationId')) + $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $searchBase -Scope Subtree -Filter '(objectClass=nTDSDSA)' -Attributes @('distinguishedName', 'name', 'objectClass', 'options', 'invocationId', 'msDS-Behavior-Version', 'msDS-isRODC')) + $siteNames = @{} return @($entries | ForEach-Object { - $serverDn = $_.DistinguishedName -replace '^[^,]+,', '' + $serverDn = $_.DistinguishedName -replace '^(?:\\.|[^,])+,', '' # Extract site name from DN: CN=,CN=Servers,CN=,CN=Sites,... $site = $null - $parts = $serverDn -split ',CN=Sites,', 2 - if ($parts.Count -eq 2) { - $siteParts = $parts[0] -split ',CN=Servers,', 2 - if ($siteParts.Count -eq 2) { - $site = $siteParts[1] -replace '^CN=', '' + $siteDn = $null + $collectionError = $null + if ($serverDn -match '(?i),CN=Servers,(?.+)$') { + $siteDn = $matches['siteDn'] + if (-not $siteNames.ContainsKey($siteDn)) { + try { + $siteEntry = Invoke-MtLdapSearch -Connection $Connection -SearchBase $siteDn -Scope Base -Filter '(objectClass=site)' -Attributes @('name') -PageSize 0 | Select-Object -First 1 + $siteNames[$siteDn] = if ($null -ne $siteEntry) { [string]$siteEntry.name } else { $null } + } + catch { $siteNames[$siteDn] = $null } } + $site = $siteNames[$siteDn] } - $server = Invoke-MtLdapSearch -Connection $Connection -SearchBase $serverDn -Scope Base -Filter '(objectClass=server)' -Attributes @('name', 'dNSHostName', 'serverReference') -PageSize 0 | Select-Object -First 1 + $server = $null + try { + $server = Invoke-MtLdapSearch -Connection $Connection -SearchBase $serverDn -Scope Base -Filter '(objectClass=server)' -Attributes @('name', 'dNSHostName', 'serverReference') -PageSize 0 | Select-Object -First 1 + } + catch { $collectionError = 'DC server metadata could not be read from the selected directory target.' } + if ($null -eq $server) { $collectionError = 'DC server metadata was not returned by the selected directory target.' } # Query computer object for operatingSystem and RODC status $operatingSystem = $null - $isReadOnly = $false + $operatingSystemVersion = $null + $isReadOnly = if ($null -ne $_.'msDS-isRODC') { [bool]$_.'msDS-isRODC' } elseif (@($_.objectClass) -contains 'nTDSDSARO') { $true } elseif (@($_.objectClass) -contains 'nTDSDSA') { $false } else { $null } if (-not [string]::IsNullOrWhiteSpace($server.serverReference)) { - $computer = Invoke-MtLdapSearch -Connection $Connection -SearchBase $server.serverReference -Scope Base -Filter '(objectClass=computer)' -Attributes @('operatingSystem', 'msDS-IsRODC') -PageSize 0 | Select-Object -First 1 - $operatingSystem = $computer.operatingSystem - $isReadOnly = if ($null -ne $computer.'msDS-IsRODC') { [bool]$computer.'msDS-IsRODC' } else { $false } + try { + $computer = Invoke-MtLdapSearch -Connection $Connection -SearchBase $server.serverReference -Scope Base -Filter '(objectClass=computer)' -Attributes @('operatingSystem', 'operatingSystemVersion', 'msDS-IsRODC') -PageSize 0 | Select-Object -First 1 + if ($null -eq $computer) { $collectionError = 'DC computer metadata was not returned; cross-domain visibility may be incomplete.' } + else { + $operatingSystem = $computer.operatingSystem + $operatingSystemVersion = $computer.operatingSystemVersion + if ($null -eq $isReadOnly -and $null -ne $computer.'msDS-IsRODC') { $isReadOnly = [bool]$computer.'msDS-IsRODC' } + } + } + catch { $collectionError = 'DC computer metadata could not be read; cross-domain visibility may be incomplete.' } } + elseif ($null -eq $collectionError) { $collectionError = 'DC serverReference is unavailable; computer metadata cannot be resolved.' } $optionsValue = if ($null -ne $_.options) { [int]$_.options } else { 0 } @@ -45,11 +66,16 @@ Options = $_.options InvocationId = $_.invocationId Site = $site + SiteDistinguishedName = $siteDn OperatingSystem = [string]$operatingSystem + OperatingSystemVersion = [string]$operatingSystemVersion + SupportedLevelValue = if ($null -ne $_.'msDS-Behavior-Version') { [int]$_.'msDS-Behavior-Version' } else { $null } IsGlobalCatalog = [bool]($optionsValue -band 0x1) IsReadOnly = $isReadOnly - LdapPort = 389 - SslPort = 636 + LdapPort = $null + SslPort = $null + PortEvidence = 'Not measured' + CollectionError = $collectionError } }) } diff --git a/powershell/internal/services/ad/queries/Get-MtLdapFineGrainedPasswordPolicy.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapFineGrainedPasswordPolicy.ps1 index 59fd5fa584..f1adf24e36 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapFineGrainedPasswordPolicy.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapFineGrainedPasswordPolicy.ps1 @@ -9,12 +9,16 @@ ) if ([string]::IsNullOrWhiteSpace($SearchBase)) { $SearchBase = (Get-MtLdapRootDse -Connection $Connection).DefaultNamingContext } - $attributes = @('distinguishedName', 'name', 'msDS-PasswordSettingsPrecedence', 'msDS-LockoutDuration', 'msDS-LockoutThreshold', 'msDS-MaximumPasswordAge', 'msDS-MinimumPasswordAge', 'msDS-MinimumPasswordLength', 'msDS-PasswordComplexityEnabled', 'msDS-PasswordHistoryLength', 'msDS-PSOAppliesTo') + $attributes = @('distinguishedName', 'name', 'msDS-PasswordSettingsPrecedence', 'msDS-LockoutDuration', 'msDS-LockoutThreshold', 'msDS-LockoutObservationWindow', 'msDS-MaximumPasswordAge', 'msDS-MinimumPasswordAge', 'msDS-MinimumPasswordLength', 'msDS-PasswordComplexityEnabled', 'msDS-PasswordReversibleEncryptionEnabled', 'msDS-PasswordHistoryLength', 'msDS-PSOAppliesTo') $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter '(objectClass=msDS-PasswordSettings)' -Attributes $attributes) return @($entries | ForEach-Object { [PSCustomObject]@{ DistinguishedName = [string]$_.DistinguishedName; Name = [string]$_.name; MsDsPasswordSettingsPrecedence = $_.'msDS-PasswordSettingsPrecedence' LockoutDuration = $_.'msDS-LockoutDuration'; LockoutThreshold = $_.'msDS-LockoutThreshold'; MaxPwdAge = $_.'msDS-MaximumPasswordAge' MinPwdAge = $_.'msDS-MinimumPasswordAge'; MinPwdLength = $_.'msDS-MinimumPasswordLength'; PwdProperties = $_.'msDS-PasswordComplexityEnabled' + ComplexityEnabled = $_.'msDS-PasswordComplexityEnabled'; ReversibleEncryptionEnabled = $_.'msDS-PasswordReversibleEncryptionEnabled' + LockoutObservationWindow = $_.'msDS-LockoutObservationWindow' + PasswordExpirationDisabled = if ($null -ne $_.'msDS-MaximumPasswordAge') { $_.'msDS-MaximumPasswordAge' -eq [timespan]::Zero } else { $null } + LockoutRequiresAdminUnlock = if ($null -ne $_.'msDS-LockoutDuration') { $_.'msDS-LockoutDuration' -eq [timespan]::Zero } else { $null } PwdHistoryLength = $_.'msDS-PasswordHistoryLength'; MsDsPsoAppliesTo = @($_.'msDS-PSOAppliesTo' | Where-Object { $null -ne $_ }) } }) } diff --git a/powershell/internal/services/ad/queries/Get-MtLdapForest.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapForest.ps1 index 38fcadd55c..7a218b2a72 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapForest.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapForest.ps1 @@ -38,7 +38,7 @@ }) $rootPartition = $domainPartitions | Where-Object { $_.nCName -eq $rootDse.RootDomainNamingContext } | Select-Object -First 1 $forestModeNames = @('Windows2000Forest', 'Windows2003InterimForest', 'Windows2003Forest', 'Windows2008Forest', 'Windows2008R2Forest', 'Windows2012Forest', 'Windows2012R2Forest', 'Windows2016Forest') - $forestModeValue = [int]$rootDse.ForestFunctionality + $forestModeValue = if ($null -ne $rootDse.ForestFunctionality) { [int]$rootDse.ForestFunctionality } else { $null } $fallbackRootDomain = (([regex]::Matches($rootDse.RootDomainNamingContext, '(?i)(?:^|,)DC=([^,]+)') | ForEach-Object { $_.Groups[1].Value }) -join '.') $crossForestReferences = @($partitions | Where-Object { @@ -59,9 +59,14 @@ return [PSCustomObject]@{ RootDomain = if ($null -ne $rootPartition) { [string]$rootPartition.dnsRoot } else { $fallbackRootDomain } Domains = [string[]]@($domainPartitions | ForEach-Object { $_.dnsRoot } | Sort-Object -Unique) - ForestMode = if ($forestModeValue -ge 0 -and $forestModeValue -lt $forestModeNames.Count) { $forestModeNames[$forestModeValue] } else { $forestModeValue } + ForestMode = if ($forestModeValue -eq 10) { 'Windows2025Forest' } elseif ($null -ne $forestModeValue -and $forestModeValue -ge 0 -and $forestModeValue -lt $forestModeNames.Count) { $forestModeNames[$forestModeValue] } else { $forestModeValue } + ForestLevelValue = $forestModeValue + RootDomainDistinguishedName = [string]$rootDse.RootDomainNamingContext + DomainPartitions = @($domainPartitions | ForEach-Object { [pscustomobject]@{ DistinguishedName = [string]$_.nCName; DnsRoot = [string]$_.dnsRoot; NetBIOSName = [string]$_.nETBIOSName } }) SchemaMaster = Resolve-FsmoOwner -OwnerDistinguishedName ([string]$schemaFsmo.fSMORoleOwner) DomainNamingMaster = Resolve-FsmoOwner -OwnerDistinguishedName ([string]$partitionsContainer.fSMORoleOwner) + SchemaOwnerDistinguishedName = [string]$schemaFsmo.fSMORoleOwner + DomainNamingOwnerDistinguishedName = [string]$partitionsContainer.fSMORoleOwner UPNSuffixes = [string[]]@(@($partitionsContainer.uPNSuffixes) | Where-Object { $null -ne $_ }) SPNSuffixes = [string[]]@(@($partitionsContainer.'msDS-SPNSuffixes') | Where-Object { $null -ne $_ }) CrossForestReferences = $crossForestReferences diff --git a/powershell/internal/services/ad/queries/Get-MtLdapPrinter.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapPrinter.ps1 index 3f7077edd9..bb484f9474 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapPrinter.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapPrinter.ps1 @@ -9,6 +9,6 @@ ) if ([string]::IsNullOrWhiteSpace($SearchBase)) { $SearchBase = (Get-MtLdapRootDse -Connection $Connection).DefaultNamingContext } - $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter '(objectClass=printQueue)' -Attributes @('distinguishedName', 'name', 'serverName', 'location')) - return @($entries | ForEach-Object { [PSCustomObject]@{ DistinguishedName = [string]$_.DistinguishedName; Name = [string]$_.name; ServerName = [string]$_.serverName; Location = [string]$_.location } }) + $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter '(objectClass=printQueue)' -Attributes @('distinguishedName', 'name', 'serverName', 'location', 'description')) + return @($entries | ForEach-Object { [PSCustomObject]@{ DistinguishedName = [string]$_.DistinguishedName; Name = [string]$_.name; ServerName = [string]$_.serverName; Location = [string]$_.location; Description = [string]$_.description } }) } diff --git a/powershell/internal/services/ad/queries/Get-MtLdapReplicationSite.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapReplicationSite.ps1 index b6ac800456..b6d875aa6a 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapReplicationSite.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapReplicationSite.ps1 @@ -10,5 +10,5 @@ ) $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase "CN=Sites,$ConfigurationNamingContext" -Scope Subtree -Filter '(objectClass=site)' -Attributes @('distinguishedName', 'name')) - return @($entries | ForEach-Object { [PSCustomObject]@{ Name = [string]$_.name; DistinguishedName = [string]$_.DistinguishedName } }) + return @($entries | ForEach-Object { [PSCustomObject]@{ Name = [string]$_.name; DistinguishedName = [string]$_.DistinguishedName; ObjectClass = @('site') } }) } diff --git a/powershell/internal/services/ad/queries/Get-MtLdapUser.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapUser.ps1 index 75090d437d..2624ea12ba 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapUser.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapUser.ps1 @@ -9,7 +9,7 @@ ) if ([string]::IsNullOrWhiteSpace($SearchBase)) { $SearchBase = (Get-MtLdapRootDse -Connection $Connection).DefaultNamingContext } - $attributes = @('distinguishedName', 'name', 'sAMAccountName', 'userAccountControl', 'adminCount', 'homeDirectory', 'badPasswordTime', 'lastLogonTimestamp', 'lockoutTime', 'logonHours', 'userWorkstations', 'managedBy', 'manager', 'pwdLastSet', 'profilePath', 'scriptPath', 'objectSid', 'sIDHistory', 'servicePrincipalName', 'whenCreated', 'whenChanged', 'isCriticalSystemObject', 'primaryGroupID') + $attributes = @('distinguishedName', 'name', 'sAMAccountName', 'userAccountControl', 'adminCount', 'homeDirectory', 'badPasswordTime', 'lastLogonTimestamp', 'lockoutTime', 'logonHours', 'userWorkstations', 'managedBy', 'manager', 'pwdLastSet', 'profilePath', 'scriptPath', 'objectSid', 'sIDHistory', 'servicePrincipalName', 'whenCreated', 'whenChanged', 'isCriticalSystemObject', 'primaryGroupID', 'msDS-ResultantPSO', 'msDS-SecondaryKrbTgtNumber', 'msDS-KrbTgtLinkBL', 'msDS-AllowedToDelegateTo', 'msDS-AllowedToActOnBehalfOfOtherIdentity') $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter '(&(objectClass=user)(!(objectClass=computer)))' -Attributes $attributes) return @($entries | ForEach-Object { $uac = if ($null -ne $_.userAccountControl) { ConvertFrom-MtLdapUserAccountControl -UserAccountControl ([int]$_.userAccountControl) } else { $null } @@ -22,6 +22,13 @@ PasswordNeverExpires = if ($null -ne $uac) { $uac.DontExpirePassword } else { $null }; PasswordNotRequired = if ($null -ne $uac) { $uac.PasswordNotRequired } else { $null }; ProfilePath = [string]$_.profilePath ScriptPath = [string]$_.scriptPath; Sid = $_.objectSid; SidHistory = @($_.sIDHistory | Where-Object { $null -ne $_ }); ServicePrincipalName = [string[]]@($_.servicePrincipalName | Where-Object { $null -ne $_ }) PrimaryGroupId = $_.primaryGroupID + ResultantPasswordPolicyDN = if ($null -ne $_.'msDS-ResultantPSO') { [string]$_.'msDS-ResultantPSO' } else { $null } + ResultantPasswordPolicyAttributeReturned = -not [string]::IsNullOrWhiteSpace([string]$_.'msDS-ResultantPSO') + SecondaryKrbtgtNumber = $_.'msDS-SecondaryKrbTgtNumber' + KrbtgtLinkBacklinks = @($_.'msDS-KrbTgtLinkBL' | Where-Object { $null -ne $_ }) + ReversibleEncryptionEnabled = if ($null -ne $_.userAccountControl) { ([int]$_.userAccountControl -band 0x80) -ne 0 } else { $null } + AllowedToDelegateTo = [string[]]@($_.'msDS-AllowedToDelegateTo' | Where-Object { $null -ne $_ }) + HasResourceBasedConstrainedDelegation = $null -ne $_.'msDS-AllowedToActOnBehalfOfOtherIdentity' TrustedForDelegation = if ($null -ne $uac) { $uac.TrustedForDelegation } else { $null }; TrustedToAuthForDelegation = if ($null -ne $uac) { $uac.TrustedToAuthForDelegation } else { $null }; UseDESKeyOnly = if ($null -ne $uac) { $uac.UseDesKeyOnly } else { $null } UserAccountControl = if ($null -ne $_.userAccountControl) { [int]$_.userAccountControl } else { $null }; Created = $_.whenCreated; Modified = $_.whenChanged; IsCriticalSystemObject = if ($null -ne $_.isCriticalSystemObject) { [bool]$_.isCriticalSystemObject } else { $null } } diff --git a/powershell/tests/functions/ADSecondBatchCollectors.Tests.ps1 b/powershell/tests/functions/ADSecondBatchCollectors.Tests.ps1 new file mode 100644 index 0000000000..c85ddf17f6 --- /dev/null +++ b/powershell/tests/functions/ADSecondBatchCollectors.Tests.ps1 @@ -0,0 +1,128 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'AD second-batch collector contracts' { + BeforeEach { + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { } + Mock -ModuleName Maester Get-MtLdapRootDse -RemoveParameterType Connection { + [pscustomobject]@{ DefaultNamingContext = 'DC=example,DC=com'; RootDomainNamingContext = 'DC=example,DC=com'; ConfigurationNamingContext = 'CN=Configuration,DC=example,DC=com'; ForestFunctionality = 10 } + } + } + + It 'normalizes AD interval sentinels without conflating their meanings' { + InModuleScope Maester { + (ConvertFrom-MtLdapValue -Value ([long]::MinValue.ToString()) -AttributeName 'maxPwdAge') | Should -Be ([timespan]::Zero) + (ConvertFrom-MtLdapValue -Value '-9000000000' -AttributeName 'lockOutObservationWindow') | Should -Be ([timespan]::FromMinutes(15)) + (ConvertFrom-MtLdapValue -Value '-9000000000' -AttributeName 'msDS-LockoutObservationWindow') | Should -Be ([timespan]::FromMinutes(15)) + (ConvertFrom-MtLdapValue -Value 'FALSE' -AttributeName 'msDS-PasswordReversibleEncryptionEnabled') | Should -BeFalse + } + } + + It 'keeps PSO complexity and reversible encryption as separate booleans' { + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { + [pscustomobject]@{ + name = 'PSO'; DistinguishedName = 'CN=PSO,DC=example,DC=com' + 'msDS-PasswordComplexityEnabled' = $false; 'msDS-PasswordReversibleEncryptionEnabled' = $true + 'msDS-MaximumPasswordAge' = [timespan]::Zero; 'msDS-LockoutDuration' = [timespan]::Zero + 'msDS-LockoutObservationWindow' = [timespan]::FromMinutes(15) + } + } + InModuleScope Maester { + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') + try { + $pso = @(Get-MtLdapFineGrainedPasswordPolicy -Connection $connection -SearchBase 'DC=example,DC=com')[0] + $pso.ComplexityEnabled | Should -BeFalse + $pso.ReversibleEncryptionEnabled | Should -BeTrue + $pso.PasswordExpirationDisabled | Should -BeTrue + $pso.LockoutRequiresAdminUnlock | Should -BeTrue + $pso.LockoutObservationWindow | Should -Be ([timespan]::FromMinutes(15)) + } + finally { $connection.Dispose() } + } + } + + It 'collects protected krbtgt markers and resultant policy without password secrets' { + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { + [pscustomobject]@{ + name = 'RODC key'; sAMAccountName = 'krbtgt_1234'; userAccountControl = 514 + 'msDS-SecondaryKrbTgtNumber' = 1234; 'msDS-KrbTgtLinkBL' = @('CN=RODC,DC=example,DC=com') + 'msDS-ResultantPSO' = 'CN=PSO,DC=example,DC=com' + } + } + InModuleScope Maester { + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') + try { + $user = @(Get-MtLdapUser -Connection $connection -SearchBase 'DC=example,DC=com')[0] + $user.SecondaryKrbtgtNumber | Should -Be 1234 + $user.KrbtgtLinkBacklinks | Should -HaveCount 1 + $user.ResultantPasswordPolicyDN | Should -Be 'CN=PSO,DC=example,DC=com' + } + finally { $connection.Dispose() } + } + Should -Invoke Invoke-MtLdapSearch -ModuleName Maester -ParameterFilter { + $Attributes -contains 'msDS-ResultantPSO' -and $Attributes -contains 'msDS-SecondaryKrbTgtNumber' -and + @($Attributes | Where-Object { $_ -in 'unicodePwd', 'supplementalCredentials', 'ntPwdHistory', 'msDS-ManagedPassword' }).Count -eq 0 + } + } + + It 'reports foreign DC metadata as unknown without erasing the forest inventory' { + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { + @( + [pscustomobject]@{ DistinguishedName = 'CN=NTDS Settings,CN=DC1,CN=Servers,CN=East\,Branch,CN=Sites,CN=Configuration,DC=example,DC=com'; objectClass = @('nTDSDSA'); options = 1; 'msDS-Behavior-Version' = 10 } + [pscustomobject]@{ DistinguishedName = 'CN=NTDS Settings,CN=DC2,CN=Servers,CN=East\,Branch,CN=Sites,CN=Configuration,DC=example,DC=com'; objectClass = @('nTDSDSA'); options = $null } + ) + } -ParameterFilter { $Filter -eq '(objectClass=nTDSDSA)' } + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { + [pscustomobject]@{ name = 'East,Branch' } + } -ParameterFilter { $Filter -eq '(objectClass=site)' } + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { + if ($SearchBase -match '^CN=DC1,') { [pscustomobject]@{ name = 'DC1'; dNSHostName = 'dc1.example.com'; serverReference = 'CN=DC1,OU=DCs,DC=example,DC=com' } } + else { [pscustomobject]@{ name = 'DC2'; dNSHostName = 'dc2.child.example.com'; serverReference = 'CN=DC2,OU=DCs,DC=child,DC=example,DC=com' } } + } -ParameterFilter { $Filter -eq '(objectClass=server)' } + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { + if ($SearchBase -match 'DC=child,') { throw 'Foreign naming context unavailable' } + [pscustomobject]@{ operatingSystem = 'Windows Server 2025'; operatingSystemVersion = '10.0 (26100)'; 'msDS-IsRODC' = $false } + } -ParameterFilter { $Filter -eq '(objectClass=computer)' } + InModuleScope Maester { + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') + try { + $dcs = @(Get-MtLdapDomainController -Connection $connection -ConfigurationNamingContext 'CN=Configuration,DC=example,DC=com') + $dcs | Should -HaveCount 2 + $dcs[0].Site | Should -Be 'East,Branch' + $dcs[0].OperatingSystemVersion | Should -Be '10.0 (26100)' + $dcs[0].LdapPort | Should -BeNullOrEmpty + $dcs[0].SslPort | Should -BeNullOrEmpty + $dcs[1].CollectionError | Should -Match 'cross-domain visibility' + $dcs[1].OperatingSystem | Should -BeNullOrEmpty + $dcs[1].IsReadOnly | Should -BeFalse + $dcs[1].IsGlobalCatalog | Should -BeFalse + } + finally { $connection.Dispose() } + } + } + + It 'reads RID availability from the RID manager and exposes stable domain role DNs' { + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { + [pscustomobject]@{ DistinguishedName = 'DC=example,DC=com'; name = 'example'; 'msDS-Behavior-Version' = 10; pwdProperties = 17; maxPwdAge = [timespan]::Zero; lockoutDuration = [timespan]::Zero; fSMORoleOwner = 'CN=NTDS Settings,CN=DC1,CN=Servers,CN=Site,CN=Sites,CN=Configuration,DC=example,DC=com' } + } -ParameterFilter { $Filter -eq '(objectClass=domainDNS)' } + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { + [pscustomobject]@{ rIDAvailablePool = 4611686014132422709L; fSMORoleOwner = 'CN=NTDS Settings,CN=DC1,CN=Servers,CN=Site,CN=Sites,CN=Configuration,DC=example,DC=com' } + } -ParameterFilter { $Filter -eq '(objectClass=rIDManager)' } + InModuleScope Maester { + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') + try { + $domain = Get-MtLdapDomain -Connection $connection -SearchBase 'DC=example,DC=com' + $domain.DomainMode | Should -Be 'Windows2025Domain' + $domain.DomainLevelValue | Should -Be 10 + $domain.RIDAvailablePool | Should -Be 4611686014132422709L + $domain.PdcOwnerDistinguishedName | Should -Match '^CN=NTDS Settings,' + $domain.ComplexityEnabled | Should -BeTrue + $domain.ReversibleEncryptionEnabled | Should -BeTrue + $domain.PasswordExpirationDisabled | Should -BeTrue + $domain.LockoutRequiresAdminUnlock | Should -BeTrue + } + finally { $connection.Dispose() } + } + } +} From da6d453aa8ad75f1509485bb1a89b8e8c65f1a4a Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 18:47:11 +0000 Subject: [PATCH 025/100] fix(ad): consolidate user delegation assessment --- tests/ad/delegation/Test.AD-USER-05.md | 8 ++ tests/ad/delegation/Test.AD-USER-05.ps1 | 21 +++++ tests/ad/user/Test.AD-USER-05.md | 27 ------ tests/ad/user/Test.AD-USER-05.ps1 | 82 ------------------ tests/ad/user/Test.AD-USER-28.md | 28 ------ tests/ad/user/Test.AD-USER-28.ps1 | 72 ---------------- tests/ad/user/Test.AD-USER-29.md | 28 ------ tests/ad/user/Test.AD-USER-29.ps1 | 109 ------------------------ 8 files changed, 29 insertions(+), 346 deletions(-) create mode 100644 tests/ad/delegation/Test.AD-USER-05.md create mode 100644 tests/ad/delegation/Test.AD-USER-05.ps1 delete mode 100644 tests/ad/user/Test.AD-USER-05.md delete mode 100644 tests/ad/user/Test.AD-USER-05.ps1 delete mode 100644 tests/ad/user/Test.AD-USER-28.md delete mode 100644 tests/ad/user/Test.AD-USER-28.ps1 delete mode 100644 tests/ad/user/Test.AD-USER-29.md delete mode 100644 tests/ad/user/Test.AD-USER-29.ps1 diff --git a/tests/ad/delegation/Test.AD-USER-05.md b/tests/ad/delegation/Test.AD-USER-05.md new file mode 100644 index 0000000000..695db41583 --- /dev/null +++ b/tests/ad/delegation/Test.AD-USER-05.md @@ -0,0 +1,8 @@ +User accounts trusted for unconstrained delegation can expose tickets and support lateral movement after compromise. This check fails on the unconstrained flag and separately reports constrained, protocol-transition and resource-based delegation indicators for human review; protocol transition alone does not establish a valid constrained target. AD-USER-28 and AD-USER-29 were consolidated here. + +#### Remediation action +1. Review delegated users and their service dependencies using [Microsoft delegation guidance](https://learn.microsoft.com/windows-server/security/kerberos/kerberos-constrained-delegation-overview). +2. Remove unconstrained delegation, migrate to scoped delegation or managed identities and review all allowed targets. + + +%TestResult% diff --git a/tests/ad/delegation/Test.AD-USER-05.ps1 b/tests/ad/delegation/Test.AD-USER-05.ps1 new file mode 100644 index 0000000000..12c08bff26 --- /dev/null +++ b/tests/ad/delegation/Test.AD-USER-05.ps1 @@ -0,0 +1,21 @@ +function Test-MtAdUserDelegationAllowedCount { + <# .SYNOPSIS + Detects user accounts trusted for unconstrained delegation and inventories other delegation modes. + #> + [MaesterTest(Id = 'AD-USER-05', Title = 'No user should have unconstrained Kerberos delegation', Product = 'ad', Feature = 'permissions', Area = 'authentication', ResourceType = 'User', Severity = 'High', UserImpact = 'Low', ImplementationCost = 'Medium', Mitre = ('T1558', 'T1550.003'), Control = 'nist-800-53-r5:AC-6', Service = 'ActiveDirectory', Permission = 'ActiveDirectory:Ldap:user:ReadProperty', Author = 'soulemike')] + [CmdletBinding()] + [OutputType([bool])] + param() + + $state = Get-MtADDomainState -Categories @('Users') + if ($null -eq $state.Users) { throw 'AD user data was not returned.' } + Assert-MtAdUserAccountControl -Users @($state.Users) + $unconstrained = @($state.Users | Where-Object { $_.TrustedForDelegation -eq $true -or ($null -ne $_.UserAccountControl -and (([int64]$_.UserAccountControl -band 0x80000) -ne 0)) }) + $constrained = @($state.Users | Where-Object { @($_.AllowedToDelegateTo | Where-Object { $null -ne $_ }).Count -gt 0 -or $_.TrustedToAuthForDelegation -eq $true -or $_.HasResourceBasedConstrainedDelegation -eq $true }) + $reviewAccounts = @(@($unconstrained) + @($constrained) | Sort-Object DistinguishedName -Unique) + $table = Format-MtAdUserSecurityTable $reviewAccounts @('SamAccountName', 'Enabled', 'TrustedForDelegation', 'TrustedToAuthForDelegation', 'AllowedToDelegateTo', 'HasResourceBasedConstrainedDelegation', 'DistinguishedName') + if ($unconstrained.Count) { Add-MtTestResultDetail -Result "Found $($unconstrained.Count) users with unconstrained delegation; restrict or migrate delegation. $($constrained.Count) users have constrained/protocol-transition/resource-based indicators that require separate review; a protocol-transition flag alone does not establish a constrained delegation target.`n`n$table" } + elseif ($constrained.Count) { Add-MtTestResultDetail -Result "No unconstrained delegation found. Review $($constrained.Count) users with constrained/protocol-transition/resource-based delegation indicators; no claim of unconstrained delegation is made.`n`n$table" -Investigate } + else { Add-MtTestResultDetail -Result 'Well done. No user delegation indicators were found.' } + return ($unconstrained.Count -eq 0) +} diff --git a/tests/ad/user/Test.AD-USER-05.md b/tests/ad/user/Test.AD-USER-05.md deleted file mode 100644 index 360e04e8df..0000000000 --- a/tests/ad/user/Test.AD-USER-05.md +++ /dev/null @@ -1,27 +0,0 @@ -Delegation-capable user accounts can impersonate users to downstream services. If these accounts are over-privileged or poorly protected, they can become valuable pivot points for privilege escalation and lateral movement. - -#### Control Type - -**Detective** - -#### Security Recommendation - -Limit delegation to only the accounts that need it, prefer constrained models, and protect delegated accounts with strong authentication, tiering, and monitoring. - -#### How the Test Works - -This test retrieves Active Directory user data from `Get-MtADDomainState` and counts accounts where `TrustedForDelegation` or `TrustedToAuthForDelegation` is enabled. The results break out delegation types and show the overall count. - -#### Related Tests - -- `Test-MtAdUserNoPreAuthCount` -- `Test-MtAdUserKerberosDesOnlyCount` -- `Test-MtAdUserPasswordNeverExpiresCount` - -#### Related links - -- [Microsoft Defender for Identity: Ensure privileged accounts are not delegated](https://learn.microsoft.com/defender-for-identity/security-posture-assessments/accounts#ensure-privileged-accounts-are-not-delegated) -- [ANSSI Active Directory checkpoints: Unconstrained authentication delegation](https://www.cert.ssi.gouv.fr/uploads/ad_checklist.html#vuln_delegation_t4d) - - -%TestResult% diff --git a/tests/ad/user/Test.AD-USER-05.ps1 b/tests/ad/user/Test.AD-USER-05.ps1 deleted file mode 100644 index 9ae21c34f8..0000000000 --- a/tests/ad/user/Test.AD-USER-05.ps1 +++ /dev/null @@ -1,82 +0,0 @@ -function Test-MtAdUserDelegationAllowedCount { - <# - .SYNOPSIS - Counts user accounts that are trusted for Kerberos delegation. - - .DESCRIPTION - This test identifies user accounts that allow unconstrained or constrained Kerberos - delegation. Delegation-capable accounts can be abused for privilege escalation or - lateral movement if they are not tightly controlled. - - .EXAMPLE - Test-MtAdUserDelegationAllowedCount - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserDelegationAllowedCount - #> - [MaesterTest( - Id = 'AD-USER-05', - Title = 'Delegation-enabled user count should be retrievable', - Product = 'ad', - Feature = 'users', - Area = 'authentication', - ResourceType = 'User', - Severity = 'Info', - Mitre = ('T1558', 'T1550.003'), - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserDelegationAllowedCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user delegation allowed count" - - $users = @($adState.Users) - $delegatedUsers = @($users | Where-Object { - $_.TrustedForDelegation -eq $true -or $_.TrustedToAuthForDelegation -eq $true - }) - $unconstrainedCount = @($delegatedUsers | Where-Object { $_.TrustedForDelegation -eq $true }).Count - $protocolTransitionCount = @($delegatedUsers | Where-Object { $_.TrustedToAuthForDelegation -eq $true }).Count - $delegatedCount = $delegatedUsers.Count - $enabledCount = @($users | Where-Object { $_.Enabled -eq $true }).Count - $totalCount = $users.Count - - $testResult = $null -ne $adState.Users - - if ($testResult) { - $percentage = if ($totalCount -gt 0) { - [Math]::Round(($delegatedCount / $totalCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users | $totalCount |" + "`n" - $result += "| Enabled Users | $enabledCount |" + "`n" - $result += "| Users with Any Delegation | $delegatedCount |" + "`n" - $result += "| Trusted for Delegation | $unconstrainedCount |" + "`n" - $result += "| Trusted to Auth for Delegation | $protocolTransitionCount |" + "`n" - $result += "| Delegation Percentage | $percentage% |" + "`n" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory user objects have been analyzed. $delegatedCount out of $totalCount users ($percentage%) are configured for Kerberos delegation.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory user objects. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdUserDelegationAllowedCount" - - return $testResult -} diff --git a/tests/ad/user/Test.AD-USER-28.md b/tests/ad/user/Test.AD-USER-28.md deleted file mode 100644 index f3490fe6a1..0000000000 --- a/tests/ad/user/Test.AD-USER-28.md +++ /dev/null @@ -1,28 +0,0 @@ -Delegation on user accounts can be especially risky because user identities are often easier to misuse than computer accounts. Service accounts configured for delegation can become powerful lateral movement pivots. - -- **Lateral movement risk**: Delegation can expand the blast radius of compromise. -- **Privilege abuse**: User-based services with delegation deserve special scrutiny. -- **Exposure tracking**: Supports routine review of delegation-enabled identities. - -#### Control Type - -**Operational** - -#### Security Recommendation - -- Minimize delegation on user accounts. -- Prefer modern and least-privileged service identity patterns. -- Review all delegation-enabled users for valid business justification. -- Prioritize removal of unnecessary unconstrained delegation. - -#### How the Test Works - -This test counts user accounts with either `TrustedForDelegation` or `TrustedToAuthForDelegation` enabled and breaks out how many have each flag. - -#### Related Tests - -- `Test-MtAdUserDelegationDetails` -- `Test-MtAdUserKnownServiceAccountDetails` - - -%TestResult% diff --git a/tests/ad/user/Test.AD-USER-28.ps1 b/tests/ad/user/Test.AD-USER-28.ps1 deleted file mode 100644 index 8717bd601b..0000000000 --- a/tests/ad/user/Test.AD-USER-28.ps1 +++ /dev/null @@ -1,72 +0,0 @@ -function Test-MtAdUserDelegationConfiguredCount { - <# - .SYNOPSIS - Counts users with delegation configured. - - .DESCRIPTION - This test identifies user accounts with delegation-related settings enabled. - Delegation can allow services to impersonate users and should be tightly - controlled, especially for user-based service accounts. - - .EXAMPLE - Test-MtAdUserDelegationConfiguredCount - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserDelegationConfiguredCount - #> - [MaesterTest( - Id = 'AD-USER-28', - Title = 'User delegation configured count should be investigated', - Product = 'ad', - Feature = 'users', - Area = 'authentication', - ResourceType = 'User', - Severity = 'Info', - Mitre = ('T1558', 'T1550.003'), - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserDelegationConfiguredCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user delegation configured count" - - $users = $adState.Users - - $delegatedUsers = @($users | Where-Object { - $_.TrustedForDelegation -eq $true -or $_.TrustedToAuthForDelegation -eq $true - }) - - $unconstrainedCount = (@($delegatedUsers | Where-Object { $_.TrustedForDelegation -eq $true }) | Measure-Object).Count - $protocolTransitionCount = (@($delegatedUsers | Where-Object { $_.TrustedToAuthForDelegation -eq $true }) | Measure-Object).Count - $bothCount = (@($delegatedUsers | Where-Object { $_.TrustedForDelegation -eq $true -and $_.TrustedToAuthForDelegation -eq $true }) | Measure-Object).Count - $totalCount = ($delegatedUsers | Measure-Object).Count - - $testResult = $true - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users Reviewed | $((@($users) | Measure-Object).Count) |" + "`n" - $result += "| Users with Any Delegation Setting | $totalCount |" + "`n" - $result += "| TrustedForDelegation Enabled | $unconstrainedCount |" + "`n" - $result += "| TrustedToAuthForDelegation Enabled | $protocolTransitionCount |" + "`n" - $result += "| Both Delegation Flags Enabled | $bothCount |" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory users were reviewed for delegation configuration.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdUserDelegationConfiguredCount" - - return $testResult -} diff --git a/tests/ad/user/Test.AD-USER-29.md b/tests/ad/user/Test.AD-USER-29.md deleted file mode 100644 index 6f987a2f60..0000000000 --- a/tests/ad/user/Test.AD-USER-29.md +++ /dev/null @@ -1,28 +0,0 @@ -Delegation details on user accounts help defenders quickly identify high-risk service identities and prioritize cleanup. - -- **Risk prioritization**: Unconstrained delegation is usually more dangerous than protocol transition alone. -- **Account review**: User-based service accounts with SPNs and delegation need strong justification. -- **Incident response**: Detailed visibility speeds triage during suspected Kerberos abuse. - -#### Control Type - -**Preventive** - -#### Security Recommendation - -- Review each delegation-enabled user for business need, owner, and scope. -- Remove unnecessary delegation settings. -- Replace legacy service users with safer identity patterns where possible. -- Monitor delegation-enabled accounts for unusual logon or ticket activity. - -#### How the Test Works - -This test lists each user with `TrustedForDelegation` or `TrustedToAuthForDelegation` enabled and labels the effective delegation type based on the available account flags. - -#### Related Tests - -- `Test-MtAdUserDelegationConfiguredCount` -- `Test-MtAdUserKnownServiceAccountDetails` - - -%TestResult% diff --git a/tests/ad/user/Test.AD-USER-29.ps1 b/tests/ad/user/Test.AD-USER-29.ps1 deleted file mode 100644 index c3d689e45f..0000000000 --- a/tests/ad/user/Test.AD-USER-29.ps1 +++ /dev/null @@ -1,109 +0,0 @@ -function Test-MtAdUserDelegationDetails { - <# - .SYNOPSIS - Returns delegation details for users with delegation configured. - - .DESCRIPTION - This test provides a per-user breakdown of delegation-related settings found - on Active Directory user objects. The output helps identify whether risky - user-based service accounts are configured for unconstrained delegation, - protocol transition, or both. - - .EXAMPLE - Test-MtAdUserDelegationDetails - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserDelegationDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-USER-29', - Title = 'No users should be configured for unconstrained delegation', - Product = 'ad', - Feature = 'users', - Area = 'authentication', - ResourceType = 'User', - Severity = 'High', - UserImpact = 'Low', - ImplementationCost = 'Medium', - Mitre = ('T1558', 'T1550.003'), - Control = 'nist-800-53-r5:AC-6', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserDelegationDetails" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user delegation details" - - $users = $adState.Users - - $delegatedUsers = @($users | Where-Object { - $_.TrustedForDelegation -eq $true -or $_.TrustedToAuthForDelegation -eq $true - } | ForEach-Object { - $delegationType = if ($_.TrustedForDelegation -eq $true -and $_.TrustedToAuthForDelegation -eq $true) { - 'Unconstrained + Protocol Transition' - } elseif ($_.TrustedForDelegation -eq $true) { - 'Unconstrained' - } else { - 'Constrained/Protocol Transition' - } - - [PSCustomObject]@{ - SamAccountName = $_.SamAccountName - Name = $_.Name - Enabled = $_.Enabled - DelegationType = $delegationType - TrustedForDelegation = $_.TrustedForDelegation - TrustedToAuthForDelegation = $_.TrustedToAuthForDelegation - HasSpn = @($_.ServicePrincipalName).Count -gt 0 - DistinguishedName = $_.DistinguishedName - } - } | Sort-Object SamAccountName) - - $unconstrainedDelegationCount = (@($delegatedUsers | Where-Object { $_.TrustedForDelegation -eq $true }) | Measure-Object).Count - $testResult = $unconstrainedDelegationCount -eq 0 - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Users with Any Delegation Setting | $(($delegatedUsers | Measure-Object).Count) |" + "`n" - $result += "| Unconstrained Delegation | $((@($delegatedUsers | Where-Object { $_.TrustedForDelegation -eq $true }) | Measure-Object).Count) |" + "`n" - $result += "| Protocol Transition Enabled | $((@($delegatedUsers | Where-Object { $_.TrustedToAuthForDelegation -eq $true }) | Measure-Object).Count) |" + "`n" + "`n" - - if ($delegatedUsers.Count -gt 0) { - $result += "### Delegation Details" + "`n" + "`n" - $result += "| SamAccountName | Display Name | Enabled | Delegation Type | Has SPN |" + "`n" - $result += "| --- | --- | --- | --- | --- |" + "`n" - foreach ($user in ($delegatedUsers | Select-Object -First 25)) { - $result += "| $($user.SamAccountName) | $($user.Name) | $($user.Enabled) | $($user.DelegationType) | $($user.HasSpn) |" + "`n" - } - - if ($delegatedUsers.Count -gt 25) { - $result += "| ... | ... | ... | ... | ... ($($delegatedUsers.Count - 25) more) |" + "`n" - } - } else { - $result += "No users with delegation-related settings were identified." + "`n" - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "Delegation-enabled Active Directory user details were retrieved.`n`n%TestResult%" - if ($delegatedUsers.Count -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", "" - } - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdUserDelegationDetails" - - return $testResult -} From 4775355908d97777149f83cdfed7055752ca0895 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 18:47:11 +0000 Subject: [PATCH 026/100] fix(ad): assess user lifecycle and protected identities --- .../ad/ad/Assert-MtAdUserAccountControl.ps1 | 7 + .../ad/ad/Format-MtAdUserSecurityTable.ps1 | 19 +++ .../checks/ad/ad/Get-MtAdUserPathFindings.ps1 | 32 +++++ .../ad/ad/Test-MtAdUserOrdinaryIdentity.ps1 | 13 ++ .../functions/ADUserSecurityBatch.Tests.ps1 | 136 ++++++++++++++++++ .../functions/ActiveDirectoryOptIn.Tests.ps1 | 9 +- tests/ad/user/Test.AD-USER-01.md | 22 +-- tests/ad/user/Test.AD-USER-01.ps1 | 93 +++--------- tests/ad/user/Test.AD-USER-02.md | 27 +--- tests/ad/user/Test.AD-USER-02.ps1 | 110 ++------------ tests/ad/user/Test.AD-USER-08.md | 22 +-- tests/ad/user/Test.AD-USER-08.ps1 | 90 +++--------- 12 files changed, 280 insertions(+), 300 deletions(-) create mode 100644 powershell/internal/checks/ad/ad/Assert-MtAdUserAccountControl.ps1 create mode 100644 powershell/internal/checks/ad/ad/Format-MtAdUserSecurityTable.ps1 create mode 100644 powershell/internal/checks/ad/ad/Get-MtAdUserPathFindings.ps1 create mode 100644 powershell/internal/checks/ad/ad/Test-MtAdUserOrdinaryIdentity.ps1 create mode 100644 powershell/tests/functions/ADUserSecurityBatch.Tests.ps1 diff --git a/powershell/internal/checks/ad/ad/Assert-MtAdUserAccountControl.ps1 b/powershell/internal/checks/ad/ad/Assert-MtAdUserAccountControl.ps1 new file mode 100644 index 0000000000..7cefa6f8f3 --- /dev/null +++ b/powershell/internal/checks/ad/ad/Assert-MtAdUserAccountControl.ps1 @@ -0,0 +1,7 @@ +function Assert-MtAdUserAccountControl { + [CmdletBinding()] + param([object[]] $Users) + + $missing = @($Users | Where-Object { $null -eq $_.UserAccountControl }) + if ($missing.Count) { throw "UserAccountControl is unavailable for $($missing.Count) users; cannot treat missing flags as clear." } +} diff --git a/powershell/internal/checks/ad/ad/Format-MtAdUserSecurityTable.ps1 b/powershell/internal/checks/ad/ad/Format-MtAdUserSecurityTable.ps1 new file mode 100644 index 0000000000..74cb5a930a --- /dev/null +++ b/powershell/internal/checks/ad/ad/Format-MtAdUserSecurityTable.ps1 @@ -0,0 +1,19 @@ +function Format-MtAdUserSecurityTable { + [CmdletBinding()] + param( + [object[]] $Rows, + [string[]] $Columns + ) + + $lines = @() + $lines += '| ' + ($Columns -join ' | ') + ' |' + $lines += '| ' + (($Columns | ForEach-Object { '---' }) -join ' | ') + ' |' + foreach ($row in $Rows) { + $values = foreach ($column in $Columns) { + $value = $row.$column + if ($null -eq $value) { 'Unknown' } else { ([string]$value -replace '\|', '\|' -replace '[\r\n]+', ' ') } + } + $lines += '| ' + ($values -join ' | ') + ' |' + } + return ($lines -join "`n") +} diff --git a/powershell/internal/checks/ad/ad/Get-MtAdUserPathFindings.ps1 b/powershell/internal/checks/ad/ad/Get-MtAdUserPathFindings.ps1 new file mode 100644 index 0000000000..f239cb231f --- /dev/null +++ b/powershell/internal/checks/ad/ad/Get-MtAdUserPathFindings.ps1 @@ -0,0 +1,32 @@ +function Get-MtAdUserPathFindings { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Internal helper returns a collection of path findings.')] + [CmdletBinding()] + param([object[]] $Users, [string[]] $ApprovedPathPrefixes) + + foreach ($user in $Users) { + foreach ($field in @('HomeDirectory', 'ProfilePath', 'ScriptPath')) { + $path = [string]$user.$field + if ([string]::IsNullOrWhiteSpace($path)) { continue } + $normalized = $path.Replace('/', '\').TrimEnd('\') + $reason = $null + if ($normalized -match '(^|\\)\.\.(\\|$)') { $reason = 'Parent traversal (reject)' } + elseif ($field -eq 'ScriptPath' -and $normalized -notmatch '^(\\\\|[A-Za-z]:\\)') { + $reason = 'Relative NETLOGON script: review (not failed)' + } else { + $approved = $false + foreach ($prefix in $ApprovedPathPrefixes) { + if ([string]::IsNullOrWhiteSpace($prefix)) { continue } + $base = $prefix.Replace('/', '\').TrimEnd('\') + if ($base -match '(^|\\)\.\.(\\|$)') { throw "Approved prefix contains traversal: $prefix" } + if ($base -notmatch '^(\\\\[^\\]+\\[^\\]+|[A-Za-z]:\\)') { throw "Approved prefix must be an absolute UNC or drive path: $prefix" } + if ($normalized.Equals($base, [StringComparison]::OrdinalIgnoreCase) -or + $normalized.StartsWith($base + '\', [StringComparison]::OrdinalIgnoreCase)) { $approved = $true; break } + } + if (-not $approved) { $reason = 'Unapproved path' } + } + if ($null -ne $reason) { + [pscustomobject]@{ SamAccountName = $user.SamAccountName; Field = $field; Path = $path; Finding = $reason } + } + } + } +} diff --git a/powershell/internal/checks/ad/ad/Test-MtAdUserOrdinaryIdentity.ps1 b/powershell/internal/checks/ad/ad/Test-MtAdUserOrdinaryIdentity.ps1 new file mode 100644 index 0000000000..546a20c47f --- /dev/null +++ b/powershell/internal/checks/ad/ad/Test-MtAdUserOrdinaryIdentity.ps1 @@ -0,0 +1,13 @@ +function Test-MtAdUserOrdinaryIdentity { + [CmdletBinding()] + [OutputType([bool])] + param([object] $User) + + if ($User.IsCriticalSystemObject -eq $true -or $null -ne $User.SecondaryKrbtgtNumber -or + @($User.KrbtgtLinkBacklinks | Where-Object { $null -ne $_ }).Count -gt 0 -or + $User.SamAccountName -like 'krbtgt_AzureAD*') { return $false } + $sid = if ($User.Sid -is [string]) { $User.Sid } else { [string]$User.Sid.Value } + if ([string]::IsNullOrWhiteSpace($sid)) { throw 'User SID is unavailable; protected-account exclusions cannot be established.' } + if ($sid -match '-(500|501|502|503)$') { return $false } + return $true +} diff --git a/powershell/tests/functions/ADUserSecurityBatch.Tests.ps1 b/powershell/tests/functions/ADUserSecurityBatch.Tests.ps1 new file mode 100644 index 0000000000..63159ace26 --- /dev/null +++ b/powershell/tests/functions/ADUserSecurityBatch.Tests.ps1 @@ -0,0 +1,136 @@ +BeforeAll { + . "$PSScriptRoot/../../internal/checks/ad/ad/Test-MtAdUserOrdinaryIdentity.ps1" + . "$PSScriptRoot/../../internal/checks/ad/ad/Get-MtAdUserPathFindings.ps1" + . "$PSScriptRoot/../../internal/checks/ad/ad/Format-MtAdUserSecurityTable.ps1" + . "$PSScriptRoot/../../internal/checks/ad/ad/Assert-MtAdUserAccountControl.ps1" +} + +Describe 'Native USER security outcomes' { + BeforeAll { Import-Module "$PSScriptRoot/../../Maester.psd1" -Force } + BeforeEach { + $script:batchDetail = $null + $script:batchState = [pscustomobject]@{ + Domain = [pscustomobject]@{ DomainSID = 'S-1-5-21-1-2-3' } + Users = @([pscustomobject]@{ + Sid = 'S-1-5-21-1-2-3-1100'; SamAccountName = 'ordinary'; Name = 'ordinary' + DistinguishedName = 'CN=ordinary,OU=Staff,DC=example,DC=com' + Enabled = $false; Modified = (Get-Date).AddDays(-365); Created = (Get-Date).AddYears(-2) + UserAccountControl = 514; PasswordNotRequired = $false; PrimaryGroupId = 513 + IsCriticalSystemObject = $false; SecondaryKrbtgtNumber = $null; KrbtgtLinkBacklinks = @() + Manager = ''; HomeDirectory = ''; ProfilePath = ''; ScriptPath = '' + }) + } + Mock -ModuleName Maester Get-MtADDomainState { $script:batchState } + Mock -ModuleName Maester Add-MtTestResultDetail { $script:batchDetail = $Result } + } + It 'fails old disabled ordinary accounts but not fresh offboarding records' { + InModuleScope Maester { Test-MtAdUserDisabledCount | Should -BeFalse } + $script:batchState.Users[0].Modified = Get-Date + InModuleScope Maester { Test-MtAdUserDisabledCount | Should -BeTrue } + } + It 'retains protected disabled identities' -ForEach @(@{ Kind = 'Critical' }, @{ Kind = 'DefaultAccount' }, @{ Kind = 'RODC' }, @{ Kind = 'AzureAD' }) { + switch ($Kind) { + 'Critical' { $script:batchState.Users[0].IsCriticalSystemObject = $true } + 'DefaultAccount' { $script:batchState.Users[0].Sid = 'S-1-5-21-1-2-3-503' } + 'RODC' { $script:batchState.Users[0].SecondaryKrbtgtNumber = 1234 } + 'AzureAD' { $script:batchState.Users[0].SamAccountName = 'krbtgt_AzureAD' } + } + InModuleScope Maester { Test-MtAdUserDisabledCount | Should -BeTrue } + } + It 'errors on unavailable account identity rather than weakening lifecycle exclusions' { + $script:batchState.Users[0].Sid = $null + InModuleScope Maester { { Test-MtAdUserDisabledCount } | Should -Throw '*SID is unavailable*' } + } + It 'honors the configurable manager exclusion' { + $script:batchState.Users[0].Enabled = $true + InModuleScope Maester { Test-MtAdUserManagerSetCount | Should -BeFalse } + InModuleScope Maester { Test-MtAdUserManagerSetCount -ExcludedUsers 'ordinary' | Should -BeTrue } + } + It 'uses a supported string-array primary-group parameter' { + $script:batchState.Users[0].PrimaryGroupId = 600 + InModuleScope Maester { + Test-MtAdUserNonStandardPrimaryGroupCount | Should -BeFalse + Test-MtAdUserNonStandardPrimaryGroupCount -AllowedPrimaryGroupIds '513', '600' | Should -BeTrue + } + } + It 'shows enabled password-not-required accounts without claiming a blank password' { + $script:batchState.Users[0].Enabled = $true + $script:batchState.Users[0].UserAccountControl = 544 + $script:batchState.Users[0].PasswordNotRequired = $true + InModuleScope Maester { Test-MtAdUserPasswordNotRequiredCount | Should -BeFalse } + $script:batchDetail | Should -Match 'does not prove a blank password' + $script:batchDetail | Should -Match 'True' + } + It 'fails reversible-encryption configuration rather than merely counting it' { + InModuleScope Maester { Test-MtAdUserReversibleEncryptionCount | Should -BeTrue } + $script:batchState.Users[0].UserAccountControl = 642 + InModuleScope Maester { Test-MtAdUserReversibleEncryptionCount | Should -BeFalse } + $script:batchDetail | Should -Match 'reset affected passwords' + } + It 'does not fail protected disabled Guest defaults but fails an enabled Guest' { + $script:batchState.Users[0].Sid = 'S-1-5-21-1-2-3-501' + $script:batchState.Users[0].UserAccountControl = 66082 + InModuleScope Maester { Test-MtAdUserPasswordNotRequiredCount | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + $script:batchState.Users[0].Enabled = $true + InModuleScope Maester { Test-MtAdUserPasswordNotRequiredCount | Should -BeFalse } + } + It 'fails unapproved paths but permits approved roots and investigates relative scripts' { + $script:batchState.Users[0].HomeDirectory = '\\files\staff\ordinary' + InModuleScope Maester { Test-MtAdUserHomeDirectoryCount | Should -BeFalse } + InModuleScope Maester { Test-MtAdUserHomeDirectoryCount -ApprovedPathPrefixes '\\files\staff' | Should -BeTrue } + $script:batchState.Users[0].ScriptPath = 'staff.cmd' + InModuleScope Maester { Test-MtAdUserHomeDirectoryCount -ApprovedPathPrefixes '\\files\staff' | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + } + It 'uses the domain RID-500 identity and refuses an unknown enabled state' { + $script:batchState.Users[0].Sid = 'S-1-5-21-1-2-3-500' + $script:batchState.Users[0] | Add-Member -NotePropertyName PasswordLastSet -NotePropertyValue (Get-Date).AddDays(-30) + $script:batchState.Users[0] | Add-Member -NotePropertyName LastLogonDate -NotePropertyValue (Get-Date).AddDays(-35) + $script:batchState.Users[0].Enabled = $true + InModuleScope Maester { Test-MtAdUserBuiltInAdminCount | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + $script:batchState.Users[0].Enabled = $null + InModuleScope Maester { { Test-MtAdUserBuiltInAdminCount } | Should -Throw '*enabled state is unavailable*' } + } + It 'uses a larger collected logon synchronization interval for RID-500 ambiguity' { + $script:batchState.Domain | Add-Member -NotePropertyName LogonTimeSyncIntervalDays -NotePropertyValue 90 + $script:batchState.Users[0].Sid = 'S-1-5-21-1-2-3-500' + $script:batchState.Users[0].Enabled = $true + $script:batchState.Users[0] | Add-Member -NotePropertyName PasswordLastSet -NotePropertyValue (Get-Date).AddDays(-30) + $script:batchState.Users[0] | Add-Member -NotePropertyName LastLogonDate -NotePropertyValue (Get-Date).AddDays(-60) + InModuleScope Maester { Test-MtAdUserBuiltInAdminCount | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + $script:batchDetail | Should -Match '90 days' + } +} + +Describe 'AD user security batch helpers' { + It 'excludes protected built-in and secondary krbtgt users without relying on names of ordinary users' { + (Test-MtAdUserOrdinaryIdentity ([pscustomobject]@{ Sid = 'S-1-5-21-1-2-3-500'; SamAccountName = 'renamed-admin' })) | Should -BeFalse + (Test-MtAdUserOrdinaryIdentity ([pscustomobject]@{ Sid = 'S-1-5-21-1-2-3-1100'; SamAccountName = 'krbtgt_AzureAD_test' })) | Should -BeFalse + (Test-MtAdUserOrdinaryIdentity ([pscustomobject]@{ Sid = 'S-1-5-21-1-2-3-1101'; SamAccountName = 'ordinary-user'; KrbtgtLinkBacklinks = @('CN=RODC') })) | Should -BeFalse + (Test-MtAdUserOrdinaryIdentity ([pscustomobject]@{ Sid = 'S-1-5-21-1-2-3-1101'; SamAccountName = 'ordinary-user'; SecondaryKrbtgtNumber = 0 })) | Should -BeFalse + (Test-MtAdUserOrdinaryIdentity ([pscustomobject]@{ Sid = 'S-1-5-21-1-2-3-1102'; SamAccountName = 'ordinary-user' })) | Should -BeTrue + } + + It 'requires approved path component boundaries, allows case-insensitive prefixes and reviews relative scripts' { + $users = @( + [pscustomobject]@{ SamAccountName = 'allowed'; HomeDirectory = '\\server\home\allowed'; ProfilePath = $null; ScriptPath = 'staff.cmd' }, + [pscustomobject]@{ SamAccountName = 'evil'; HomeDirectory = '\\server\homeevil\evil'; ProfilePath = '\\server\home\..\secret'; ScriptPath = $null } + ) + $findings = @(Get-MtAdUserPathFindings $users @('\\SERVER\HOME')) + @($findings | Where-Object { $_.SamAccountName -eq 'allowed' -and $_.Field -eq 'HomeDirectory' }).Count | Should -Be 0 + @($findings | Where-Object { $_.Finding -eq 'Unapproved path' }).Count | Should -Be 1 + @($findings | Where-Object { $_.Finding -eq 'Parent traversal (reject)' }).Count | Should -Be 1 + @($findings | Where-Object { $_.Finding -like 'Relative NETLOGON*' }).Count | Should -Be 1 + } + + It 'escapes markdown cell separators in reported account names' { + (Format-MtAdUserSecurityTable @([pscustomobject]@{ SamAccountName = 'a|b' }) @('SamAccountName')) | Should -Match 'a\\\|b' + } + + It 'does not interpret unavailable account control as a cleared security flag' { + { Assert-MtAdUserAccountControl @([pscustomobject]@{ SamAccountName = 'missing'; UserAccountControl = $null }) } | Should -Throw '*unavailable*' + } +} diff --git a/powershell/tests/functions/ActiveDirectoryOptIn.Tests.ps1 b/powershell/tests/functions/ActiveDirectoryOptIn.Tests.ps1 index c94bd06490..648bc493d3 100644 --- a/powershell/tests/functions/ActiveDirectoryOptIn.Tests.ps1 +++ b/powershell/tests/functions/ActiveDirectoryOptIn.Tests.ps1 @@ -230,7 +230,14 @@ Describe 'Active Directory test source safety' { Sort-Object { $_.Extent.StartOffset } | Select-Object -First 1 - if ($null -eq $collector) { + # Pure assessment/formatting helpers consume an already-collected snapshot and + # perform no AD operation. Native tests still require an explicit guarded read. + $isHelper = $adHelperFiles.FullName -contains $file.FullName + $transportCall = $commands | Where-Object { + $_.GetCommandName() -match '^(Get-MtLdap|Invoke-MtLdap|New-MtAdProtocolConnection|Invoke-MtADManagementCommand|Get-MtSysvolContent|Get-AD|Get-GPO|Get-DnsServer)' -or $_.GetCommandName() -eq 'Invoke-Command' + } | Select-Object -First 1 + $sessionAccess = $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.VariableExpressionAst] -and $node.VariablePath.UserPath -match '__MtSession' }, $true) | Select-Object -First 1 + if ($null -eq $collector -and (-not $isHelper -or $null -ne $transportCall -or $null -ne $sessionAccess)) { $issues += "$($file.FullName): does not call a guarded Active Directory collector." } diff --git a/tests/ad/user/Test.AD-USER-01.md b/tests/ad/user/Test.AD-USER-01.md index 7cacfa802d..940e55fa79 100644 --- a/tests/ad/user/Test.AD-USER-01.md +++ b/tests/ad/user/Test.AD-USER-01.md @@ -1,22 +1,8 @@ -Disabled user accounts are expected during offboarding, investigations, and staged deprovisioning. Tracking their volume helps identify stale objects that should be deleted, reduces directory clutter, and supports lifecycle governance. +Disabled ordinary users last modified over 180 days ago (configurable) require retention review. `Modified` is local `whenChanged`, **not** a disable date; other edits reset this estimate and it is not replicated. Protected/system accounts, RID 500–503, secondary krbtgt identities and Azure AD krbtgt accounts are excluded; this check does not delete RODC keys. -#### Control Type - -**Detective** - -#### Security Recommendation - -Review disabled user accounts regularly and remove accounts that no longer need to exist. For retained accounts, document the business reason and expected retention period. - -#### How the Test Works - -This test retrieves cached Active Directory user data from `Get-MtADDomainState` and counts user objects where `Enabled = $false`. The result includes total, enabled, and disabled user counts plus the disabled percentage. - -#### Related Tests - -- `Test-MtAdUserDormantEnabledCount` -- `Test-MtAdUserNeverLoggedInCount` -- `Test-MtAdUserPasswordNotRequiredCount` +#### Remediation action +1. Verify the actual disable date and legal retention requirements with the account owner. +2. After approval, remove stale objects in [Active Directory Users and Computers](https://learn.microsoft.com/windows-server/identity/ad-ds/get-started/adac/active-directory-administrative-center). %TestResult% diff --git a/tests/ad/user/Test.AD-USER-01.ps1 b/tests/ad/user/Test.AD-USER-01.ps1 index e6abbc4bb8..6dd3c7db3e 100644 --- a/tests/ad/user/Test.AD-USER-01.ps1 +++ b/tests/ad/user/Test.AD-USER-01.ps1 @@ -1,77 +1,26 @@ function Test-MtAdUserDisabledCount { - <# - .SYNOPSIS - Counts the number of disabled user objects in Active Directory. - - .DESCRIPTION - This test analyzes Active Directory user objects and counts how many accounts are - currently disabled. Disabled accounts are often expected during offboarding or - service account lifecycle management, but tracking them helps validate directory - hygiene and identify stale objects that should be removed. - - .EXAMPLE - Test-MtAdUserDisabledCount - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserDisabledCount + <# .SYNOPSIS + Checks whether disabled ordinary users have exceeded the retention period. #> - [MaesterTest( - Id = 'AD-USER-01', - Title = 'Disabled user count should be retrievable', - Product = 'ad', - Feature = 'users', - Area = 'identity-lifecycle', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] + [MaesterTest(Id = 'AD-USER-01', Title = 'Disabled users should be removed after the retention period', Product = 'ad', Feature = 'users', Area = 'identity-lifecycle', ResourceType = 'User', Severity = 'Low', UserImpact = 'Low', ImplementationCost = 'Medium', Mitre = 'T1078.002', Control = 'nist-800-53-r5:AC-2(3)', Service = 'ActiveDirectory', Permission = 'ActiveDirectory:Ldap:user:ReadProperty', Author = 'soulemike')] [CmdletBinding()] [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserDisabledCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user disabled count" - - $users = @($adState.Users) - $disabledUsers = @($users | Where-Object { $_.Enabled -eq $false }) - $disabledCount = $disabledUsers.Count - $enabledCount = @($users | Where-Object { $_.Enabled -eq $true }).Count - $totalCount = $users.Count - - $testResult = $null -ne $adState.Users - - if ($testResult) { - $percentage = if ($totalCount -gt 0) { - [Math]::Round(($disabledCount / $totalCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users | $totalCount |" + "`n" - $result += "| Enabled Users | $enabledCount |" + "`n" - $result += "| Disabled Users | $disabledCount |" + "`n" - $result += "| Disabled Percentage | $percentage% |" + "`n" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory user objects have been analyzed. $disabledCount out of $totalCount users ($percentage%) are disabled.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory user objects. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdUserDisabledCount" - - return $testResult + param( + # Maximum days since the last local modification of a disabled user before review. + [ValidateRange(1, 3650)] + [int] $RetentionDays = 180 + ) + + $state = Get-MtADDomainState -Categories @('Users') + if ($null -eq $state.Users) { throw 'AD user data was not returned.' } + if (@($state.Users | Where-Object { $null -eq $_.Enabled }).Count -gt 0) { throw 'User enabled state is missing; disabled-account scope cannot be established.' } + $old = @($state.Users | Where-Object { + if ($_.Enabled -ne $false -or -not (Test-MtAdUserOrdinaryIdentity $_)) { return $false } + if ($null -eq $_.Modified) { throw "Modification time missing for $($_.SamAccountName)." } + [datetime]$_.Modified -lt (Get-Date).AddDays(-$RetentionDays) + }) + $table = Format-MtAdUserSecurityTable -Rows $old -Columns @('SamAccountName', 'Modified', 'DistinguishedName') + if ($old.Count) { Add-MtTestResultDetail -Result "Found $($old.Count) disabled ordinary users last modified more than $RetentionDays days ago; review retention and remove when approved. Modification time is not a disable date and may change for other reasons. Local whenChanged is not replicated.`n`n$table" } + else { Add-MtTestResultDetail -Result "Well done. No disabled ordinary user exceeds the $RetentionDays-day modification-age review threshold. This does not prove when each account was disabled." } + return ($old.Count -eq 0) } diff --git a/tests/ad/user/Test.AD-USER-02.md b/tests/ad/user/Test.AD-USER-02.md index 599d39986f..6fa27165c8 100644 --- a/tests/ad/user/Test.AD-USER-02.md +++ b/tests/ad/user/Test.AD-USER-02.md @@ -1,27 +1,8 @@ -Enabled user accounts that have not logged on for more than the configured threshold (default 90 days) are a common sign of weak identity hygiene. Forgotten but still-enabled accounts can retain access, group memberships, and password material that attackers may target. +Enabled users with a recorded logon older than the configurable 90-day threshold are dormant. Replicated `lastLogonTimestamp` can lag by approximately 14 days; missing timestamps need separate review. -#### Control Type - -**Detective** - -#### Security Recommendation - -Investigate dormant enabled accounts and disable or remove those that are no longer needed. For exceptions such as break-glass or low-use service accounts, apply stronger controls and document ownership. - -#### How the Test Works - -This test retrieves Active Directory user data from `Get-MtADDomainState`, filters to enabled users, and counts accounts where `LastLogonDate` is older than `DormantThresholdDays` (default 90 days). The output shows the number and percentage of dormant enabled users. - -#### Related Tests - -- `Test-MtAdUserDisabledCount` -- `Test-MtAdUserNeverLoggedInCount` -- `Test-MtAdUserPasswordNeverExpiresCount` - -#### Related links - -- [Microsoft Defender for Identity: Remove stale Active Directory accounts](https://learn.microsoft.com/defender-for-identity/security-posture-assessments/accounts#remove-stale-active-directory-accounts) -- [ANSSI Active Directory checkpoints: Dormant accounts](https://www.cert.ssi.gouv.fr/uploads/ad_checklist.html#vuln_user_accounts_dormant) +#### Remediation action +1. Confirm actual use against domain-controller logon records before changing an account. +2. Disable unused identities through [Active Directory administration](https://learn.microsoft.com/windows-server/identity/ad-ds/get-started/adac/active-directory-administrative-center) after owner approval. %TestResult% diff --git a/tests/ad/user/Test.AD-USER-02.ps1 b/tests/ad/user/Test.AD-USER-02.ps1 index a2c050a406..2cd0d9148c 100644 --- a/tests/ad/user/Test.AD-USER-02.ps1 +++ b/tests/ad/user/Test.AD-USER-02.ps1 @@ -1,104 +1,24 @@ function Test-MtAdUserDormantEnabledCount { - <# - .SYNOPSIS - Counts enabled user accounts that have been dormant beyond the configured threshold. - - .DESCRIPTION - This test identifies enabled user accounts whose last recorded logon date is older - than the configured threshold. Dormant enabled accounts increase risk because they may be forgotten, - retain privileges, and become attractive targets for unauthorized access. - - .EXAMPLE - Test-MtAdUserDormantEnabledCount - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserDormantEnabledCount + <# .SYNOPSIS + Checks for enabled users with old recorded logon timestamps. #> - [MaesterTest( - Id = 'AD-USER-02', - Title = 'Dormant enabled user count should be retrievable', - Product = 'ad', - Feature = 'users', - Area = 'identity-lifecycle', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'T1078.002', - Control = 'nist-800-53-r5:AC-2(3)', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] + [MaesterTest(Id = 'AD-USER-02', Title = 'Enabled users should not remain dormant', Product = 'ad', Feature = 'users', Area = 'identity-lifecycle', ResourceType = 'User', Severity = 'Medium', UserImpact = 'Low', ImplementationCost = 'Medium', Mitre = 'T1078.002', Control = 'nist-800-53-r5:AC-2(3)', Service = 'ActiveDirectory', Permission = 'ActiveDirectory:Ldap:user:ReadProperty', Author = 'soulemike')] [CmdletBinding()] [OutputType([bool])] param( - # Number of days without a logon before an enabled account is considered dormant. - [ValidateRange(1, 3650)] + # Number of days since the recorded logon after which an enabled account is dormant. + [ValidateRange(15, 3650)] [int] $DormantThresholdDays = 90 ) - Write-Verbose "Starting Test-MtAdUserDormantEnabledCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user dormant enabled count" - - $thresholdDays = $DormantThresholdDays - $thresholdDate = (Get-Date).AddDays(-$thresholdDays) - $users = @($adState.Users) - $enabledUsers = @($users | Where-Object { $_.Enabled -eq $true }) - $dormantUsers = @($enabledUsers | Where-Object { - $null -ne $_.LastLogonDate -and $_.LastLogonDate -lt $thresholdDate - }) - - $dormantCount = $dormantUsers.Count - $enabledCount = $enabledUsers.Count - $totalCount = $users.Count - - $testResult = $null -ne $adState.Users - - if ($testResult) { - $percentage = if ($enabledCount -gt 0) { - [Math]::Round(($dormantCount / $enabledCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users | $totalCount |" + "`n" - $result += "| Enabled Users | $enabledCount |" + "`n" - $result += "| Dormant Enabled Users (>$thresholdDays days) | $dormantCount |" + "`n" - $result += "| Dormant Percentage (of enabled) | $percentage% |" + "`n" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory user objects have been analyzed. $dormantCount out of $enabledCount enabled users ($percentage%) have not logged on in more than $thresholdDays days.`n`n%TestResult%" - if ($dormantCount -eq 0) { - $datedEnabledUsers = $enabledUsers | Where-Object { $null -ne $_.LastLogonDate } - $undatedEnabledCount = $enabledCount - $datedEnabledUsers.Count - $oldestLastLogonDate = $datedEnabledUsers | - Sort-Object -Property LastLogonDate | - Select-Object -First 1 -ExpandProperty LastLogonDate - - if ($null -eq $oldestLastLogonDate) { - $testResultMarkdown += "`n`nThere are $enabledCount enabled users. None have a recorded last logon date, so dormant status cannot be determined from available data." - } else { - $oldestLastLogonDate = [datetime]$oldestLastLogonDate - $oldestLastLogon = $oldestLastLogonDate.ToString('yyyy-MM-dd') - $daysUntilThreshold = [Math]::Max(1, [Math]::Ceiling(($oldestLastLogonDate.AddDays($thresholdDays) - (Get-Date)).TotalDays)) - $undatedNote = if ($undatedEnabledCount -gt 0) { " $undatedEnabledCount enabled user(s) have no recorded logon date and are not counted in this analysis." } else { "" } - $testResultMarkdown += "`n`nThere are $enabledCount enabled users. The oldest last logon date is $oldestLastLogon. No users currently exceed the dormant threshold of $thresholdDays days. The oldest user would reach the threshold in $daysUntilThreshold days.$undatedNote" - } - } - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory user objects. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdUserDormantEnabledCount" - - return $testResult + $state = Get-MtADDomainState -Categories @('Users') + if ($null -eq $state.Users) { throw 'AD user data was not returned.' } + if (@($state.Users | Where-Object { $null -eq $_.Enabled }).Count -gt 0) { throw 'User enabled state is missing; dormancy scope cannot be established.' } + $old = @($state.Users | Where-Object { $_.Enabled -eq $true -and $null -ne $_.LastLogonDate -and [datetime]$_.LastLogonDate -lt (Get-Date).AddDays(-$DormantThresholdDays) }) + $unknown = @($state.Users | Where-Object { $_.Enabled -eq $true -and $null -eq $_.LastLogonDate }) + $table = Format-MtAdUserSecurityTable -Rows $old -Columns @('SamAccountName', 'LastLogonDate', 'DistinguishedName') + if ($old.Count) { Add-MtTestResultDetail -Result "Found $($old.Count) enabled users with a recorded logon older than $DormantThresholdDays days. Review and disable unneeded identities; $($unknown.Count) enabled users lack a logon date and need separate review. Replicated lastLogonTimestamp can lag by about 14 days.`n`n$table" } + elseif ($unknown.Count) { Add-MtTestResultDetail -Result "No old logons found, but $($unknown.Count) enabled users lack a recorded logon date. Review them before treating this as clean." -Investigate } + else { Add-MtTestResultDetail -Result "Well done. No enabled user has a recorded logon older than $DormantThresholdDays days (replicated timestamps can lag)." } + return ($old.Count -eq 0) } diff --git a/tests/ad/user/Test.AD-USER-08.md b/tests/ad/user/Test.AD-USER-08.md index 268c948207..7a46e175ab 100644 --- a/tests/ad/user/Test.AD-USER-08.md +++ b/tests/ad/user/Test.AD-USER-08.md @@ -1,22 +1,8 @@ -Enabled accounts that have never logged on may indicate incomplete provisioning, abandoned onboarding, or unnecessary standing access. These objects should be reviewed to ensure they still have a valid business purpose. +Enabled accounts older than the configurable 30-day provisioning grace period with no recorded logon need review. A missing replicated timestamp is not definitive proof the user has never logged in. -#### Control Type - -**Detective** - -#### Security Recommendation - -Investigate enabled accounts with no recorded logon activity. Disable or remove unused accounts and make sure future provisioning workflows include validation and cleanup steps. - -#### How the Test Works - -This test retrieves Active Directory user data from `Get-MtADDomainState`, filters to enabled users, and counts accounts where `LastLogonDate` is null. - -#### Related Tests - -- `Test-MtAdUserDormantEnabledCount` -- `Test-MtAdUserDisabledCount` -- `Test-MtAdUserPasswordNeverExpiresCount` +#### Remediation action +1. Check authoritative authentication logs and ask the owner whether provisioning is complete. +2. Disable unnecessary accounts in [Active Directory administration](https://learn.microsoft.com/windows-server/identity/ad-ds/get-started/adac/active-directory-administrative-center). %TestResult% diff --git a/tests/ad/user/Test.AD-USER-08.ps1 b/tests/ad/user/Test.AD-USER-08.ps1 index 9a1f5e880d..1dff88f93c 100644 --- a/tests/ad/user/Test.AD-USER-08.ps1 +++ b/tests/ad/user/Test.AD-USER-08.ps1 @@ -1,78 +1,22 @@ function Test-MtAdUserNeverLoggedInCount { - <# - .SYNOPSIS - Counts enabled user accounts that have never logged on. - - .DESCRIPTION - This test identifies enabled user accounts with no recorded last logon date. These - accounts can indicate incomplete provisioning, abandoned onboarding, or dormant - accounts that were never validated or used. - - .EXAMPLE - Test-MtAdUserNeverLoggedInCount - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserNeverLoggedInCount + <# .SYNOPSIS + Detects enabled accounts with no recorded logon after their provisioning grace period. #> - [MaesterTest( - Id = 'AD-USER-08', - Title = 'Never-logged-in enabled user count should be retrievable', - Product = 'ad', - Feature = 'users', - Area = 'identity-lifecycle', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] + [MaesterTest(Id = 'AD-USER-08', Title = 'Enabled users should not remain unused after provisioning', Product = 'ad', Feature = 'users', Area = 'identity-lifecycle', ResourceType = 'User', Severity = 'Low', UserImpact = 'Low', ImplementationCost = 'Medium', Mitre = 'T1078.002', Control = 'nist-800-53-r5:AC-2(3)', Service = 'ActiveDirectory', Permission = 'ActiveDirectory:Ldap:user:ReadProperty', Author = 'soulemike')] [CmdletBinding()] [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserNeverLoggedInCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user never logged in count" - - $users = @($adState.Users) - $enabledUsers = @($users | Where-Object { $_.Enabled -eq $true }) - $neverLoggedInUsers = @($enabledUsers | Where-Object { $null -eq $_.LastLogonDate }) - - $neverLoggedInCount = $neverLoggedInUsers.Count - $enabledCount = $enabledUsers.Count - $totalCount = $users.Count - - $testResult = $null -ne $adState.Users - - if ($testResult) { - $percentage = if ($enabledCount -gt 0) { - [Math]::Round(($neverLoggedInCount / $enabledCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users | $totalCount |" + "`n" - $result += "| Enabled Users | $enabledCount |" + "`n" - $result += "| Enabled Users Never Logged In | $neverLoggedInCount |" + "`n" - $result += "| Never Logged In Percentage (of enabled) | $percentage% |" + "`n" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory user objects have been analyzed. $neverLoggedInCount out of $enabledCount enabled users ($percentage%) have never logged on.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory user objects. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdUserNeverLoggedInCount" - - return $testResult + param( + # Minimum age in days before a newly created, never-logged-in account fails. + [ValidateRange(1, 3650)] + [int] $GraceDays = 30 + ) + + $state = Get-MtADDomainState -Categories @('Users') + if ($null -eq $state.Users) { throw 'AD user data was not returned.' } + $unknown = @($state.Users | Where-Object { $_.Enabled -eq $true -and $null -eq $_.LastLogonDate -and $null -eq $_.Created }) + if ($unknown.Count) { throw "Creation time missing for $($unknown.Count) enabled users with no recorded logon." } + $found = @($state.Users | Where-Object { $_.Enabled -eq $true -and $null -eq $_.LastLogonDate -and $null -ne $_.Created -and [datetime]$_.Created -lt (Get-Date).AddDays(-$GraceDays) }) + if ($found.Count) { Add-MtTestResultDetail -Result "Found $($found.Count) enabled users without a recorded logon after $GraceDays days. Confirm usage in authoritative logs before disabling: lastLogonTimestamp may be missing or lag.`n`n$(Format-MtAdUserSecurityTable $found @('SamAccountName', 'Created', 'DistinguishedName'))" } + else { Add-MtTestResultDetail -Result "Well done. No enabled account older than $GraceDays days lacks a recorded logon; verify actual usage with sign-in logs." } + return ($found.Count -eq 0) } From c299c13e11ee81097cb94e088a0fd23a7c3c1220 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 18:47:11 +0000 Subject: [PATCH 027/100] fix(ad): assess effective user password expiration --- tests/ad/user/Test.AD-USER-03.md | 24 ++---- tests/ad/user/Test.AD-USER-03.ps1 | 130 +++++++++++++++--------------- 2 files changed, 71 insertions(+), 83 deletions(-) diff --git a/tests/ad/user/Test.AD-USER-03.md b/tests/ad/user/Test.AD-USER-03.md index cd1a335330..74fb4efc9b 100644 --- a/tests/ad/user/Test.AD-USER-03.md +++ b/tests/ad/user/Test.AD-USER-03.md @@ -1,26 +1,16 @@ -Passwords that never expire reduce credential hygiene and increase the blast radius of password theft. While some service accounts may require non-expiring credentials, they should be rare, controlled, and closely monitored. +Checks effective password expiration for enabled users, including account-level `PasswordNeverExpires` overrides and the computed resultant fine-grained policy or default domain policy. -#### Control Type +The default `CurrentNist` profile does **not** require periodic expiration. The optional `LegacyRotation` profile requires a positive maximum age no greater than 90 days by default and no account-level never-expire override; it is an organization-selected rotation requirement, **not earlier NIST guidance** (Rev. 3 already discouraged arbitrary changes). Set `Profile`, `MaximumAgeDays`, and `PolicyInventoryReadAccessConfirmed` in `TestSettings[].Parameters`; visibility confirmation is **operator-provided**, not automatically inferred from LDAP. A missing resultant-policy attribute, unknown DN or absent policy age is an error; an unconfirmed empty DN or empty visible user set is **Investigate**, not proof of default-policy coverage. LDAP cannot prove MFA, password blocklisting, actual credential strength or complete compliance. -**Detective** +#### Remediation action -#### Security Recommendation - -Minimize the use of non-expiring passwords. Where legacy constraints require them, migrate to managed service accounts, vaulting, or other compensating controls. - -#### How the Test Works - -This test retrieves Active Directory user data from `Get-MtADDomainState`, filters to enabled users, and counts accounts where `PasswordNeverExpires = $true`. The output includes the count and percentage relative to enabled users. - -#### Related Tests - -- `Test-MtAdUserDormantEnabledCount` -- `Test-MtAdUserPasswordNotRequiredCount` -- `Test-MtAdUserNeverLoggedInCount` +1. In **Active Directory Administrative Center**, inspect each listed user and its **Resultant Password Settings**; inspect the domain default policy and the **Password Settings Container** for effective expiration settings. +2. Under `CurrentNist`, configure maximum password age through the effective domain policy or PSO; do not enable per-account `PasswordNeverExpires` just to satisfy this check. Those overrides are separately reported as Investigate. Under `LegacyRotation`, review policy and approved account exceptions with the owner. Independently verify password blocklisting and reset passwords when compromise is known. #### Related links -- [ANSSI Active Directory checkpoints: Accounts with never-expiring passwords](https://www.cert.ssi.gouv.fr/uploads/ad_checklist.html#vuln_dont_expire) +* [NIST SP 800-63B password verifier requirements](https://pages.nist.gov/800-63-4/sp800-63b/authenticators/#passwords) +* [NIST SP 800-63B Rev. 3](https://pages.nist.gov/800-63-3/sp800-63b.html#reqauthtype) %TestResult% diff --git a/tests/ad/user/Test.AD-USER-03.ps1 b/tests/ad/user/Test.AD-USER-03.ps1 index 8d297b8554..09648f9d32 100644 --- a/tests/ad/user/Test.AD-USER-03.ps1 +++ b/tests/ad/user/Test.AD-USER-03.ps1 @@ -1,78 +1,76 @@ -function Test-MtAdUserPasswordNeverExpiresCount { +function Test-MtAdUserEffectivePasswordExpiration { <# .SYNOPSIS - Counts enabled user accounts with passwords set to never expire. - - .DESCRIPTION - This test identifies enabled user accounts where password expiration has been - disabled. Non-expiring passwords can weaken password hygiene and are often used for - legacy or service accounts that require stronger compensating controls. - - .EXAMPLE - Test-MtAdUserPasswordNeverExpiresCount - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserPasswordNeverExpiresCount + Assesses password expiration for enabled users using their effective policy and account override. #> [MaesterTest( - Id = 'AD-USER-03', - Title = 'Non-expiring password user count should be retrievable', - Product = 'ad', - Feature = 'users', - Area = 'authentication', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'T1078.002', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' + Id = 'AD-USER-03', Title = 'Enabled users should meet the selected effective password expiration policy', + Product = 'ad', Feature = 'users', Area = 'authentication', ResourceType = 'User', + Severity = 'Low', UserImpact = 'Medium', ImplementationCost = 'Medium', Mitre = 'T1078.002', + Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:user:ReadProperty', 'ActiveDirectory:Ldap:msDS-PasswordSettings:ReadProperty'), Author = 'soulemike' )] [CmdletBinding()] [OutputType([bool])] - param() + param( + # CurrentNist does not require periodic rotation; LegacyRotation enforces it. + [ValidateSet('CurrentNist', 'LegacyRotation')][string] $Profile = 'CurrentNist', + # Maximum allowed age in days for organization-selected LegacyRotation. + [ValidateRange(1, 3650)][int] $MaximumAgeDays = 90, + # Confirm complete access to PSOs and computed user resultant-policy attributes. + [bool] $PolicyInventoryReadAccessConfirmed = $false + ) - Write-Verbose "Starting Test-MtAdUserPasswordNeverExpiresCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null + $state = Get-MtADDomainState -Categories @('Domain', 'FineGrainedPasswordPolicies', 'Users') + if ($null -eq $state -or $null -eq $state.Domain -or $null -eq $state.Users -or $null -eq $state.FineGrainedPasswordPolicies) { + throw 'Domain, user or PSO inventory was not returned.' } - Write-Verbose "Filtering/counting user password never expires count" - - $users = @($adState.Users) - $enabledUsers = @($users | Where-Object { $_.Enabled -eq $true }) - $nonExpiringUsers = @($enabledUsers | Where-Object { $_.PasswordNeverExpires -eq $true }) - - $nonExpiringCount = $nonExpiringUsers.Count - $enabledCount = $enabledUsers.Count - $totalCount = $users.Count - - $testResult = $null -ne $adState.Users - - if ($testResult) { - $percentage = if ($enabledCount -gt 0) { - [Math]::Round(($nonExpiringCount / $enabledCount) * 100, 2) - } else { - 0 + $users = @($state.Users) + $policies = @($state.FineGrainedPasswordPolicies) + $usage = Get-MtAdPasswordPolicyUsage -Users $users -Policies $policies + if ($usage.EnabledCount -eq 0) { + Add-MtTestResultDetail -Result 'No enabled users were visible; effective password expiration cannot be established.' -Investigate + return $true + } + $policyByDn = @{} + foreach ($policy in $policies) { $policyByDn[[string]$policy.DistinguishedName] = $policy } + $lines = [System.Collections.Generic.List[string]]::new() + $lines.Add('| User | Effective policy | NeverExpires override | Max age | Status |') | Out-Null + $lines.Add('| --- | --- | --- | --- | --- |') | Out-Null + $passed = $true + $unknownDefault = $false + $overrideReview = $false + foreach ($user in $users) { + if (-not $user.Enabled) { continue } + if ($null -eq $user.PSObject.Properties['PasswordNeverExpires'] -or $null -eq $user.PasswordNeverExpires) { + throw "PasswordNeverExpires is missing for enabled user '$($user.Name)'." } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users | $totalCount |" + "`n" - $result += "| Enabled Users | $enabledCount |" + "`n" - $result += "| Enabled Users with Password Never Expires | $nonExpiringCount |" + "`n" - $result += "| Non-Expiring Percentage (of enabled) | $percentage% |" + "`n" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory user objects have been analyzed. $nonExpiringCount out of $enabledCount enabled users ($percentage%) have non-expiring passwords.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory user objects. Ensure you have appropriate permissions and the Active Directory module is installed." + $dn = [string]$user.ResultantPasswordPolicyDN + if ([string]::IsNullOrWhiteSpace($dn) -and -not $PolicyInventoryReadAccessConfirmed) { + $unknownDefault = $true + $lines.Add("| $($user.Name) | Unconfirmed default-policy visibility | $($user.PasswordNeverExpires) | Unknown | Investigate |") | Out-Null + continue + } + $policy = if ([string]::IsNullOrWhiteSpace($dn)) { $state.Domain } else { $policyByDn[$dn] } + if ($null -eq $policy -or $null -eq $policy.PSObject.Properties['MaxPwdAge'] -or $null -eq $policy.MaxPwdAge -or $policy.MaxPwdAge -isnot [timespan]) { + throw "MaxPwdAge is missing or invalid for effective policy of '$($user.Name)'." + } + $age = [math]::Abs($policy.MaxPwdAge.TotalDays) + $valid = if ($Profile -eq 'CurrentNist') { $age -eq 0 } else { -not $user.PasswordNeverExpires -and $age -gt 0 -and $age -le $MaximumAgeDays } + if ($Profile -eq 'CurrentNist' -and $user.PasswordNeverExpires) { $overrideReview = $true } + if (-not $valid) { $passed = $false } + $policyName = if ([string]::IsNullOrWhiteSpace($dn)) { 'Default domain' } else { $policy.Name } + $status = if ($valid) { 'Pass' } else { 'Fail' } + $lines.Add("| $($user.Name) | $policyName | $($user.PasswordNeverExpires) | $age days | $status |") | Out-Null } - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdUserPasswordNeverExpiresCount" - - return $testResult + $table = $lines -join "`n" + if (-not $passed) { + Add-MtTestResultDetail -Result "Some visible enabled users do not meet the $Profile password expiration policy criterion. Correct the effective PSO/default policy; do not set per-account PasswordNeverExpires merely to satisfy CurrentNist. Review account overrides separately. Unconfirmed default-policy rows do not hide known failures.`n`n$table" + return $false + } + if ($unknownDefault -or $overrideReview -or -not $PolicyInventoryReadAccessConfirmed) { + Add-MtTestResultDetail -Result "Review unconfirmed default-policy visibility or per-account PasswordNeverExpires overrides separately. CurrentNist is satisfied through the effective policy, not account overrides; this is not proof of complete policy coverage.`n`n$table" -Investigate + return $true + } + Add-MtTestResultDetail -Result "Well done. Visible enabled users meet the $Profile effective password expiration criterion; this does not verify compromise response or MFA.`n`n$table" + return $true } From 04dba4c2b5c53c9ab6f3de5a2930c7a3fd19d280 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 18:47:11 +0000 Subject: [PATCH 028/100] fix(ad): assess user authentication flags --- tests/ad/user/Test.AD-USER-04.md | 6 +-- tests/ad/user/Test.AD-USER-04.ps1 | 24 +++++---- tests/ad/user/Test.AD-USER-06.md | 27 ++-------- tests/ad/user/Test.AD-USER-06.ps1 | 83 ++++-------------------------- tests/ad/user/Test.AD-USER-07.md | 27 ++-------- tests/ad/user/Test.AD-USER-07.ps1 | 83 ++++-------------------------- tests/ad/user/Test.AD-USER-09.md | 21 ++------ tests/ad/user/Test.AD-USER-09.ps1 | 85 ++++++------------------------- 8 files changed, 63 insertions(+), 293 deletions(-) diff --git a/tests/ad/user/Test.AD-USER-04.md b/tests/ad/user/Test.AD-USER-04.md index 1a397179c5..73e28a3781 100644 --- a/tests/ad/user/Test.AD-USER-04.md +++ b/tests/ad/user/Test.AD-USER-04.md @@ -4,13 +4,13 @@ Reversible password encryption is effectively equivalent to storing passwords in **Detective** -#### Security Recommendation +#### Remediation action -Disable reversible password encryption unless it is required for a documented legacy dependency that cannot be modernized immediately. Remediate those dependencies as a priority. +Review legacy application dependencies, disable reversible password encryption on the affected accounts and effective policies, then reset affected passwords. Turning the flag off alone does not prove previously stored credential material was removed. Pilot changes where dependent authentication mechanisms may break. #### How the Test Works -This test retrieves Active Directory user data from `Get-MtADDomainState` and counts accounts with reversible-encryption-style indicators. It checks explicit reversible encryption properties when available and falls back to the relevant `userAccountControl` flag. +This check fails when an account permits reversible password encryption and lists those accounts. It reads cached account-control data and errors when that data is unavailable. The configuration flag is not proof that a current password was actually stored reversibly; default and fine-grained policy settings are assessed separately by AD-PWDPOL-01 and AD-FGPP-01. #### Related Tests diff --git a/tests/ad/user/Test.AD-USER-04.ps1 b/tests/ad/user/Test.AD-USER-04.ps1 index 2d8084a598..f1fd0c235f 100644 --- a/tests/ad/user/Test.AD-USER-04.ps1 +++ b/tests/ad/user/Test.AD-USER-04.ps1 @@ -1,7 +1,7 @@ function Test-MtAdUserReversibleEncryptionCount { <# .SYNOPSIS - Counts user accounts configured to allow reversible password encryption. + Fails user accounts configured to allow reversible password encryption. .DESCRIPTION This test identifies user accounts where password storage may allow reversible @@ -17,13 +17,16 @@ #> [MaesterTest( Id = 'AD-USER-04', - Title = 'Reversible encryption user count should be retrievable', + Title = 'User accounts should not allow reversible password encryption', Product = 'ad', Feature = 'users', Area = 'authentication', ResourceType = 'User', - Severity = 'Info', - Mitre = 'T1556.005', + Severity = 'Medium', + UserImpact = 'Medium', + ImplementationCost = 'Medium', + Mitre = 'T1003.003', + Control = 'nist-800-53-r5:IA-5(1)', Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), Author = 'soulemike' @@ -35,13 +38,13 @@ Write-Verbose "Starting Test-MtAdUserReversibleEncryptionCount" $adState = Get-MtADDomainState -Categories @('Users') Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null + if ($null -eq $adState -or $null -eq $adState.Users) { + throw 'User inventory is unavailable; reversible encryption cannot be assessed.' } Write-Verbose "Filtering/counting user reversible encryption count" $users = @($adState.Users) + Assert-MtAdUserAccountControl -Users $users $reversibleEncryptionUsers = @($users | Where-Object { $hasExplicitFlag = ($_.PSObject.Properties['ReversibleEncryption'] -and $_.ReversibleEncryption -eq $true) -or ($_.PSObject.Properties['AllowReversiblePasswordEncryption'] -and $_.AllowReversiblePasswordEncryption -eq $true) @@ -56,9 +59,9 @@ $totalCount = $users.Count $enabledCount = @($users | Where-Object { $_.Enabled -eq $true }).Count - $testResult = $null -ne $adState.Users + $testResult = $reversibleEncryptionCount -eq 0 - if ($testResult) { + if ($null -ne $adState.Users) { $percentage = if ($totalCount -gt 0) { [Math]::Round(($reversibleEncryptionCount / $totalCount) * 100, 2) } else { @@ -73,7 +76,8 @@ $result += "| Reversible Encryption Percentage | $percentage% |" + "`n" + "`n" Write-Verbose "Counts computed" - $testResultMarkdown = "Active Directory user objects have been analyzed. $reversibleEncryptionCount out of $totalCount users ($percentage%) are configured for reversible password encryption behavior.`n`n%TestResult%" + $table = Format-MtAdUserSecurityTable $reversibleEncryptionUsers @('SamAccountName', 'Enabled', 'DistinguishedName') + $testResultMarkdown = "$(if ($testResult) { 'Well done. No user account permits reversible password encryption.' } else { 'User accounts permit reversible password encryption. Remove that setting, check the effective password policy and reset affected passwords after validating application dependencies.' }) This checks account configuration, not whether an existing plaintext-equivalent password was actually stored.`n`n%TestResult%`n`n$table" $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result } else { $testResultMarkdown = "Unable to retrieve Active Directory user objects. Ensure you have appropriate permissions and the Active Directory module is installed." diff --git a/tests/ad/user/Test.AD-USER-06.md b/tests/ad/user/Test.AD-USER-06.md index 94edb47c3f..8d315d04d7 100644 --- a/tests/ad/user/Test.AD-USER-06.md +++ b/tests/ad/user/Test.AD-USER-06.md @@ -1,27 +1,8 @@ -DES is an obsolete Kerberos encryption type with known cryptographic weakness. Accounts limited to DES-only support should be considered legacy debt and prioritized for cleanup. +DES-only user Kerberos keys weaken encryption and expose authentication material to offline attack. -#### Control Type - -**Detective** - -#### Security Recommendation - -Move DES-only accounts to stronger Kerberos encryption types such as AES and eliminate dependencies on deprecated protocols. Validate application compatibility before enforcement. - -#### How the Test Works - -This test retrieves Active Directory user data from `Get-MtADDomainState` and counts accounts whose Kerberos settings indicate DES usage. It checks `KerberosEncryptionType` when available and falls back to `UseDESKeyOnly`. - -#### Related Tests - -- `Test-MtAdUserDelegationAllowedCount` -- `Test-MtAdUserReversibleEncryptionCount` -- `Test-MtAdUserNoPreAuthCount` - -#### Related links - -- [Microsoft Defender for Identity: Unsecure account attributes](https://learn.microsoft.com/defender-for-identity/security-posture-assessments/accounts#unsecure-account-attributes) -- [ANSSI Active Directory checkpoints: Use of Kerberos with weak encryption](https://www.cert.ssi.gouv.fr/uploads/ad_checklist.html#vuln_kerberos_properties_deskey) +#### Remediation action +1. Identify legacy applications requiring DES with their owners. +2. Migrate to modern Kerberos encryption and clear the DES-only setting in [AD account settings](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/understand-security-identifiers). %TestResult% diff --git a/tests/ad/user/Test.AD-USER-06.ps1 b/tests/ad/user/Test.AD-USER-06.ps1 index c818da94d1..f8ce376c7d 100644 --- a/tests/ad/user/Test.AD-USER-06.ps1 +++ b/tests/ad/user/Test.AD-USER-06.ps1 @@ -1,80 +1,17 @@ function Test-MtAdUserKerberosDesOnlyCount { - <# - .SYNOPSIS - Counts user accounts configured to use DES-only Kerberos encryption. - - .DESCRIPTION - This test identifies user accounts that still rely on DES for Kerberos. DES is - deprecated and cryptographically weak, so these accounts should be remediated and - moved to stronger encryption types where possible. - - .EXAMPLE - Test-MtAdUserKerberosDesOnlyCount - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserKerberosDesOnlyCount + <# .SYNOPSIS + Detects users configured for obsolete DES-only Kerberos keys. #> - [MaesterTest( - Id = 'AD-USER-06', - Title = 'DES-only Kerberos user count should be retrievable', - Product = 'ad', - Feature = 'users', - Area = 'authentication', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'T1558', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] + [MaesterTest(Id = 'AD-USER-06', Title = 'No user should require DES-only Kerberos keys', Product = 'ad', Feature = 'users', Area = 'authentication', ResourceType = 'User', Severity = 'High', UserImpact = 'Medium', ImplementationCost = 'Medium', Mitre = 'T1558', Control = 'nist-800-53-r5:IA-5', Service = 'ActiveDirectory', Permission = 'ActiveDirectory:Ldap:user:ReadProperty', Author = 'soulemike')] [CmdletBinding()] [OutputType([bool])] param() - Write-Verbose "Starting Test-MtAdUserKerberosDesOnlyCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user kerberos des only count" - - $users = @($adState.Users) - $desOnlyUsers = @($users | Where-Object { - ($_.PSObject.Properties['KerberosEncryptionType'] -and (($_.KerberosEncryptionType | Out-String) -match 'DES')) -or - ($_.PSObject.Properties['UseDESKeyOnly'] -and $_.UseDESKeyOnly -eq $true) - }) - - $desOnlyCount = $desOnlyUsers.Count - $totalCount = $users.Count - $enabledCount = @($users | Where-Object { $_.Enabled -eq $true }).Count - - $testResult = $null -ne $adState.Users - - if ($testResult) { - $percentage = if ($totalCount -gt 0) { - [Math]::Round(($desOnlyCount / $totalCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users | $totalCount |" + "`n" - $result += "| Enabled Users | $enabledCount |" + "`n" - $result += "| Users with DES-Only Kerberos | $desOnlyCount |" + "`n" - $result += "| DES-Only Percentage | $percentage% |" + "`n" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory user objects have been analyzed. $desOnlyCount out of $totalCount users ($percentage%) are configured to use DES-only Kerberos encryption.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory user objects. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdUserKerberosDesOnlyCount" - - return $testResult + $state = Get-MtADDomainState -Categories @('Users') + if ($null -eq $state.Users) { throw 'AD user data was not returned.' } + Assert-MtAdUserAccountControl -Users @($state.Users) + $found = @($state.Users | Where-Object { $_.UseDESKeyOnly -eq $true -or ($null -ne $_.UserAccountControl -and (([int64]$_.UserAccountControl -band 0x200000) -ne 0)) }) + if ($found.Count) { Add-MtTestResultDetail -Result "Found $($found.Count) DES-only users. Migrate dependent services to modern Kerberos encryption and remove DES-only configuration.`n`n$(Format-MtAdUserSecurityTable $found @('SamAccountName', 'Enabled', 'DistinguishedName'))" } + else { Add-MtTestResultDetail -Result 'Well done. No user is configured for DES-only Kerberos keys.' } + return ($found.Count -eq 0) } diff --git a/tests/ad/user/Test.AD-USER-07.md b/tests/ad/user/Test.AD-USER-07.md index 202808f57a..470429e79e 100644 --- a/tests/ad/user/Test.AD-USER-07.md +++ b/tests/ad/user/Test.AD-USER-07.md @@ -1,27 +1,8 @@ -Accounts that do not require Kerberos pre-authentication are directly exposed to AS-REP roasting. Attackers can request offline-crackable material without first proving knowledge of the password. +Disabling Kerberos pre-authentication permits AS-REP roasting: an attacker can request crackable material without the password. -#### Control Type - -**Detective** - -#### Security Recommendation - -Require pre-authentication for all accounts unless there is a justified exception. Review and remove legacy settings that disable this protection. - -#### How the Test Works - -This test retrieves Active Directory user data from `Get-MtADDomainState` and counts users where `DoesNotRequirePreAuth = $true` or the corresponding `userAccountControl` bit is set. - -#### Related Tests - -- `Test-MtAdUserDelegationAllowedCount` -- `Test-MtAdUserKerberosDesOnlyCount` -- `Test-MtAdUserPasswordNotRequiredCount` - -#### Related links - -- [Microsoft Defender for Identity: Unsecure account attributes](https://learn.microsoft.com/defender-for-identity/security-posture-assessments/accounts#unsecure-account-attributes) -- [ANSSI Active Directory checkpoints: Kerberos preauthentication disabled](https://www.cert.ssi.gouv.fr/uploads/ad_checklist.html#vuln_kerberos_properties_preauth) +#### Remediation action +1. Confirm dependencies and enable Kerberos pre-authentication on affected [AD user accounts](https://learn.microsoft.com/windows-server/identity/ad-ds/get-started/adac/active-directory-administrative-center). +2. Rotate exposed credentials according to incident-response policy. %TestResult% diff --git a/tests/ad/user/Test.AD-USER-07.ps1 b/tests/ad/user/Test.AD-USER-07.ps1 index d2102d31d1..ed0f63146b 100644 --- a/tests/ad/user/Test.AD-USER-07.ps1 +++ b/tests/ad/user/Test.AD-USER-07.ps1 @@ -1,80 +1,17 @@ function Test-MtAdUserNoPreAuthCount { - <# - .SYNOPSIS - Counts user accounts that do not require Kerberos pre-authentication. - - .DESCRIPTION - This test identifies user accounts with pre-authentication disabled. These accounts - are more exposed to AS-REP roasting attacks because an attacker can request Kerberos - material without proving knowledge of the password first. - - .EXAMPLE - Test-MtAdUserNoPreAuthCount - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserNoPreAuthCount + <# .SYNOPSIS + Detects users that do not require Kerberos pre-authentication. #> - [MaesterTest( - Id = 'AD-USER-07', - Title = 'No pre-authentication user count should be retrievable', - Product = 'ad', - Feature = 'users', - Area = 'authentication', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'T1558.004', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] + [MaesterTest(Id = 'AD-USER-07', Title = 'All users should require Kerberos pre-authentication', Product = 'ad', Feature = 'users', Area = 'authentication', ResourceType = 'User', Severity = 'High', UserImpact = 'Low', ImplementationCost = 'Medium', Mitre = 'T1558.004', Control = 'nist-800-53-r5:IA-2', Service = 'ActiveDirectory', Permission = 'ActiveDirectory:Ldap:user:ReadProperty', Author = 'soulemike')] [CmdletBinding()] [OutputType([bool])] param() - Write-Verbose "Starting Test-MtAdUserNoPreAuthCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user no pre auth count" - - $users = @($adState.Users) - $noPreAuthUsers = @($users | Where-Object { - ($_.PSObject.Properties['DoesNotRequirePreAuth'] -and $_.DoesNotRequirePreAuth -eq $true) -or - ($_.PSObject.Properties['userAccountControl'] -and ($_.userAccountControl -band 0x400000)) - }) - - $noPreAuthCount = $noPreAuthUsers.Count - $totalCount = $users.Count - $enabledCount = @($users | Where-Object { $_.Enabled -eq $true }).Count - - $testResult = $null -ne $adState.Users - - if ($testResult) { - $percentage = if ($totalCount -gt 0) { - [Math]::Round(($noPreAuthCount / $totalCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users | $totalCount |" + "`n" - $result += "| Enabled Users | $enabledCount |" + "`n" - $result += "| Users Without Pre-Authentication | $noPreAuthCount |" + "`n" - $result += "| No Pre-Authentication Percentage | $percentage% |" + "`n" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory user objects have been analyzed. $noPreAuthCount out of $totalCount users ($percentage%) do not require Kerberos pre-authentication.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory user objects. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdUserNoPreAuthCount" - - return $testResult + $state = Get-MtADDomainState -Categories @('Users') + if ($null -eq $state.Users) { throw 'AD user data was not returned.' } + Assert-MtAdUserAccountControl -Users @($state.Users) + $found = @($state.Users | Where-Object { $_.DoesNotRequirePreAuth -eq $true -or ($null -ne $_.UserAccountControl -and (([int64]$_.UserAccountControl -band 0x400000) -ne 0)) }) + if ($found.Count) { Add-MtTestResultDetail -Result "Found $($found.Count) users exposed to AS-REP roasting. Require Kerberos pre-authentication after validating dependencies.`n`n$(Format-MtAdUserSecurityTable $found @('SamAccountName', 'Enabled', 'DistinguishedName'))" } + else { Add-MtTestResultDetail -Result 'Well done. All users require Kerberos pre-authentication.' } + return ($found.Count -eq 0) } diff --git a/tests/ad/user/Test.AD-USER-09.md b/tests/ad/user/Test.AD-USER-09.md index 7781e18bac..1b795b7076 100644 --- a/tests/ad/user/Test.AD-USER-09.md +++ b/tests/ad/user/Test.AD-USER-09.md @@ -1,22 +1,7 @@ -Accounts that do not require passwords are a severe security weakness. Even if rarely used, they represent a misconfiguration that can undermine core authentication protections. +The `PASSWORD_NOT_REQUIRED` user flag weakens credential requirements; it does not itself establish that a password is blank. Both enabled and disabled accounts are shown. -#### Control Type - -**Detective** - -#### Security Recommendation - -Investigate every account with `PasswordNotRequired` set. Require passwords, rotate credentials, and validate that no workflow depends on this unsafe configuration. - -#### How the Test Works - -This test retrieves Active Directory user data from `Get-MtADDomainState` and counts accounts where `PasswordNotRequired = $true`. The output shows the total count and percentage of affected users. - -#### Related Tests - -- `Test-MtAdUserPasswordNeverExpiresCount` -- `Test-MtAdUserNoPreAuthCount` -- `Test-MtAdUserReversibleEncryptionCount` +#### Remediation action +1. Review application dependencies, set a strong credential and clear the flag in [AD account settings](https://learn.microsoft.com/windows-server/identity/ad-ds/get-started/adac/active-directory-administrative-center). %TestResult% diff --git a/tests/ad/user/Test.AD-USER-09.ps1 b/tests/ad/user/Test.AD-USER-09.ps1 index 2f8855f0a6..673c6f6e3b 100644 --- a/tests/ad/user/Test.AD-USER-09.ps1 +++ b/tests/ad/user/Test.AD-USER-09.ps1 @@ -1,77 +1,22 @@ function Test-MtAdUserPasswordNotRequiredCount { - <# - .SYNOPSIS - Counts user accounts where a password is not required. - - .DESCRIPTION - This test identifies user accounts configured with the PasswordNotRequired flag. - Accounts that do not require passwords represent a high-risk configuration and should - be investigated immediately. - - .EXAMPLE - Test-MtAdUserPasswordNotRequiredCount - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserPasswordNotRequiredCount + <# .SYNOPSIS + Detects users with the password-not-required account control flag. #> - [MaesterTest( - Id = 'AD-USER-09', - Title = 'Password-not-required user count should be retrievable', - Product = 'ad', - Feature = 'users', - Area = 'authentication', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'T1078.002', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] + [MaesterTest(Id = 'AD-USER-09', Title = 'No user should have PasswordNotRequired set', Product = 'ad', Feature = 'users', Area = 'authentication', ResourceType = 'User', Severity = 'High', UserImpact = 'Medium', ImplementationCost = 'Medium', Mitre = 'T1078.002', Control = 'nist-800-53-r5:IA-5', Service = 'ActiveDirectory', Permission = 'ActiveDirectory:Ldap:user:ReadProperty', Author = 'soulemike')] [CmdletBinding()] [OutputType([bool])] param() - Write-Verbose "Starting Test-MtAdUserPasswordNotRequiredCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user password not required count" - - $users = @($adState.Users) - $passwordNotRequiredUsers = @($users | Where-Object { $_.PasswordNotRequired -eq $true }) - - $passwordNotRequiredCount = $passwordNotRequiredUsers.Count - $totalCount = $users.Count - $enabledCount = @($users | Where-Object { $_.Enabled -eq $true }).Count - - $testResult = $null -ne $adState.Users - - if ($testResult) { - $percentage = if ($totalCount -gt 0) { - [Math]::Round(($passwordNotRequiredCount / $totalCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users | $totalCount |" + "`n" - $result += "| Enabled Users | $enabledCount |" + "`n" - $result += "| Users with Password Not Required | $passwordNotRequiredCount |" + "`n" - $result += "| Password Not Required Percentage | $percentage% |" + "`n" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory user objects have been analyzed. $passwordNotRequiredCount out of $totalCount users ($percentage%) do not require a password.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory user objects. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdUserPasswordNotRequiredCount" - - return $testResult + $state = Get-MtADDomainState -Categories @('Users') + if ($null -eq $state.Users) { throw 'AD user data was not returned.' } + Assert-MtAdUserAccountControl -Users @($state.Users) + $found = @($state.Users | Where-Object { $_.PasswordNotRequired -eq $true -or ($null -ne $_.UserAccountControl -and (([int64]$_.UserAccountControl -band 0x20) -ne 0)) }) + if (@($found | Where-Object { $null -eq $_.Enabled }).Count -gt 0) { throw 'Enabled state is unavailable for password-not-required accounts.' } + $findings = @($found | Where-Object { $_.Enabled -eq $true -or (Test-MtAdUserOrdinaryIdentity $_) }) + $protectedReview = @($found | Where-Object { $_.Enabled -eq $false -and -not (Test-MtAdUserOrdinaryIdentity $_) }) + $enabledCount = @($found | Where-Object { $_.Enabled -eq $true }).Count + if ($findings.Count) { Add-MtTestResultDetail -Result "Found $($findings.Count) enabled or ordinary accounts with the PASSWORD_NOT_REQUIRED flag. Review password requirements; the flag alone does not prove a blank password. $($protectedReview.Count) protected disabled built-ins are shown for review, not counted as failures.`n`n| Metric | Count |`n| --- | --- |`n| Enabled users with password not required | $enabledCount |`n`n$(Format-MtAdUserSecurityTable $found @('SamAccountName', 'Enabled', 'PasswordNotRequired', 'DistinguishedName'))" } + elseif ($protectedReview.Count) { Add-MtTestResultDetail -Result "Only protected disabled built-ins have PASSWORD_NOT_REQUIRED; review their expected state without treating them as active password exposure.`n`n$(Format-MtAdUserSecurityTable $protectedReview @('SamAccountName', 'Enabled', 'PasswordNotRequired', 'DistinguishedName'))" -Investigate } + else { Add-MtTestResultDetail -Result 'Well done. No user has the PASSWORD_NOT_REQUIRED flag.' } + return ($findings.Count -eq 0) } From e4f7c2fafb5bc79b75def95643ecc9788cb393be Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 18:47:11 +0000 Subject: [PATCH 029/100] fix(ad): assess user ownership and account governance --- tests/ad/user/Test.AD-USER-10.md | 22 ++----- tests/ad/user/Test.AD-USER-10.ps1 | 80 +++----------------------- tests/ad/user/Test.AD-USER-11.md | 27 ++------- tests/ad/user/Test.AD-USER-11.ps1 | 81 +++----------------------- tests/ad/user/Test.AD-USER-12.md | 32 ++--------- tests/ad/user/Test.AD-USER-12.ps1 | 94 ++++++------------------------ tests/ad/user/Test.AD-USER-13.md | 32 ++--------- tests/ad/user/Test.AD-USER-13.ps1 | 90 +++++------------------------ tests/ad/user/Test.AD-USER-15.md | 27 ++------- tests/ad/user/Test.AD-USER-15.ps1 | 89 +++++----------------------- tests/ad/user/Test.AD-USER-19.md | 26 +-------- tests/ad/user/Test.AD-USER-19.ps1 | 96 ++++++------------------------- 12 files changed, 101 insertions(+), 595 deletions(-) diff --git a/tests/ad/user/Test.AD-USER-10.md b/tests/ad/user/Test.AD-USER-10.md index f5b2d9f981..18b45cd78f 100644 --- a/tests/ad/user/Test.AD-USER-10.md +++ b/tests/ad/user/Test.AD-USER-10.md @@ -1,22 +1,8 @@ -Restricting where a user can log on can reduce exposure for privileged, administrative, or sensitive accounts. Measuring how often workstation restrictions are used helps assess adoption of this hardening control. +Workstation logon restrictions are inventoried for investigation, not treated as a pass/fail baseline. Their absence alone does not prove exposure. -#### Control Type - -**Detective** - -#### Security Recommendation - -Consider applying workstation restrictions to privileged and high-value accounts where operationally feasible. Review configured restrictions periodically to ensure they remain accurate. - -#### How the Test Works - -This test retrieves Active Directory user data from `Get-MtADDomainState` and counts accounts where `LogonWorkstations` is populated. - -#### Related Tests - -- `Test-MtAdUserDelegationAllowedCount` -- `Test-MtAdUserDormantEnabledCount` -- `Test-MtAdUserNeverLoggedInCount` +#### Remediation action +1. Review listed user restrictions with account owners in [Active Directory administration](https://learn.microsoft.com/windows-server/identity/ad-ds/get-started/adac/active-directory-administrative-center). +2. Remove obsolete restrictions and document restrictions required for sensitive accounts. %TestResult% diff --git a/tests/ad/user/Test.AD-USER-10.ps1 b/tests/ad/user/Test.AD-USER-10.ps1 index 07396ee81f..e8f1965556 100644 --- a/tests/ad/user/Test.AD-USER-10.ps1 +++ b/tests/ad/user/Test.AD-USER-10.ps1 @@ -1,79 +1,15 @@ function Test-MtAdUserWorkstationRestrictionCount { - <# - .SYNOPSIS - Counts user accounts with logon workstation restrictions configured. - - .DESCRIPTION - This test identifies user accounts where the LogonWorkstations attribute is set. - Workstation restrictions can be a useful hardening control for sensitive accounts and - this test helps measure how broadly that control is being used. - - .EXAMPLE - Test-MtAdUserWorkstationRestrictionCount - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserWorkstationRestrictionCount + <# .SYNOPSIS + Inventories user accounts with logon workstation restrictions for review. #> - [MaesterTest( - Id = 'AD-USER-10', - Title = 'Workstation-restricted user count should be retrievable', - Product = 'ad', - Feature = 'users', - Area = 'access-control', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] + [MaesterTest(Id = 'AD-USER-10', Title = 'User workstation restrictions should be reviewed', Product = 'ad', Feature = 'users', Area = 'access-control', ResourceType = 'User', Severity = 'Info', Mitre = 'None', Service = 'ActiveDirectory', Permission = 'ActiveDirectory:Ldap:user:ReadProperty', Author = 'soulemike')] [CmdletBinding()] [OutputType([bool])] param() - Write-Verbose "Starting Test-MtAdUserWorkstationRestrictionCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user workstation restriction count" - - $users = @($adState.Users) - $restrictedUsers = @($users | Where-Object { - -not [string]::IsNullOrWhiteSpace([string]$_.LogonWorkstations) - }) - - $restrictedCount = $restrictedUsers.Count - $totalCount = $users.Count - $enabledCount = @($users | Where-Object { $_.Enabled -eq $true }).Count - - $testResult = $null -ne $adState.Users - - if ($testResult) { - $percentage = if ($totalCount -gt 0) { - [Math]::Round(($restrictedCount / $totalCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users | $totalCount |" + "`n" - $result += "| Enabled Users | $enabledCount |" + "`n" - $result += "| Users with Workstation Restrictions | $restrictedCount |" + "`n" - $result += "| Restriction Percentage | $percentage% |" + "`n" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory user objects have been analyzed. $restrictedCount out of $totalCount users ($percentage%) have workstation logon restrictions configured.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory user objects. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdUserWorkstationRestrictionCount" - - return $testResult + $state = Get-MtADDomainState -Categories @('Users') + if ($null -eq $state.Users) { throw 'AD user data was not returned.' } + $found = @($state.Users | Where-Object { -not [string]::IsNullOrWhiteSpace($_.LogonWorkstations) }) + Add-MtTestResultDetail -Result "Review $($found.Count) users with workstation restrictions (an empty restriction is not proof of risk).`n`n$(Format-MtAdUserSecurityTable $found @('SamAccountName', 'Enabled', 'LogonWorkstations'))" -Investigate + return $true } diff --git a/tests/ad/user/Test.AD-USER-11.md b/tests/ad/user/Test.AD-USER-11.md index 79af76b2a2..ec142b0e96 100644 --- a/tests/ad/user/Test.AD-USER-11.md +++ b/tests/ad/user/Test.AD-USER-11.md @@ -1,27 +1,8 @@ -The `AdminCount` attribute is commonly set on protected and privileged accounts. These users often inherit AdminSDHolder protections and may retain elevated access or restricted ACL inheritance. +Accounts with `AdminCount=1` require human review; this flag can persist after privileged group removal and is not proof of current administrator rights. -- **Privilege visibility**: Highlights accounts that may be administrative or formerly administrative -- **Delegation impact**: Protected accounts behave differently from standard users -- **Security review**: Helps identify users that warrant stronger monitoring and change control - -#### Control Type - -**Detective** - -#### Security Recommendation - -- Review each account with `AdminCount = 1` to confirm it still requires elevated protections -- Validate that privileged accounts are intentionally assigned and documented -- Investigate stale or unexpected protected users and remove unnecessary privileged group membership - -#### How the Test Works - -This test counts user objects where the `AdminCount` attribute equals `1`. - -#### Related Tests - -- `Test-MtAdUserNonStandardPrimaryGroupCount` - Finds users with unusual group membership baselines -- `AD-SPN-06` - Identifies accounts with SPNs +#### Remediation action +1. Review group membership and inherited permissions in [AD administration](https://learn.microsoft.com/windows-server/identity/ad-ds/get-started/adac/active-directory-administrative-center). +2. Remove unnecessary privileges; clear stale protection only after validating the account is no longer protected. %TestResult% diff --git a/tests/ad/user/Test.AD-USER-11.ps1 b/tests/ad/user/Test.AD-USER-11.ps1 index 7b29538fea..4af3c23384 100644 --- a/tests/ad/user/Test.AD-USER-11.ps1 +++ b/tests/ad/user/Test.AD-USER-11.ps1 @@ -1,80 +1,15 @@ function Test-MtAdUserAdminCountCount { - <# - .SYNOPSIS - Counts users with AdminCount set in Active Directory. - - .DESCRIPTION - This test identifies user objects that have the AdminCount attribute set to 1. - AdminCount is commonly applied to privileged or protected accounts that inherit - AdminSDHolder protection. These accounts warrant additional review because they - often retain elevated rights or have previously held privileged memberships. - - .EXAMPLE - Test-MtAdUserAdminCountCount - - Returns $true if user data is accessible, $false otherwise. - The test result includes the count of users with AdminCount set. - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserAdminCountCount + <# .SYNOPSIS + Inventories users with AdminCount set for privilege review. #> - [MaesterTest( - Id = 'AD-USER-11', - Title = 'User AdminCount count should be retrievable', - Product = 'ad', - Feature = 'users', - Area = 'privileged-access', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] + [MaesterTest(Id = 'AD-USER-11', Title = 'AdminCount users should be reviewed', Product = 'ad', Feature = 'users', Area = 'privileged-access', ResourceType = 'User', Severity = 'Info', Mitre = 'None', Service = 'ActiveDirectory', Permission = 'ActiveDirectory:Ldap:user:ReadProperty', Author = 'soulemike')] [CmdletBinding()] [OutputType([bool])] param() - Write-Verbose "Starting Test-MtAdUserAdminCountCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user admin count count" - - $users = $adState.Users - $usersWithAdminCount = $users | Where-Object { - $_.AdminCount -eq 1 - } - - $adminCount = ($usersWithAdminCount | Measure-Object).Count - $totalCount = ($users | Measure-Object).Count - $testResult = $totalCount -gt 0 - - if ($testResult) { - $percentage = if ($totalCount -gt 0) { - [Math]::Round(($adminCount / $totalCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users | $totalCount |" + "`n" - $result += "| Users with AdminCount = 1 | $adminCount |" + "`n" - $result += "| AdminCount Percentage | $percentage% |" + "`n" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory users have been analyzed. $adminCount out of $totalCount users ($percentage%) have AdminCount set to 1.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory users. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdUserAdminCountCount" - - return $testResult + $state = Get-MtADDomainState -Categories @('Users') + if ($null -eq $state.Users) { throw 'AD user data was not returned.' } + $found = @($state.Users | Where-Object { $_.AdminCount -eq 1 }) + Add-MtTestResultDetail -Result "Review $($found.Count) users with AdminCount=1. This flag can persist after privilege removal and does not alone prove current administrator rights.`n`n$(Format-MtAdUserSecurityTable $found @('SamAccountName', 'Enabled', 'AdminCount', 'DistinguishedName'))" -Investigate + return $true } diff --git a/tests/ad/user/Test.AD-USER-12.md b/tests/ad/user/Test.AD-USER-12.md index 3f6a4b1eeb..ae6e6af6b1 100644 --- a/tests/ad/user/Test.AD-USER-12.md +++ b/tests/ad/user/Test.AD-USER-12.md @@ -1,32 +1,8 @@ -Most user accounts use `PrimaryGroupId = 513`, which corresponds to `Domain Users`. When a user has a different primary group, the configuration is often intentional but uncommon. +Ordinary users should use approved primary group RIDs (default 513, Domain Users). Protected identities and built-in RID 500–503 accounts are exempt. Hidden primary group membership can complicate reviews. -- **Privilege review**: Non-standard primary groups can indicate elevated or specialized access models -- **Migration residue**: Legacy migrations and scripted provisioning may leave unusual values behind -- **Access clarity**: Atypical primary groups make account analysis more complex - -#### Control Type - -**Detective** - -#### Security Recommendation - -- Review users whose `PrimaryGroupId` is not `513` -- Confirm the configuration is required and documented -- Standardize primary groups where there is no operational reason for deviation - -#### How the Test Works - -This test counts user objects where `primaryGroupId` is populated and not equal to `513`. - -#### Related Tests - -- `Test-MtAdUserAdminCountCount` - Highlights protected or privileged accounts -- `Test-MtAdUserSidHistoryCount` - Identifies migration-related account artifacts - -#### Related links - -- [Microsoft Defender for Identity: Accounts with non-default Primary Group ID](https://learn.microsoft.com/defender-for-identity/security-posture-assessments/accounts#accounts-with-non-default-primary-group-id) -- [ANSSI Active Directory checkpoints: Accounts with modified PrimaryGroupID](https://www.cert.ssi.gouv.fr/uploads/ad_checklist.html#vuln_primary_group_id_nochange) +#### Remediation action +1. Validate required group membership, then restore an approved primary group through [AD administration](https://learn.microsoft.com/windows-server/identity/ad-ds/get-started/adac/active-directory-administrative-center). +2. Add documented legitimate RID exceptions to `AllowedPrimaryGroupIds`. %TestResult% diff --git a/tests/ad/user/Test.AD-USER-12.ps1 b/tests/ad/user/Test.AD-USER-12.ps1 index cfaf7910de..f572d92cbf 100644 --- a/tests/ad/user/Test.AD-USER-12.ps1 +++ b/tests/ad/user/Test.AD-USER-12.ps1 @@ -1,81 +1,23 @@ function Test-MtAdUserNonStandardPrimaryGroupCount { - <# - .SYNOPSIS - Counts users with a non-standard primary group in Active Directory. - - .DESCRIPTION - This test identifies user objects whose PrimaryGroupId is not set to 513 - (Domain Users). A non-standard primary group can be legitimate in some cases, - but it is uncommon and may indicate privileged configurations, legacy migrations, - or unusual access control requirements that should be validated. - - .EXAMPLE - Test-MtAdUserNonStandardPrimaryGroupCount - - Returns $true if user data is accessible, $false otherwise. - The test result includes the count of users with a non-standard primary group. - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserNonStandardPrimaryGroupCount + <# .SYNOPSIS + Checks for ordinary users with unapproved primary group IDs. #> - [MaesterTest( - Id = 'AD-USER-12', - Title = 'User non-standard primary group count should be retrievable', - Product = 'ad', - Feature = 'users', - Area = 'identity-lifecycle', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] + [MaesterTest(Id = 'AD-USER-12', Title = 'Ordinary users should use an approved primary group', Product = 'ad', Feature = 'users', Area = 'identity-lifecycle', ResourceType = 'User', Severity = 'Low', UserImpact = 'Low', ImplementationCost = 'Medium', Mitre = 'T1078.002', Service = 'ActiveDirectory', Permission = 'ActiveDirectory:Ldap:user:ReadProperty', Author = 'soulemike')] [CmdletBinding()] [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserNonStandardPrimaryGroupCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user non standard primary group count" - - $users = $adState.Users - $usersWithNonStandardPrimaryGroup = $users | Where-Object { - $null -ne $_.primaryGroupId -and $_.primaryGroupId -ne 513 - } - - $nonStandardPrimaryGroupCount = ($usersWithNonStandardPrimaryGroup | Measure-Object).Count - $totalCount = ($users | Measure-Object).Count - $testResult = $totalCount -gt 0 - - if ($testResult) { - $percentage = if ($totalCount -gt 0) { - [Math]::Round(($nonStandardPrimaryGroupCount / $totalCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users | $totalCount |" + "`n" - $result += "| Users with PrimaryGroupId = 513 | $($totalCount - $nonStandardPrimaryGroupCount) |" + "`n" - $result += "| Users with Non-Standard Primary Group | $nonStandardPrimaryGroupCount |" + "`n" - $result += "| Non-Standard Primary Group Percentage | $percentage% |" + "`n" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory users have been analyzed. $nonStandardPrimaryGroupCount out of $totalCount users ($percentage%) have a primaryGroupId other than 513 (Domain Users).`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory users. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdUserNonStandardPrimaryGroupCount" - - return $testResult + param( + # Primary group RID values permitted for ordinary user accounts. + [ValidatePattern('^[0-9]+$')] + [string[]] $AllowedPrimaryGroupIds = @('513') + ) + + $state = Get-MtADDomainState -Categories @('Users') + if ($null -eq $state.Users) { throw 'AD user data was not returned.' } + $allowedIds = @($AllowedPrimaryGroupIds | ForEach-Object { [int]$_ }) + $unknown = @($state.Users | Where-Object { (Test-MtAdUserOrdinaryIdentity $_) -and $null -eq $_.PrimaryGroupId }) + if ($unknown.Count) { throw "PrimaryGroupId missing for $($unknown.Count) ordinary users." } + $found = @($state.Users | Where-Object { (Test-MtAdUserOrdinaryIdentity $_) -and $allowedIds -notcontains [int]$_.PrimaryGroupId }) + if ($found.Count) { Add-MtTestResultDetail -Result "Found $($found.Count) ordinary users with unapproved primary groups. Review effective membership and approve exceptions before changing groups.`n`n$(Format-MtAdUserSecurityTable $found @('SamAccountName', 'PrimaryGroupId', 'DistinguishedName'))" } + else { Add-MtTestResultDetail -Result 'Well done. Ordinary users have approved primary group IDs.' } + return ($found.Count -eq 0) } diff --git a/tests/ad/user/Test.AD-USER-13.md b/tests/ad/user/Test.AD-USER-13.md index 1bce78278c..cc4760db85 100644 --- a/tests/ad/user/Test.AD-USER-13.md +++ b/tests/ad/user/Test.AD-USER-13.md @@ -1,32 +1,8 @@ -`SIDHistory` is commonly used during migrations so users can retain access to resources secured with legacy SIDs. Long-term SID history can create unnecessary complexity and unintended access paths. +Unapproved SID history can retain access granted to older identities after migrations. Migration exceptions must be documented and passed in `ApprovedAccountIds`. -- **Migration artifact detection**: Identifies users that may still carry legacy identities -- **Trust boundary review**: Helps spot cross-domain access dependencies -- **Permission cleanup**: Supports least-privilege remediation after migrations - -#### Control Type - -**Detective** - -#### Security Recommendation - -- Review users with `SIDHistory` to confirm ongoing business need -- Remove unnecessary SID history entries after resource migration is complete -- Pay special attention to SIDs originating from external or less-trusted domains - -#### How the Test Works - -This test counts user objects where the `SIDHistory` attribute contains one or more values. - -#### Related Tests - -- `Test-MtAdUserNonStandardPrimaryGroupCount` - Finds other migration or provisioning anomalies -- `Test-MtAdUserAdminCountCount` - Helps prioritize review of privileged accounts - -#### Related links - -- [Microsoft Defender for Identity: Unsecure SID History attributes](https://learn.microsoft.com/defender-for-identity/security-posture-assessments/accounts#unsecure-sid-history-attributes) -- [ANSSI Active Directory checkpoints: Accounts or groups with SID history set](https://www.cert.ssi.gouv.fr/uploads/ad_checklist.html#vuln_sidhistory_present) +#### Remediation action +1. Validate each migration dependency and resource ACL before removing [SID history](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/understand-security-identifiers). +2. Review exceptions periodically and remove unnecessary history under a change plan. %TestResult% diff --git a/tests/ad/user/Test.AD-USER-13.ps1 b/tests/ad/user/Test.AD-USER-13.ps1 index 8e8feb0d76..f47d997c62 100644 --- a/tests/ad/user/Test.AD-USER-13.ps1 +++ b/tests/ad/user/Test.AD-USER-13.ps1 @@ -1,81 +1,19 @@ function Test-MtAdUserSidHistoryCount { - <# - .SYNOPSIS - Counts users with SID History set in Active Directory. - - .DESCRIPTION - This test identifies user objects that have the SIDHistory attribute populated. - SID History is typically used during migrations to preserve access to resources. - Persistent SID History can represent legacy migration artifacts or access paths - that should be reviewed for least privilege and trust boundary concerns. - - .EXAMPLE - Test-MtAdUserSidHistoryCount - - Returns $true if user data is accessible, $false otherwise. - The test result includes the count of users with SID History. - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserSidHistoryCount + <# .SYNOPSIS + Checks whether any users retain unapproved migrated SID history. #> - [MaesterTest( - Id = 'AD-USER-13', - Title = 'User SID History count should be retrievable', - Product = 'ad', - Feature = 'users', - Area = 'identity-lifecycle', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'T1134.005', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] + [MaesterTest(Id = 'AD-USER-13', Title = 'Users should not retain unapproved SID history', Product = 'ad', Feature = 'users', Area = 'identity-lifecycle', ResourceType = 'User', Severity = 'Medium', UserImpact = 'Low', ImplementationCost = 'Medium', Mitre = 'T1134.005', Control = 'nist-800-53-r5:AC-2', Service = 'ActiveDirectory', Permission = 'ActiveDirectory:Ldap:user:ReadProperty', Author = 'soulemike')] [CmdletBinding()] [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserSidHistoryCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user sid history count" - - $users = $adState.Users - $usersWithSidHistory = $users | Where-Object { - $_.SIDHistory -and - ($_.SIDHistory | Measure-Object).Count -gt 0 - } - - $sidHistoryCount = ($usersWithSidHistory | Measure-Object).Count - $totalCount = ($users | Measure-Object).Count - $testResult = $totalCount -gt 0 - - if ($testResult) { - $percentage = if ($totalCount -gt 0) { - [Math]::Round(($sidHistoryCount / $totalCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users | $totalCount |" + "`n" - $result += "| Users with SID History | $sidHistoryCount |" + "`n" - $result += "| SID History Percentage | $percentage% |" + "`n" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory users have been analyzed. $sidHistoryCount out of $totalCount users ($percentage%) have SID History set.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory users. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdUserSidHistoryCount" - - return $testResult + param( + # Account IDs with approved migration SID history exceptions. + [string[]] $ApprovedAccountIds = @() + ) + + $state = Get-MtADDomainState -Categories @('Users') + if ($null -eq $state.Users) { throw 'AD user data was not returned.' } + $found = @($state.Users | Where-Object { @($_.SIDHistory | Where-Object { $null -ne $_ }).Count -gt 0 -and $ApprovedAccountIds -notcontains $_.SamAccountName -and $ApprovedAccountIds -notcontains $_.DistinguishedName }) + if ($found.Count) { Add-MtTestResultDetail -Result "Found $($found.Count) users with unapproved SID history. Validate migration dependencies and approved exceptions; remove history only after access and trust review.`n`n$(Format-MtAdUserSecurityTable $found @('SamAccountName', 'SIDHistory', 'DistinguishedName'))" } + else { Add-MtTestResultDetail -Result 'Well done. No unapproved SID history remains on user accounts.' } + return ($found.Count -eq 0) } diff --git a/tests/ad/user/Test.AD-USER-15.md b/tests/ad/user/Test.AD-USER-15.md index 7ded1ab37e..a662559b1b 100644 --- a/tests/ad/user/Test.AD-USER-15.md +++ b/tests/ad/user/Test.AD-USER-15.md @@ -1,27 +1,8 @@ -The `Manager` attribute is frequently used in governance workflows, approval chains, and identity lifecycle processes. Missing or inconsistent manager data can weaken access review quality. +Enabled ordinary users missing a manager can be omitted from manager-led identity reviews. Built-in and protected accounts are excluded; configure `ExcludedUsers` for documented exceptions. -- **Governance readiness**: Supports manager-based approval and review processes -- **Data quality insight**: Shows how complete identity metadata is across the domain -- **Operational control**: Helps identify where HR or provisioning integrations may be incomplete - -#### Control Type - -**Detective** - -#### Security Recommendation - -- Populate manager data for workforce identities where appropriate -- Validate synchronization from authoritative systems such as HR platforms -- Use complete manager relationships to strengthen approval and certification processes - -#### How the Test Works - -This test counts user objects where the `Manager` attribute contains a non-empty value. - -#### Related Tests - -- `Test-MtAdUserHomeDirectoryCount` - Highlights legacy user provisioning attributes -- `Test-MtAdUserProfilePathCount` - Identifies additional operational dependencies +#### Remediation action +1. Verify ownership and populate the manager attribute through [AD administration](https://learn.microsoft.com/windows-server/identity/ad-ds/get-started/adac/active-directory-administrative-center). +2. Document account types for which no manager is appropriate. %TestResult% diff --git a/tests/ad/user/Test.AD-USER-15.ps1 b/tests/ad/user/Test.AD-USER-15.ps1 index d596379b99..664b8fcf05 100644 --- a/tests/ad/user/Test.AD-USER-15.ps1 +++ b/tests/ad/user/Test.AD-USER-15.ps1 @@ -1,80 +1,19 @@ function Test-MtAdUserManagerSetCount { - <# - .SYNOPSIS - Counts users with the manager attribute set in Active Directory. - - .DESCRIPTION - This test identifies user objects where the Manager attribute is populated. - While this is not inherently a security issue, manager relationships are often - used in approval workflows, access reviews, and delegated business processes. - Understanding coverage helps assess the reliability of identity governance data. - - .EXAMPLE - Test-MtAdUserManagerSetCount - - Returns $true if user data is accessible, $false otherwise. - The test result includes the count of users with a manager assigned. - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserManagerSetCount + <# .SYNOPSIS + Checks for enabled ordinary users missing a manager for access review. #> - [MaesterTest( - Id = 'AD-USER-15', - Title = 'User manager count should be retrievable', - Product = 'ad', - Feature = 'users', - Area = 'identity-lifecycle', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] + [MaesterTest(Id = 'AD-USER-15', Title = 'Enabled ordinary users should have a manager', Product = 'ad', Feature = 'users', Area = 'identity-lifecycle', ResourceType = 'User', Severity = 'Low', UserImpact = 'Low', ImplementationCost = 'Medium', Mitre = 'None', Control = 'nist-800-53-r5:AC-2', Service = 'ActiveDirectory', Permission = 'ActiveDirectory:Ldap:user:ReadProperty', Author = 'soulemike')] [CmdletBinding()] [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserManagerSetCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user manager set count" - - $users = $adState.Users - $usersWithManager = $users | Where-Object { - -not [string]::IsNullOrWhiteSpace($_.Manager) - } - - $managerCount = ($usersWithManager | Measure-Object).Count - $totalCount = ($users | Measure-Object).Count - $testResult = $totalCount -gt 0 - - if ($testResult) { - $percentage = if ($totalCount -gt 0) { - [Math]::Round(($managerCount / $totalCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users | $totalCount |" + "`n" - $result += "| Users with Manager Set | $managerCount |" + "`n" - $result += "| Manager Coverage | $percentage% |" + "`n" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory users have been analyzed. $managerCount out of $totalCount users ($percentage%) have the Manager attribute populated.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory users. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdUserManagerSetCount" - - return $testResult + param( + # Ordinary account IDs (sAMAccountName or distinguished name) without a manager by design. + [string[]] $ExcludedUsers = @() + ) + + $state = Get-MtADDomainState -Categories @('Users') + if ($null -eq $state.Users) { throw 'AD user data was not returned.' } + $found = @($state.Users | Where-Object { $_.Enabled -eq $true -and (Test-MtAdUserOrdinaryIdentity $_) -and [string]::IsNullOrWhiteSpace($_.Manager) -and $ExcludedUsers -notcontains $_.SamAccountName -and $ExcludedUsers -notcontains $_.DistinguishedName }) + if ($found.Count) { Add-MtTestResultDetail -Result "Found $($found.Count) enabled ordinary users without a manager. Assign owners or document exclusions for access reviews.`n`n$(Format-MtAdUserSecurityTable $found @('SamAccountName', 'DistinguishedName'))" } + else { Add-MtTestResultDetail -Result 'Well done. Enabled ordinary users have managers or approved exclusions.' } + return ($found.Count -eq 0) } diff --git a/tests/ad/user/Test.AD-USER-19.md b/tests/ad/user/Test.AD-USER-19.md index b904a391dc..4f616bad4c 100644 --- a/tests/ad/user/Test.AD-USER-19.md +++ b/tests/ad/user/Test.AD-USER-19.md @@ -1,27 +1,7 @@ -Users are easier to manage when placed in organizational units (OUs) that align to administration, policy, and lifecycle requirements. Accounts stored in container paths such as `CN=Users` often indicate default placement or limited organizational structure. +Ordinary users under CN containers rather than managed OUs may miss intended OU-linked policies and delegated administration. Escaped commas in distinguished names are handled as part of the RDN. -- **Delegation limitations**: Containers are less flexible for delegated administration -- **Policy design impact**: OUs are the preferred structure for policy and lifecycle management -- **Default placement visibility**: Helps identify accounts still living in `CN=Users` or similar container paths - -#### Control Type - -**Detective** - -#### Security Recommendation - -- Move standard user accounts from container paths into appropriate OUs -- Define an OU model that supports administration, policy, and lifecycle requirements -- Regularly review new accounts for default or non-standard placement - -#### How the Test Works - -This test counts user objects whose distinguished names indicate they are beneath a container path, including accounts under `CN=Users`. - -#### Related Tests - -- `Test-MtAdUserManagerSetCount` - Helps assess whether organizational metadata is mature enough for governance -- `Test-MtAdUserKnownServiceAccountCount` - Finds service accounts that may also require dedicated OUs +#### Remediation action +1. Check OU policy and delegation requirements before moving affected users using [AD administration](https://learn.microsoft.com/windows-server/identity/ad-ds/get-started/adac/active-directory-administrative-center). %TestResult% diff --git a/tests/ad/user/Test.AD-USER-19.ps1 b/tests/ad/user/Test.AD-USER-19.ps1 index e21bc4cd3a..a2c82957af 100644 --- a/tests/ad/user/Test.AD-USER-19.ps1 +++ b/tests/ad/user/Test.AD-USER-19.ps1 @@ -1,87 +1,23 @@ function Test-MtAdUserInContainerCount { - <# - .SYNOPSIS - Counts users located in container objects instead of OUs. - - .DESCRIPTION - This test identifies user objects whose distinguished name indicates they are - stored beneath a container path (CN=) rather than an organizational unit (OU=). - Users in default or custom containers can be harder to manage consistently because - containers do not support the same delegation and Group Policy design patterns as OUs. - - .EXAMPLE - Test-MtAdUserInContainerCount - - Returns $true if user data is accessible, $false otherwise. - The test result includes the count of users located in container objects. - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserInContainerCount + <# .SYNOPSIS + Finds ordinary users beneath CN containers instead of OUs. #> - [MaesterTest( - Id = 'AD-USER-19', - Title = 'User in container count should be retrievable', - Product = 'ad', - Feature = 'users', - Area = 'infrastructure', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] + [MaesterTest(Id = 'AD-USER-19', Title = 'Ordinary users should be managed in organizational units', Product = 'ad', Feature = 'users', Area = 'identity-lifecycle', ResourceType = 'User', Severity = 'Low', UserImpact = 'Low', ImplementationCost = 'Medium', Mitre = 'None', Service = 'ActiveDirectory', Permission = 'ActiveDirectory:Ldap:user:ReadProperty', Author = 'soulemike')] [CmdletBinding()] [OutputType([bool])] param() - Write-Verbose "Starting Test-MtAdUserInContainerCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user in container count" - - $users = $adState.Users - $usersInContainers = $users | Where-Object { - $_.DistinguishedName -and ( - $_.DistinguishedName -like "CN=*,CN=Users,*" -or - $_.DistinguishedName -match '^CN=[^,]+,CN=' - ) - } - - $defaultUsersContainerCount = ($usersInContainers | Where-Object { - $_.DistinguishedName -like "CN=*,CN=Users,*" - } | Measure-Object).Count - $containerCount = ($usersInContainers | Measure-Object).Count - $totalCount = ($users | Measure-Object).Count - $testResult = $totalCount -gt 0 - - if ($testResult) { - $percentage = if ($totalCount -gt 0) { - [Math]::Round(($containerCount / $totalCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users | $totalCount |" + "`n" - $result += "| Users in CN=Users | $defaultUsersContainerCount |" + "`n" - $result += "| Users in Container Paths | $containerCount |" + "`n" - $result += "| Container Percentage | $percentage% |" + "`n" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory users have been analyzed. $containerCount out of $totalCount users ($percentage%) are located in container paths such as CN=Users instead of OUs.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory users. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdUserInContainerCount" - - return $testResult + $state = Get-MtADDomainState -Categories @('Users') + if ($null -eq $state.Users) { throw 'AD user data was not returned.' } + $found = @($state.Users | Where-Object { + if (-not (Test-MtAdUserOrdinaryIdentity $_)) { return $false } + $dn = [string]$_.DistinguishedName + if ([string]::IsNullOrWhiteSpace($dn)) { throw "Distinguished name missing for $($_.SamAccountName)." } + # A comma escaped with backslash is part of an RDN, not a DN separator. + $parts = [regex]::Split($dn, '(? Date: Sun, 8 Nov 2026 18:47:12 +0000 Subject: [PATCH 030/100] fix(ad): consolidate approved user path assessment --- tests/ad/user/Test.AD-USER-16.md | 27 ++------- tests/ad/user/Test.AD-USER-16.ps1 | 93 ++++++------------------------- tests/ad/user/Test.AD-USER-17.md | 27 --------- tests/ad/user/Test.AD-USER-17.ps1 | 80 -------------------------- tests/ad/user/Test.AD-USER-18.md | 27 --------- tests/ad/user/Test.AD-USER-18.ps1 | 80 -------------------------- 6 files changed, 22 insertions(+), 312 deletions(-) delete mode 100644 tests/ad/user/Test.AD-USER-17.md delete mode 100644 tests/ad/user/Test.AD-USER-17.ps1 delete mode 100644 tests/ad/user/Test.AD-USER-18.md delete mode 100644 tests/ad/user/Test.AD-USER-18.ps1 diff --git a/tests/ad/user/Test.AD-USER-16.md b/tests/ad/user/Test.AD-USER-16.md index 68d72e1246..ae1888488e 100644 --- a/tests/ad/user/Test.AD-USER-16.md +++ b/tests/ad/user/Test.AD-USER-16.md @@ -1,27 +1,8 @@ -The `HomeDirectory` attribute points users to network-based storage locations. While useful in legacy environments, it can reveal older provisioning patterns and dependencies on file servers. +HomeDirectory, ProfilePath and absolute ScriptPath entries are checked against `ApprovedPathPrefixes` (empty by default, so all populated absolute paths are unapproved). Prefix matching is case-insensitive and respects path-component boundaries. Parent traversal is rejected; relative NETLOGON scripts require review, not automatic failure. This check **does not inspect file or share ACLs**. -- **Legacy infrastructure visibility**: Identifies users tied to mapped-drive style home folders -- **Access control review**: Highlights centralized storage paths that may contain sensitive data -- **Modernization planning**: Helps quantify remaining on-premises file service dependencies - -#### Control Type - -**Detective** - -#### Security Recommendation - -- Review home directory locations for proper ACLs and ownership controls -- Confirm the attribute is still required for active users -- Retire obsolete mappings and legacy storage dependencies where feasible - -#### How the Test Works - -This test counts user objects where the `HomeDirectory` attribute contains a non-empty value. - -#### Related Tests - -- `Test-MtAdUserProfilePathCount` - Finds roaming profile dependencies -- `Test-MtAdUserScriptPathCount` - Identifies legacy logon automation +#### Remediation action +1. Verify affected home, profile and logon-script roots with their owners in [AD administration](https://learn.microsoft.com/windows-server/identity/ad-ds/get-started/adac/active-directory-administrative-center). +2. Correct untrusted paths and approve only reviewed roots using `ApprovedPathPrefixes`. Inspect ACLs separately. %TestResult% diff --git a/tests/ad/user/Test.AD-USER-16.ps1 b/tests/ad/user/Test.AD-USER-16.ps1 index eebdbefe15..7c14c9cba6 100644 --- a/tests/ad/user/Test.AD-USER-16.ps1 +++ b/tests/ad/user/Test.AD-USER-16.ps1 @@ -1,80 +1,23 @@ function Test-MtAdUserHomeDirectoryCount { - <# - .SYNOPSIS - Counts users with a home directory configured in Active Directory. - - .DESCRIPTION - This test identifies user objects where the HomeDirectory attribute is populated. - Home directories can indicate legacy file storage models, mapped drive usage, or - sensitive data locations tied directly to account provisioning. Knowing how many - accounts use this attribute helps assess operational dependencies and cleanup needs. - - .EXAMPLE - Test-MtAdUserHomeDirectoryCount - - Returns $true if user data is accessible, $false otherwise. - The test result includes the count of users with a home directory configured. - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserHomeDirectoryCount + <# .SYNOPSIS + Checks user home, profile and logon-script paths against approved roots. #> - [MaesterTest( - Id = 'AD-USER-16', - Title = 'User home directory count should be retrievable', - Product = 'ad', - Feature = 'users', - Area = 'infrastructure', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] + [MaesterTest(Id = 'AD-USER-16', Title = 'User home, profile and script paths should be approved', Product = 'ad', Feature = 'users', Area = 'access-control', ResourceType = 'User', Severity = 'Low', UserImpact = 'Low', ImplementationCost = 'Medium', Mitre = 'T1037.003', Service = 'ActiveDirectory', Permission = 'ActiveDirectory:Ldap:user:ReadProperty', Author = 'soulemike')] [CmdletBinding()] [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserHomeDirectoryCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user home directory count" - - $users = $adState.Users - $usersWithHomeDirectory = $users | Where-Object { - -not [string]::IsNullOrWhiteSpace($_.HomeDirectory) - } - - $homeDirectoryCount = ($usersWithHomeDirectory | Measure-Object).Count - $totalCount = ($users | Measure-Object).Count - $testResult = $totalCount -gt 0 - - if ($testResult) { - $percentage = if ($totalCount -gt 0) { - [Math]::Round(($homeDirectoryCount / $totalCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users | $totalCount |" + "`n" - $result += "| Users with Home Directory | $homeDirectoryCount |" + "`n" - $result += "| Home Directory Percentage | $percentage% |" + "`n" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory users have been analyzed. $homeDirectoryCount out of $totalCount users ($percentage%) have the HomeDirectory attribute populated.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory users. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdUserHomeDirectoryCount" - - return $testResult + param( + # Case-insensitive approved UNC or absolute path roots; empty means no absolute paths approved. + [string[]] $ApprovedPathPrefixes = @() + ) + + $state = Get-MtADDomainState -Categories @('Users') + if ($null -eq $state.Users) { throw 'AD user data was not returned.' } + $found = @(Get-MtAdUserPathFindings -Users @($state.Users) -ApprovedPathPrefixes $ApprovedPathPrefixes) + $failed = @($found | Where-Object { $_.Finding -ne 'Relative NETLOGON script: review (not failed)' }) + $review = @($found | Where-Object { $_.Finding -eq 'Relative NETLOGON script: review (not failed)' }) + $table = Format-MtAdUserSecurityTable $found @('SamAccountName', 'Field', 'Path', 'Finding') + if ($failed.Count) { Add-MtTestResultDetail -Result "Found $($failed.Count) unapproved or traversal paths; $($review.Count) relative NETLOGON scripts require review. Approve trusted roots or correct affected account paths. Path approval does not verify share or file ACLs.`n`n$table" } + elseif ($review.Count) { Add-MtTestResultDetail -Result "Relative NETLOGON scripts for $($review.Count) users need a manual review; no unapproved absolute paths were found. ACL security has not been assessed.`n`n$table" -Investigate } + else { Add-MtTestResultDetail -Result 'Well done. No unapproved home, profile or absolute logon-script paths were found. File and share ACLs are not assessed.' } + return ($failed.Count -eq 0) } diff --git a/tests/ad/user/Test.AD-USER-17.md b/tests/ad/user/Test.AD-USER-17.md deleted file mode 100644 index 40e5837ebf..0000000000 --- a/tests/ad/user/Test.AD-USER-17.md +++ /dev/null @@ -1,27 +0,0 @@ -The `ProfilePath` attribute is commonly associated with roaming profiles and centralized workstation state. It often points to legacy file server infrastructure that should be reviewed for resilience and access control. - -- **Legacy profile management**: Identifies users depending on roaming profiles -- **Data exposure review**: Highlights centralized storage paths that may require tighter controls -- **Operational dependency mapping**: Helps quantify reliance on older desktop management models - -#### Control Type - -**Detective** - -#### Security Recommendation - -- Review profile share permissions and access paths -- Confirm roaming profiles are still necessary for affected users -- Consider modern endpoint and profile management approaches where appropriate - -#### How the Test Works - -This test counts user objects where the `ProfilePath` attribute contains a non-empty value. - -#### Related Tests - -- `Test-MtAdUserHomeDirectoryCount` - Highlights related file share dependencies -- `Test-MtAdUserScriptPathCount` - Finds additional legacy sign-in configuration - - -%TestResult% diff --git a/tests/ad/user/Test.AD-USER-17.ps1 b/tests/ad/user/Test.AD-USER-17.ps1 deleted file mode 100644 index f2e4939259..0000000000 --- a/tests/ad/user/Test.AD-USER-17.ps1 +++ /dev/null @@ -1,80 +0,0 @@ -function Test-MtAdUserProfilePathCount { - <# - .SYNOPSIS - Counts users with a profile path configured in Active Directory. - - .DESCRIPTION - This test identifies user objects where the ProfilePath attribute is populated. - Roaming profile paths often reveal legacy workstation management approaches and - file server dependencies. These paths can also expose centralized storage locations - that should be reviewed for access control and modernization opportunities. - - .EXAMPLE - Test-MtAdUserProfilePathCount - - Returns $true if user data is accessible, $false otherwise. - The test result includes the count of users with a profile path configured. - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserProfilePathCount - #> - [MaesterTest( - Id = 'AD-USER-17', - Title = 'User profile path count should be retrievable', - Product = 'ad', - Feature = 'users', - Area = 'infrastructure', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserProfilePathCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user profile path count" - - $users = $adState.Users - $usersWithProfilePath = $users | Where-Object { - -not [string]::IsNullOrWhiteSpace($_.ProfilePath) - } - - $profilePathCount = ($usersWithProfilePath | Measure-Object).Count - $totalCount = ($users | Measure-Object).Count - $testResult = $totalCount -gt 0 - - if ($testResult) { - $percentage = if ($totalCount -gt 0) { - [Math]::Round(($profilePathCount / $totalCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users | $totalCount |" + "`n" - $result += "| Users with Profile Path | $profilePathCount |" + "`n" - $result += "| Profile Path Percentage | $percentage% |" + "`n" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory users have been analyzed. $profilePathCount out of $totalCount users ($percentage%) have the ProfilePath attribute populated.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory users. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdUserProfilePathCount" - - return $testResult -} diff --git a/tests/ad/user/Test.AD-USER-18.md b/tests/ad/user/Test.AD-USER-18.md deleted file mode 100644 index 27d0323e4b..0000000000 --- a/tests/ad/user/Test.AD-USER-18.md +++ /dev/null @@ -1,27 +0,0 @@ -The `ScriptPath` attribute can launch scripts automatically during user sign-in. These scripts may map drives, alter environment settings, or execute legacy administrative logic. - -- **Execution surface**: Logon scripts can introduce code execution paths during authentication -- **Legacy dependency detection**: Helps identify environments still relying on older sign-in automation -- **Review priority**: Highlights scripts and shares that may need access hardening or modernization - -#### Control Type - -**Detective** - -#### Security Recommendation - -- Review every configured logon script for business need and secure coding practices -- Protect the storage locations that host scripts from unauthorized modification -- Retire unnecessary scripts and move critical logic to managed modern tooling where possible - -#### How the Test Works - -This test counts user objects where the `ScriptPath` attribute contains a non-empty value. - -#### Related Tests - -- `Test-MtAdUserHomeDirectoryCount` - Identifies related legacy provisioning settings -- `Test-MtAdUserProfilePathCount` - Finds users with additional sign-in infrastructure dependencies - - -%TestResult% diff --git a/tests/ad/user/Test.AD-USER-18.ps1 b/tests/ad/user/Test.AD-USER-18.ps1 deleted file mode 100644 index a72317bc1d..0000000000 --- a/tests/ad/user/Test.AD-USER-18.ps1 +++ /dev/null @@ -1,80 +0,0 @@ -function Test-MtAdUserScriptPathCount { - <# - .SYNOPSIS - Counts users with a logon script configured in Active Directory. - - .DESCRIPTION - This test identifies user objects where the ScriptPath attribute is populated. - Logon scripts can execute automatically during sign-in and may point to legacy - operational logic, network shares, or privileged automation. Tracking these - accounts helps identify script-based dependencies and potential attack surface. - - .EXAMPLE - Test-MtAdUserScriptPathCount - - Returns $true if user data is accessible, $false otherwise. - The test result includes the count of users with a logon script configured. - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserScriptPathCount - #> - [MaesterTest( - Id = 'AD-USER-18', - Title = 'User script path count should be retrievable', - Product = 'ad', - Feature = 'users', - Area = 'infrastructure', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'T1037.003', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserScriptPathCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user script path count" - - $users = $adState.Users - $usersWithScriptPath = $users | Where-Object { - -not [string]::IsNullOrWhiteSpace($_.ScriptPath) - } - - $scriptPathCount = ($usersWithScriptPath | Measure-Object).Count - $totalCount = ($users | Measure-Object).Count - $testResult = $totalCount -gt 0 - - if ($testResult) { - $percentage = if ($totalCount -gt 0) { - [Math]::Round(($scriptPathCount / $totalCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users | $totalCount |" + "`n" - $result += "| Users with Script Path | $scriptPathCount |" + "`n" - $result += "| Script Path Percentage | $percentage% |" + "`n" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory users have been analyzed. $scriptPathCount out of $totalCount users ($percentage%) have the ScriptPath attribute populated.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory users. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdUserScriptPathCount" - - return $testResult -} From a1db65f847ca1f1fff609d780fa8f29a46edfa67 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 18:47:12 +0000 Subject: [PATCH 031/100] fix(ad): consolidate account pattern inventories --- tests/ad/user/Test.AD-USER-20.md | 27 +------ tests/ad/user/Test.AD-USER-20.ps1 | 100 +++++------------------- tests/ad/user/Test.AD-USER-21.md | 29 ------- tests/ad/user/Test.AD-USER-21.ps1 | 123 ------------------------------ tests/ad/user/Test.AD-USER-26.md | 27 +------ tests/ad/user/Test.AD-USER-26.ps1 | 103 ++++--------------------- tests/ad/user/Test.AD-USER-27.md | 27 ------- tests/ad/user/Test.AD-USER-27.ps1 | 114 --------------------------- 8 files changed, 40 insertions(+), 510 deletions(-) delete mode 100644 tests/ad/user/Test.AD-USER-21.md delete mode 100644 tests/ad/user/Test.AD-USER-21.ps1 delete mode 100644 tests/ad/user/Test.AD-USER-27.md delete mode 100644 tests/ad/user/Test.AD-USER-27.ps1 diff --git a/tests/ad/user/Test.AD-USER-20.md b/tests/ad/user/Test.AD-USER-20.md index 17f7bc5386..56429a8f66 100644 --- a/tests/ad/user/Test.AD-USER-20.md +++ b/tests/ad/user/Test.AD-USER-20.md @@ -1,27 +1,8 @@ -Many environments use recognizable naming conventions for service accounts such as `svc_`, `service_`, or `_svc`. These patterns make service accounts easier to inventory and harden. +User names matching configurable `RegexPatterns` are an investigation inventory of possible service accounts, not evidence of their actual purpose. One consistent pattern set drives both count and details; malformed expressions produce errors. Service identities with SPNs are also covered by AD-SPN-06; AD-USER-14 was retired into that cross-feature check. -- **Service account inventory**: Helps locate likely service identities quickly -- **Hardening prioritization**: Supports focused review of passwords, SPNs, and delegation -- **Monitoring alignment**: Makes it easier to target logon, privilege, and usage monitoring - -#### Control Type - -**Detective** - -#### Security Recommendation - -- Review accounts matching known service account naming patterns for proper ownership and documentation -- Apply stronger controls to service accounts, including long random passwords and interactive logon restrictions -- Prefer managed service account options where the workload supports them - -#### How the Test Works - -This test counts user objects whose `SamAccountName` or `Name` matches common service account naming patterns such as `svc_`, `service_`, `_svc`, `sa_`, and similar variants. - -#### Related Tests - -- `AD-SPN-06` - Identifies service accounts through SPN usage -- `Test-MtAdUserAdminCountCount` - Highlights service accounts that may also be protected or privileged +#### Remediation action +1. Confirm ownership, permissions and purpose of matches using [AD administration](https://learn.microsoft.com/windows-server/identity/ad-ds/get-started/adac/active-directory-administrative-center). +2. Prefer managed service identities where feasible. %TestResult% diff --git a/tests/ad/user/Test.AD-USER-20.ps1 b/tests/ad/user/Test.AD-USER-20.ps1 index 71173b0144..f56661c820 100644 --- a/tests/ad/user/Test.AD-USER-20.ps1 +++ b/tests/ad/user/Test.AD-USER-20.ps1 @@ -1,87 +1,23 @@ function Test-MtAdUserKnownServiceAccountCount { - <# - .SYNOPSIS - Counts users that match known service account naming patterns. - - .DESCRIPTION - This test identifies user objects whose SamAccountName or Name matches common - service account naming conventions such as svc_, service_, _svc, sa_, or similar - patterns. Consistent naming helps operations, but it also makes it easier to locate - accounts that should receive stronger password, delegation, and monitoring controls. - - .EXAMPLE - Test-MtAdUserKnownServiceAccountCount - - Returns $true if user data is accessible, $false otherwise. - The test result includes the count of users matching known service account patterns. - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserKnownServiceAccountCount + <# .SYNOPSIS + Inventories user names matching configurable service account naming patterns. #> - [MaesterTest( - Id = 'AD-USER-20', - Title = 'Known service account count should be retrievable', - Product = 'ad', - Feature = 'users', - Area = 'applications', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] + [MaesterTest(Id = 'AD-USER-20', Title = 'Service-like user names should be reviewed', Product = 'ad', Feature = 'users', Area = 'applications', ResourceType = 'User', Severity = 'Info', Mitre = 'None', Service = 'ActiveDirectory', Permission = 'ActiveDirectory:Ldap:user:ReadProperty', Author = 'soulemike')] [CmdletBinding()] [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserKnownServiceAccountCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user known service account count" - - $users = $adState.Users - $serviceAccountPattern = '(?i)(^svc[_-]|^service[_-]|[_-]svc$|[_-]service$|^sa[_-]|[_-]sa$|^sqlsvc[_-]?|^appsvc[_-]?)' - $knownServiceAccounts = $users | Where-Object { - $identifiers = @($_.SamAccountName, $_.Name) | Where-Object { - -not [string]::IsNullOrWhiteSpace($_) - } - - ($identifiers | Where-Object { - $_ -match $serviceAccountPattern - } | Measure-Object).Count -gt 0 - } - - $serviceAccountCount = ($knownServiceAccounts | Measure-Object).Count - $totalCount = ($users | Measure-Object).Count - $testResult = $totalCount -gt 0 - - if ($testResult) { - $percentage = if ($totalCount -gt 0) { - [Math]::Round(($serviceAccountCount / $totalCount) * 100, 2) - } else { - 0 - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users | $totalCount |" + "`n" - $result += "| Users Matching Known Service Account Patterns | $serviceAccountCount |" + "`n" - $result += "| Service Account Pattern Percentage | $percentage% |" + "`n" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory users have been analyzed. $serviceAccountCount out of $totalCount users ($percentage%) match common service account naming patterns.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory users. Ensure you have appropriate permissions and the Active Directory module is installed." - } - - Add-MtTestResultDetail -Result $testResultMarkdown - Write-Verbose "Completed Test-MtAdUserKnownServiceAccountCount" - - return $testResult + param( + # Case-insensitive regular expressions used for both inventory count and details. + [string[]] $RegexPatterns = @('^(svc|service|sa|app|web|api|batch|job|task|sql|db)[-_.]', '[-_.](svc|service|sa)$') + ) + + $compiled = foreach ($pattern in $RegexPatterns) { [regex]::new($pattern, [Text.RegularExpressions.RegexOptions]::IgnoreCase) } + $state = Get-MtADDomainState -Categories @('Users') + if ($null -eq $state.Users) { throw 'AD user data was not returned.' } + $found = @($state.Users | Where-Object { + $name = [string]$_.SamAccountName + $display = [string]$_.Name + @($compiled | Where-Object { $_.IsMatch($name) -or $_.IsMatch($display) }).Count -gt 0 + }) + Add-MtTestResultDetail -Result "Review $($found.Count) users matching the configured naming expressions. Names are not proof of service-account purpose, ownership or permissions.`n`n$(Format-MtAdUserSecurityTable $found @('SamAccountName', 'Name', 'Enabled', 'PasswordNeverExpires', 'DistinguishedName'))" -Investigate + return $true } diff --git a/tests/ad/user/Test.AD-USER-21.md b/tests/ad/user/Test.AD-USER-21.md deleted file mode 100644 index 431d2b36fd..0000000000 --- a/tests/ad/user/Test.AD-USER-21.md +++ /dev/null @@ -1,29 +0,0 @@ -Service accounts often run business-critical workloads and commonly receive exceptions such as long-lived credentials, SPNs, or privileged access. Naming-pattern reviews help defenders quickly identify accounts that deserve deeper validation. - -- **Exposure reduction**: Find accounts likely used by services before attackers do. -- **Privilege review**: Verify service accounts are not over-privileged. -- **Credential hygiene**: Check for non-expiring passwords and stale patterns. -- **Inventory accuracy**: Confirm naming standards are applied consistently. - -#### Control Type - -**Operational** - -#### Security Recommendation - -- Maintain a defined naming standard for service accounts. -- Review matched accounts for owner, purpose, and required privileges. -- Prefer gMSAs where possible instead of traditional user-based service accounts. -- Investigate service-like names that lack documentation. - -#### How the Test Works - -This test reviews AD user objects and flags accounts whose `SamAccountName` or `Name` matches common service-account conventions such as `svc-`, `service-`, `app-`, `sql-`, or `admin-svc`. - -#### Related Tests - -- `Test-MtAdUserDelegationConfiguredCount` -- `Test-MtAdUserDelegationDetails` - - -%TestResult% diff --git a/tests/ad/user/Test.AD-USER-21.ps1 b/tests/ad/user/Test.AD-USER-21.ps1 deleted file mode 100644 index 9676bf1d75..0000000000 --- a/tests/ad/user/Test.AD-USER-21.ps1 +++ /dev/null @@ -1,123 +0,0 @@ -function Test-MtAdUserKnownServiceAccountDetails { - <# - .SYNOPSIS - Returns details for users matching known service account naming patterns. - - .DESCRIPTION - This test identifies user accounts that look like service accounts based on - commonly used naming conventions. Service accounts often receive elevated - permissions, non-expiring passwords, or SPNs, so maintaining visibility into - them is important for Active Directory hygiene and security reviews. - - .EXAMPLE - Test-MtAdUserKnownServiceAccountDetails - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserKnownServiceAccountDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-USER-21', - Title = 'Known service account details should be investigated', - Product = 'ad', - Feature = 'users', - Area = 'applications', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserKnownServiceAccountDetails" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user known service account details" - - $users = $adState.Users - - $serviceAccountPatterns = @( - @{ Name = 'svc-prefix'; Regex = '^(svc|service)[-_.]' }, - @{ Name = 'svc-suffix'; Regex = '[-_.](svc|service)$' }, - @{ Name = 'application-prefix'; Regex = '^(app|web|api|batch|job|task)[-_.]' }, - @{ Name = 'sql-prefix'; Regex = '^(sql|db)[-_.]' }, - @{ Name = 'admin-service'; Regex = '^(adm|admin)[-_.](svc|service)' }, - @{ Name = 'sa-prefix'; Regex = '^sa[-_.]' } - ) - - $serviceAccounts = foreach ($user in $users) { - $candidateValues = @($user.SamAccountName, $user.Name) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } - $matchedPattern = $null - - foreach ($pattern in $serviceAccountPatterns) { - if ($candidateValues | Where-Object { $_ -match $pattern.Regex }) { - $matchedPattern = $pattern.Name - break - } - } - - if ($null -ne $matchedPattern) { - [PSCustomObject]@{ - SamAccountName = $user.SamAccountName - Name = $user.Name - Enabled = $user.Enabled - PatternMatched = $matchedPattern - PasswordNeverExpires = $user.PasswordNeverExpires - HasSpn = @($user.ServicePrincipalName).Count -gt 0 - DistinguishedName = $user.DistinguishedName - } - } - } - - $serviceAccounts = @($serviceAccounts | Sort-Object SamAccountName -Unique) - $serviceAccountCount = ($serviceAccounts | Measure-Object).Count - $enabledCount = (@($serviceAccounts | Where-Object { $_.Enabled -eq $true }) | Measure-Object).Count - $passwordNeverExpiresCount = (@($serviceAccounts | Where-Object { $_.PasswordNeverExpires -eq $true }) | Measure-Object).Count - $hasSpnCount = (@($serviceAccounts | Where-Object { $_.HasSpn -eq $true }) | Measure-Object).Count - - $testResult = $true - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users Reviewed | $((@($users) | Measure-Object).Count) |" + "`n" - $result += "| Matching Service Account Patterns | $serviceAccountCount |" + "`n" - $result += "| Enabled Matches | $enabledCount |" + "`n" - $result += "| Password Never Expires | $passwordNeverExpiresCount |" + "`n" - $result += "| Matches with SPNs | $hasSpnCount |" + "`n" + "`n" - - if ($serviceAccountCount -gt 0) { - $result += "### Matching User Accounts" + "`n" + "`n" - $result += "| SamAccountName | Display Name | Enabled | Pattern | Password Never Expires | Has SPN |" + "`n" - $result += "| --- | --- | --- | --- | --- | --- |" + "`n" - foreach ($account in ($serviceAccounts | Select-Object -First 25)) { - $result += "| $($account.SamAccountName) | $($account.Name) | $($account.Enabled) | $($account.PatternMatched) | $($account.PasswordNeverExpires) | $($account.HasSpn) |" + "`n" - } - - if ($serviceAccountCount -gt 25) { - $result += "| ... | ... | ... | ... | ... | ... ($($serviceAccountCount - 25) more) |" + "`n" - } - } else { - $result += "No users matched the configured service account naming patterns." + "`n" - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory users were reviewed for known service account naming patterns.`n`n%TestResult%" - if ($serviceAccountCount -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", "" - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdUserKnownServiceAccountDetails" - - return $testResult -} diff --git a/tests/ad/user/Test.AD-USER-26.md b/tests/ad/user/Test.AD-USER-26.md index 892c00105f..f82cd90d11 100644 --- a/tests/ad/user/Test.AD-USER-26.md +++ b/tests/ad/user/Test.AD-USER-26.md @@ -1,27 +1,8 @@ -Accounts with names that look especially attractive to attackers can be useful as deliberate decoys, but they can also reflect risky naming practices or forgotten identities that warrant review. +Only account SIDs, distinguished names or sAMAccountNames explicitly supplied in `AccountIds` are treated as decoys. Without configured IDs this check is not applicable; unknown IDs error. Attractive words in a name are never proof of a decoy. -- **Threat detection support**: Decoy-style names can be monitored for malicious interaction. -- **Naming hygiene**: Identifies user names likely to draw attacker attention. -- **Access review**: Confirms whether these accounts are intentional and documented. - -#### Control Type - -**Operational** - -#### Security Recommendation - -- Document whether identified accounts are real users, service accounts, or deception assets. -- Apply strong monitoring to any deliberate honey pot or lure account. -- Disable or clean up misleading accounts that no longer serve a purpose. - -#### How the Test Works - -This test counts non-system user accounts whose names match attractive terms such as `admin`, `root`, `test`, `backup`, or `sql`. - -#### Related Tests - -- `Test-MtAdUserHoneyPotDetails` -- `Test-MtAdUserBuiltInAdminEnabledDetails` +#### Remediation action +1. Identify authorized decoy accounts and configure their IDs; review the accounts in [AD administration](https://learn.microsoft.com/windows-server/identity/ad-ds/get-started/adac/active-directory-administrative-center). +2. Confirm alert coverage for attempted authentication separately; this test does not test monitoring. %TestResult% diff --git a/tests/ad/user/Test.AD-USER-26.ps1 b/tests/ad/user/Test.AD-USER-26.ps1 index 5a0335684f..1e98e0f8b0 100644 --- a/tests/ad/user/Test.AD-USER-26.ps1 +++ b/tests/ad/user/Test.AD-USER-26.ps1 @@ -1,97 +1,22 @@ function Test-MtAdUserHoneyPotCount { - <# - .SYNOPSIS - Counts potential honey pot style user accounts. - - .DESCRIPTION - This test identifies user accounts with names that may be intentionally - attractive to attackers, such as accounts containing terms like admin, - root, test, backup, or sql. These names can indicate decoy accounts, - monitoring traps, or simply risky naming patterns that deserve review. - - .EXAMPLE - Test-MtAdUserHoneyPotCount - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserHoneyPotCount + <# .SYNOPSIS + Inventories explicitly configured decoy account IDs for review. #> - [MaesterTest( - Id = 'AD-USER-26', - Title = 'Honey pot user count should be investigated', - Product = 'ad', - Feature = 'users', - Area = 'logging-and-detection', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] + [MaesterTest(Id = 'AD-USER-26', Title = 'Configured decoy users should be reviewed', Product = 'ad', Feature = 'users', Area = 'logging-and-detection', ResourceType = 'User', Severity = 'Info', Mitre = 'None', Service = 'ActiveDirectory', Permission = 'ActiveDirectory:Ldap:user:ReadProperty', Author = 'soulemike')] [CmdletBinding()] [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserHoneyPotCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user honey pot count" - - $users = $adState.Users - - $honeyPotPatterns = @( - @{ Name = 'admin'; Regex = '(^|[-_.])(admin|administrator)([-_.]|$)' }, - @{ Name = 'root'; Regex = '(^|[-_.])root([-_.]|$)' }, - @{ Name = 'test'; Regex = '(^|[-_.])(test|temp)([-_.]|$)' }, - @{ Name = 'backup'; Regex = '(^|[-_.])backup([-_.]|$)' }, - @{ Name = 'sql'; Regex = '(^|[-_.])(sql|dba|oracle)([-_.]|$)' } + param( + # Explicit decoy SIDs, distinguished names or sAMAccountNames; names alone never imply decoys. + [string[]] $AccountIds = @() ) - $potentialHoneyPots = foreach ($user in $users) { - $sidValue = [string]$user.SID - if ($sidValue -match '-500$|-(501|502)$' -or $user.isCriticalSystemObject -eq $true) { - continue - } - - $candidateValues = @($user.SamAccountName, $user.Name) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } - $matchesFound = foreach ($pattern in $honeyPotPatterns) { - if ($candidateValues | Where-Object { $_ -match $pattern.Regex }) { - $pattern - } - } - if ($matchesFound.Count -gt 0) { - [PSCustomObject]@{ - SamAccountName = $user.SamAccountName - Name = $user.Name - Enabled = $user.Enabled - MatchCount = $matchesFound.Count - MatchTypes = ($matchesFound.Name -join ', ') - } - } + if (-not $AccountIds.Count) { Add-MtTestResultDetail -SkippedBecause NotApplicable; return $false } + $state = Get-MtADDomainState -Categories @('Users') + if ($null -eq $state.Users) { throw 'AD user data was not returned.' } + $found = @($state.Users | Where-Object { $AccountIds -contains $_.SamAccountName -or $AccountIds -contains $_.DistinguishedName -or $AccountIds -contains [string]$_.SID -or $AccountIds -contains [string]$_.SID.Value }) + foreach ($id in $AccountIds) { + if (-not @($found | Where-Object { $id -eq $_.SamAccountName -or $id -eq $_.DistinguishedName -or $id -eq [string]$_.SID -or $id -eq [string]$_.SID.Value }).Count) { throw "Configured decoy account not found: $id" } } - - $potentialHoneyPots = @($potentialHoneyPots | Sort-Object SamAccountName -Unique) - $totalCount = ($potentialHoneyPots | Measure-Object).Count - $enabledCount = (@($potentialHoneyPots | Where-Object { $_.Enabled -eq $true }) | Measure-Object).Count - - $testResult = $true - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users Reviewed | $((@($users) | Measure-Object).Count) |" + "`n" - $result += "| Potential Honey Pot Users | $totalCount |" + "`n" - $result += "| Enabled Potential Honey Pot Users | $enabledCount |" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory users were reviewed for potential honey pot naming patterns.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdUserHoneyPotCount" - - return $testResult + Add-MtTestResultDetail -Result "Review $($found.Count) explicitly configured decoy identities and confirm monitoring/ownership. Account names alone were not used as evidence.`n`n$(Format-MtAdUserSecurityTable $found @('SamAccountName', 'Enabled', 'LastLogonDate', 'DistinguishedName'))" -Investigate + return $true } diff --git a/tests/ad/user/Test.AD-USER-27.md b/tests/ad/user/Test.AD-USER-27.md deleted file mode 100644 index 13370b137f..0000000000 --- a/tests/ad/user/Test.AD-USER-27.md +++ /dev/null @@ -1,27 +0,0 @@ -Detailed visibility into potential honey pot style users helps separate intentional deception assets from legacy, misleading, or risky accounts. - -- **Deception validation**: Confirm lure accounts are intentional and monitored. -- **Operational clarity**: Distinguish test or stale accounts from active users. -- **Risk reduction**: Remove attractive-but-unnecessary account names. - -#### Control Type - -**Operational** - -#### Security Recommendation - -- Track owner and purpose for each identified account. -- Alert on any authentication attempts to intentional lure accounts. -- Disable or rename unnecessary accounts that imitate privileged or attractive targets. - -#### How the Test Works - -This test returns non-system users whose names match attacker-attractive terms and includes usage-oriented details such as enabled state, last logon, and password expiry status. - -#### Related Tests - -- `Test-MtAdUserHoneyPotCount` -- `Test-MtAdUserKnownServiceAccountDetails` - - -%TestResult% diff --git a/tests/ad/user/Test.AD-USER-27.ps1 b/tests/ad/user/Test.AD-USER-27.ps1 deleted file mode 100644 index e36f40f3a7..0000000000 --- a/tests/ad/user/Test.AD-USER-27.ps1 +++ /dev/null @@ -1,114 +0,0 @@ -function Test-MtAdUserHoneyPotDetails { - <# - .SYNOPSIS - Returns details for potential honey pot style user accounts. - - .DESCRIPTION - This test lists non-system users whose names contain terms that may attract - attackers. The output helps teams validate whether those accounts are true - deception assets, old test users, or risky naming artifacts. - - .EXAMPLE - Test-MtAdUserHoneyPotDetails - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserHoneyPotDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-USER-27', - Title = 'Honey pot user details should be investigated', - Product = 'ad', - Feature = 'users', - Area = 'logging-and-detection', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserHoneyPotDetails" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user honey pot details" - - $users = $adState.Users - - $honeyPotPatterns = @( - @{ Name = 'admin'; Regex = '(^|[-_.])(admin|administrator)([-_.]|$)' }, - @{ Name = 'root'; Regex = '(^|[-_.])root([-_.]|$)' }, - @{ Name = 'test'; Regex = '(^|[-_.])(test|temp)([-_.]|$)' }, - @{ Name = 'backup'; Regex = '(^|[-_.])backup([-_.]|$)' }, - @{ Name = 'sql'; Regex = '(^|[-_.])(sql|dba|oracle)([-_.]|$)' } - ) - - $potentialHoneyPots = foreach ($user in $users) { - $sidValue = [string]$user.SID - if ($sidValue -match '-500$|-(501|502)$' -or $user.isCriticalSystemObject -eq $true) { - continue - } - - $candidateValues = @($user.SamAccountName, $user.Name) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } - $matchesFound = foreach ($pattern in $honeyPotPatterns) { - if ($candidateValues | Where-Object { $_ -match $pattern.Regex }) { - $pattern - } - } - if ($matchesFound.Count -gt 0) { - [PSCustomObject]@{ - SamAccountName = $user.SamAccountName - Name = $user.Name - Enabled = $user.Enabled - MatchTypes = ($matchesFound.Name -join ', ') - LastLogonDate = if ($null -ne $user.LastLogonDate) { Get-Date $user.LastLogonDate -Format 'yyyy-MM-dd HH:mm:ss' } else { 'Never/Unknown' } - PasswordNeverExpires = $user.PasswordNeverExpires - DistinguishedName = $user.DistinguishedName - } - } - } - - $potentialHoneyPots = @($potentialHoneyPots | Sort-Object SamAccountName -Unique) - - $testResult = $true - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Potential Honey Pot Users | $(($potentialHoneyPots | Measure-Object).Count) |" + "`n" + "`n" - - if ($potentialHoneyPots.Count -gt 0) { - $result += "### Potential Honey Pot User Details" + "`n" + "`n" - $result += "| SamAccountName | Display Name | Enabled | Match Types | Last Logon | Password Never Expires |" + "`n" - $result += "| --- | --- | --- | --- | --- | --- |" + "`n" - foreach ($user in ($potentialHoneyPots | Select-Object -First 25)) { - $result += "| $($user.SamAccountName) | $($user.Name) | $($user.Enabled) | $($user.MatchTypes) | $($user.LastLogonDate) | $($user.PasswordNeverExpires) |" + "`n" - } - - if ($potentialHoneyPots.Count -gt 25) { - $result += "| ... | ... | ... | ... | ... | ... ($($potentialHoneyPots.Count - 25) more) |" + "`n" - } - } else { - $result += "No potential honey pot users were identified using the configured naming rules." + "`n" - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "Potential honey pot style Active Directory users were reviewed in detail.`n`n%TestResult%" - if ($potentialHoneyPots.Count -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", "" - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdUserHoneyPotDetails" - - return $testResult -} From a7fd7a3d4fb6b1769d0b5e6fb4b1578b1f2cb50f Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 18:47:12 +0000 Subject: [PATCH 032/100] fix(ad): consolidate built-in administrator hygiene --- tests/ad/user/Test.AD-USER-22.md | 29 ++------ tests/ad/user/Test.AD-USER-22.ps1 | 107 +++++++++++------------------- tests/ad/user/Test.AD-USER-23.md | 27 -------- tests/ad/user/Test.AD-USER-23.ps1 | 81 ---------------------- tests/ad/user/Test.AD-USER-24.md | 27 -------- tests/ad/user/Test.AD-USER-24.ps1 | 79 ---------------------- tests/ad/user/Test.AD-USER-25.md | 27 -------- tests/ad/user/Test.AD-USER-25.ps1 | 79 ---------------------- 8 files changed, 42 insertions(+), 414 deletions(-) delete mode 100644 tests/ad/user/Test.AD-USER-23.md delete mode 100644 tests/ad/user/Test.AD-USER-23.ps1 delete mode 100644 tests/ad/user/Test.AD-USER-24.md delete mode 100644 tests/ad/user/Test.AD-USER-24.ps1 delete mode 100644 tests/ad/user/Test.AD-USER-25.md delete mode 100644 tests/ad/user/Test.AD-USER-25.ps1 diff --git a/tests/ad/user/Test.AD-USER-22.md b/tests/ad/user/Test.AD-USER-22.md index cd76d80e86..2402d9afc1 100644 --- a/tests/ad/user/Test.AD-USER-22.md +++ b/tests/ad/user/Test.AD-USER-22.md @@ -1,29 +1,8 @@ -Built-in and critical administrator-related accounts are among the most sensitive identities in Active Directory. Attackers frequently target these accounts because they provide durable, high-impact access. +The domain SID plus RID 500 identifies the built-in administrator, regardless of renaming. This check evaluates its disabled state, recent recorded logon (configurable minimum 30 idle days) and password age (configurable maximum 180 days). Replicated logon timestamps can lag; the configurable `MaximumLogonTimestampLagDays` defaults to 14. Recorded idle ages from 30 through 43 days require investigation rather than a clean pass. This is not an exact all-domain-controller last-logon audit. Other critical system objects are **not** RID-500 accounts. -- **High-value targets**: RID 500 accounts are especially attractive to attackers. -- **Detection support**: Helps validate whether renamed administrator accounts still exist. -- **Tier-0 review**: Critical system objects warrant extra monitoring and protection. - -#### Control Type - -**Operational** - -#### Security Recommendation - -- Minimize use of built-in administrator accounts. -- Monitor all RID 500 activity closely. -- Apply strong credential protection and privileged access controls. -- Review critical system accounts for expected state and usage. - -#### How the Test Works - -This test counts user objects whose SID ends in `-500` or are marked as `isCriticalSystemObject`. - -#### Related Tests - -- `Test-MtAdUserBuiltInAdminEnabledDetails` -- `Test-MtAdUserBuiltInAdminLastLogonDetails` -- `Test-MtAdUserBuiltInAdminPasswordAgeDetails` +#### Remediation action +1. Validate emergency access before changing [the built-in administrator](https://learn.microsoft.com/windows-server/identity/ad-ds/manage/understand-security-identifiers). +2. Corroborate usage with DC logon events and rotate old credentials under break-glass procedures; restrict or disable unused access when appropriate. %TestResult% diff --git a/tests/ad/user/Test.AD-USER-22.ps1 b/tests/ad/user/Test.AD-USER-22.ps1 index bd6939b206..f944de2669 100644 --- a/tests/ad/user/Test.AD-USER-22.ps1 +++ b/tests/ad/user/Test.AD-USER-22.ps1 @@ -1,74 +1,43 @@ function Test-MtAdUserBuiltInAdminCount { - <# - .SYNOPSIS - Counts built-in administrator style user accounts. - - .DESCRIPTION - This test identifies built-in administrator style user objects by looking for - the built-in administrator RID (`-500`) and critical system objects. Tracking - these accounts helps defenders focus on highly sensitive identities that are - commonly targeted during Active Directory compromise. - - .EXAMPLE - Test-MtAdUserBuiltInAdminCount - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserBuiltInAdminCount + <# .SYNOPSIS + Checks that the domain RID-500 administrator is present and not stale. #> - [MaesterTest( - Id = 'AD-USER-22', - Title = 'Built-in administrator account count should be investigated', - Product = 'ad', - Feature = 'users', - Area = 'privileged-access', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'T1078.001', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] + [MaesterTest(Id = 'AD-USER-22', Title = 'The built-in domain administrator should not have stale access or credentials', Product = 'ad', Feature = 'users', Area = 'privileged-access', ResourceType = 'User', Severity = 'Medium', UserImpact = 'Low', ImplementationCost = 'Medium', Mitre = 'T1078.002', Control = 'nist-800-53-r5:AC-2(3)', Service = 'ActiveDirectory', Permission = ('ActiveDirectory:Ldap:user:ReadProperty', 'ActiveDirectory:Ldap:domainDNS.objectSid:ReadProperty'), Author = 'soulemike')] [CmdletBinding()] [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserBuiltInAdminCount" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user built in admin count" - - $users = $adState.Users - - $builtInAdminUsers = @($users | Where-Object { - $sidValue = [string]$_.SID - $sidValue -match '-500$' -or $_.isCriticalSystemObject -eq $true - }) - - $totalCount = ($builtInAdminUsers | Measure-Object).Count - $enabledCount = (@($builtInAdminUsers | Where-Object { $_.Enabled -eq $true }) | Measure-Object).Count - $criticalCount = (@($builtInAdminUsers | Where-Object { $_.isCriticalSystemObject -eq $true }) | Measure-Object).Count - $rid500Count = (@($builtInAdminUsers | Where-Object { ([string]$_.SID) -match '-500$' }) | Measure-Object).Count - - $testResult = $true - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Users Reviewed | $((@($users) | Measure-Object).Count) |" + "`n" - $result += "| Built-In Administrator Style Accounts | $totalCount |" + "`n" - $result += "| Enabled Built-In Administrator Style Accounts | $enabledCount |" + "`n" - $result += "| RID 500 Accounts | $rid500Count |" + "`n" - $result += "| Critical System Objects | $criticalCount |" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory built-in administrator style accounts were counted.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdUserBuiltInAdminCount" - - return $testResult + param( + # Minimum days since the last recorded logon before enabled RID-500 usage needs review. + [ValidateRange(15, 3650)] + [int] $MinimumIdleDays = 30, + # Maximum age in days of the built-in administrator password. + [ValidateRange(1, 3650)] + [int] $MaximumPasswordAgeDays = 180, + # Conservative upper bound in days for replicated lastLogonTimestamp delay. + [ValidateRange(1, 30)] + [int] $MaximumLogonTimestampLagDays = 14 + ) + + $state = Get-MtADDomainState -Categories @('Domain', 'Users') + if ($null -eq $state.Users) { throw 'AD user data was not returned.' } + $domainSid = if ($state.Domain.DomainSID -is [string]) { $state.Domain.DomainSID } else { [string]$state.Domain.DomainSID.Value } + if ($domainSid -notmatch '^S-1-5-21-(\d+-){2}\d+$') { throw 'Domain SID is unavailable; cannot identify the RID-500 account.' } + $admin = @($state.Users | Where-Object { ([string]$_.SID -eq "$domainSid-500") -or ([string]$_.SID.Value -eq "$domainSid-500") }) + if ($admin.Count -ne 1) { throw "Expected one domain RID-500 administrator, found $($admin.Count)." } + $account = $admin[0] + if ($null -eq $account.Enabled) { throw 'RID-500 enabled state is unavailable; recent-use scope cannot be established.' } + if ($null -eq $account.PasswordLastSet) { throw 'RID-500 password last-set data is unavailable.' } + $passwordAge = [int]((Get-Date) - [datetime]$account.PasswordLastSet).TotalDays + $lastLogon = if ($null -eq $account.LastLogonDate) { 'Unknown' } else { [string]$account.LastLogonDate } + $idle = if ($null -eq $account.LastLogonDate) { 'Unknown' } else { [int]((Get-Date) - [datetime]$account.LastLogonDate).TotalDays } + $syncInterval = if ($null -eq $state.Domain.LogonTimeSyncIntervalDays) { 14 } else { [int]$state.Domain.LogonTimeSyncIntervalDays } + if ($syncInterval -lt 0) { throw 'Domain logon-time synchronization interval is invalid.' } + $effectiveLagDays = [math]::Max($MaximumLogonTimestampLagDays, $syncInterval) + # Respect a configured domain interval larger than the parameter's conservative default. + $ambiguous = $account.Enabled -eq $true -and ($idle -eq 'Unknown' -or ($idle -is [int] -and $idle -ge $MinimumIdleDays -and $idle -lt ($MinimumIdleDays + $effectiveLagDays))) + $failed = $passwordAge -gt $MaximumPasswordAgeDays -or ($account.Enabled -eq $true -and $idle -is [int] -and $idle -lt $MinimumIdleDays) + $detail = "RID-500: $($account.SamAccountName); enabled: $($account.Enabled); last replicated logon: $lastLogon; days since logon: $idle; password age: $passwordAge days; password never expires: $($account.PasswordNeverExpires). Conservative replication lag allowance: $effectiveLagDays days (domain interval and parameter maximum); this is not an exact all-DC last-logon audit." + if ($failed) { Add-MtTestResultDetail -Result "Review recent RID-500 usage or rotate its old password after checking break-glass procedures. $detail" } + elseif ($ambiguous) { Add-MtTestResultDetail -Result "RID-500 usage is ambiguous near the idle threshold; corroborate with DC logon records. $detail" -Investigate } + else { Add-MtTestResultDetail -Result "Well done. No stale RID-500 password or confirmed recent enabled-account usage was found. $detail" } + return (-not $failed) } diff --git a/tests/ad/user/Test.AD-USER-23.md b/tests/ad/user/Test.AD-USER-23.md deleted file mode 100644 index d8e0e68844..0000000000 --- a/tests/ad/user/Test.AD-USER-23.md +++ /dev/null @@ -1,27 +0,0 @@ -Enabled built-in administrator style accounts provide immediate opportunities for misuse if their credentials are exposed. A simple inventory of active accounts in this category helps confirm whether emergency or legacy access remains enabled unnecessarily. - -- **Exposure review**: Enabled privileged accounts increase attack surface. -- **Account validation**: Confirms which sensitive accounts remain active. -- **Operational control**: Supports decisions to disable or tightly restrict use. - -#### Control Type - -**Operational** - -#### Security Recommendation - -- Disable built-in administrator accounts when not required. -- If they must remain enabled, restrict sign-in paths and monitor all usage. -- Ensure password rotation, MFA-equivalent controls, and break-glass procedures are documented. - -#### How the Test Works - -This test returns enabled user accounts that match the built-in administrator RID (`-500`) or are marked as critical system objects. - -#### Related Tests - -- `Test-MtAdUserBuiltInAdminCount` -- `Test-MtAdUserBuiltInAdminLastLogonDetails` - - -%TestResult% diff --git a/tests/ad/user/Test.AD-USER-23.ps1 b/tests/ad/user/Test.AD-USER-23.ps1 deleted file mode 100644 index 5985ce9ce7..0000000000 --- a/tests/ad/user/Test.AD-USER-23.ps1 +++ /dev/null @@ -1,81 +0,0 @@ -function Test-MtAdUserBuiltInAdminEnabledDetails { - <# - .SYNOPSIS - Returns enabled built-in administrator style user details. - - .DESCRIPTION - This test lists enabled built-in administrator style accounts based on the - RID 500 pattern and critical system object flag. These accounts deserve extra - scrutiny because they are commonly targeted and often retain elevated rights. - - .EXAMPLE - Test-MtAdUserBuiltInAdminEnabledDetails - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserBuiltInAdminEnabledDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-USER-23', - Title = 'Enabled built-in administrator details should be investigated', - Product = 'ad', - Feature = 'users', - Area = 'privileged-access', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'T1078.001', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserBuiltInAdminEnabledDetails" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user built in admin enabled details" - - $users = $adState.Users - - $enabledBuiltInAdmins = @($users | Where-Object { - $sidValue = [string]$_.SID - ($sidValue -match '-500$' -or $_.isCriticalSystemObject -eq $true) -and $_.Enabled -eq $true - } | Sort-Object SamAccountName) - - $testResult = $true - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Enabled Built-In Administrator Style Accounts | $(($enabledBuiltInAdmins | Measure-Object).Count) |" + "`n" + "`n" - - if ($enabledBuiltInAdmins.Count -gt 0) { - $result += "### Enabled Account Details" + "`n" + "`n" - $result += "| SamAccountName | Display Name | SID | AdminCount | Last Logon |" + "`n" - $result += "| --- | --- | --- | --- | --- |" + "`n" - foreach ($user in $enabledBuiltInAdmins) { - $lastLogon = if ($null -ne $user.LastLogonDate) { Get-Date $user.LastLogonDate -Format 'yyyy-MM-dd HH:mm:ss' } else { 'Never/Unknown' } - $result += "| $($user.SamAccountName) | $($user.Name) | $([string]$user.SID) | $($user.AdminCount) | $lastLogon |" + "`n" - } - } else { - $result += "No enabled built-in administrator style accounts were found." + "`n" - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "Enabled built-in administrator style Active Directory user details were retrieved.`n`n%TestResult%" - if ($enabledBuiltInAdmins.Count -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", "" - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdUserBuiltInAdminEnabledDetails" - - return $testResult -} diff --git a/tests/ad/user/Test.AD-USER-24.md b/tests/ad/user/Test.AD-USER-24.md deleted file mode 100644 index f528070184..0000000000 --- a/tests/ad/user/Test.AD-USER-24.md +++ /dev/null @@ -1,27 +0,0 @@ -Knowing when built-in administrator style accounts last authenticated is critical for detecting stale privileged access and spotting suspicious activity. - -- **Unexpected use detection**: Recent logons on sensitive accounts may warrant investigation. -- **Stale privilege cleanup**: Dormant privileged accounts should be reviewed or disabled. -- **Incident response**: Last logon data helps reconstruct privileged account activity. - -#### Control Type - -**Operational** - -#### Security Recommendation - -- Investigate interactive or unexpected usage of RID 500 accounts. -- Disable or tightly restrict privileged accounts with no valid business need. -- Correlate recent logons with change windows, tickets, and admin workflows. - -#### How the Test Works - -This test lists built-in administrator style accounts and returns their `LastLogonDate` plus the number of days since the recorded logon. - -#### Related Tests - -- `Test-MtAdUserBuiltInAdminEnabledDetails` -- `Test-MtAdUserBuiltInAdminPasswordAgeDetails` - - -%TestResult% diff --git a/tests/ad/user/Test.AD-USER-24.ps1 b/tests/ad/user/Test.AD-USER-24.ps1 deleted file mode 100644 index bb794a38db..0000000000 --- a/tests/ad/user/Test.AD-USER-24.ps1 +++ /dev/null @@ -1,79 +0,0 @@ -function Test-MtAdUserBuiltInAdminLastLogonDetails { - <# - .SYNOPSIS - Returns last logon details for built-in administrator style accounts. - - .DESCRIPTION - This test reports when built-in administrator style accounts last logged on. - Reviewing recent and historical activity for these accounts helps identify - stale privileged identities, unexpected usage, and potential incident leads. - - .EXAMPLE - Test-MtAdUserBuiltInAdminLastLogonDetails - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserBuiltInAdminLastLogonDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-USER-24', - Title = 'Built-in administrator last logon details should be investigated', - Product = 'ad', - Feature = 'users', - Area = 'privileged-access', - ResourceType = 'User', - Severity = 'Info', - Mitre = 'T1078.001', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserBuiltInAdminLastLogonDetails" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user built in admin last logon details" - - $users = $adState.Users - - $builtInAdminUsers = @($users | Where-Object { - $sidValue = [string]$_.SID - $sidValue -match '-500$' -or $_.isCriticalSystemObject -eq $true - } | Sort-Object SamAccountName) - - $testResult = $true - - $result = "### Built-In Administrator Last Logon Details" + "`n" + "`n" - $result += "| SamAccountName | Display Name | Enabled | Last Logon | Days Since Last Logon |" + "`n" - $result += "| --- | --- | --- | --- | --- |" + "`n" - - if ($builtInAdminUsers.Count -gt 0) { - foreach ($user in $builtInAdminUsers) { - $lastLogonText = if ($null -ne $user.LastLogonDate) { Get-Date $user.LastLogonDate -Format 'yyyy-MM-dd HH:mm:ss' } else { 'Never/Unknown' } - $daysSinceLogon = if ($null -ne $user.LastLogonDate) { [int](((Get-Date) - $user.LastLogonDate).TotalDays) } else { 'N/A' } - $result += "| $($user.SamAccountName) | $($user.Name) | $($user.Enabled) | $lastLogonText | $daysSinceLogon |" + "`n" - } - } else { - $result += "| No built-in administrator style accounts found | - | - | - | - |" + "`n" - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "Built-in administrator style account last logon data was retrieved from Active Directory.`n`n%TestResult%" - if ($builtInAdminUsers.Count -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", "" - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdUserBuiltInAdminLastLogonDetails" - - return $testResult -} diff --git a/tests/ad/user/Test.AD-USER-25.md b/tests/ad/user/Test.AD-USER-25.md deleted file mode 100644 index 1214b70ba8..0000000000 --- a/tests/ad/user/Test.AD-USER-25.md +++ /dev/null @@ -1,27 +0,0 @@ -Highly privileged accounts with old passwords are prime targets for password spraying, credential theft, and persistence. Reviewing password age for built-in administrator style accounts helps validate that sensitive credentials are rotated appropriately. - -- **Credential risk reduction**: Long-lived privileged passwords increase exposure. -- **Control validation**: Supports verification of password rotation practices. -- **Exception tracking**: Highlights accounts with non-expiring privileged credentials. - -#### Control Type - -**Operational** - -#### Security Recommendation - -- Rotate passwords for privileged accounts on a defined schedule. -- Avoid non-expiring passwords on privileged identities wherever possible. -- Review break-glass or emergency accounts separately with compensating controls. - -#### How the Test Works - -This test lists built-in administrator style accounts and reports `PasswordLastSet`, calculated password age in days, and `PasswordNeverExpires` state. - -#### Related Tests - -- `Test-MtAdUserBuiltInAdminCount` -- `Test-MtAdUserBuiltInAdminLastLogonDetails` - - -%TestResult% diff --git a/tests/ad/user/Test.AD-USER-25.ps1 b/tests/ad/user/Test.AD-USER-25.ps1 deleted file mode 100644 index 88a089ae06..0000000000 --- a/tests/ad/user/Test.AD-USER-25.ps1 +++ /dev/null @@ -1,79 +0,0 @@ -function Test-MtAdUserBuiltInAdminPasswordAgeDetails { - <# - .SYNOPSIS - Returns password age details for built-in administrator style accounts. - - .DESCRIPTION - This test reports when built-in administrator style accounts last changed - their passwords. Long-lived credentials on highly privileged accounts can - materially increase risk and should be reviewed regularly. - - .EXAMPLE - Test-MtAdUserBuiltInAdminPasswordAgeDetails - - .LINK - https://maester.dev/docs/commands/Test-MtAdUserBuiltInAdminPasswordAgeDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-USER-25', - Title = 'Built-in administrator password age details should be investigated', - Product = 'ad', - Feature = 'users', - Area = 'privileged-access', - ResourceType = 'User', - Severity = 'Info', - Mitre = ('T1078.001', 'T1110.003'), - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:user:ReadProperty'), - Author = 'soulemike' - )] - [CmdletBinding()] - [OutputType([bool])] - param() - - Write-Verbose "Starting Test-MtAdUserBuiltInAdminPasswordAgeDetails" - $adState = Get-MtADDomainState -Categories @('Users') - Write-Verbose "Retrieved AD state" - if ($null -eq $adState) { - Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "Not connected to Active Directory." - return $null - } - Write-Verbose "Filtering/counting user built in admin password age details" - - $users = $adState.Users - - $builtInAdminUsers = @($users | Where-Object { - $sidValue = [string]$_.SID - $sidValue -match '-500$' -or $_.isCriticalSystemObject -eq $true - } | Sort-Object SamAccountName) - - $testResult = $true - - $result = "### Built-In Administrator Password Age Details" + "`n" + "`n" - $result += "| SamAccountName | Display Name | Enabled | Password Last Set | Password Age (Days) | Password Never Expires |" + "`n" - $result += "| --- | --- | --- | --- | --- | --- |" + "`n" - - if ($builtInAdminUsers.Count -gt 0) { - foreach ($user in $builtInAdminUsers) { - $passwordLastSetText = if ($null -ne $user.PasswordLastSet) { Get-Date $user.PasswordLastSet -Format 'yyyy-MM-dd HH:mm:ss' } else { 'Never/Unknown' } - $passwordAgeDays = if ($null -ne $user.PasswordLastSet) { [int](((Get-Date) - $user.PasswordLastSet).TotalDays) } else { 'N/A' } - $result += "| $($user.SamAccountName) | $($user.Name) | $($user.Enabled) | $passwordLastSetText | $passwordAgeDays | $($user.PasswordNeverExpires) |" + "`n" - } - } else { - $result += "| No built-in administrator style accounts found | - | - | - | - | - |" + "`n" - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "Built-in administrator style account password age data was retrieved from Active Directory.`n`n%TestResult%" - if ($builtInAdminUsers.Count -gt 0) { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", "" - } - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdUserBuiltInAdminPasswordAgeDetails" - - return $testResult -} From bdfe743fe7512737214a3c00385083b2b90b365a Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sun, 8 Nov 2026 18:47:12 +0000 Subject: [PATCH 033/100] fix(ad): consolidate CA and template inventories --- ...nvertTo-MtAdConfigurationInventoryCell.ps1 | 8 ++ .../ad/ad/Get-MtAdCertificateInventory.ps1 | 51 +++++++++++ .../ad/ad/Get-MtAdConfigurationInventory.ps1 | 17 ++++ ...onfigurationInventorySiteLinkTransport.ps1 | 20 +++++ ...nvoke-MtAdConfigurationInventoryReport.ps1 | 89 +++++++++++++++++++ .../ADCertificateInventoryBatch.Tests.ps1 | 71 +++++++++++++++ tests/ad/config/Test.AD-CFG-12.md | 22 ++--- tests/ad/config/Test.AD-CFG-12.ps1 | 61 ++----------- tests/ad/config/Test.AD-CFG-13.md | 21 ++--- tests/ad/config/Test.AD-CFG-13.ps1 | 61 ++----------- tests/ad/config/Test.AD-CFG-14.md | 23 ----- tests/ad/config/Test.AD-CFG-14.ps1 | 66 -------------- 12 files changed, 282 insertions(+), 228 deletions(-) create mode 100644 powershell/internal/checks/ad/ad/ConvertTo-MtAdConfigurationInventoryCell.ps1 create mode 100644 powershell/internal/checks/ad/ad/Get-MtAdCertificateInventory.ps1 create mode 100644 powershell/internal/checks/ad/ad/Get-MtAdConfigurationInventory.ps1 create mode 100644 powershell/internal/checks/ad/ad/Get-MtAdConfigurationInventorySiteLinkTransport.ps1 create mode 100644 powershell/internal/checks/ad/ad/Invoke-MtAdConfigurationInventoryReport.ps1 create mode 100644 powershell/tests/functions/ADCertificateInventoryBatch.Tests.ps1 delete mode 100644 tests/ad/config/Test.AD-CFG-14.md delete mode 100644 tests/ad/config/Test.AD-CFG-14.ps1 diff --git a/powershell/internal/checks/ad/ad/ConvertTo-MtAdConfigurationInventoryCell.ps1 b/powershell/internal/checks/ad/ad/ConvertTo-MtAdConfigurationInventoryCell.ps1 new file mode 100644 index 0000000000..18b1ec193e --- /dev/null +++ b/powershell/internal/checks/ad/ad/ConvertTo-MtAdConfigurationInventoryCell.ps1 @@ -0,0 +1,8 @@ +function ConvertTo-MtAdConfigurationInventoryCell { + [CmdletBinding()] + [OutputType([string])] + param($Value) + + if ($null -eq $Value -or [string]::IsNullOrWhiteSpace([string]$Value)) { return '—' } + return [System.Net.WebUtility]::HtmlEncode(([string]$Value -replace '\r\n|\r|\n', ' ')).Replace('|', '|') +} diff --git a/powershell/internal/checks/ad/ad/Get-MtAdCertificateInventory.ps1 b/powershell/internal/checks/ad/ad/Get-MtAdCertificateInventory.ps1 new file mode 100644 index 0000000000..c0b95aa787 --- /dev/null +++ b/powershell/internal/checks/ad/ad/Get-MtAdCertificateInventory.ps1 @@ -0,0 +1,51 @@ +function Get-MtAdCertificateInventory { + [CmdletBinding()] + [OutputType([object[]])] + param( + [Parameter(Mandatory)] $Configuration + ) + + $rows = @() + $roles = @( + @{ Name = 'Enterprise CA'; Property = 'EnterpriseCAs' }, + @{ Name = 'Trusted root'; Property = 'TrustedRootCAs' }, + @{ Name = 'Intermediate'; Property = 'IntermediateCAs' }, + @{ Name = 'NTAuth'; Property = 'NtAuthCertificates' } + ) + foreach ($role in $roles) { + foreach ($entry in @($Configuration.($role.Property))) { + $raw = $entry.cACertificate + # A single DER certificate is a byte array, not an array of certificates. + $values = [System.Collections.Generic.List[object]]::new() + if ($raw -is [byte[]] -or $raw -is [string]) { + $values.Add($raw) + } elseif ($null -ne $raw) { + foreach ($value in $raw) { $values.Add($value) } + } + foreach ($value in $values) { + if ($null -eq $value) { continue } + $bytes = if ($value -is [byte[]]) { $value } elseif ($value -is [string]) { + try { [Convert]::FromBase64String($value) } catch { throw "Invalid certificate encoding for $($role.Name) $($entry.Name)." } + } else { throw "Unsupported certificate value for $($role.Name) $($entry.Name)." } + try { + $cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new([byte[]]$bytes) + $rows += [pscustomobject]@{ + Role = $role.Name + Name = [string]$entry.Name + Subject = $cert.Subject + Issuer = $cert.Issuer + NotBefore = $cert.NotBefore.ToString('yyyy-MM-dd') + NotAfter = $cert.NotAfter.ToString('yyyy-MM-dd') + Thumbprint = $cert.Thumbprint + Status = if ($cert.NotAfter -lt (Get-Date)) { 'Expired (review)' } elseif ($cert.NotBefore -gt (Get-Date)) { 'Not yet valid (review)' } else { 'Within validity dates' } + } + } catch { + throw "Unable to parse public certificate for $($role.Name) $($entry.Name)." + } finally { + if ($null -ne $cert) { $cert.Dispose(); $cert = $null } + } + } + } + } + return $rows +} diff --git a/powershell/internal/checks/ad/ad/Get-MtAdConfigurationInventory.ps1 b/powershell/internal/checks/ad/ad/Get-MtAdConfigurationInventory.ps1 new file mode 100644 index 0000000000..36968f9372 --- /dev/null +++ b/powershell/internal/checks/ad/ad/Get-MtAdConfigurationInventory.ps1 @@ -0,0 +1,17 @@ +function Get-MtAdConfigurationInventory { + [CmdletBinding()] + param( + [Parameter(Mandatory)] $State, + [Parameter(Mandatory)] [string[]] $Required + ) + + if ($null -eq $State -or $null -eq $State.Configuration) { + throw 'Active Directory configuration data is unavailable.' + } + foreach ($name in $Required) { + if ($null -eq $State.Configuration.PSObject.Properties[$name] -or $null -eq $State.Configuration.$name) { + throw "Active Directory configuration $name data is unavailable." + } + } + return $State.Configuration +} diff --git a/powershell/internal/checks/ad/ad/Get-MtAdConfigurationInventorySiteLinkTransport.ps1 b/powershell/internal/checks/ad/ad/Get-MtAdConfigurationInventorySiteLinkTransport.ps1 new file mode 100644 index 0000000000..54b36c353f --- /dev/null +++ b/powershell/internal/checks/ad/ad/Get-MtAdConfigurationInventorySiteLinkTransport.ps1 @@ -0,0 +1,20 @@ +function Get-MtAdConfigurationInventorySiteLinkTransport { + [CmdletBinding()] + param([Parameter(Mandatory)] $Configuration) + + $rows = @() + foreach ($link in @($Configuration.SiteLinks)) { + $match = [regex]::Match([string]$link.DistinguishedName, '(?i)^CN=(?:\\.|[^,])+,CN=(IP|SMTP),CN=Inter-Site Transports,') + $transport = if ($match.Success) { $match.Groups[1].Value } else { '' } + if ($transport -notin @('IP', 'SMTP')) { throw "Unknown site link transport for $($link.Name): $($link.DistinguishedName)." } + $rows += [pscustomobject]@{ + Name = $link.Name + Transport = $transport.ToUpperInvariant() + Cost = $link.cost + Interval = $link.ReplicationFrequencyInMinutes + Sites = (@($link.siteList | Where-Object { $null -ne $_ }) -join ', ') + DistinguishedName = $link.DistinguishedName + } + } + return $rows +} diff --git a/powershell/internal/checks/ad/ad/Invoke-MtAdConfigurationInventoryReport.ps1 b/powershell/internal/checks/ad/ad/Invoke-MtAdConfigurationInventoryReport.ps1 new file mode 100644 index 0000000000..2d555e553b --- /dev/null +++ b/powershell/internal/checks/ad/ad/Invoke-MtAdConfigurationInventoryReport.ps1 @@ -0,0 +1,89 @@ +function Invoke-MtAdConfigurationInventoryReport { + [CmdletBinding()] + [OutputType([bool])] + param([Parameter(Mandatory)][ValidateSet('EnterpriseCAs', 'Templates', 'Certificates', 'CDP', 'NTAuth', 'SiteLinks')][string] $Kind) + + $required = switch ($Kind) { + 'EnterpriseCAs' { @('EnterpriseCAs') } + 'Templates' { @('EnterpriseCAs', 'CertificateTemplates', 'EnrollmentTemplates') } + 'Certificates' { @('EnterpriseCAs', 'TrustedRootCAs', 'IntermediateCAs') } + 'CDP' { @('CrlDistributionPoints') } + 'NTAuth' { @('NtAuthCertificates') } + 'SiteLinks' { @('SiteLinks') } + } + $config = Get-MtAdConfigurationInventory -State (Get-MtADDomainState -Categories @('Configuration')) -Required $required + $lines = [System.Collections.Generic.List[string]]::new() + switch ($Kind) { + 'EnterpriseCAs' { + $cas = @($config.EnterpriseCAs) + $lines.Add("Enterprise CAs: $($cas.Count). Review the published templates and host names below.") + $lines.Add('| CA | DNS host | Published templates |') + $lines.Add('| --- | --- | --- |') + foreach ($ca in $cas) { + $templates = @($ca.certificateTemplates | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) }) + $lines.Add("| $(ConvertTo-MtAdConfigurationInventoryCell $ca.Name) | $(ConvertTo-MtAdConfigurationInventoryCell $ca.dNSHostName) | $(ConvertTo-MtAdConfigurationInventoryCell ($templates -join ', ')) |") + } + } + 'Templates' { + $templates = @($config.CertificateTemplates) + $published = @($config.EnrollmentTemplates | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) } | Sort-Object -Unique) + $known = @{} + foreach ($template in $templates) { $known[[string]$template.Name] = $true } + $unknown = @($published | Where-Object { -not $known.ContainsKey([string]$_) }) + $lines.Add("Template objects: $($templates.Count); distinct published names: $($published.Count); published names without a template object: $($unknown.Count).") + $lines.Add('| Template CN | Display name | Publishing CAs |') + $lines.Add('| --- | --- | --- |') + foreach ($template in $templates) { + $publishers = @($config.EnterpriseCAs | Where-Object { @($_.certificateTemplates) -contains $template.Name } | ForEach-Object { $_.Name }) + $lines.Add("| $(ConvertTo-MtAdConfigurationInventoryCell $template.Name) | $(ConvertTo-MtAdConfigurationInventoryCell $template.displayName) | $(ConvertTo-MtAdConfigurationInventoryCell ($publishers -join ', ')) |") + } + foreach ($name in $unknown) { + $publishers = @($config.EnterpriseCAs | Where-Object { @($_.certificateTemplates) -contains $name } | ForEach-Object { $_.Name }) + $lines.Add("| $(ConvertTo-MtAdConfigurationInventoryCell $name) (unknown template) | — | $(ConvertTo-MtAdConfigurationInventoryCell ($publishers -join ', ')) |") + } + } + 'Certificates' { + $certs = @(Get-MtAdCertificateInventory -Configuration $config) + $lines.Add("Enterprise CA objects: $(@($config.EnterpriseCAs).Count); trusted root objects: $(@($config.TrustedRootCAs).Count); intermediate objects: $(@($config.IntermediateCAs).Count); public certificate entries: $($certs.Count). A certificate in multiple roles appears once per role.") + $lines.Add('| Role | Object | Subject | Issuer | Valid from | Valid to | Thumbprint | Observation |') + $lines.Add('| --- | --- | --- | --- | --- | --- | --- | --- |') + foreach ($cert in $certs) { + $lines.Add("| $(ConvertTo-MtAdConfigurationInventoryCell $cert.Role) | $(ConvertTo-MtAdConfigurationInventoryCell $cert.Name) | $(ConvertTo-MtAdConfigurationInventoryCell $cert.Subject) | $(ConvertTo-MtAdConfigurationInventoryCell $cert.Issuer) | $($cert.NotBefore) | $($cert.NotAfter) | $($cert.Thumbprint) | $($cert.Status) |") + } + } + 'CDP' { + $entries = @($config.CrlDistributionPoints) + $lines.Add("CRL distribution point objects: $($entries.Count). This is an inventory, not a CRL validity or reachability check.") + $lines.Add('| Name | Distinguished name | CRL published |') + $lines.Add('| --- | --- | --- |') + foreach ($entry in $entries) { + $present = if ($null -ne $entry.certificateRevocationList -and @($entry.certificateRevocationList).Count -gt 0) { 'Yes' } else { 'No' } + $lines.Add("| $(ConvertTo-MtAdConfigurationInventoryCell $entry.Name) | $(ConvertTo-MtAdConfigurationInventoryCell $entry.DistinguishedName) | $present |") + } + } + 'NTAuth' { + $certs = @(Get-MtAdCertificateInventory -Configuration $config) + $ntAuth = @($certs | Where-Object { $_.Role -eq 'NTAuth' }) + $lines.Add("NTAuth objects: $(@($config.NtAuthCertificates).Count); public certificates: $($ntAuth.Count). Expiry observations require review and do not fail this inventory.") + $lines.Add('| Object | Subject | Issuer | Valid from | Valid to | Thumbprint | Observation |') + $lines.Add('| --- | --- | --- | --- | --- | --- | --- |') + foreach ($cert in $ntAuth) { + $lines.Add("| $(ConvertTo-MtAdConfigurationInventoryCell $cert.Name) | $(ConvertTo-MtAdConfigurationInventoryCell $cert.Subject) | $(ConvertTo-MtAdConfigurationInventoryCell $cert.Issuer) | $($cert.NotBefore) | $($cert.NotAfter) | $($cert.Thumbprint) | $($cert.Status) |") + } + } + 'SiteLinks' { + $links = @(Get-MtAdConfigurationInventorySiteLinkTransport -Configuration $config) + $ip = @($links | Where-Object { $_.Transport -eq 'IP' }).Count + $smtp = @($links | Where-Object { $_.Transport -eq 'SMTP' }).Count + $lines.Add("Site links: $($links.Count); IP: $ip; SMTP: $smtp. Transport is identified by the parent DN, not cost or replication interval.") + $lines.Add('| Link | Transport | Cost | Replication interval (minutes) | Sites | Distinguished name |') + $lines.Add('| --- | --- | --- | --- | --- | --- |') + foreach ($link in $links) { + $lines.Add("| $(ConvertTo-MtAdConfigurationInventoryCell $link.Name) | $($link.Transport) | $(ConvertTo-MtAdConfigurationInventoryCell $link.Cost) | $(ConvertTo-MtAdConfigurationInventoryCell $link.Interval) | $(ConvertTo-MtAdConfigurationInventoryCell $link.Sites) | $(ConvertTo-MtAdConfigurationInventoryCell $link.DistinguishedName) |") + } + } + } + if ($lines.Count -eq 0) { throw 'Inventory report could not be generated.' } + Add-MtTestResultDetail -Result ($lines -join "`n") -Investigate + return $true +} diff --git a/powershell/tests/functions/ADCertificateInventoryBatch.Tests.ps1 b/powershell/tests/functions/ADCertificateInventoryBatch.Tests.ps1 new file mode 100644 index 0000000000..c1f16062d5 --- /dev/null +++ b/powershell/tests/functions/ADCertificateInventoryBatch.Tests.ps1 @@ -0,0 +1,71 @@ +BeforeAll { + $root = (Resolve-Path (Join-Path $PSScriptRoot '../../..')).Path + foreach ($name in @('ConvertTo-MtAdConfigurationInventoryCell', 'Get-MtAdConfigurationInventory', 'Get-MtAdCertificateInventory', 'Get-MtAdConfigurationInventorySiteLinkTransport', 'Invoke-MtAdConfigurationInventoryReport')) { + . (Join-Path $root "powershell/internal/checks/ad/ad/$name.ps1") + } + function Get-MtADDomainState { param($Categories) } + function Add-MtTestResultDetail { param($Result, [switch]$Investigate) } +} + +Describe 'AD configuration inventory batch' { + BeforeAll { + $certificate = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new('CN=Inventory CA', [System.Security.Cryptography.RSA]::Create(2048), [System.Security.Cryptography.HashAlgorithmName]::SHA256, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1).CreateSelfSigned((Get-Date).AddDays(-20), (Get-Date).AddDays(-1)) + $bytes = $certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert) + $script:certBytes = $bytes + } + + It 'treats a single DER byte array as one expired observation in each published role' { + $config = [pscustomobject]@{ EnterpriseCAs = @([pscustomobject]@{ Name = 'CA'; cACertificate = $script:certBytes }); TrustedRootCAs = @([pscustomobject]@{ Name = 'Root'; cACertificate = @($script:certBytes, $script:certBytes) }); IntermediateCAs = @(); NtAuthCertificates = @() } + $rows = @(Get-MtAdCertificateInventory -Configuration $config) + $rows.Count | Should -Be 3 + @($rows | Where-Object Role -eq 'Trusted root').Count | Should -Be 2 + $rows[0].Status | Should -Be 'Expired (review)' + $rows[0].Thumbprint | Should -Not -BeNullOrEmpty + } + + It 'throws on malformed certificate data rather than reporting an incomplete inventory' { + $config = [pscustomobject]@{ EnterpriseCAs = @([pscustomobject]@{ Name = 'Bad'; cACertificate = [byte[]](1, 2, 3) }); TrustedRootCAs = @(); IntermediateCAs = @(); NtAuthCertificates = @() } + { Get-MtAdCertificateInventory -Configuration $config } | Should -Throw '*Unable to parse public certificate*' + } + + It 'distinguishes missing data from a retrieved empty collection' { + $state = [pscustomobject]@{ Configuration = [pscustomobject]@{ SiteLinks = @() } } + @(Get-MtAdConfigurationInventory -State $state -Required SiteLinks).Count | Should -Be 1 + { Get-MtAdConfigurationInventory -State $state -Required CertificateTemplates } | Should -Throw '*unavailable*' + } + + It 'classifies transport by parent DN and retains zero cost' { + $config = [pscustomobject]@{ SiteLinks = @( + [pscustomobject]@{ Name = 'A'; DistinguishedName = 'CN=A,CN=SMTP,CN=Inter-Site Transports,CN=Sites,DC=test'; cost = 0; ReplicationFrequencyInMinutes = 15; siteList = @('CN=Site1') }, + [pscustomobject]@{ Name = 'B'; DistinguishedName = 'CN=B,CN=IP,CN=Inter-Site Transports,CN=Sites,DC=test'; cost = 10; ReplicationFrequencyInMinutes = $null; siteList = @() } + ) } + $links = @(Get-MtAdConfigurationInventorySiteLinkTransport -Configuration $config) + $links[0].Transport | Should -Be 'SMTP' + $links[0].Cost | Should -Be 0 + $links[1].Transport | Should -Be 'IP' + } + + It 'escapes Markdown table markup and HTML in directory values' { + (ConvertTo-MtAdConfigurationInventoryCell "bad|