diff --git a/.github/workflows/attribute-review.yaml b/.github/workflows/attribute-review.yaml index 206c364f22..905281db6b 100644 --- a/.github/workflows/attribute-review.yaml +++ b/.github/workflows/attribute-review.yaml @@ -69,16 +69,17 @@ jobs: exit 0 } - $changed = gh api "repos/$env:REPO/pulls/$env:PR_NUMBER/files" --paginate --jq '.[] | select(.status != "removed") | .filename' + $changed = @(gh api "repos/$env:REPO/pulls/$env:PR_NUMBER/files" --paginate --jq '.[] | {status, filename, previous_filename} | @json' | ForEach-Object { $_ | ConvertFrom-Json }) if ($LASTEXITCODE -ne 0) { throw 'Could not list the files of the pull request.' } - # Test files only, with plain path characters, so a file name cannot point outside the temp folder. - $tests = @($changed | Where-Object { $_ -match '^tests/[A-Za-z0-9._/-]+/Test\.[A-Za-z0-9._-]+\.(ps1|md)$' -and $_ -notmatch '\.\.' }) - if ($tests.Count -gt 400) { throw "The pull request changes $($tests.Count) test files, more than this job downloads. Ask a maintainer to review the attributes." } + # Keep deleted and renamed-old paths for the related-test index; download only paths present at head. + . ./build/review/Get-MtReviewPullRequestFile.ps1 + $tests = Get-MtReviewPullRequestFile -Changed $changed $head = Join-Path $env:RUNNER_TEMP 'pr-head' + $null = New-Item -ItemType Directory -Path $head -Force $headers = @{ Authorization = "Bearer $env:GH_TOKEN"; Accept = 'application/vnd.github.raw'; 'X-GitHub-Api-Version' = '2022-11-28' } - foreach ($path in $tests) { + foreach ($path in $tests.Download) { $target = Join-Path $head $path $null = New-Item -ItemType Directory -Path (Split-Path $target) -Force $encoded = ($path -split '/' | ForEach-Object { [uri]::EscapeDataString($_) }) -join '/' @@ -87,9 +88,9 @@ jobs: if ((Get-Item -LiteralPath $target).Length -gt 512KB) { throw "$path is larger than 512 KB." } } - $tests | Set-Content (Join-Path $env:RUNNER_TEMP 'pr-files.txt') - "count=$($tests.Count)" >> $env:GITHUB_OUTPUT - Write-Host "Downloaded $($tests.Count) test file(s)." + $tests.Review | Set-Content (Join-Path $env:RUNNER_TEMP 'pr-files.txt') + "count=$($tests.Review.Count)" >> $env:GITHUB_OUTPUT + Write-Host "Downloaded $($tests.Download.Count) test file(s); listed $($tests.Review.Count) for review." - name: Review the attributes against the rubric id: review diff --git a/build/docs/Export-MtTestCatalogForDocs.ps1 b/build/docs/Export-MtTestCatalogForDocs.ps1 index b861bda0a2..c0fa8912f5 100644 --- a/build/docs/Export-MtTestCatalogForDocs.ps1 +++ b/build/docs/Export-MtTestCatalogForDocs.ps1 @@ -20,6 +20,9 @@ requirement relates to. Benchmark is null for every other test. Frameworks at the top level gives the Name, Version and Url of each framework by Key. + TestReplacements maps retired native test IDs to surviving checks so the website + preserves their historical test-page URLs after consolidation. + Packs lists the packs that ship with Maester (packs//maester-pack.json) with the tests of their catalog, such as the Zero Trust Assessment's, so the site can show them beside the built-in checks. The Taxonomy names the keys and techniques that the packs' tests use as well. @@ -162,7 +165,10 @@ $frameworks = @([System.Linq.Enumerable]::OrderBy([object[]]$declared, [Func[obj [ordered]@{ Key = $_.Key; Name = $_.Name; Version = $_.Version; Url = $_.Url } }) -$json = ConvertTo-Json -InputObject ([ordered]@{ Taxonomy = $taxonomy; Frameworks = $frameworks; Packs = @($packs); Tests = @($catalog) }) -Depth 6 +$replacements = Import-PowerShellDataFile -LiteralPath (Join-Path $repoRoot 'build/golden/native-test-replacements.psd1') +$orderedReplacements = [ordered]@{} +foreach ($id in ($replacements.Keys | Sort-Object)) { $orderedReplacements[$id] = $replacements[$id] } +$json = ConvertTo-Json -InputObject ([ordered]@{ Taxonomy = $taxonomy; Frameworks = $frameworks; Packs = @($packs); Tests = @($catalog); TestReplacements = $orderedReplacements }) -Depth 6 $json = $json.Replace("`r`n", "`n") + "`n" $outDir = Split-Path $OutputPath -Parent if ($outDir -and -not (Test-Path $outDir)) { New-Item -ItemType Directory -Path $outDir -Force | Out-Null } diff --git a/build/golden/Export-MtLegacyTagTable.ps1 b/build/golden/Export-MtLegacyTagTable.ps1 index 33da8e4eff..d598a81cdf 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) + 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 replace a historical check. + Regenerate when native replacements change; never edit the table 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..c19105d696 --- /dev/null +++ b/build/golden/native-test-replacements.psd1 @@ -0,0 +1,22 @@ +@{ + # Explicit replacements preserve historical selection without hiding accidental deletions. + 'MT1060' = 'MT.1060' + '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-GPOS-01' = 'AD-GPO-01' + 'AD-GPOS-03' = 'AD-GPOS-02' + 'AD-GPOS-05' = 'AD-GPOS-04' + 'AD-GPOS-06' = 'AD-GPOS-04' + 'AD-GPOS-07' = 'AD-GPOS-04' + 'AD-GPOS-09' = 'AD-GPOS-08' +} diff --git a/build/review/Get-MtReviewPullRequestFile.ps1 b/build/review/Get-MtReviewPullRequestFile.ps1 new file mode 100644 index 0000000000..ad0c62851c --- /dev/null +++ b/build/review/Get-MtReviewPullRequestFile.ps1 @@ -0,0 +1,35 @@ +function Get-MtReviewPullRequestFile { + <# + .SYNOPSIS + Selects safe test paths for review and head downloads from the pull request files API. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [AllowEmptyCollection()] + [object[]] $Changed, + + [int] $MaxFiles = 400 + ) + + $review = [System.Collections.Generic.List[string]]::new() + $download = [System.Collections.Generic.List[string]]::new() + $seen = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) + foreach ($file in $Changed) { + $paths = @([string] $file.filename) + if ($file.status -eq 'renamed' -and $file.PSObject.Properties['previous_filename'] -and $file.previous_filename) { + $paths += [string] $file.previous_filename + } + foreach ($path in $paths) { + if ($path -notmatch '^tests/[A-Za-z0-9._/-]+/Test\.[A-Za-z0-9._-]+\.(ps1|md)$' -or $path -match '\.\.') { continue } + if ($seen.Add($path)) { $review.Add($path) } + if ($path -eq $file.filename -and $file.status -ne 'removed' -and $path -notin $download) { + $download.Add($path) + } + } + } + if ($review.Count -gt $MaxFiles) { + throw "The pull request changes $($review.Count) test files, more than this job downloads. Ask a maintainer to review the attributes." + } + [pscustomobject]@{ Review = $review.ToArray(); Download = $download.ToArray() } +} diff --git a/build/review/Invoke-MtAttributeReview.ps1 b/build/review/Invoke-MtAttributeReview.ps1 index ee8534ced2..42a33f47c3 100644 --- a/build/review/Invoke-MtAttributeReview.ps1 +++ b/build/review/Invoke-MtAttributeReview.ps1 @@ -265,6 +265,11 @@ function Get-MtReviewTarget { Sort-Object -Unique foreach ($path in $testPaths) { + # A listed .ps1 absent from the downloaded head was deleted (or renamed). Do not fall back to the + # trusted base copy; that fallback is only for a Markdown-only change whose .ps1 was not listed. + if ($path -in @($File | Where-Object { $_ } | ForEach-Object { $_ -replace '\\', '/' }) -and + -not (Test-Path -LiteralPath (Join-Path $HeadRoot $path) -PathType Leaf) -and + (Resolve-Path $HeadRoot).Path -ne (Resolve-Path $Root).Path) { continue } $source = Get-MtReviewContent -Root $Root -HeadRoot $HeadRoot -BaseRef $BaseRef -RelativePath $path if ($null -eq $source.Head) { continue } # the test was deleted $markdown = Get-MtReviewContent -Root $Root -HeadRoot $HeadRoot -BaseRef $BaseRef -RelativePath ($path -replace '\.ps1$', '.md') diff --git a/powershell/assets/Maester.LegacyTags.json b/powershell/assets/Maester.LegacyTags.json index 2ba8db3c4b..ff3166fe9f 100644 --- a/powershell/assets/Maester.LegacyTags.json +++ b/powershell/assets/Maester.LegacyTags.json @@ -146,44 +146,26 @@ "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", "AD-GPOS-04", - "AD-GPOS-05", - "AD-GPOS-06", - "AD-GPOS-07", "AD-GPOS-08", - "AD-GPOS-09", "AD-GRP-01", "AD-GRP-02", "AD-GRP-03", @@ -288,6 +270,114 @@ "AD-USER-29" ] }, + { + "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-GPOS-01", + "Tests": [ + "AD-GPO-01" + ] + }, + { + "Tag": "AD-GPOS-03", + "Tests": [ + "AD-GPOS-02" + ] + }, + { + "Tag": "AD-GPOS-05", + "Tests": [ + "AD-GPOS-04" + ] + }, + { + "Tag": "AD-GPOS-06", + "Tests": [ + "AD-GPOS-04" + ] + }, + { + "Tag": "AD-GPOS-07", + "Tests": [ + "AD-GPOS-04" + ] + }, + { + "Tag": "AD-GPOS-09", + "Tests": [ + "AD-GPOS-08" + ] + }, { "Tag": "AD.Computer", "Tests": [ @@ -444,49 +534,32 @@ "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-GPO-01", "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", "AD-GPOS-04", - "AD-GPOS-05", - "AD-GPOS-06", - "AD-GPOS-07", - "AD-GPOS-08", - "AD-GPOS-09" + "AD-GPOS-08" ] }, { diff --git a/powershell/internal/checks/ad/gpo/Test-MtAdGpoDisabledLinkCount.ps1 b/powershell/internal/checks/ad/gpo/Test-MtAdGpoDisabledLinkCount.ps1 index ad0335ab22..00a2786b0d 100644 --- a/powershell/internal/checks/ad/gpo/Test-MtAdGpoDisabledLinkCount.ps1 +++ b/powershell/internal/checks/ad/gpo/Test-MtAdGpoDisabledLinkCount.ps1 @@ -1,90 +1,44 @@ function Test-MtAdGpoDisabledLinkCount { <# .SYNOPSIS - Counts the number of disabled GPO links in Active Directory. - + Counts disabled GPO links and lists their policies and linked containers. .DESCRIPTION - This test retrieves the count of disabled GPO links across all organizational units, - domains, and sites. Disabled links indicate GPOs that are linked but not applied, - which can create confusion and security gaps if not properly managed. - - .EXAMPLE - Test-MtAdGpoDisabledLinkCount - - Returns $true if GPO link data is accessible, $false otherwise. - The test result includes counts of disabled vs total links. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoDisabledLinkCount + Uses normalized cached link states, including links that are both disabled and enforced. + .PARAMETER Investigate + Marks the inventory for investigation instead of reporting a successful read as Passed. #> [CmdletBinding()] [OutputType([bool])] - param() + param([switch] $Investigate) - Write-Verbose "Starting Test-MtAdGpoDisabledLinkCount" - - # 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 + $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.' } - - $gpoLinks = $gpoState.GPOLinks - - # Parse gPLink attribute to count disabled links - # gPLink format: [LDAP://cn={guid},cn=policies,cn=system,DC=domain,DC=com;0] - # The number after the semicolon indicates: 0=enabled, 1=disabled, 2=enforced - $totalLinks = 0 - $disabledLinks = 0 - $enabledLinks = 0 - $enforcedLinks = 0 - - foreach ($link in $gpoLinks) { - if ($link.gPLink) { - # Split by brackets to get individual links - $linkEntries = $link.gPLink -split '\]' | Where-Object { $_ -match 'LDAP://' } - foreach ($entry in $linkEntries) { - $totalLinks++ - # Check the suffix after the semicolon - if ($entry -match ';(\d)$') { - $linkState = [int]$matches[1] - switch ($linkState) { - 0 { $enabledLinks++ } - 1 { $disabledLinks++ } - 2 { $enforcedLinks++ } - } - } - } - } + $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.' } - - # Test passes if we successfully retrieved GPO link data - $testResult = $totalLinks -ge 0 - - # Generate markdown results - if ($testResult) { - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total Links | $totalLinks |" + "`n" - $result += "| Enabled Links | $enabledLinks |" + "`n" - $result += "| Disabled Links | $disabledLinks |" + "`n" - $result += "| Enforced Links | $enforcedLinks |" + "`n" - - if ($totalLinks -gt 0) { - $disabledPercentage = [Math]::Round(($disabledLinks / $totalLinks) * 100, 2) - $result += "| Disabled Percentage | $disabledPercentage% |" + "`n" - } - - $testResultMarkdown = "Active Directory GPO links have been analyzed. $disabledLinks out of $totalLinks links are disabled.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $testResultMarkdown = "Unable to retrieve Active Directory GPO links. Ensure you have appropriate permissions and the Group Policy Management Console is installed." + $disabled = @($links | Where-Object { $true -eq $_.IsDisabled }) + $linksComplete = Test-MtAdGpoLinksComplete -State $state + $gpoIndex = [System.Collections.Generic.Dictionary[string, object]]::new([StringComparer]::OrdinalIgnoreCase) + foreach ($gpo in @($state.GPOs | Where-Object { $null -ne $_ })) { + $id = ([string]$gpo.Id).Trim('{}') + if (-not [string]::IsNullOrWhiteSpace($id) -and -not $gpoIndex.ContainsKey($id)) { $gpoIndex.Add($id, $gpo) } } - - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult + $details = @(foreach ($link in @($disabled | Sort-Object DistinguishedName, GpoGuid)) { + $id = ([string]$link.GpoGuid).Trim('{}') + $name = if ($gpoIndex.ContainsKey($id)) { [string]$gpoIndex[$id].DisplayName } else { [string]$link.GpoGuid } + [pscustomobject]@{ Name = $name; Container = $link.DistinguishedName } + }) + $summary = if ($links.Count -eq 0) { 'No GPO links were returned in the collected inventory.' } + elseif ($disabled.Count -eq 0) { "No disabled GPO links were found. All $($links.Count) collected links are enabled." } + else { "$($disabled.Count) of $($links.Count) GPO links are disabled. Review whether these disabled links are intentional." } + if (-not $linksComplete) { $summary = "Partial link inventory: $($disabled.Count) known disabled links among $($links.Count) parsed links. Additional links could not be parsed; zero findings would not prove that all links are enabled." } + elseif (-not $Investigate -and $disabled.Count -eq 0 -and $links.Count -gt 0) { $summary = "Well done. $summary" } + $metrics = if ($linksComplete) { [ordered]@{ 'Total GPO links' = $links.Count; 'Enabled GPO links' = $links.Count - $disabled.Count; 'Disabled GPO links' = $disabled.Count } } + else { [ordered]@{ 'Parsed GPO links' = $links.Count; 'Known enabled GPO links' = $links.Count - $disabled.Count; 'Known disabled GPO links' = $disabled.Count; 'Link collection complete' = $false } } + $result = Format-MtAdGpoResult -Summary $summary -Metrics $metrics -Details $details -Properties Name, Container -Headers GPO, 'Linked container' + Add-MtTestResultDetail -Result $result -Investigate:($Investigate -or -not $linksComplete) + return $true } diff --git a/powershell/internal/checks/ad/gpo/Test-MtAdGpoPermission.ps1 b/powershell/internal/checks/ad/gpo/Test-MtAdGpoPermission.ps1 new file mode 100644 index 0000000000..3a16417a13 --- /dev/null +++ b/powershell/internal/checks/ad/gpo/Test-MtAdGpoPermission.ps1 @@ -0,0 +1,58 @@ +function Test-MtAdGpoPermission { + <# + .SYNOPSIS + Evaluates a cached GPO permission summary and formats findings and unknown values. + .DESCRIPTION + Multiple permission properties are alternatives: one matching value proves the + condition. With no matching value, an unknown alternative remains inconclusive. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [string[]] $PermissionProperties, + [Parameter(Mandatory)] + [bool] $ExpectedValue, + [Parameter(Mandatory)] + [string] $FindingLabel, + [Parameter(Mandatory)] + [string] $PassMessage, + [Parameter(Mandatory)] + [string] $FailureMessage + ) + + $state = Get-MtADGpoState + if ($null -eq $state -or $null -eq $state.GPOReports) { throw 'GPO permission data could not be collected.' } + $reports = @($state.GPOReports | Where-Object { $null -ne $_ }) + $assessed = @(foreach ($report in $reports) { + $matchedValue = $false + $hasUnknown = $false + foreach ($property in $PermissionProperties) { + if ($null -eq $report.$property) { $hasUnknown = $true } + elseif ($report.$property -eq $ExpectedValue) { $matchedValue = $true } + } + $assessment = if ($matchedValue) { 'Expected' } + elseif ($hasUnknown) { 'Unknown' } + else { 'Finding' } + [pscustomobject]@{ Name = $report.Name; Assessment = $assessment } + }) + $findings = @($assessed | Where-Object Assessment -EQ 'Finding') + $unknown = @($assessed | Where-Object Assessment -EQ 'Unknown') + if ($unknown.Count -eq $reports.Count) { + Add-MtTestResultDetail -SkippedBecause Custom -SkippedCustomReason "GPO permission conditions could not be determined (0 of $($reports.Count) GPOs evaluated). Descriptors may be unreadable or contain conflicting allow and deny entries." + return $null + } + $pass = $findings.Count -eq 0 + $summary = if ($pass -and $unknown.Count -eq 0) { "Well done. $PassMessage" } + elseif ($pass) { 'No findings among evaluated GPOs; incomplete or inconclusive permissions require investigation.' } + else { "$($findings.Count) of $($reports.Count) GPOs $FailureMessage" } + if ($unknown.Count -gt 0) { $summary += " Permission conditions could not be determined for $($unknown.Count) GPOs; inspect unreadable descriptors or conflicting allow and deny entries." } + $metrics = [ordered]@{ 'Total GPOs' = $reports.Count; $FindingLabel = $findings.Count; 'GPOs with unknown permissions' = $unknown.Count } + if ($PermissionProperties -contains 'HasDomainComputers') { + $metrics['GPOs without Domain Computers'] = @($reports | Where-Object { $false -eq $_.HasDomainComputers }).Count + } + $details = @($findings + $unknown | Sort-Object Name) + $result = Format-MtAdGpoResult -Summary $summary -Metrics $metrics -Details $details -Properties Name, Assessment -Headers GPO, Assessment + Add-MtTestResultDetail -Result $result -Investigate:($pass -and $unknown.Count -gt 0) + return $pass +} diff --git a/powershell/internal/report/Format-MtAdGpoResult.ps1 b/powershell/internal/report/Format-MtAdGpoResult.ps1 new file mode 100644 index 0000000000..53341e5f8c --- /dev/null +++ b/powershell/internal/report/Format-MtAdGpoResult.ps1 @@ -0,0 +1,60 @@ +function Format-MtAdGpoResult { + <# + .SYNOPSIS + Formats a Group Policy summary, metrics and non-empty detail table. + .DESCRIPTION + Uses one report layout for Group Policy checks. Empty detail sets never render + table headers. Tenant values are HTML-encoded, pipe-escaped, normalized to + one line, then escaped for Markdown autolinks and syntax. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [string] $Summary, + + [System.Collections.IDictionary] $Metrics, + + [object[]] $Details = @(), + + [string[]] $Properties = @(), + + [string[]] $Headers = @() + ) + + $escapeCell = { + param([AllowNull()][string] $Text) + Get-MtSafeMarkdown -Text ([System.Net.WebUtility]::HtmlEncode($Text).Replace('|', '|') -replace '[\r\n]+', ' ') + } + + $result = [System.Text.StringBuilder]::new() + [void]$result.Append($Summary) + if ($null -ne $Metrics -and $Metrics.Count -gt 0) { + [void]$result.Append("`n`n| Metric | Value |`n| --- | --- |`n") + foreach ($key in $Metrics.Keys) { + $label = & $escapeCell ([string]$key) + $value = if ($null -eq $Metrics[$key]) { 'Unknown' } else { [string]$Metrics[$key] } + $value = & $escapeCell $value + [void]$result.Append("| $label | $value |`n") + } + } + + $rows = @($Details | Where-Object { $null -ne $_ }) + if ($rows.Count -gt 0) { + if ($Properties.Count -eq 0) { throw 'Detail properties are required for a Group Policy table.' } + if ($Headers.Count -eq 0) { $Headers = $Properties } + if ($Headers.Count -ne $Properties.Count) { throw 'Group Policy table headers and properties must have the same count.' } + $labels = @($Headers | ForEach-Object { + & $escapeCell $_ + }) + [void]$result.Append("`n`n#### Details`n`n| $($labels -join ' | ') |`n| $((@($Properties | ForEach-Object { '---' })) -join ' | ') |`n") + foreach ($row in $rows) { + $cells = foreach ($property in $Properties) { + $value = if ($null -eq $row.$property) { 'Unknown' } else { [string]$row.$property } + & $escapeCell $value + } + [void]$result.Append("| $($cells -join ' | ') |`n") + } + } + return $result.ToString() +} diff --git a/powershell/internal/services/ad/Test-MtAdGpoLinksComplete.ps1 b/powershell/internal/services/ad/Test-MtAdGpoLinksComplete.ps1 new file mode 100644 index 0000000000..9a61ccecce --- /dev/null +++ b/powershell/internal/services/ad/Test-MtAdGpoLinksComplete.ps1 @@ -0,0 +1,24 @@ +function Test-MtAdGpoLinksComplete { + <# + .SYNOPSIS + Checks whether a GPO state's link-completeness signal is conclusive. + .DESCRIPTION + Older state objects without a signal retain compatibility. A present signal + must be the Boolean value true; null, strings and false are inconclusive. + #> + [CmdletBinding()] + [OutputType([bool])] + param([AllowNull()][object] $State) + + if ($null -eq $State) { return $false } + if ($State -is [System.Collections.IDictionary]) { + if (-not $State.Contains('GPOLinksComplete')) { return $true } + $value = $State['GPOLinksComplete'] + } + else { + $property = $State.PSObject.Properties['GPOLinksComplete'] + if ($null -eq $property) { return $true } + $value = $property.Value + } + return ($value -is [bool] -and $value) +} diff --git a/powershell/internal/services/ad/queries/Get-MtLdapGpo.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapGpo.ps1 index ebb9a483f3..71fc424fdc 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapGpo.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapGpo.ps1 @@ -14,14 +14,17 @@ $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter '(objectClass=groupPolicyContainer)' -Attributes $attributes -SecurityDescriptorFlags $securityDescriptorFlags) return @($entries | ForEach-Object { $entry = $_ - $version = [int]$_.versionNumber + # LDAP exposes a signed 32-bit value; GPT.INI stores the same bits as unsigned. + $version = if ($null -ne $_.versionNumber) { [long]$_.versionNumber -band 0xffffffffL } else { $null } $idText = ([string]$_.name).Trim('{}') $id = $idText try { $id = [guid]$idText } catch { Write-Verbose "GPO '$($entry.name)' does not contain a valid GUID name." } [PSCustomObject]@{ Id = $id; DisplayName = [string]$_.displayName; DistinguishedName = [string]$_.DistinguishedName; Created = $_.whenCreated; Modified = $_.whenChanged Flags = $_.flags; Owner = $_.ntSecurityDescriptor.Owner.IdentityReference; ntSecurityDescriptor = $_.ntSecurityDescriptor; WmiFilter = [string]$_.gPCWQLFilter; GpcFileSysPath = [string]$_.gPCFileSysPath - VersionNumber = $version; UserVersion = (($version -shr 16) -band 0xffff); ComputerVersion = ($version -band 0xffff) + VersionNumber = $version + UserVersion = if ($null -ne $version) { ($version -shr 16) -band 0xffff } else { $null } + ComputerVersion = if ($null -ne $version) { $version -band 0xffff } else { $null } } }) } diff --git a/powershell/internal/services/ad/transport/Get-MtSysvolContent.ps1 b/powershell/internal/services/ad/transport/Get-MtSysvolContent.ps1 index 8777578f30..e8f091ff43 100644 --- a/powershell/internal/services/ad/transport/Get-MtSysvolContent.ps1 +++ b/powershell/internal/services/ad/transport/Get-MtSysvolContent.ps1 @@ -785,11 +785,18 @@ function Get-MtSysvolContent { $gptIni = $null $gppXml = [Collections.Generic.List[object]]::new() $securityTemplates = [Collections.Generic.List[object]]::new() + $scanErrors = [Collections.Generic.List[string]]::new() foreach ($file in $files) { $path = [string]$file.RelativePath - if ($path -match '(?i)(^|/)GPT\.INI$') { + if ($path -match '(?i)^GPT\.INI$') { $adapterParameters['RelativePath'] = $path - $gptIni = ConvertFrom-MtSysvolGptIni -Content (& $invokeAdapter 'ReadText' $TimeoutSeconds) + try { + $gptIni = ConvertFrom-MtSysvolGptIni -Content (& $invokeAdapter 'ReadText' $TimeoutSeconds) + } + catch { + $scanErrors.Add($path) + Write-Verbose "Could not scan SYSVOL version file '$path'." + } } elseif ($path -match '(?i)\.xml$') { $adapterParameters['RelativePath'] = $path @@ -797,21 +804,38 @@ 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)" + # Do not expose XML contents or exception text that may include credentials. + $scanErrors.Add($path) + Write-Verbose "Could not scan SYSVOL XML file '$path'." } } elseif ($path -match '(?i)(^|/)GptTmpl\.inf$') { $adapterParameters['RelativePath'] = $path - $parsedTemplate = ConvertFrom-MtSysvolSecurityTemplate -Content (& $invokeAdapter 'ReadText' $TimeoutSeconds) - $securityTemplates.Add([PSCustomObject][ordered]@{ - RelativePath = $path - RegistryValues = $parsedTemplate.RegistryValues - PrivilegeRights = $parsedTemplate.PrivilegeRights - DefaultPasswordFound = $parsedTemplate.DefaultPasswordFound - }) + try { + $parsedTemplate = ConvertFrom-MtSysvolSecurityTemplate -Content (& $invokeAdapter 'ReadText' $TimeoutSeconds) + $securityTemplates.Add([PSCustomObject][ordered]@{ + RelativePath = $path + RegistryValues = $parsedTemplate.RegistryValues + PrivilegeRights = $parsedTemplate.PrivilegeRights + DefaultPasswordFound = $parsedTemplate.DefaultPasswordFound + }) + } + catch { + $scanErrors.Add($path) + Write-Verbose "Could not scan SYSVOL security template '$path'." + } } } + # Every GPO should have GPT.INI. An empty or incomplete listing cannot establish a clean scan. + if (($null -eq $gptIni -or $null -eq $gptIni.Version) -and $scanErrors -notcontains 'GPT.INI') { + $scanErrors.Add('GPT.INI') + } + $cpasswordFound = [bool]($gppXml | Where-Object CpasswordFound | Select-Object -First 1) + $defaultPasswordFound = [bool]( + ($gppXml | Where-Object DefaultPasswordFound | Select-Object -First 1) -or + ($securityTemplates | Where-Object DefaultPasswordFound | Select-Object -First 1) + ) return [PSCustomObject][ordered]@{ GpoGuid = $normalizedGuid Server = $server @@ -823,10 +847,8 @@ function Get-MtSysvolContent { GptIni = $gptIni GppXml = @($gppXml) SecurityTemplates = @($securityTemplates) - CpasswordFound = [bool]($gppXml | Where-Object CpasswordFound | Select-Object -First 1) - DefaultPasswordFound = [bool]( - ($gppXml | Where-Object DefaultPasswordFound | Select-Object -First 1) -or - ($securityTemplates | Where-Object DefaultPasswordFound | Select-Object -First 1) - ) + ScanErrors = @($scanErrors) + CpasswordFound = if ($cpasswordFound -or $scanErrors.Count -eq 0) { $cpasswordFound } else { $null } + DefaultPasswordFound = if ($defaultPasswordFound -or $scanErrors.Count -eq 0) { $defaultPasswordFound } else { $null } } } diff --git a/powershell/public/services/ad/Get-MtADGpoState.ps1 b/powershell/public/services/ad/Get-MtADGpoState.ps1 index fcf944230e..07632bd5e7 100644 --- a/powershell/public/services/ad/Get-MtADGpoState.ps1 +++ b/powershell/public/services/ad/Get-MtADGpoState.ps1 @@ -13,6 +13,13 @@ that principal applies to the GPO) and HasInheritedPermissions (an entry is inherited from the parent container). These are $null when the security descriptor of the GPO was not returned. + DirectoryVersion and SysvolVersion expose the versions compared by HasVersionMismatch. + Password scan flags are $null when files could not be scanned, unless a secret was found. + Errors records incomplete SYSVOL scans. Failed metadata or link collection remains $null. + GPOLinksComplete is false when any link target or option could not be parsed, + or a link-container query failed. Valid parsed links remain available after a + malformed entry; a zero derived link count is then unknown, not proof of absence. + .PARAMETER Refresh Forces a refresh of the data from Active Directory, bypassing the cache. @@ -79,6 +86,7 @@ CollectionTime = Get-Date GPOReports = @() GPOLinks = @() + GPOLinksComplete = $true SiteContainers = @() LinkContainers = @() } @@ -103,23 +111,34 @@ } catch { Write-Verbose "Could not collect GPO metadata: $($_.Exception.Message)" + $gpoState['GPOs'] = $null } $parsedGpoLinks = [System.Collections.Generic.List[object]]::new() $domainLinksFailed = $false $siteLinksFailed = $false + # Do not let a malformed prefix consume the opening bracket of the next link. + $linkPattern = '\[(?[^\[\]]+);\s*(?[^\[\];]*)\s*\]' try { $linkContainers = @(Get-MtLdapGpoLink -Connection $protocolConnection -SearchBase $protocolRootDse.DefaultNamingContext) $gpoState['LinkContainers'] = $linkContainers foreach ($container in $linkContainers) { - foreach ($linkMatch in [regex]::Matches([string]$container.GpLink, '\[(?[^\]]+);\s*(?\d+)\s*\]')) { + $linkText = [string]$container.GpLink + if (-not [string]::IsNullOrWhiteSpace([regex]::Replace($linkText, $linkPattern, ''))) { $gpoState['GPOLinksComplete'] = $false } + foreach ($linkMatch in [regex]::Matches($linkText, $linkPattern)) { $guidMatch = [regex]::Match($linkMatch.Groups['target'].Value, '(?i)\{?(?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})\}?') if (-not $guidMatch.Success) { + $gpoState['GPOLinksComplete'] = $false Write-Verbose "Ignoring malformed GPO link on $($container.DistinguishedName): $($linkMatch.Value)" continue } - $options = [int]$linkMatch.Groups['options'].Value + $options = 0 + if (-not [int]::TryParse($linkMatch.Groups['options'].Value.Trim(), [ref]$options) -or $options -notin 0, 1, 2, 3) { + $gpoState['GPOLinksComplete'] = $false + Write-Verbose "Ignoring unknown GPO link options on $($container.DistinguishedName)." + continue + } $isDisabled = [bool]($options -band 1) $isEnforced = [bool]($options -band 2) $parsedGpoLinks.Add([PSCustomObject]@{ @@ -139,6 +158,7 @@ catch { Write-Verbose "Could not collect domain and OU GPO links: $($_.Exception.Message)" $domainLinksFailed = $true + $gpoState['GPOLinksComplete'] = $false $gpoState['LinkContainers'] = $null $gpoState['GPOLinks'] = $null } @@ -147,14 +167,22 @@ $siteContainers = @(Get-MtLdapSiteContainer -Connection $protocolConnection -ConfigurationNamingContext $protocolRootDse.ConfigurationNamingContext) $gpoState['SiteContainers'] = $siteContainers foreach ($container in $siteContainers) { - foreach ($linkMatch in [regex]::Matches([string]$container.GpLink, '\[(?[^\]]+);\s*(?\d+)\s*\]')) { + $linkText = [string]$container.GpLink + if (-not [string]::IsNullOrWhiteSpace([regex]::Replace($linkText, $linkPattern, ''))) { $gpoState['GPOLinksComplete'] = $false } + foreach ($linkMatch in [regex]::Matches($linkText, $linkPattern)) { $guidMatch = [regex]::Match($linkMatch.Groups['target'].Value, '(?i)\{?(?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})\}?') if (-not $guidMatch.Success) { + $gpoState['GPOLinksComplete'] = $false Write-Verbose "Ignoring malformed site GPO link on $($container.DistinguishedName): $($linkMatch.Value)" continue } - $options = [int]$linkMatch.Groups['options'].Value + $options = 0 + if (-not [int]::TryParse($linkMatch.Groups['options'].Value.Trim(), [ref]$options) -or $options -notin 0, 1, 2, 3) { + $gpoState['GPOLinksComplete'] = $false + Write-Verbose "Ignoring unknown site GPO link options on $($container.DistinguishedName)." + continue + } $isDisabled = [bool]($options -band 1) $isEnforced = [bool]($options -band 2) $parsedGpoLinks.Add([PSCustomObject]@{ @@ -174,7 +202,9 @@ catch { Write-Verbose "Could not collect site GPO links: $($_.Exception.Message)" $siteLinksFailed = $true + $gpoState['GPOLinksComplete'] = $false $gpoState['SiteContainers'] = $null + $gpoState['GPOLinks'] = $null } if (-not $domainLinksFailed -and -not $siteLinksFailed) { $gpoState['GPOLinks'] = @($parsedGpoLinks) @@ -184,9 +214,10 @@ $applyGroupPolicyGuid = 'edacfd8f-ffb3-11d1-b41d-00a0c968f939' $gpoReports = foreach ($gpo in $gpoState.GPOs) { $gpoGuid = ([string]$gpo.Id).Trim('{}') - $gpoLinks = if ($null -ne $gpoState.GPOLinks) { - @($gpoState.GPOLinks | Where-Object { ([string]$_.GpoGuid).Trim('{}') -eq $gpoGuid }) - } else { $null } + $gpoLinks = @() + if ($null -ne $gpoState.GPOLinks) { + $gpoLinks = @($gpoState.GPOLinks | Where-Object { ([string]$_.GpoGuid).Trim('{}') -eq $gpoGuid }) + } $descriptor = $gpo.ntSecurityDescriptor if ($descriptor -is [byte[]]) { $descriptor = ConvertFrom-MtLdapSecurityDescriptor -RawSecurityDescriptor $descriptor @@ -199,9 +230,10 @@ $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]$_.ActiveDirectoryRights -match 'ApplyGroupPolicy') -or - (([string]$_.ActiveDirectoryRights -match 'ExtendedRight') -and ([string]$_.ObjectType -eq $applyGroupPolicyGuid))) + [string]$_.AceFlags -notmatch 'InheritOnly' -and + (([string]$_.ActiveDirectoryRights -match 'ApplyGroupPolicy') -or + (([string]$_.ActiveDirectoryRights -match 'ExtendedRight') -and + ([string]$_.ObjectType -eq $applyGroupPolicyGuid))) } | Select-Object -First 1) } @@ -234,17 +266,25 @@ } $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) { throw 'SYSVOL content scanning returned no result.' } if ($null -ne $sysvolContent.GptIni -and $null -ne $sysvolContent.GptIni.Version) { - $hasVersionMismatch = [long]$gpo.VersionNumber -ne [long]$sysvolContent.GptIni.Version + $sysvolVersion = [long]$sysvolContent.GptIni.Version + if ($null -ne $gpo.VersionNumber) { + $hasVersionMismatch = [long]$gpo.VersionNumber -ne $sysvolVersion + } + } + $cpasswordFound = $sysvolContent.CpasswordFound + $defaultPasswordFound = $sysvolContent.DefaultPasswordFound + foreach ($path in @($sysvolContent.ScanErrors | Where-Object { $_ })) { + $errors.Add([PSCustomObject]@{ Transport = 'SYSVOL'; Message = "File could not be scanned: $path" }) | Out-Null } - $cpasswordFound = [bool]$sysvolContent.CpasswordFound - $defaultPasswordFound = [bool]$sysvolContent.DefaultPasswordFound } catch { $errors.Add([PSCustomObject][ordered]@{ @@ -254,15 +294,19 @@ Write-Verbose "Could not collect SYSVOL content for GPO '$gpoGuid': $($_.Exception.Message)" } - $enforcementEnabled = if ($null -ne $gpoLinks) { - [bool]($gpoLinks | Where-Object { $_.IsEnforced } | Select-Object -First 1) - } else { $null } + $knownEnforced = [bool]($gpoLinks | Where-Object { $_.IsEnforced } | Select-Object -First 1) + $knownDisabledCount = @($gpoLinks | Where-Object { $_.IsDisabled }).Count + $linksComplete = Test-MtAdGpoLinksComplete -State $gpoState + $enforcementEnabled = if ($knownEnforced) { $true } elseif ($linksComplete) { $false } else { $null } + $disabledLinkCount = if ($knownDisabledCount -gt 0 -or $linksComplete) { $knownDisabledCount } else { $null } [PSCustomObject][ordered]@{ GPOId = $gpo.Id GPOName = $gpo.DisplayName Name = $gpo.DisplayName - DisabledLinks = if ($null -ne $gpoLinks) { @($gpoLinks | Where-Object { $_.IsDisabled }).Count } else { $null } + DisabledLinks = $disabledLinkCount HasVersionMismatch = $hasVersionMismatch + DirectoryVersion = $gpo.VersionNumber + SysvolVersion = $sysvolVersion CpasswordFound = $cpasswordFound DefaultPasswordFound = $defaultPasswordFound HasApplyGroupPolicyAce = $hasApplyGroupPolicyAce @@ -278,11 +322,12 @@ } } $gpoState['GPOReports'] = @($gpoReports) + if ($null -eq $gpoState.GPOs) { $gpoState['GPOReports'] = $null } Write-Verbose "Collected $($gpoState.GPOReports.Count) GPO reports" } 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..8ba00e49e5 100644 --- a/powershell/tests/ad/transport/Get-MtSysvolContent.Tests.ps1 +++ b/powershell/tests/ad/transport/Get-MtSysvolContent.Tests.ps1 @@ -86,6 +86,110 @@ Describe 'Get-MtSysvolContent transport contract' { } } + It 'does not treat unreadable XML as a clean scan' { + Mock Test-MtSysvolWindowsPlatform -ModuleName Maester { $true } + Mock Invoke-MtSysvolWindowsAdapter -ModuleName Maester { + if ($Operation -eq 'List') { + return [PSCustomObject]@{ RelativePath = 'Machine/Preferences/Groups/Groups.xml'; Length = 20 } + } + if ($Operation -eq 'ReadText') { throw 'SECRET-MUST-NOT-PRINT' } + return $true + } + InModuleScope Maester { + $result = Get-MtSysvolContent -GpoGuid '11111111-1111-1111-1111-111111111111' + $result.ScanErrors | Should -Contain 'Machine/Preferences/Groups/Groups.xml' + $null -eq $result.CpasswordFound | Should -BeTrue + $null -eq $result.DefaultPasswordFound | Should -BeTrue + ($result | ConvertTo-Json -Depth 10) | Should -Not -Match 'SECRET-MUST-NOT-PRINT' + } + } + + It 'preserves a known secret when another XML file is malformed' { + Mock Test-MtSysvolWindowsPlatform -ModuleName Maester { $true } + Mock Invoke-MtSysvolWindowsAdapter -ModuleName Maester { + if ($Operation -eq 'List') { + return @( + [PSCustomObject]@{ RelativePath = 'Machine/Preferences/Groups/Groups.xml'; Length = 20 } + [PSCustomObject]@{ RelativePath = 'User/Preferences/Groups/Groups.xml'; Length = 20 } + ) + } + if ($Operation -eq 'ReadText') { + if ($RelativePath -like 'Machine/*') { return '' } + return '' + } + return $true + } + InModuleScope Maester { + $result = Get-MtSysvolContent -GpoGuid '11111111-1111-1111-1111-111111111111' + $result.CpasswordFound | Should -BeTrue + $null -eq $result.DefaultPasswordFound | Should -BeTrue + $result.ScanErrors | Should -Contain 'User/Preferences/Groups/Groups.xml' + $result.ScanErrors | Should -Contain 'GPT.INI' + } + } + + It 'does not treat an empty SYSVOL listing as a clean scan' { + Mock Test-MtSysvolWindowsPlatform -ModuleName Maester { $true } + Mock Invoke-MtSysvolWindowsAdapter -ModuleName Maester { + if ($Operation -eq 'List') { return @() } + return $true + } + InModuleScope Maester { + $result = Get-MtSysvolContent -GpoGuid '11111111-1111-1111-1111-111111111111' + $result.ScanErrors | Should -Contain 'GPT.INI' + $null -eq $result.CpasswordFound | Should -BeTrue + $null -eq $result.DefaultPasswordFound | Should -BeTrue + } + } + + It 'preserves password findings before or after an unreadable or malformed GPT.INI' -ForEach @( + @{ IniFirst = $true; Failure = 'Read' } + @{ IniFirst = $false; Failure = 'Read' } + @{ IniFirst = $true; Failure = 'Parse' } + @{ IniFirst = $false; Failure = 'Parse' } + ) { + $script:iniFirst = $IniFirst + $script:iniFailure = $Failure + Mock Test-MtSysvolWindowsPlatform -ModuleName Maester { $true } + Mock Invoke-MtSysvolWindowsAdapter -ModuleName Maester { + if ($Operation -eq 'List') { + $ini = [pscustomobject]@{ RelativePath = 'GPT.INI'; Length = 20 } + $xml = [pscustomobject]@{ RelativePath = 'Machine/Preferences/Groups/Groups.xml'; Length = 50 } + if ($script:iniFirst) { return @($ini, $xml) } + return @($xml, $ini) + } + if ($Operation -eq 'ReadText') { + if ($RelativePath -eq 'GPT.INI') { + if ($script:iniFailure -eq 'Read') { throw 'SECRET-MUST-NOT-PRINT' } + return '[General] Version=not-a-version' + } + return '' + } + return $true + } + InModuleScope Maester { + $result = Get-MtSysvolContent -GpoGuid '11111111-1111-1111-1111-111111111111' + $result.CpasswordFound | Should -BeTrue + $null -eq $result.DefaultPasswordFound | Should -BeTrue + @($result.ScanErrors | Where-Object { $_ -eq 'GPT.INI' }) | Should -HaveCount 1 + ($result | ConvertTo-Json -Depth 10) | Should -Not -Match 'SECRET-MUST-NOT-PRINT' + } + } + + It 'does not let a nested GPT.INI overwrite the root version' { + Mock Test-MtSysvolWindowsPlatform -ModuleName Maester { $true } + Mock Invoke-MtSysvolWindowsAdapter -ModuleName Maester { + if ($Operation -eq 'List') { return @([pscustomobject]@{ RelativePath = 'GPT.INI'; Length = 20 }, [pscustomobject]@{ RelativePath = 'Machine/GPT.INI'; Length = 20 }) } + if ($Operation -eq 'ReadText') { if ($RelativePath -eq 'GPT.INI') { return "[General]`nVersion=1" }; return "[General]`nVersion=99" } + return $true + } + InModuleScope Maester { + $result = Get-MtSysvolContent -GpoGuid '11111111-1111-1111-1111-111111111111' + $result.GptIni.Version | Should -Be 1 + $result.ScanErrors | Should -HaveCount 0 + } + } + It 'uses the Unix adapter with the same normalized file contract' { Mock Test-MtSysvolWindowsPlatform -ModuleName Maester { $false } Mock Invoke-MtSysvolUnixAdapter -ModuleName Maester { diff --git a/powershell/tests/functions/ADGpoInventory.Tests.ps1 b/powershell/tests/functions/ADGpoInventory.Tests.ps1 new file mode 100644 index 0000000000..3115cbd788 --- /dev/null +++ b/powershell/tests/functions/ADGpoInventory.Tests.ps1 @@ -0,0 +1,133 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'AD GPO version normalization' { + It 'normalizes signed directory versions and preserves missing values' -ForEach @( + @{ Raw = -1; Expected = 4294967295L } + @{ Raw = 65538; Expected = 65538L } + @{ Raw = $null; Expected = $null } + ) { + InModuleScope Maester -Parameters @{ Raw = $Raw; Expected = $Expected } { + param($Raw, $Expected) + $script:rawVersion = $Raw + Mock Invoke-MtLdapSearch { + [PSCustomObject]@{ + name = '{11111111-1111-1111-1111-111111111111}' + displayName = 'Policy' + versionNumber = $script:rawVersion + ntSecurityDescriptor = $null + } + } + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') + try { + $gpo = @(Get-MtLdapGpo -Connection $connection -SearchBase 'DC=example,DC=com')[0] + if ($null -eq $Expected) { + $null -eq $gpo.VersionNumber | Should -BeTrue + $null -eq $gpo.UserVersion | Should -BeTrue + $null -eq $gpo.ComputerVersion | Should -BeTrue + } + else { $gpo.VersionNumber | Should -Be $Expected } + } + finally { $connection.Dispose() } + } + } +} + +Describe 'AD GPO modification age and link inventories' { + BeforeEach { + $script:now = [DateTimeOffset]'2026-11-08T12:00:00+00:00' + $script:state = [pscustomobject]@{ + GPOs = @([pscustomobject]@{ + Id = '{11111111-1111-1111-1111-111111111111}' + DisplayName = 'Policy | pilot' + CreationTime = [datetime]::new(2000, 1, 1, 0, 0, 0, [DateTimeKind]::Utc) + ModificationTime = [datetime]::new(2026, 1, 1, 0, 0, 0, [DateTimeKind]::Utc) + }) + 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]::new(2021, 11, 8, 11, 59, 59, [DateTimeKind]::Utc) + InModuleScope Maester { Test-MtAdGpoStale | Should -BeFalse } + } + + It 'accepts a modification exactly at the cutoff' { + $script:state.GPOs[0].ModificationTime = $script:now.UtcDateTime.AddYears(-5) + InModuleScope Maester { Test-MtAdGpoStale | Should -BeTrue } + } + + It 'honors a configurable age limit' { + $script:state.GPOs[0].ModificationTime = [datetime]::new(2022, 1, 1, 0, 0, 0, [DateTimeKind]::Utc) + InModuleScope Maester { Test-MtAdGpoStale -MaximumModificationAgeYears 3 | Should -BeFalse } + } + + It 'rejects invalid age limits' { + InModuleScope Maester { { Test-MtAdGpoStale -MaximumModificationAgeYears 0 } | Should -Throw } + } + + It 'errors on missing modification dates' { + $script:state.GPOs[0].ModificationTime = $null + InModuleScope Maester { { Test-MtAdGpoStale } | Should -Throw '*no modification date*' } + } + + It 'uses the exact UTC cutoff with a non-UTC clock' { + $script:now = [DateTimeOffset]'2026-11-20T12:00:00-05:00' + $script:state.GPOs[0].ModificationTime = [datetime]::new(2021, 11, 20, 14, 0, 0, [DateTimeKind]::Utc) + InModuleScope Maester { Test-MtAdGpoStale | Should -BeFalse } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Result -match '2021-11-20 17' } + $script:state.GPOs[0].ModificationTime = [datetime]::new(2021, 11, 20, 17, 0, 0, [DateTimeKind]::Utc) + InModuleScope Maester { Test-MtAdGpoStale | Should -BeTrue } + } + + It 'errors on an empty inventory instead of passing' { + $script:state.GPOs = @() + InModuleScope Maester { { Test-MtAdGpoStale } | Should -Throw '*inventory is empty*' } + } + + 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 the GPO inventory' { + InModuleScope Maester { Test-MtAdGpoTotalCount | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + } + + 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' -and $Result -match 'OUs with direct links \| 0' + } + } + + It 'counts OUs with direct links without claiming effective coverage' { + $script:state.LinkContainers[0].GpLink = '[LDAP://CN={11111111-1111-1111-1111-111111111111},CN=Policies,DC=example,DC=com;1]' + InModuleScope Maester { Test-MtAdGpoUnlinkedTargetCount | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate -and $Result -match 'OUs with direct links \| 1' } + } +} diff --git a/powershell/tests/functions/ADGpoOutput.Tests.ps1 b/powershell/tests/functions/ADGpoOutput.Tests.ps1 new file mode 100644 index 0000000000..143e6ea5b6 --- /dev/null +++ b/powershell/tests/functions/ADGpoOutput.Tests.ps1 @@ -0,0 +1,386 @@ +BeforeDiscovery { + $guideRoot = (Resolve-Path "$PSScriptRoot/../../../tests/ad").Path + $script:guideCases = @(Get-ChildItem "$guideRoot/gpo", "$guideRoot/gpo-state" -Filter 'Test.*.md' -File | ForEach-Object { + @{ GuidePath = $_.FullName; GuideName = $_.Name; TestPath = [System.IO.Path]::ChangeExtension($_.FullName, '.ps1'); TestId = $_.BaseName.Substring(5) } + }) + $script:checks = @( + @{ Command = 'Test-MtAdGpoTotalCount'; Investigate = $true; Details = $false } + @{ Command = 'Test-MtAdGpoStale'; Investigate = $false; Details = $true } + @{ Command = 'Test-MtAdGpoUnlinkedCount'; Investigate = $false; Details = $false } + @{ Command = 'Test-MtAdGpoLinkedCount'; Investigate = $true; Details = $true } + @{ Command = 'Test-MtCheckADGPOL02'; Investigate = $false; Details = $false } + @{ Command = 'Test-MtAdGpoUnlinkedTargetCount'; Investigate = $true; Details = $false } + @{ Command = 'Test-MtAdGpoEnforcedCount'; Investigate = $false; Details = $false } + @{ Command = 'Test-MtAdGpoBlockedInheritanceCount'; Investigate = $false; Details = $false } + @{ Command = 'Test-MtAdGpoNoPermissionsCount'; Investigate = $false; Details = $false } + @{ Command = 'Test-MtAdGpoNoAuthenticatedUsersCount'; Investigate = $false; Details = $false } + @{ Command = 'Test-MtAdGpoNoEnterpriseDcCount'; Investigate = $false; Details = $false } + @{ Command = 'Test-MtAdGpoNoDomainComputersCount'; Investigate = $false; Details = $false } + @{ Command = 'Test-MtAdGpoDenyAceCount'; Investigate = $false; Details = $false } + @{ Command = 'Test-MtAdGpoInheritedPermissionsCount'; Investigate = $false; Details = $false } + @{ Command = 'Test-MtAdGpoNoApplyGroupPolicyAceCount'; Investigate = $false; Details = $false } + @{ Command = 'Test-MtCheckADGPOREP12'; Investigate = $true; Details = $false } + @{ Command = 'Test-MtAdGpoEnforcementCount'; Investigate = $true; Details = $false } + @{ Command = 'Test-MtAdGpoVersionMismatchCount'; Investigate = $false; Details = $false } + @{ Command = 'Test-MtAdGpoCpasswordFoundCount'; Investigate = $false; Details = $false } + @{ Command = 'Test-MtAdGpoWmiFilterCount'; Investigate = $true; Details = $false } + @{ Command = 'Test-MtAdGpoSettingsDisabledCount'; Investigate = $true; Details = $false } + @{ Command = 'Test-MtAdGpoOwnerDistinctCount'; Investigate = $true; Details = $true } + ) +} + +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'Group Policy guide context' { + It 'discovers the complete set of Group Policy guides' -ForEach @(@{ DiscoveredCount = $script:guideCases.Count }) { + $DiscoveredCount | Should -Be 22 + $paths = Get-ChildItem "$PSScriptRoot/../../../tests/ad/gpo", "$PSScriptRoot/../../../tests/ad/gpo-state" -Filter 'Test.*.md' -File + $paths.Count | Should -Be 22 + } + + It ' retains explanatory context and the results footer' -ForEach $script:guideCases { + $text = Get-Content -LiteralPath $GuidePath -Raw + $text.Split([string[]]@('####'), [System.StringSplitOptions]::None)[0].Trim() | Should -Not -BeNullOrEmpty + foreach ($heading in 'Control Type', 'Why This Test Matters', 'Security Recommendation', 'How the Test Works', 'Remediation action', 'Related Tests', 'Related links') { + $pattern = '(?ms)^#### ' + [regex]::Escape($heading) + '\s*\r?\n(?.*?)(?=^#### |\z)' + $section = [regex]::Match($text, $pattern) + $section.Success | Should -BeTrue -Because "the guide must explain $heading, not just the result layout" + $section.Groups['body'].Value.Trim() | Should -Not -BeNullOrEmpty + } + [regex]::Matches($text, '').Count | Should -Be 1 + $text | Should -Match '\s*%TestResult%\s*$' + $text | Should -Match '\*\*(Detective|Operational)\*\*' + $ids = @((Get-ChildItem "$PSScriptRoot/../../../tests/ad/gpo", "$PSScriptRoot/../../../tests/ad/gpo-state" -Filter 'Test.*.md' -File).BaseName | ForEach-Object { $_.Substring(5) }) + foreach ($id in [regex]::Matches($text, 'AD-GPO(?:REP|L|S)?-\d+') | ForEach-Object Value) { + $ids | Should -Contain $id -Because 'related test references must not point at retired IDs' + } + } + + It ' documents each related test with its name, ID and relationship' -ForEach $script:guideCases { + $text = Get-Content -LiteralPath $GuidePath -Raw + $related = [regex]::Match($text, '(?ms)^#### Related Tests\s*\r?\n(?.*?)(?=^#### |\z)').Groups['body'].Value + $entries = [regex]::Matches($related, '(?ms)^- (?.*?)(?=^- |\z)') + $entries.Count | Should -BeGreaterThan 0 + foreach ($entry in $entries) { + $value = $entry.Groups['entry'].Value.Trim() + $ids = [regex]::Matches($value, 'AD-GPO(?:REP|L|S)?-\d+') | ForEach-Object Value | Select-Object -Unique + @($ids).Count | Should -Be 1 -Because 'each related test needs its own complete entry' + $id = @($ids)[0] + $path = Get-ChildItem "$PSScriptRoot/../../../tests/ad/gpo", "$PSScriptRoot/../../../tests/ad/gpo-state" -Filter "Test.$id.ps1" -File | Select-Object -First 1 + $source = Get-Content -LiteralPath $path.FullName -Raw + $name = [regex]::Match($source, '(?m)^function\s+(\S+)\s*\{').Groups[1].Value + $title = [regex]::Match($source, "\bTitle\s*=\s*'([^']+)'").Groups[1].Value + $value | Should -Match ([regex]::Escape($name)) + $value | Should -Match ([regex]::Escape($title)) + $value | Should -Match ([regex]::Escape('`' + $name + '`') + '\)\s+(?:—\s*)?\S.+') -Because 'the reference must explain its relationship after the function name' + } + } + + It ' retains examples, a test-page link and readable metadata formatting' -ForEach $script:guideCases { + $tokens = $null + $errors = $null + $ast = [System.Management.Automation.Language.Parser]::ParseFile($TestPath, [ref]$tokens, [ref]$errors) + $errors | Should -BeNullOrEmpty + $function = $ast.Find({ param($node) $node -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true) + $function.GetHelpContent().Examples.Count | Should -BeGreaterThan 0 + $source = Get-Content -LiteralPath $TestPath -Raw + $source | Should -Match ([regex]::Escape("Invoke-MtTest -Id '$TestId'")) + $source | Should -Match '(?im)^\s*\.LINK\s*$' + $source | Should -Match ([regex]::Escape("https://maester.dev/docs/tests/$TestId")) + $attribute = $ast.Find({ param($node) $node -is [System.Management.Automation.Language.AttributeAst] -and $node.TypeName.FullName -eq 'MaesterTest' }, $true) + $lines = @($attribute.NamedArguments | ForEach-Object { $_.Extent.StartLineNumber }) + @($lines | Select-Object -Unique).Count | Should -Be $lines.Count -Because 'each named attribute must start on its own line' + foreach ($argument in $attribute.NamedArguments) { + $line = (Get-Content -LiteralPath $TestPath)[$argument.Extent.StartLineNumber - 1] + $line | Should -Match '^ \w+\s+=\s+' + } + } +} + +Describe 'Native Group Policy results' { + BeforeEach { + $script:detail = $null + $script:report = [pscustomobject]@{ + Name = 'Policy | ' + PermissionsPresent = $true + HasAuthenticatedUsers = $true + HasEnterpriseDomainControllers = $true + HasDomainComputers = $true + HasDenyAce = $false + HasInheritedPermissions = $false + HasApplyGroupPolicyAce = $true + Enforcement = $false + HasVersionMismatch = $false + DirectoryVersion = 1 + SysvolVersion = 1 + CpasswordFound = $false + DefaultPasswordFound = $false + Errors = @() + } + $linkText = '[LDAP://CN={11111111-1111-1111-1111-111111111111},CN=Policies,DC=example,DC=com;0]' + $script:state = [pscustomobject]@{ + GPOs = @([pscustomobject]@{ + Id = '11111111-1111-1111-1111-111111111111' + DisplayName = 'Policy | ' + CreationTime = [datetime]'2026-01-01' + ModificationTime = [datetime]'2026-01-01' + WmiFilter = '' + GpoStatus = 3 + Owner = 'CONTOSO\PolicyOwner' + }) + GPOReports = @($script:report) + GPOLinks = @([pscustomobject]@{ GpoGuid = '11111111-1111-1111-1111-111111111111'; GpLink = $linkText; IsDisabled = $false; IsEnforced = $false }) + LinkContainers = @([pscustomobject]@{ ObjectClass = @('organizationalUnit'); DistinguishedName = 'OU=Pilot|test,DC=example,DC=com'; GpLink = $linkText; GpOptions = 0 }) + SiteContainers = @() + } + Mock Get-MtADGpoState -ModuleName Maester { $script:state } + Mock Get-Date -ModuleName Maester { [datetime]'2026-11-19T12:00:00' } + Mock Add-MtTestResultDetail -ModuleName Maester { + $script:detail = [pscustomobject]@{ Result = $Result; Investigate = [bool]$Investigate; Skip = $SkippedBecause } + } + } + + It ' uses the common layout without empty detail tables' -ForEach $script:checks { + InModuleScope Maester -Parameters @{ Command = $Command } { param($Command) & $Command | Should -BeTrue } + $script:detail.Investigate | Should -Be $Investigate + $script:detail.Result | Should -Match '\| Metric \| Value \|' + $script:detail.Result | Should -Not -Match 'GPO Reports' + ($script:detail.Result -match '#### Details') | Should -Be $Details + $lines = $script:detail.Result -split '\r?\n' + for ($i = 0; $i -lt $lines.Count; $i++) { + if ($lines[$i] -match '^\| ---') { $lines[$i + 1] | Should -Match '^\| .+ \|$' -Because 'every table header must be followed by a data row' } + } + } + + It 'reports zero disabled links clearly in both shared-helper tests' -ForEach @('Test-MtCheckADGPOL02', 'Test-MtCheckADGPOREP12') { + InModuleScope Maester -Parameters @{ Command = $_ } { param($Command) & $Command | Should -BeTrue } + $script:detail.Result | Should -Match 'No disabled GPO links were found. All 1 collected links are enabled' + $script:detail.Result | Should -Match 'Enabled GPO links \| 1' + $script:detail.Result | Should -Match 'Disabled GPO links \| 0' + $script:detail.Result | Should -Not -Match '#### Details|Review 0' + } + + It 'shows the WMI filter reference and count when a filter is present' { + $script:state.GPOs[0].WmiFilter = 'Filter | ' + InModuleScope Maester { Test-MtAdGpoWmiFilterCount | Should -BeTrue } + $script:detail.Investigate | Should -BeTrue + $script:detail.Result | Should -Match 'GPOs with WMI filters \| 1' + $script:detail.Result | Should -Match 'Filter | <reference>' + } + + It 'counts all disabled categories once and lists readable status labels' { + $script:state.GPOs = @(0..3 | ForEach-Object { [pscustomobject]@{ DisplayName = "Policy $_"; Id = "id$_"; GpoStatus = $_ } }) + InModuleScope Maester { Test-MtAdGpoSettingsDisabledCount | Should -BeTrue } + $script:detail.Result | Should -Match 'GPOs with disabled settings \| 3' + $script:detail.Result | Should -Match 'Only user settings disabled \| 1' + $script:detail.Result | Should -Match 'Only computer settings disabled \| 1' + $script:detail.Result | Should -Match 'All settings disabled \| 1' + $script:detail.Result | Should -Not -Match '\| Policy 3 \|' + } + + It 'matches named statuses exactly and reports unrecognized statuses as unknown' { + $script:state.GPOs = @( + [pscustomobject]@{ DisplayName = 'Named'; Id = 'named'; GpoStatus = 'ComputerDisabled' } + [pscustomobject]@{ DisplayName = 'Unknown'; Id = 'unknown'; GpoStatus = 'NotComputerDisabled' } + ) + InModuleScope Maester { Test-MtAdGpoSettingsDisabledCount | Should -BeTrue } + $script:detail.Result | Should -Match 'GPOs with disabled settings \| 1' + $script:detail.Result | Should -Match 'GPOs with unknown status \| 1' + $script:detail.Result | Should -Match 'Unknown \| unknown \| Unknown' + } + + It 'lists unresolved owners without counting them as known owners' { + $script:state.GPOs += [pscustomobject]@{ DisplayName = 'Unreadable | GPO'; Owner = $null } + InModuleScope Maester { Test-MtAdGpoOwnerDistinctCount | Should -BeTrue } + $script:detail.Result | Should -Match 'Distinct known owners \| 1' + $script:detail.Result | Should -Match 'GPOs with unknown owners \| 1' + $script:detail.Result | Should -Match 'Unknown \| 1 \| Unreadable | GPO' + } + + It 'does not treat an unknown alternative computer-access principal as clean' -ForEach @( + @{ Computers = $false; Authenticated = $null; Expected = $true; Investigate = $true; Details = $true } + @{ Computers = $false; Authenticated = $false; Expected = $false; Investigate = $false; Details = $true } + @{ Computers = $false; Authenticated = $true; Expected = $true; Investigate = $false; Details = $false } + @{ Computers = $null; Authenticated = $true; Expected = $true; Investigate = $false; Details = $false } + ) { + $script:state.GPOReports += [pscustomobject]@{ Name = 'Alternative | GPO'; HasDomainComputers = $Computers; HasAuthenticatedUsers = $Authenticated } + InModuleScope Maester -Parameters @{ Expected = $Expected } { param($Expected) Test-MtAdGpoNoDomainComputersCount | Should -Be $Expected } + $script:detail.Investigate | Should -Be $Investigate + ($script:detail.Result -match '#### Details') | Should -Be $Details + if ($Investigate) { $script:detail.Result | Should -Match 'Alternative | GPO \| Unknown' } + } + + It 'fails enforced links and lists the affected container' { + $script:state.GPOLinks[0].IsEnforced = $true + $script:state.GPOLinks[0] | Add-Member -NotePropertyName DistinguishedName -NotePropertyValue 'OU=Pilot|test,DC=example,DC=com' + InModuleScope Maester { Test-MtAdGpoEnforcedCount | Should -BeFalse } + $script:detail.Result | Should -Match 'Enforced GPO links \| 1' + $script:detail.Result | Should -Match 'OU=Pilot|test' + } + + It 'does not count disabled links as enabled links' { + $script:state.GPOLinks[0].IsDisabled = $true + InModuleScope Maester { Test-MtAdGpoLinkedCount | Should -BeTrue } + $script:detail.Result | Should -Match 'GPOs with enabled links \| 0' + $script:detail.Result | Should -Not -Match '#### Details' + } + + It 'errors rather than reporting zero when link collection failed' -ForEach @('Test-MtAdGpoLinkedCount', 'Test-MtAdGpoEnforcedCount') { + $script:state.GPOLinks = $null + InModuleScope Maester -Parameters @{ Command = $_ } { + param($Command) + $script:commandUnderTest = $Command + { & $script:commandUnderTest } | Should -Throw '*could not be collected*' + } + } + + It 'does not treat unknown enforcement as zero in the GPO inventory' { + $script:state.GPOLinks[0].IsEnforced = $null + InModuleScope Maester { Test-MtAdGpoEnforcementCount | Should -BeTrue } + $script:detail.Investigate | Should -BeTrue + $script:detail.Result | Should -Match 'GPOs with unknown enforcement \| 1' + $script:detail.Result | Should -Match 'Policy | <pilot> \| Unknown' + $script:detail.Result | Should -Not -Match 'No collected GPO has an enforced link' + } + + It 'treats unlinked GPOs as known unenforced when link collection succeeded' { + $script:state.GPOLinks = @() + $script:report.Enforcement = $null + InModuleScope Maester { Test-MtAdGpoEnforcementCount | Should -BeTrue } + $script:detail.Result | Should -Match 'GPOs with unknown enforcement \| 0' + $script:detail.Result | Should -Match 'No collected GPO has an enforced link' + $script:detail.Result | Should -Not -Match '#### Details' + } + + It 'keeps enforcement unknown when link collection failed' { + $script:state.GPOLinks = $null + InModuleScope Maester { Test-MtAdGpoEnforcementCount | Should -BeTrue } + $script:detail.Result | Should -Match 'GPOs with unknown enforcement \| 1' + $script:detail.Result | Should -Match 'could not be determined for any collected GPO' + $script:detail.Result | Should -Not -Match 'No enforced links were found among evaluated GPOs' + $script:detail.Result | Should -Match '#### Details' + } + + It 'does not imply evaluated settings when every GPO status is unknown' { + $script:state.GPOs[0].GpoStatus = $null + InModuleScope Maester { Test-MtAdGpoSettingsDisabledCount | Should -BeTrue } + $script:detail.Result | Should -Match 'Settings status could not be determined for any collected GPO' + $script:detail.Result | Should -Match 'GPOs with unknown status \| 1' + } + + It 'counts each GPO once even when several of its links are enforced' { + $script:state.GPOLinks[0].IsEnforced = $true + $script:state.GPOLinks += $script:state.GPOLinks[0].PSObject.Copy() + InModuleScope Maester { Test-MtAdGpoEnforcementCount | Should -BeTrue } + $script:detail.Result | Should -Match 'GPOs with enforced links \| 1' + } + + It 'treats incomplete maps as unknown unless a known enforced link proves the finding' { + $script:state | Add-Member -NotePropertyName GPOLinksComplete -NotePropertyValue $false + InModuleScope Maester { Test-MtAdGpoEnforcementCount | Should -BeTrue } + $script:detail.Result | Should -Match 'GPOs with unknown enforcement \| 1' + $script:state.GPOLinks[0].IsEnforced = $true + InModuleScope Maester { Test-MtAdGpoEnforcementCount | Should -BeTrue } + $script:detail.Result | Should -Match 'GPOs with enforced links \| 1' + $script:detail.Result | Should -Match 'GPOs with unknown enforcement \| 0' + } + + It 'preserves OU metrics when site collection alone failed' { + $script:state.SiteContainers = $null + InModuleScope Maester { Test-MtAdGpoUnlinkedTargetCount | Should -BeTrue } + $script:detail.Investigate | Should -BeTrue + $script:detail.Result | Should -Match 'Partial inventory' + $script:detail.Result | Should -Match 'OUs with direct links \| 1' + $script:detail.Result | Should -Match 'Total sites \| Unknown' + $script:detail.Result | Should -Match 'Targets without direct links \| Unknown' + } + + It 'distinguishes configured disabled flags from enabled enforcement overrides' -ForEach @( + @{ Options = 2; Disabled = $false; State = 'Enabled'; Active = 1 } + @{ Options = 3; Disabled = $true; State = 'Disabled'; Active = 0 } + ) { + $script:state.GPOLinks[0].IsEnforced = $true + $script:state.GPOLinks[0].IsDisabled = $Disabled + $script:state.GPOLinks[0] | Add-Member -NotePropertyName Options -NotePropertyValue $Options + InModuleScope Maester { Test-MtAdGpoEnforcedCount | Should -BeFalse } + $script:detail.Result | Should -Match "Enabled enforcement overrides \| $Active" + $script:detail.Result | Should -Match "\| $State \|" + $script:detail.Result | Should -Match 'Disabled links do not actively override inheritance' + } + + It 'does not declare missing links or absent enforcement from incomplete maps' { + $script:state | Add-Member -NotePropertyName GPOLinksComplete -NotePropertyValue $false + InModuleScope Maester { { Test-MtAdGpoUnlinkedCount } | Should -Throw '*incomplete*' } + InModuleScope Maester { { Test-MtAdGpoEnforcedCount } | Should -Throw '*incomplete*' } + InModuleScope Maester { Test-MtAdGpoLinkedCount | Should -BeTrue } + $script:detail.Result | Should -Match 'Partial link inventory' + $script:detail.Result | Should -Match 'GPOs without enabled links \| Unknown' + InModuleScope Maester { Test-MtCheckADGPOL02 | Should -BeTrue } + $script:detail.Investigate | Should -BeTrue + $script:detail.Result | Should -Match 'Partial link inventory' + $script:detail.Result | Should -Not -Match 'All 1 collected links are enabled' + } + + It 'fails blocked inheritance and errors on missing containers' { + $script:state.LinkContainers[0].GpOptions = 1 + InModuleScope Maester { Test-MtAdGpoBlockedInheritanceCount | Should -BeFalse } + $script:detail.Result | Should -Match 'OU=Pilot|test' + $script:state.LinkContainers = $null + InModuleScope Maester { { Test-MtAdGpoBlockedInheritanceCount } | Should -Throw '*cannot be assessed*' } + } + + It 'does not mistake a settings-status label for proof that a linked GPO is unlinked' { + $script:state.GPOs[0].GpoStatus = 'Unlinked' + InModuleScope Maester { Test-MtAdGpoUnlinkedCount | Should -BeTrue } + } +} + +Describe 'Group Policy result layout' { + It 'requires a Boolean true completeness flag when the field is present' -ForEach @( + @{ Value = $true; Expected = $true } + @{ Value = $false; Expected = $false } + @{ Value = $null; Expected = $false } + @{ Value = 'true'; Expected = $false } + ) { + InModuleScope Maester -Parameters @{ Value = $Value; Expected = $Expected } { + param($Value, $Expected) + Test-MtAdGpoLinksComplete -State ([ordered]@{ GPOLinksComplete = $Value }) | Should -Be $Expected + Test-MtAdGpoLinksComplete -State ([pscustomobject]@{ GPOLinksComplete = $Value }) | Should -Be $Expected + } + } + + It 'preserves compatibility for state objects without a completeness field' { + InModuleScope Maester { + Test-MtAdGpoLinksComplete -State ([ordered]@{ GPOs = @() }) | Should -BeTrue + Test-MtAdGpoLinksComplete -State ([pscustomobject]@{ GPOs = @() }) | Should -BeTrue + } + } + It 'renders zero metrics without an empty detail table' { + InModuleScope Maester { + $result = Format-MtAdGpoResult -Summary 'No disabled links found.' -Metrics ([ordered]@{ 'Total links' = 2; 'Disabled links' = 0 }) -Details @() -Properties Name + $result | Should -Match 'No disabled links found' + $result | Should -Match 'Disabled links \| 0' + $result | Should -Not -Match '#### Details|\| Name \|' + } + } + + It 'renders one consistent non-empty detail table and escapes every cell' { + InModuleScope Maester { + $result = Format-MtAdGpoResult -Summary 'Review one policy.' -Metrics ([ordered]@{ 'Total GPOs' = 1 }) -Details @([pscustomobject]@{ Name = "Policy | `nsecond line"; Flag = $false }) -Properties Name, Flag -Headers GPO, Finding + $result | Should -Match '#### Details' + $result | Should -Match '\| GPO \| Finding \|' + $result | Should -Match 'Policy | <test> second line \| False' + } + } + + It 'distinguishes unknown values from zero and false' { + InModuleScope Maester { + $result = Format-MtAdGpoResult -Summary 'Review collection.' -Metrics ([ordered]@{ Known = 0; Unknown = $null }) -Details @([pscustomobject]@{ Name = 'Policy'; Unknown = $null }) -Properties Name, Unknown + $result | Should -Match 'Known \| 0' + $result | Should -Match 'Unknown \| Unknown' + $result | Should -Match 'Policy \| Unknown' + } + } +} diff --git a/powershell/tests/functions/ADGpoReports.Tests.ps1 b/powershell/tests/functions/ADGpoReports.Tests.ps1 new file mode 100644 index 0000000000..297dd3c81f --- /dev/null +++ b/powershell/tests/functions/ADGpoReports.Tests.ps1 @@ -0,0 +1,151 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'Merged AD Group Policy checks' { + BeforeEach { + $script:report = [PSCustomObject]@{ + Name = 'Example | GPO' + CpasswordFound = $false + DefaultPasswordFound = $false + HasVersionMismatch = $false + DirectoryVersion = 65538 + SysvolVersion = 65538 + Errors = @() + HasApplyGroupPolicyAce = $true + PermissionsPresent = $true + HasAuthenticatedUsers = $true + HasDenyAce = $false + } + $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 { } + } + + It 'passes only after both secret scan flags are evaluated' { + InModuleScope Maester { Test-MtAdGpoCpasswordFoundCount | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Result -match 'Well done' } + } + + 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' + InModuleScope Maester { Test-MtAdGpoCpasswordFoundCount | Should -BeFalse } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { + $Result -match 'Example | GPO' -and $Result -notmatch 'SECRET-MUST-NOT-PRINT' + } + } + + It 'fails on a default password alone' { + $script:report.DefaultPasswordFound = $true + InModuleScope Maester { Test-MtAdGpoCpasswordFoundCount | Should -BeFalse } + } + + It 'fails once for a policy exposing both password types' { + $script:report.CpasswordFound = $true + $script:report.DefaultPasswordFound = $true + InModuleScope Maester { Test-MtAdGpoCpasswordFoundCount | Should -BeFalse } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { + $Result -match '1 of 1 GPOs expose passwords' -and + [regex]::Matches($Result, '(?m)^\| Example | GPO \|').Count -eq 1 + } + } + + It 'does not hide a known secret behind another incomplete scan' { + $script:report.CpasswordFound = $true + $script:report.DefaultPasswordFound = $null + $script:report.Errors = @('unreadable file') + InModuleScope Maester { Test-MtAdGpoCpasswordFoundCount | Should -BeFalse } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Result -match 'Unknown' -and $Result -match 'incomplete for 1 GPOs' } + } + + It 'errors on incomplete scans without findings' -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 = @('failed') } + } + InModuleScope Maester { { Test-MtAdGpoCpasswordFoundCount } | Should -Throw '*incomplete*' } + } + + It 'errors if report collection silently drops a GPO' { + $script:state.GPOs += [PSCustomObject]@{ Id = '00000000-0000-0000-0000-000000000002' } + InModuleScope Maester { { Test-MtAdGpoCpasswordFoundCount } | Should -Throw '*inventory*' } + } + + It 'shows both versions for mismatched policies' { + $script:report.HasVersionMismatch = $true + $script:report.SysvolVersion = 65539 + InModuleScope Maester { Test-MtAdGpoVersionMismatchCount | Should -BeFalse } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Result -match '65538 \| 65539' } + } + + It 'passes matching versions' { + InModuleScope Maester { Test-MtAdGpoVersionMismatchCount | Should -BeTrue } + } + + It 'does not pass when a version is missing' -ForEach @('DirectoryVersion', 'SysvolVersion') { + $script:report.$_ = $null + InModuleScope Maester { { Test-MtAdGpoVersionMismatchCount } | Should -Throw '*incomplete*' } + } + + It 'passes when application rights are present' { + InModuleScope Maester { Test-MtAdGpoNoApplyGroupPolicyAceCount | Should -BeTrue } + Should -Not -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + } + + It 'fails when application rights are absent and lists affected policies' { + $script:report.HasApplyGroupPolicyAce = $false + InModuleScope Maester { Test-MtAdGpoNoApplyGroupPolicyAceCount | Should -BeFalse } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Result -match 'Example | GPO' -and -not $Investigate } + } + + It 'errors rather than passing when application rights are unreadable' { + $script:report.HasApplyGroupPolicyAce = $null + InModuleScope Maester { { Test-MtAdGpoNoApplyGroupPolicyAceCount } | Should -Throw '*could not be evaluated*' } + } + + It 'fails on deny ACEs and lists affected policies' { + $script:report.HasDenyAce = $true + InModuleScope Maester { Test-MtAdGpoDenyAceCount | Should -BeFalse } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Result -match 'Example | GPO' -and -not $Investigate } + } + + It 'does not pass unreadable deny ACEs' { + $script:state.GPOReports += [PSCustomObject]@{ Name = 'Unreadable'; HasDenyAce = $null } + InModuleScope Maester { Test-MtAdGpoDenyAceCount | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate -and $Result -match 'Unreadable' } + } + + It 'inventories disabled and enforced links with their linked containers' { + $script:state.GPOLinks = @([PSCustomObject]@{ + GpoGuid = '00000000-0000-0000-0000-000000000001' + DistinguishedName = 'OU=Clients,DC=example,DC=com' + Options = 3 + IsDisabled = $true + IsEnforced = $true + }) + InModuleScope Maester { Test-MtCheckADGPOREP12 | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { + $Investigate -and $Result -match '1 of 1 GPO links are disabled' -and $Result -match 'OU=Clients' + } + } + + It 'preserves the shared disabled-link helper default outcome' { + InModuleScope Maester { Test-MtAdGpoDisabledLinkCount | Should -BeTrue } + Should -Not -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + } + + It 'errors on missing link collection instead of reporting zero disabled links' { + $script:state.GPOLinks = $null + InModuleScope Maester { { Test-MtCheckADGPOREP12 } | Should -Throw '*cannot inventory*' } + } +} diff --git a/powershell/tests/functions/ActiveDirectoryGpoPermissions.Tests.ps1 b/powershell/tests/functions/ActiveDirectoryGpoPermissions.Tests.ps1 index 0e73dbb18f..64e00c806a 100644 --- a/powershell/tests/functions/ActiveDirectoryGpoPermissions.Tests.ps1 +++ b/powershell/tests/functions/ActiveDirectoryGpoPermissions.Tests.ps1 @@ -3,9 +3,7 @@ # 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' } @{ 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 +14,8 @@ 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-MtAdGpoNoPermissionsCount, + Test-MtAdGpoNoAuthenticatedUsersCount, Test-MtAdGpoNoEnterpriseDcCount, Test-MtAdGpoNoDomainComputersCount, Test-MtAdGpoInheritedPermissionsCount $script:domainSid = 'S-1-5-21-1111111111-2222222222-3333333333' @@ -173,6 +171,149 @@ Describe 'Active Directory GPO permissions' { } } + Context 'GPO version and SYSVOL collection' { + It 'treats whitespace-only link attributes as a complete empty map' { + $script:testGpos = @(New-TestGpo -PermissionProfile 'Default') + Mock Get-MtLdapGpoLink -ModuleName Maester -RemoveParameterType Connection { + [pscustomobject]@{ DistinguishedName = 'OU=Empty,DC=contoso,DC=com'; ObjectClass = @('organizationalUnit'); GpLink = ' ' } + } + $state = Get-MtADGpoState + $state.GPOLinksComplete | Should -BeTrue + @($state.GPOLinks) | Should -HaveCount 0 + $state.GPOReports[0].Enforcement | Should -BeFalse + $state.GPOReports[0].DisabledLinks | Should -Be 0 + } + + It 'marks malformed link data incomplete without losing valid entries: ' -ForEach @( + @{ Location = 'Domain'; Malformed = '[LDAP://CN=NoGuid,DC=contoso,DC=com;2]' } + @{ Location = 'Site'; Malformed = '[LDAP://CN=NoGuid,DC=contoso,DC=com;2]' } + @{ Location = 'Domain'; Malformed = 'unparsed non-whitespace' } + @{ Location = 'Site'; Malformed = 'unparsed non-whitespace' } + @{ Location = 'Domain'; Malformed = '[LDAP://CN={11111111-1111-1111-1111-111111111111},DC=contoso,DC=com;999999999999999999999]' } + @{ Location = 'Site'; Malformed = '[LDAP://CN={11111111-1111-1111-1111-111111111111},DC=contoso,DC=com;not-a-number]' } + @{ Location = 'Domain'; Malformed = '[LDAP://CN={11111111-1111-1111-1111-111111111111},DC=contoso,DC=com;4]' } + ) { + $script:testGpos = @((New-TestGpo -PermissionProfile 'Default'), (New-TestGpo -PermissionProfile 'Default')) + $script:linkText = "[LDAP://CN={$($script:testGpos[0].Id)},CN=Policies,DC=contoso,DC=com;3]$Malformed" + if ($Location -eq 'Domain') { + Mock Get-MtLdapGpoLink -ModuleName Maester -RemoveParameterType Connection { [pscustomobject]@{ DistinguishedName = 'OU=Test,DC=contoso,DC=com'; ObjectClass = @('organizationalUnit'); GpLink = $script:linkText } } + } + else { + Mock Get-MtLdapSiteContainer -ModuleName Maester -RemoveParameterType Connection { [pscustomobject]@{ DistinguishedName = 'CN=TestSite,CN=Sites,CN=Configuration,DC=contoso,DC=com'; ObjectClass = @('site'); GpLink = $script:linkText } } + } + $state = Get-MtADGpoState + $state.GPOLinksComplete | Should -BeFalse + @($state.GPOLinks) | Should -HaveCount 1 + $state.GPOReports[0].Enforcement | Should -BeTrue + $state.GPOReports[0].DisabledLinks | Should -Be 1 + $null -eq $state.GPOReports[1].Enforcement | Should -BeTrue + $null -eq $state.GPOReports[1].DisabledLinks | Should -BeTrue + } + + It 'parses the valid link after a malformed prefix independently for ' -ForEach @( + @{ Location = 'Domain'; Part = 'Target' } + @{ Location = 'Site'; Part = 'Target' } + @{ Location = 'Domain'; Part = 'Options' } + @{ Location = 'Site'; Part = 'Options' } + ) { + $script:testGpos = @((New-TestGpo -PermissionProfile 'Default'), (New-TestGpo -PermissionProfile 'Default')) + $prefix = "[LDAP://CN={$($script:testGpos[0].Id)},CN=Policies,DC=contoso,DC=com" + if ($Part -eq 'Options') { $prefix += ';2' } + $script:validLink = "[LDAP://CN={$($script:testGpos[1].Id)},CN=Policies,DC=contoso,DC=com;2]" + $script:linkText = $prefix + $script:validLink + if ($Location -eq 'Domain') { + Mock Get-MtLdapGpoLink -ModuleName Maester -RemoveParameterType Connection { + [pscustomobject]@{ DistinguishedName = 'OU=Test,DC=contoso,DC=com'; ObjectClass = @('organizationalUnit'); GpLink = $script:linkText } + } + } + else { + Mock Get-MtLdapSiteContainer -ModuleName Maester -RemoveParameterType Connection { + [pscustomobject]@{ DistinguishedName = 'CN=TestSite,CN=Sites,CN=Configuration,DC=contoso,DC=com'; ObjectClass = @('site'); GpLink = $script:linkText } + } + } + $state = Get-MtADGpoState + $state.GPOLinksComplete | Should -BeFalse + $null -eq $state.GPOLinks | Should -BeFalse + @($state.GPOLinks) | Should -HaveCount 1 + $state.GPOLinks[0].GpLink | Should -BeExactly $script:validLink + $state.GPOLinks[0].GpoGuid | Should -Be ([guid]$script:testGpos[1].Id) + $state.GPOLinks[0].Options | Should -Be 2 + $state.GPOLinks[0].IsDisabled | Should -BeFalse + $state.GPOLinks[0].IsEnforced | Should -BeTrue + $null -eq $state.GPOReports[0].Enforcement | Should -BeTrue + $state.GPOReports[1].Enforcement | Should -BeTrue + InModuleScope Maester { Test-MtAdGpoEnforcementCount | Should -BeTrue } + $script:resultDetail.Result | Should -Match 'GPOs with unknown enforcement \| 1' + $script:resultDetail.Result | Should -Match 'GPOs with enforced links \| 1' + } + + It 'exposes directory and SYSVOL versions' { + $script:testGpos = @(New-TestGpo -PermissionProfile 'Default') + Mock Get-MtSysvolContent -ModuleName Maester { + [PSCustomObject]@{ GptIni = [PSCustomObject]@{ Version = 2 }; CpasswordFound = $false; DefaultPasswordFound = $false; ScanErrors = @() } + } + $report = @((Get-MtADGpoState).GPOReports)[0] + $report.DirectoryVersion | Should -Be 1 + $report.SysvolVersion | Should -Be 2 + $report.HasVersionMismatch | Should -BeTrue + } + + It 'keeps missing directory versions unknown' { + $script:testGpos = @(New-TestGpo -PermissionProfile 'Default') + $script:testGpos[0].VersionNumber = $null + Mock Get-MtSysvolContent -ModuleName Maester { + [PSCustomObject]@{ GptIni = [PSCustomObject]@{ Version = 2 }; CpasswordFound = $false; DefaultPasswordFound = $false } + } + $report = @((Get-MtADGpoState).GPOReports)[0] + $null -eq $report.DirectoryVersion | Should -BeTrue + $null -eq $report.HasVersionMismatch | Should -BeTrue + } + + It 'does not coerce unknown password scan flags to false' { + $script:testGpos = @(New-TestGpo -PermissionProfile 'Default') + Mock Get-MtSysvolContent -ModuleName Maester { + [PSCustomObject]@{ GptIni = $null; CpasswordFound = $null; DefaultPasswordFound = $null; ScanErrors = @('Groups.xml') } + } + $report = @((Get-MtADGpoState).GPOReports)[0] + $null -eq $report.CpasswordFound | Should -BeTrue + $null -eq $report.DefaultPasswordFound | Should -BeTrue + $report.Errors | Should -HaveCount 1 + } + + It 'does not report failed metadata collection as an empty clean inventory' { + Mock Get-MtLdapGpo -ModuleName Maester -RemoveParameterType Connection { throw 'access denied' } + $null -eq (Get-MtADGpoState).GPOs | Should -BeTrue + $null -eq (Get-MtADGpoState).GPOReports | Should -BeTrue + } + + It 'keeps combined links unavailable if site collection fails' { + Mock Get-MtLdapSiteContainer -ModuleName Maester -RemoveParameterType Connection { throw 'access denied' } + $null -eq (Get-MtADGpoState).GPOLinks | Should -BeTrue + (Get-MtADGpoState).GPOLinksComplete | Should -BeFalse + } + + It 'requires explicit application rights rather than generic administrative grants' -ForEach @( + @{ Rights = 'GenericAll'; ObjectType = '00000000-0000-0000-0000-000000000000'; AceFlags = ''; Expected = $false } + @{ Rights = 'ExtendedRight'; ObjectType = '00000000-0000-0000-0000-000000000000'; AceFlags = ''; Expected = $false } + @{ Rights = 'ExtendedRight'; ObjectType = 'edacfd8f-ffb3-11d1-b41d-00a0c968f939'; AceFlags = ''; Expected = $true } + @{ Rights = 'ExtendedRight'; ObjectType = 'edacfd8f-ffb3-11d1-b41d-00a0c968f939'; AceFlags = 'InheritOnly'; Expected = $false } + ) { + $script:testGpos = @(New-TestGpo -PermissionProfile 'EmptyDacl') + $script:testGpos[0].ntSecurityDescriptor.Access = @(New-TestAce -Sid 'S-1-5-11' -ActiveDirectoryRights $Rights -ObjectType $ObjectType -AceFlags $AceFlags) + @((Get-MtADGpoState).GPOReports)[0].HasApplyGroupPolicyAce | Should -Be $Expected + } + + It 'fails the application-right check when only administrative grants exist for ' -ForEach @( + @{ Profile = 'NoComputerAccess' } + @{ Profile = 'DomainComputers' } + ) { + $script:testGpos = @(New-TestGpo -PermissionProfile $Profile) + @((Get-MtADGpoState).GPOReports)[0].HasApplyGroupPolicyAce | Should -BeFalse + InModuleScope Maester { Test-MtAdGpoNoApplyGroupPolicyAceCount | Should -BeFalse } + $script:resultDetail.Investigate | Should -BeFalse + } + } + Context ' ' -ForEach $permissionTests { It 'Passes when every GPO has the default permissions' { $script:testGpos = @((New-TestGpo -PermissionProfile 'Default'), (New-TestGpo -PermissionProfile 'Default')) @@ -181,8 +322,9 @@ Describe 'Active Directory GPO permissions' { $script:resultDetail.Investigate | Should -BeFalse $script:resultDetail.SkippedBecause | Should -BeNullOrEmpty $script:resultDetail.Result | Should -Not -Match 'GPO Default' - # The pass is for the two GPOs, not for an empty list. The details tests print no total. - if ($Command -like '*Count') { $script:resultDetail.Result | Should -Match 'Total GPO Reports \| 2 \|' } + # A pass must be based on the two collected GPOs, not a vacuous empty set. + $script:resultDetail.Result | Should -Match 'Total GPOs \| 2 \|' + $script:resultDetail.Result | Should -Not -Match '#### Details|GPO Reports' } It 'Fails for the GPO with permissions and not for the others' { @@ -199,7 +341,7 @@ Describe 'Active Directory GPO permissions' { & $Command | Should -BeTrue $script:resultDetail.Investigate | Should -BeTrue - $script:resultDetail.Result | Should -Match 'could not be read' + $script:resultDetail.Result | Should -Match 'could not be determined' $script:resultDetail.Result | Should -Match 'GPO Unreadable' $script:resultDetail.Result | Should -Not -Match 'GPO Default' } @@ -210,7 +352,7 @@ Describe 'Active Directory GPO permissions' { & $Command | Should -BeFalse $script:resultDetail.Investigate | Should -BeFalse $script:resultDetail.Result | Should -Match "GPO $Finding" - $script:resultDetail.Result | Should -Match 'could not be read' + $script:resultDetail.Result | Should -Match 'could not be determined' } It 'Is skipped when ' -ForEach @( @@ -230,22 +372,22 @@ Describe 'Active Directory GPO permissions' { $script:testGpos = @(New-TestGpo -PermissionProfile 'DomainComputers') Test-MtAdGpoNoDomainComputersCount | Should -BeTrue - $script:resultDetail.Result | Should -Match 'GPO Reports Without Domain Computers \| 0 \|' + $script:resultDetail.Result | Should -Match 'GPOs without Domain Computers \| 0 \|' } It 'Reports a GPO without Domain Computers as expected when Authenticated Users has access' { $script:testGpos = @(New-TestGpo -PermissionProfile 'Default') Test-MtAdGpoNoDomainComputersCount | Should -BeTrue - $script:resultDetail.Result | Should -Match 'GPO Reports Without Domain Computers \| 1 \|' - $script:resultDetail.Result | Should -Match 'GPO Reports Without Domain Computers And Without Authenticated Users \| 0 \|' + $script:resultDetail.Result | Should -Match 'GPOs without Domain Computers \| 1 \|' + $script:resultDetail.Result | Should -Match 'GPOs with neither Domain Computers nor Authenticated Users \| 0 \|' } It 'Passes when one GPO has Default permissions and another has DomainComputers' { $script:testGpos = @((New-TestGpo -PermissionProfile 'Default'), (New-TestGpo -PermissionProfile 'DomainComputers')) Test-MtAdGpoNoDomainComputersCount | Should -BeTrue - $script:resultDetail.Result | Should -Match 'GPO Reports Without Domain Computers And Without Authenticated Users \| 0 \|' + $script:resultDetail.Result | Should -Match 'GPOs with neither Domain Computers nor Authenticated Users \| 0 \|' } } } diff --git a/powershell/tests/functions/Format-MtAdGpoResult.Tests.ps1 b/powershell/tests/functions/Format-MtAdGpoResult.Tests.ps1 new file mode 100644 index 0000000000..319e9576f1 --- /dev/null +++ b/powershell/tests/functions/Format-MtAdGpoResult.Tests.ps1 @@ -0,0 +1,70 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'Format-MtAdGpoResult' { + It 'escapes tenant-controlled metric labels, values, headers and detail cells without changing trusted summary Markdown' { + InModuleScope Maester { + $tenantText = "<&|[x](https://evil.example) ![x](https://evil.example/p.png) https://evil.example www.evil.example a@b.example`r`nnext\end" + $escaped = '<&|\[x\]\(https\://evil.example\) \!\[x\]\(https\://evil.example/p.png\) https\://evil.example www\.evil.example a\@b.example next\\end' + $summary = '**Trusted summary** [help](https://maester.dev)' + $metrics = [ordered]@{} + $metrics[$tenantText] = $tenantText + $result = Format-MtAdGpoResult -Summary $summary -Metrics $metrics ` + -Details @([pscustomobject]@{ Name = $tenantText }) -Properties @('Name') -Headers @($tenantText) + + $expected = @( + $summary + '' + '| Metric | Value |' + '| --- | --- |' + "| $escaped | $escaped |" + '' + '' + '#### Details' + '' + "| $escaped |" + '| --- |' + "| $escaped |" + '' + ) -join "`n" + $result | Should -BeExactly $expected + $result | Should -Not -Match '\\|' + } + } + + It 'preserves every row in a large detail table and renders one header' { + InModuleScope Maester { + $rows = @(0..2999 | ForEach-Object { [pscustomobject]@{ Name = "policy-$_"; Enabled = $false } }) + $result = Format-MtAdGpoResult -Summary 'Inventory' -Details $rows -Properties @('Name', 'Enabled') + $result | Should -Match '^Inventory\n\n#### Details\n\n\| Name \| Enabled \|\n\| --- \| --- \|\n' + @($result -split "`n" | Where-Object { $_ -match '^\| policy-\d+ \| False \|$' }) | Should -HaveCount 3000 + $result | Should -Match '(?m)^\| policy-0 \| False \|$' + $result | Should -Match '(?m)^\| policy-2999 \| False \|$' + @($result -split "`n" | Where-Object { $_ -eq '| Name | Enabled |' }) | Should -HaveCount 1 + } + } + + It 'keeps False distinct from null and omits empty detail tables' { + InModuleScope Maester { + $result = Format-MtAdGpoResult -Summary 'Summary' -Metrics ([ordered]@{ Enabled = $false; Missing = $null }) ` + -Details @($null) -Properties @('Name') + $result | Should -BeExactly "Summary`n`n| Metric | Value |`n| --- | --- |`n| Enabled | False |`n| Missing | Unknown |`n" + $result | Should -Not -Match '#### Details' + Format-MtAdGpoResult -Summary 'Summary' -Details @() | Should -BeExactly 'Summary' + + $detail = Format-MtAdGpoResult -Summary 'Summary' -Details @([pscustomobject]@{ Enabled = $false; Missing = $null }) ` + -Properties @('Enabled', 'Missing') + $detail | Should -Match '(?m)^\| False \| Unknown \|$' + } + } + + It 'requires matching headers and properties for non-empty detail rows' { + InModuleScope Maester { + $details = @([pscustomobject]@{ Name = 'Policy' }) + { Format-MtAdGpoResult -Summary 'Summary' -Details $details } | Should -Throw '*Detail properties are required*' + { Format-MtAdGpoResult -Summary 'Summary' -Details $details -Properties @('Name') -Headers @('One', 'Two') } | + Should -Throw '*headers and properties must have the same count*' + } + } +} diff --git a/powershell/tests/functions/golden/Golden.Tests.ps1 b/powershell/tests/functions/golden/Golden.Tests.ps1 index 744d5aebe5..2c79e28b88 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. + # The registry preserves consolidation intent without hiding 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' diff --git a/powershell/tests/general/AttributeReview.Tests.ps1 b/powershell/tests/general/AttributeReview.Tests.ps1 index 5e0d261415..9e4761ccc8 100644 --- a/powershell/tests/general/AttributeReview.Tests.ps1 +++ b/powershell/tests/general/AttributeReview.Tests.ps1 @@ -9,6 +9,7 @@ Describe 'Attribute review script' { BeforeAll { $script:repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '../../..')).Path . (Join-Path $script:repoRoot 'build/review/Invoke-MtAttributeReview.ps1') + . (Join-Path $script:repoRoot 'build/review/Get-MtReviewPullRequestFile.ps1') function New-TestFileText { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Test helper that only builds test data.')] @@ -122,6 +123,14 @@ function Test-MtReviewSample { @(Get-MtReviewTarget -Root $root -HeadRoot $head -File ($script:path -replace '\.ps1$', '.md')).Count | Should -Be 0 } + It 'Does not review a deleted or renamed-away test from the trusted base' { + $root = New-ReviewTree 'removed-root' + $head = New-ReviewTree 'removed-head' + $old = 'tests/maester/entra/Test.MT.9002.ps1' + New-TestFileText -Id 'MT.9002' | Set-Content (Join-Path $root $old) + @(Get-MtReviewTarget -Root $root -HeadRoot $head -File $old).Count | Should -Be 0 + } + It 'Ignores paths that are not test files and paths that climb out of the tree' { $root = New-ReviewTree 'paths-root' $head = New-ReviewTree 'paths-head' @@ -133,6 +142,34 @@ function Test-MtReviewSample { } } + Context 'Pull request file handoff' { + It 'Lists deleted tests and rename-old paths but downloads only current safe files' { + $old = 'tests/maester/entra/Test.MT.9002.ps1' + $new = 'tests/maester/entra/Test.MT.9003.ps1' + $files = Get-MtReviewPullRequestFile -Changed @( + [pscustomobject]@{ status = 'modified'; filename = $script:path } + [pscustomobject]@{ status = 'removed'; filename = $old } + [pscustomobject]@{ status = 'renamed'; filename = $new; previous_filename = $old } + [pscustomobject]@{ status = 'modified'; filename = $script:path } + ) + $files.Review | Should -Be @($script:path, $old, $new) + $files.Download | Should -Be @($script:path, $new) + } + + It 'Validates old and current paths and caps the total distinct review paths' { + $files = Get-MtReviewPullRequestFile -Changed @( + [pscustomobject]@{ status = 'renamed'; filename = $script:path; previous_filename = 'tests/../secret/Test.MT.9002.ps1' } + [pscustomobject]@{ status = 'removed'; filename = 'tests/../secret/Test.MT.9003.ps1' } + [pscustomobject]@{ status = 'renamed'; filename = 'tests/../secret/Test.MT.9004.ps1'; previous_filename = 'tests/maester/entra/Test.MT.9005.ps1' } + ) + $files.Review | Should -Be @($script:path, 'tests/maester/entra/Test.MT.9005.ps1') + $files.Download | Should -Be @($script:path) + { Get-MtReviewPullRequestFile -MaxFiles 1 -Changed @( + [pscustomobject]@{ status = 'renamed'; filename = $script:path; previous_filename = 'tests/maester/entra/Test.MT.9005.ps1' } + ) } | Should -Throw '*more than this job downloads*' + } + } + Context 'The request' { BeforeAll { $script:system = Get-MtReviewSystem -Root $script:repoRoot @@ -314,6 +351,53 @@ function Test-MtReviewSample { (Get-Content (Join-Path $script:out 'attribute-review.json') -Raw | ConvertFrom-Json)[0].Outcome | Should -Be 'Pass' } + It 'Excludes a deleted related test from the actual request sent for a changed test' { + $env:ANTHROPIC_API_KEY = 'test-key' + $rep15 = 'tests/maester/entra/Test.REP.15.ps1' + $rep16 = 'tests/maester/entra/Test.REP.16.ps1' + New-TestFileText -Id 'REP.15' -Severity 'High' | Set-Content (Join-Path $script:root $rep15) + New-TestFileText -Id 'REP.15' -Severity 'Low' | Set-Content (Join-Path $script:head $rep15) + New-TestFileText -Id 'REP.16' -Severity 'Medium' | Set-Content (Join-Path $script:root $rep16) + $files = Get-MtReviewPullRequestFile -Changed @( + [pscustomobject]@{ status = 'modified'; filename = $rep15 } + [pscustomobject]@{ status = 'removed'; filename = $rep16 } + ) + $script:arguments.File = $files.Review + $script:request = $null + Mock Invoke-WebRequest { + $script:request = [Text.Encoding]::UTF8.GetString($Body) | ConvertFrom-Json -Depth 30 + New-ApiResponse -Json '{"verdict":"pass","findings":[],"notes":[],"untrusted_instructions":false}' + } + Invoke-MtAttributeReview @script:arguments | Should -Be 0 + Should -Invoke Invoke-WebRequest -Times 1 -Exactly + $script:request.messages[0].content | Should -Match 'related_tests: none' + $script:request.messages[0].content | Should -Not -Match 'REP\.16' + (Get-Content (Join-Path $script:out 'attribute-review.json') -Raw | ConvertFrom-Json).Id | Should -Be 'REP.15' + } + + It 'Reviews only the new path after a rename and excludes the old path as related' { + $env:ANTHROPIC_API_KEY = 'test-key' + $old = 'tests/maester/entra/Test.MT.9002.ps1' + $new = 'tests/maester/entra/Test.MT.9003.ps1' + New-TestFileText -Id 'MT.9002' -Severity 'Medium' | Set-Content (Join-Path $script:root $old) + New-TestFileText -Id 'MT.9003' -Severity 'Low' | Set-Content (Join-Path $script:head $new) + $files = Get-MtReviewPullRequestFile -Changed @( + [pscustomobject]@{ status = 'renamed'; filename = $new; previous_filename = $old } + ) + $files.Review | Should -Be @($new, $old) + $files.Download | Should -Be @($new) + $script:arguments.File = $files.Review + $script:request = $null + Mock Invoke-WebRequest { + $script:request = [Text.Encoding]::UTF8.GetString($Body) | ConvertFrom-Json -Depth 30 + New-ApiResponse -Json '{"verdict":"pass","findings":[],"notes":[],"untrusted_instructions":false}' + } + Invoke-MtAttributeReview @script:arguments | Should -Be 0 + Should -Invoke Invoke-WebRequest -Times 1 -Exactly + $script:request.messages[0].content | Should -Match 'related_tests: none' + (Get-Content (Join-Path $script:out 'attribute-review.json') -Raw | ConvertFrom-Json).Id | Should -Be 'MT.9003' + } + It 'Returns 1 when an attribute does not fit the rubric' { $env:ANTHROPIC_API_KEY = 'test-key' Mock Invoke-WebRequest { New-ApiResponse -Json '{"verdict":"fail","findings":[{"attribute":"Area","declared":"authentication","expected":"access-control","reason":"Device condition."}],"notes":[],"untrusted_instructions":false}' } diff --git a/report/scripts/tests/ad-gpo-markdown.test.mjs b/report/scripts/tests/ad-gpo-markdown.test.mjs new file mode 100644 index 0000000000..ffdbb3981e --- /dev/null +++ b/report/scripts/tests/ad-gpo-markdown.test.mjs @@ -0,0 +1,19 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import test from 'node:test'; +import { marked } from 'marked'; + +test('tenant-controlled GPO cells render as literal text, never links or images', () => { + const root = fileURLToPath(new URL('../../../', import.meta.url)); + const text = '<&|[x](https://evil.example) ![x](https://evil.example/p.png) https://evil.example www.evil.example a@b.example\nnext'; + const encoded = Buffer.from(text).toString('base64'); + const script = `$ErrorActionPreference='Stop'; Import-Module ./powershell/Maester.psd1; & (Get-Module Maester) { $text=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encoded}')); Format-MtAdGpoResult -Summary 'Inventory' -Details @([pscustomobject]@{Name=$text}) -Properties Name }`; + const markdown = execFileSync('pwsh', ['-NoProfile', '-NonInteractive', '-Command', script], { cwd: root, encoding: 'utf8', timeout: 30000 }); + const html = marked.parse(markdown, { gfm: true }); + assert.doesNotMatch(html, //); + assert.match(html, /<&\|\[x\]\(https:\/\/evil\.example\)/); + assert.match(html, /www\.evil\.example a@b\.example next/); + assert.doesNotMatch(html, /\\&(?:lt|amp|#124);/); +}); diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-01.md b/tests/ad/gpo-state/Test.AD-GPOREP-01.md index 05517fc097..f53acc533a 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-01.md +++ b/tests/ad/gpo-state/Test.AD-GPOREP-01.md @@ -1,27 +1,62 @@ -#### Test-MtAdGpoNoPermissionsCount +Checks whether each evaluated GPO has permission entries in its collected permission +report. A readable GPO with no entries is a finding and fails this test. This is a +read-only assessment of a preventive ACL setting; it does not change permissions or +calculate effective access. - Counts Group Policy Objects (GPOs) with missing permissions. +#### Control Type -#### Why This Test Matters -- Detective control: counts GPO reports with missing permissions which could expose resources to unintended access. +**Detective** -#### Control Type +#### Why This Test Matters -**Preventive** +A GPO with no reported permission entries may not be manageable or accessible to its +intended policy recipients. An unintentionally empty DACL can prevent policy +retrieval and stop intended security settings from being applied. +The entry count alone does not identify every DACL state or determine effective +access. A NULL DACL grants full access and can expose the GPO to unauthorized +modification; an empty DACL denies access. Both can produce this entry-count +finding, so inspect the actual descriptor promptly to distinguish tampering +exposure from an availability problem. #### Security Recommendation -- Review and remediate missing permissions in GPO ACLs. + +Review GPOs reported with no permission entries and verify the intended delegation +and policy scope. Restore only permissions required by that design; do not infer +effective access from the entry count alone. #### 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. + +- Reads the cached GPO permission reports and checks `PermissionsPresent`. +- A readable report with no entries is a finding; a report with entries satisfies + this check, without establishing that the entries grant appropriate access. +- Unreadable permissions are unknown, not an empty list. If all reports are + unknown, the test is skipped; partial unknowns with no findings result in + **Investigate**. Any known finding still fails. +- Failed permission-report collection is an error. Details are shown for findings + or unknown reports. +- Security-descriptor parsing currently requires Windows. On other platforms, + these permissions are unknown and the test skips when no GPO can be evaluated. + +#### Remediation action + +1. In **Group Policy Management**, inspect each listed GPO under **Delegation** > + **Advanced** and review its actual security descriptor. +2. Confirm that authorized administrators and intended policy recipients retain + the required access. Investigate unreadable descriptors before treating the + inventory as complete. #### Related Tests -- `Test-MtAdGpoNoPermissionsDetails`. + +- [AD-GPOREP-03 — GPOs should include Authenticated Users permissions](https://maester.dev/docs/tests/AD-GPOREP-03) (`Test-MtAdGpoNoAuthenticatedUsersCount`) assesses a specific principal entry within the permission list checked here. +- [AD-GPOREP-06 — GPOs should include Domain Computers or Authenticated Users permissions](https://maester.dev/docs/tests/AD-GPOREP-06) (`Test-MtAdGpoNoDomainComputersCount`) checks for either of two specified read-principal entries. +- [AD-GPOREP-10 — GPOs should have an Apply Group Policy allow entry](https://maester.dev/docs/tests/AD-GPOREP-10) (`Test-MtAdGpoNoApplyGroupPolicyAceCount`) checks for a specific application-right entry; none of these checks calculates effective access for every principal. +- [AD-GPOREP-07 — GPOs should not have deny access entries](https://maester.dev/docs/tests/AD-GPOREP-07) (`Test-MtAdGpoDenyAceCount`) reports deny entries. +- [AD-GPOREP-09 — GPOs should not inherit permission entries](https://maester.dev/docs/tests/AD-GPOREP-09) (`Test-MtAdGpoInheritedPermissionsCount`) reports inherited entries. #### 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) +- [NULL and empty DACLs](https://learn.microsoft.com/windows/win32/secauthz/null-dacls-and-empty-dacls) %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..6e78abf5da 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-01.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOREP-01.ps1 @@ -1,114 +1,36 @@ function Test-MtAdGpoNoPermissionsCount { <# .SYNOPSIS - Counts Group Policy Objects (GPOs) with missing permissions. + Checks that every evaluated GPO has permission entries. .DESCRIPTION - This test retrieves GPO state data and counts how many GPO reports indicate that - permissions are not present. + Fails on an empty permission list and reports unreadable descriptors separately. .EXAMPLE - Test-MtAdGpoNoPermissionsCount + Invoke-MtTest -Id 'AD-GPOREP-01' - Returns $true when no GPOs are missing permissions, otherwise $false. - The test result includes a markdown table with the count. + Fails when an evaluated GPO has an empty permissions list. .LINK - https://maester.dev/docs/commands/Test-MtAdGpoNoPermissionsCount + https://maester.dev/docs/tests/AD-GPOREP-01 #> [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', + Id = 'AD-GPOREP-01', + 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' + Mitre = 'None', + Service = 'ActiveDirectory', + Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), + Author = 'soulemike' )] [CmdletBinding()] [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 + return Test-MtAdGpoPermission -PermissionProperties PermissionsPresent -ExpectedValue $true -FindingLabel 'GPOs with empty permissions' -PassMessage 'Every evaluated GPO has permission entries.' -FailureMessage 'have empty permission lists; restore intended GPO permissions.' } 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..81b47b2634 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-03.md +++ b/tests/ad/gpo-state/Test.AD-GPOREP-03.md @@ -1,27 +1,56 @@ +Checks whether each evaluated GPO has an access-allowed permission entry for +**Authenticated Users**. Its absence is a review finding, not proof that the GPO +is exposed or unusable. This read-only check assesses a preventive ACL setting; it +does not change permissions or calculate effective access. + #### Control Type **Detective** -#### 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. + +The principal's access can be part of how a GPO is read and targeted, but some +policies intentionally use other groups for security filtering. Treating the +absence as universally unsafe could broaden policy scope or grant access contrary +to the design. Review the intended recipients and permissions together. #### Security Recommendation -- Review missing Authenticated Users and adjust GPO ACLs as needed. + +Verify the policy's security filtering and delegation before changing its ACL. +Grant read or application permissions only to the intended principals; do not add +**Authenticated Users** or **Apply Group Policy** solely to clear this finding. #### 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. + +- Checks the cached permission report's `HasAuthenticatedUsers` value for each + GPO. +- A known-present entry satisfies the check; known absence is a finding and fails. +- Unknown can indicate an unreadable descriptor or conflicting allow and deny + entries. If all GPOs are unknown, the test is skipped; partial unknowns without + findings result in **Investigate**. Known findings still fail. +- Failed permission-report collection is an error. Details are shown for findings + or unknown reports. + +- Security-descriptor parsing currently requires Windows. On other platforms, + these permissions are unknown and the test skips when no GPO can be evaluated. + +#### Remediation action + +1. In **Group Policy Management**, inspect each listed GPO's **Scope** > + **Security Filtering** and **Delegation** > **Advanced** settings. +2. Confirm intended recipients and their read and application permissions. Review + both descriptor readability and the ACL when the principal assessment is + unknown; do not assume every unknown is a collection-permission failure. #### Related Tests -- `Test-MtAdGpoNoAuthenticatedUsersDetails`. + +- [AD-GPOREP-01 — No GPO should have an empty permissions list](https://maester.dev/docs/tests/AD-GPOREP-01) (`Test-MtAdGpoNoPermissionsCount`) checks whether permission entries are present generally. +- [AD-GPOREP-06 — GPOs should include Domain Computers or Authenticated Users permissions](https://maester.dev/docs/tests/AD-GPOREP-06) (`Test-MtAdGpoNoDomainComputersCount`) checks for either **Domain Computers** or **Authenticated Users**, unlike this test's specific principal check. +- [AD-GPOREP-10 — GPOs should have an Apply Group Policy allow entry](https://maester.dev/docs/tests/AD-GPOREP-10) (`Test-MtAdGpoNoApplyGroupPolicyAceCount`) checks for an explicit **Apply Group Policy** entry. #### 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..17a2061c47 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-03.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOREP-03.ps1 @@ -1,114 +1,37 @@ function Test-MtAdGpoNoAuthenticatedUsersCount { <# .SYNOPSIS - Counts GPO reports that do not include Authenticated Users. + Checks that evaluated GPOs include Authenticated Users permissions. .DESCRIPTION - This test retrieves GPO state data and counts how many GPO reports indicate that - Authenticated Users are not present. + Fails when Authenticated Users is absent; unknown permissions require review. + Verify intentional security filtering before changing the ACL. .EXAMPLE - Test-MtAdGpoNoAuthenticatedUsersCount + Invoke-MtTest -Id 'AD-GPOREP-03' - Returns $true when no GPO reports are missing Authenticated Users, otherwise $false. - The test result includes a markdown table with the count. + Fails when an evaluated GPO lacks Authenticated Users permissions. .LINK - https://maester.dev/docs/commands/Test-MtAdGpoNoAuthenticatedUsersCount + https://maester.dev/docs/tests/AD-GPOREP-03 #> [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', + Id = 'AD-GPOREP-03', + Title = 'GPOs should include Authenticated Users 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' + Mitre = 'None', + Service = 'ActiveDirectory', + Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), + Author = 'soulemike' )] [CmdletBinding()] [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 + return Test-MtAdGpoPermission -PermissionProperties HasAuthenticatedUsers -ExpectedValue $true -FindingLabel 'GPOs without Authenticated Users' -PassMessage 'No evaluated GPO lacks Authenticated Users permissions.' -FailureMessage 'lack Authenticated Users permissions; review intended security filtering before changing GPO permissions.' } 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-05.md b/tests/ad/gpo-state/Test.AD-GPOREP-05.md index a637815cc6..d5a3e32a24 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-05.md +++ b/tests/ad/gpo-state/Test.AD-GPOREP-05.md @@ -1,27 +1,57 @@ +Checks whether each evaluated GPO has an access-allowed permission entry for +**Enterprise Domain Controllers**. A readable GPO without that entry is a finding, +not by itself proof of incorrect effective access. This read-only assessment does +not alter the preventive ACL setting. + #### Control Type **Detective** -#### Test-MtAdGpoNoEnterpriseDcCount - - Counts GPO reports that do not include Enterprise Domain Controllers. - #### Why This Test Matters -- Detective control: flags GPO reports missing Enterprise Domain Controllers which could impact domain-wide policy targeting. + +If intended domain controllers cannot retrieve a policy, their security settings +may be missing or inconsistent. This principal-presence check does not establish +that retrieval failed: the entry's absence is not necessarily wrong for every +policy. An unnecessary ACL change can +alter delegation or policy scope. Use the finding to review the policy's purpose +and intended recipients, not as an instruction to add the principal everywhere. #### Security Recommendation -- Verify whether Enterprise DCs should be included; adjust policy accordingly. + +Confirm whether Enterprise Domain Controllers require this permission for the +policy's design. Restore an entry only when needed for intended access, and review +the full ACL rather than treating principal presence as effective-access analysis. #### How the Test Works -- Retrieves GPO state, enumerates GPO reports, and counts those without an access-allowed entry for Enterprise Domain Controllers (HasEnterpriseDomainControllers is false). -- 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. + +- Checks `HasEnterpriseDomainControllers` in the cached permission report for each + GPO. +- A known-present entry satisfies the check; known absence fails. +- Unknown can indicate an unreadable descriptor or conflicting allow and deny + entries. If all reports are unknown, the test is skipped; partial unknowns with + no finding result in **Investigate**. Known findings still fail. +- Failed permission-report collection is an error. Details are shown for findings + or unknown reports. + +- Security-descriptor parsing currently requires Windows. On other platforms, + these permissions are unknown and the test skips when no GPO can be evaluated. + +#### Remediation action + +Review each listed policy's purpose, recipients, and the role of Enterprise Domain +Controllers in its intended scope. Restore the permission only if required by that +design. For unknown assessments, check both descriptor readability and the ACL +before deciding whether collection access is the cause. #### Related Tests -- `Test-MtAdGpoNoEnterpriseDcCount`. + +- [AD-GPOREP-01 — No GPO should have an empty permissions list](https://maester.dev/docs/tests/AD-GPOREP-01) (`Test-MtAdGpoNoPermissionsCount`) checks for permission entries generally. +- [AD-GPOREP-03 — GPOs should include Authenticated Users permissions](https://maester.dev/docs/tests/AD-GPOREP-03) (`Test-MtAdGpoNoAuthenticatedUsersCount`) assesses a different read-principal entry. +- [AD-GPOREP-06 — GPOs should include Domain Computers or Authenticated Users permissions](https://maester.dev/docs/tests/AD-GPOREP-06) (`Test-MtAdGpoNoDomainComputersCount`) assesses other read-principal entries; these are separate checks and do not calculate effective access. #### 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-05.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-05.ps1 index 1cda1cc1b0..a8fa13a226 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-05.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOREP-05.ps1 @@ -1,113 +1,37 @@ function Test-MtAdGpoNoEnterpriseDcCount { <# .SYNOPSIS - Counts GPO reports that do not include Enterprise Domain Controllers. + Checks that evaluated GPOs include Enterprise Domain Controllers permissions. .DESCRIPTION - This test retrieves GPO state data and counts how many GPO reports indicate that - Enterprise Domain Controllers are not present. + Passes when the principal is present on all evaluated GPOs, fails when absent, + and reports unreadable permissions as unknown rather than missing. .EXAMPLE - Test-MtAdGpoNoEnterpriseDcCount + Invoke-MtTest -Id 'AD-GPOREP-05' - Returns $true when no GPO reports are missing Enterprise Domain Controllers, otherwise $false. + Fails when an evaluated GPO lacks Enterprise Domain Controllers permissions. .LINK - https://maester.dev/docs/commands/Test-MtAdGpoNoEnterpriseDcCount + https://maester.dev/docs/tests/AD-GPOREP-05 #> [MaesterTest( - Id = 'AD-GPOREP-05', - Title = 'GPOs without enterprise domain controllers count should be retrievable', - Product = 'ad', - Feature = 'group-policy', - Area = 'access-control', - ResourceType = 'GroupPolicy', - Severity = 'Medium', - UserImpact = 'Low', + Id = 'AD-GPOREP-05', + Title = 'GPOs should include Enterprise Domain Controllers 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' + Mitre = 'None', + Service = 'ActiveDirectory', + Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), + Author = 'soulemike' )] [CmdletBinding()] [OutputType([bool])] param() - - Write-Verbose "Starting Test-MtAdGpoNoEnterpriseDcCount" - $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 enterprise dc 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 $_ }) - # HasEnterpriseDomainControllers is $null when the security descriptor of a GPO could not be read: unknown, not missing. - $reportsWithNoEnterpriseDc = @($gpoReports | Where-Object { $false -eq $_.HasEnterpriseDomainControllers }) - $reportsNotEvaluated = @($gpoReports | Where-Object { $null -eq $_.HasEnterpriseDomainControllers }) - $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 - } - - $noEnterpriseDcCount = ($reportsWithNoEnterpriseDc | Measure-Object).Count - $testResult = $noEnterpriseDcCount -eq 0 - - $sampleLimit = 5 - $sampleGpo = $reportsWithNoEnterpriseDc | 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 ($noEnterpriseDcCount -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 Enterprise Domain Controllers | $noEnterpriseDcCount |" + "`n" - if ($noEnterpriseDcCount -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 Enterprise Domain Controllers 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 Enterprise Domain Controllers.' - } - else { - $recommendation = "⚠️ GPO reports were found missing Enterprise Domain Controllers ($noEnterpriseDcCount)." - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "$recommendation`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $resultTable - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate:$needsInvestigation - Write-Verbose "Completed Test-MtAdGpoNoEnterpriseDcCount" - return $testResult + return Test-MtAdGpoPermission -PermissionProperties HasEnterpriseDomainControllers -ExpectedValue $true -FindingLabel 'GPOs without Enterprise Domain Controllers' -PassMessage 'No evaluated GPO lacks Enterprise Domain Controllers permissions.' -FailureMessage 'lack Enterprise Domain Controllers permissions; review and restore intended access.' } diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-06.md b/tests/ad/gpo-state/Test.AD-GPOREP-06.md index 9a67055963..0d093fbe01 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-06.md +++ b/tests/ad/gpo-state/Test.AD-GPOREP-06.md @@ -1,28 +1,65 @@ +Checks whether each evaluated GPO has an access-allowed permission entry for +**Domain Computers** or **Authenticated Users**. A known-present entry for either +satisfies this check; it fails only when both are known absent. This is a read-only +assessment of preventive ACL settings, not a calculation of effective read access. + #### Control Type **Detective** -#### Test-MtAdGpoNoDomainComputersCount - - Counts GPO reports that do not include Domain Computers. - #### Why This Test Matters -- Detective control: identifies GPO reports missing Domain Computers which could impact scope or applicability. + +Computer policy retrieval depends on suitable permissions. Incorrect read access +can prevent intended security settings from reaching computer accounts. However, +the absence of a +**Domain Computers** entry alone is not a failure: **Authenticated Users** may be +present instead. Conversely, entry presence does not establish that every intended +computer can effectively read the policy. Review the full ACL and intended scope. #### Security Recommendation -- Verify whether Domain Computers should be included and adjust GpoReports as needed to reflect accurate targeting. + +Since MS16-072, Windows retrieves user-targeted Group Policy using the computer's +security context too. GPOs filtered to user groups therefore still need suitable +Read access for computer accounts, commonly through **Authenticated Users** or +**Domain Computers**. This does not mean granting those groups **Apply Group +Policy** or broadening which users receive the policy. + +Confirm that each GPO's intended computer recipients have the required read access. +Do not add a principal solely to satisfy this check; account for the policy's +security filtering and the complete allow and deny entries. #### How the Test Works -- Reads GPO state, counts the GPO reports without an access-allowed entry for Domain Computers (HasDomainComputers is false), and reports counts and samples. -- The default GPO permissions have no Domain Computers entry, so the test only fails for GPOs that have no entry for Authenticated Users either: computer accounts may be unable to read those GPOs (MS16-072). -- 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. + +- Checks `HasDomainComputers` and `HasAuthenticatedUsers` in each cached permission + report. +- Either known `true` value satisfies the check. Both known `false` values fail. +- If neither is known present and either value is unknown, that GPO is inconclusive. + Unknown can mean an unreadable descriptor or conflicting allow and deny entries. +- If all GPOs are unknown, the test is skipped. Partial unknowns with no finding + result in **Investigate**; known findings still fail. Failed collection is an + error. + +- Security-descriptor parsing currently requires Windows. On other platforms, + these permissions are unknown and the test skips when no GPO can be evaluated. + +#### Remediation action + +Review each listed GPO's intended recipients and computer policy retrieval +requirements. Confirm the required read permissions for the relevant principals +before changing the ACL. A missing **Domain Computers** entry by itself is not a +finding; investigate unknown assessments by checking the descriptor and ACL. #### Related Tests -- `Test-MtAdGpoNoDomainComputersCount`. + +- [AD-GPOREP-03 — GPOs should include Authenticated Users permissions](https://maester.dev/docs/tests/AD-GPOREP-03) (`Test-MtAdGpoNoAuthenticatedUsersCount`) checks the **Authenticated Users** entry specifically. +- [AD-GPOREP-01 — No GPO should have an empty permissions list](https://maester.dev/docs/tests/AD-GPOREP-01) (`Test-MtAdGpoNoPermissionsCount`) checks for permission entries generally. +- [AD-GPOREP-10 — GPOs should have an Apply Group Policy allow entry](https://maester.dev/docs/tests/AD-GPOREP-10) (`Test-MtAdGpoNoApplyGroupPolicyAceCount`) checks for an explicit **Apply Group Policy** entry separately from these read-principal checks. #### 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) +- [Group Policy security update background (MS16-072)](https://learn.microsoft.com/security-updates/securitybulletins/2016/ms16-072) +- [MS16-072: user-policy retrieval and required Read permissions (KB3163622)](https://support.microsoft.com/kb/3163622) %TestResult% diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-06.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-06.ps1 index 977c616433..1eb6f15a0f 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-06.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOREP-06.ps1 @@ -1,119 +1,38 @@ function Test-MtAdGpoNoDomainComputersCount { <# .SYNOPSIS - Counts GPO reports that include neither Domain Computers nor Authenticated Users. + Checks that GPO permissions include Domain Computers or Authenticated Users. .DESCRIPTION - This test retrieves GPO state data and counts how many GPO reports indicate that - Domain Computers are not present. A GPO without Domain Computers is only a finding - when Authenticated Users is not present either (MS16-072). + Fails only when both principals are absent. One known-present principal proves + the condition; absence of one with the other unknown remains inconclusive. + This principal-presence check does not calculate effective read access. .EXAMPLE - Test-MtAdGpoNoDomainComputersCount + Invoke-MtTest -Id 'AD-GPOREP-06' - Returns $true when no GPO reports are missing both Domain Computers and Authenticated Users, otherwise $false. + Fails only when a GPO lacks both Domain Computers and Authenticated Users permissions. .LINK - https://maester.dev/docs/commands/Test-MtAdGpoNoDomainComputersCount + https://maester.dev/docs/tests/AD-GPOREP-06 #> [MaesterTest( - Id = 'AD-GPOREP-06', - Title = 'GPOs without domain computers count should be retrievable', - Product = 'ad', - Feature = 'group-policy', - Area = 'access-control', - ResourceType = 'GroupPolicy', - Severity = 'Low', - UserImpact = 'Low', + Id = 'AD-GPOREP-06', + Title = 'GPOs should include Domain Computers or Authenticated Users permissions', + 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' + Mitre = 'None', + Service = 'ActiveDirectory', + Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), + Author = 'soulemike' )] [CmdletBinding()] [OutputType([bool])] param() - - Write-Verbose "Starting Test-MtAdGpoNoDomainComputersCount" - $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 domain computers 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 $_ }) - # HasDomainComputers is $null when the security descriptor of a GPO could not be read: unknown, not missing. - $reportsWithNoDomainComputers = @($gpoReports | Where-Object { $false -eq $_.HasDomainComputers }) - $reportsNotEvaluated = @($gpoReports | Where-Object { $null -eq $_.HasDomainComputers }) - $notEvaluatedCount = $reportsNotEvaluated.Count - # The default GPO permissions hold Authenticated Users and no Domain Computers entry, so a missing Domain - # Computers entry is only a finding when Authenticated Users is missing as well (MS16-072). - $reportsWithNoComputerAccess = @($reportsWithNoDomainComputers | Where-Object { $false -eq $_.HasAuthenticatedUsers }) - - 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 - } - - $noDomainComputersCount = ($reportsWithNoDomainComputers | Measure-Object).Count - $noComputerAccessCount = ($reportsWithNoComputerAccess | Measure-Object).Count - $testResult = $noComputerAccessCount -eq 0 - - $sampleLimit = 5 - $sampleGpo = $reportsWithNoComputerAccess | 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 ($noComputerAccessCount -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 Domain Computers | $noDomainComputersCount |" + "`n" - $resultTable += "| GPO Reports Without Domain Computers And Without Authenticated Users | $noComputerAccessCount |" + "`n" - if ($noComputerAccessCount -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 both Domain Computers and 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 both Domain Computers and Authenticated Users. A GPO without Domain Computers is expected when Authenticated Users has access: the default GPO permissions have no Domain Computers entry.' - } - else { - $recommendation = "⚠️ GPO reports were found missing both Domain Computers and Authenticated Users ($noComputerAccessCount). Computer accounts may be unable to read these GPOs (MS16-072)." - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "$recommendation`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $resultTable - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate:$needsInvestigation - Write-Verbose "Completed Test-MtAdGpoNoDomainComputersCount" - return $testResult + return Test-MtAdGpoPermission -PermissionProperties HasDomainComputers, HasAuthenticatedUsers -ExpectedValue $true -FindingLabel 'GPOs with neither Domain Computers nor Authenticated Users' -PassMessage 'Every evaluated GPO includes Domain Computers or Authenticated Users. A missing Domain Computers entry alone is not a failure.' -FailureMessage 'include neither Domain Computers nor Authenticated Users; review permissions required for computer policy retrieval (MS16-072).' } diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-07.md b/tests/ad/gpo-state/Test.AD-GPOREP-07.md index 07a98844a5..68117240f3 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-07.md +++ b/tests/ad/gpo-state/Test.AD-GPOREP-07.md @@ -1,26 +1,55 @@ +Checks GPO permission reports for deny access entries. Any evaluated GPO with a +deny entry is a finding and fails this test. This read-only assessment of +preventive ACL settings does not determine the entry's effective impact or modify +the descriptor. + #### Control Type **Detective** -#### 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. + +Deny entries can restrict access even when allow entries also exist. Unintended +restrictions can prevent intended recipients from retrieving or applying security +policy. Some restrictions may be deliberate. Review each entry's +scope and purpose before changing it; this check does not determine whether a deny +entry is excessive or necessary. #### Security Recommendation -- Review or remove Deny ACEs to ensure proper permission handling. + +Investigate deny entries against the intended policy scope and delegation. Retain +documented, necessary restrictions; remove an entry only after confirming it is +unintended and assessing its effect on policy recipients. #### How the Test Works -- Aggregates GPO reports, counts those with HasDenyAce true, and reports totals and a sample of affected GPOs. + +- Checks `HasDenyAce` in the cached GPO permission reports. +- A known deny entry is a finding. Descriptors that cannot be evaluated remain + unknown rather than being treated as clean. +- If all reports are unknown, the test is skipped; partial unknowns without + findings result in **Investigate**. Findings still fail when other reports are + unknown. Failed report collection is an error. +- Windows is required for security-descriptor parsing. Details are shown for + findings or unknown reports. + +#### Remediation action + +1. In **Group Policy Management**, inspect each listed GPO under **Delegation** > + **Advanced**. +2. Confirm the purpose and scope of each deny entry. Remove only restrictions + verified as unintended, and review the effect on policy recipients first. + Investigate descriptors that could not be evaluated. #### Related Tests -- `Test-MtAdGpoDenyAceDetails`. + +- [AD-GPOREP-03 — GPOs should include Authenticated Users permissions](https://maester.dev/docs/tests/AD-GPOREP-03) (`Test-MtAdGpoNoAuthenticatedUsersCount`) assesses a selected allowed-principal entry that may be affected by deny entries. +- [AD-GPOREP-05 — GPOs should include Enterprise Domain Controllers permissions](https://maester.dev/docs/tests/AD-GPOREP-05) (`Test-MtAdGpoNoEnterpriseDcCount`) assesses a selected allowed-principal entry that may be affected by deny entries. +- [AD-GPOREP-06 — GPOs should include Domain Computers or Authenticated Users permissions](https://maester.dev/docs/tests/AD-GPOREP-06) (`Test-MtAdGpoNoDomainComputersCount`) assesses selected allowed-principal entries that may be affected by deny entries. +- [AD-GPOREP-09 — GPOs should not inherit permission entries](https://maester.dev/docs/tests/AD-GPOREP-09) (`Test-MtAdGpoInheritedPermissionsCount`) reports inherited permission entries alongside deny entries. #### 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..24a1fc2bfd 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-07.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOREP-07.ps1 @@ -1,134 +1,38 @@ function Test-MtAdGpoDenyAceCount { <# .SYNOPSIS - Counts GPO reports that include a Deny ACE. + Checks for GPOs with deny access entries. .DESCRIPTION - This test retrieves GPO state data and counts how many GPO reports indicate that - a Deny ACE is present. + Fails when a deny entry is found. Lists findings and unreadable permissions; + review intentional restrictions before removing any entry. .EXAMPLE - Test-MtAdGpoDenyAceCount + Invoke-MtTest -Id 'AD-GPOREP-07' - Returns $true when no GPO reports include a Deny ACE, otherwise $false. - The test result includes a markdown table with the count. + Fails when an evaluated GPO contains a deny access entry. .LINK - https://maester.dev/docs/commands/Test-MtAdGpoDenyAceCount + https://maester.dev/docs/tests/AD-GPOREP-07 #> [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', + Id = 'AD-GPOREP-07', + Title = 'GPOs should not have deny access entries', + 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' + Mitre = 'None', + Service = 'ActiveDirectory', + Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), + Platform = 'Windows', + Author = 'soulemike' )] [CmdletBinding()] [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 + return Test-MtAdGpoPermission -PermissionProperties HasDenyAce -ExpectedValue $false -FindingLabel 'GPOs with deny entries' -PassMessage 'No evaluated GPO has a deny access entry.' -FailureMessage 'have deny access entries; review their scope and remove unintended restrictions.' } 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-09.md b/tests/ad/gpo-state/Test.AD-GPOREP-09.md index 5cf4d17ad0..a2239683ef 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-09.md +++ b/tests/ad/gpo-state/Test.AD-GPOREP-09.md @@ -1,27 +1,56 @@ -#### Control Type - -**Operational** +Checks GPO security descriptors for inherited permission entries. Any evaluated GPO +with an inherited entry is a finding and fails this test. This is a read-only +assessment of a preventive ACL setting; it does not judge effective access or +change inheritance. -#### Test-MtAdGpoInheritedPermissionsCount +#### Control Type - Counts GPO reports with inherited permissions. +**Detective** #### Why This Test Matters -- Detective control: checks for inherited permissions in GPOs which may lead to broader access than intended. + +Inherited entries can carry permissions from a parent container into GPO +delegation. If a parent grants overly broad edit or permission-management rights, +those rights can enable unauthorized policy changes across its descendant GPOs. +Inherited permissions may be intended, but can also differ from the policy's expected +administrative scope. An inherited entry is therefore a review signal, not proof +of excessive access or a reason to disable inheritance automatically. #### Security Recommendation -- Review inherited permissions and consider removing inheritance where not needed. + +Review inherited entries and their source containers against the intended GPO +delegation. Preserve inheritance where it is part of the design; change it only +when the resulting ACL and policy administration remain appropriate. #### How the Test Works -- Scans GPO state for GPO reports with a DACL entry inherited from the parent container (HasInheritedPermissions is true) and reports counts and a small sample. -- 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. + +- Checks `HasInheritedPermissions` in each cached GPO permission report. +- A known inherited entry is a finding. This property describes entries in the + descriptor; it does not indicate whether the descriptor was readable. +- Unreadable descriptors are unknown. If all are unknown, the test is skipped; + partial unknowns without findings result in **Investigate**. Findings still + fail when other reports are unknown. +- Failed permission-report collection is an error. Details are shown for findings + or unknown reports. + +- Security-descriptor parsing currently requires Windows. On other platforms, + these permissions are unknown and the test skips when no GPO can be evaluated. + +#### Remediation action + +Review each listed inherited entry and identify its source container. Confirm that +the inherited access matches intended GPO delegation before changing permissions +or inheritance. Do not treat inheritance itself as a retrieval failure, and +investigate descriptors that could not be read. #### Related Tests -- `Test-MtAdGpoInheritedPermissionsCount`. + +- [AD-GPOREP-01 — No GPO should have an empty permissions list](https://maester.dev/docs/tests/AD-GPOREP-01) (`Test-MtAdGpoNoPermissionsCount`) checks for permission entries generally. +- [AD-GPOREP-07 — GPOs should not have deny access entries](https://maester.dev/docs/tests/AD-GPOREP-07) (`Test-MtAdGpoDenyAceCount`) reports deny entries that may affect access alongside inherited entries. #### 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-09.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-09.ps1 index cec0bafbdb..3b2e6180c9 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-09.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOREP-09.ps1 @@ -1,114 +1,37 @@ function Test-MtAdGpoInheritedPermissionsCount { <# .SYNOPSIS - Counts GPO reports with inherited permissions. + Checks for inherited GPO permissions. .DESCRIPTION - This test retrieves GPO state data and counts how many GPO reports indicate that - permissions are inherited. + Fails when a GPO inherits permission entries. Reports unreadable descriptors + separately; verify intended delegation before changing inheritance. .EXAMPLE - Test-MtAdGpoInheritedPermissionsCount + Invoke-MtTest -Id 'AD-GPOREP-09' - Returns $true when no GPO reports are using inherited permissions, otherwise $false. - The test result includes a markdown table with the count. + Fails when an evaluated GPO inherits permission entries. .LINK - https://maester.dev/docs/commands/Test-MtAdGpoInheritedPermissionsCount + https://maester.dev/docs/tests/AD-GPOREP-09 #> [MaesterTest( - Id = 'AD-GPOREP-09', - Title = 'GPO inherited permissions count should be retrievable', - Product = 'ad', - Feature = 'group-policy', - Area = 'access-control', - ResourceType = 'GroupPolicy', - Severity = 'Medium', - UserImpact = 'Low', + Id = 'AD-GPOREP-09', + Title = 'GPOs should not inherit permission entries', + 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' + Mitre = 'None', + Service = 'ActiveDirectory', + Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), + Author = 'soulemike' )] [CmdletBinding()] [OutputType([bool])] param() - - Write-Verbose "Starting Test-MtAdGpoInheritedPermissionsCount" - $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 inherited 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 $_ }) - # HasInheritedPermissions is $null when the security descriptor of a GPO could not be read: unknown, not absent. - $reportsWithInheritedPermissions = @($gpoReports | Where-Object { $true -eq $_.HasInheritedPermissions }) - $reportsNotEvaluated = @($gpoReports | Where-Object { $null -eq $_.HasInheritedPermissions }) - $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 - } - - $inheritedPermissionsCount = ($reportsWithInheritedPermissions | Measure-Object).Count - $testResult = $inheritedPermissionsCount -eq 0 - - $sampleLimit = 5 - $sampleGpo = $reportsWithInheritedPermissions | 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 ($inheritedPermissionsCount -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 Inherited Permissions | $inheritedPermissionsCount |" + "`n" - if ($inheritedPermissionsCount -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 using inherited 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 using inherited permissions.' - } - else { - $recommendation = "⚠️ GPO reports were found using inherited permissions ($inheritedPermissionsCount). Review and explicitly define GPO permissions where appropriate." - } - Write-Verbose "Counts computed" - - $testResultMarkdown = "$recommendation`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $resultTable - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate:$needsInvestigation - Write-Verbose "Completed Test-MtAdGpoInheritedPermissionsCount" - return $testResult + return Test-MtAdGpoPermission -PermissionProperties HasInheritedPermissions -ExpectedValue $false -FindingLabel 'GPOs with inherited permissions' -PassMessage 'No evaluated GPO has inherited permission entries.' -FailureMessage 'have inherited permission entries; review delegation and define intended GPO permissions explicitly where appropriate.' } diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-10.md b/tests/ad/gpo-state/Test.AD-GPOREP-10.md index fd451d53db..39c8132419 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-10.md +++ b/tests/ad/gpo-state/Test.AD-GPOREP-10.md @@ -1,26 +1,58 @@ -#### Test-MtAdGpoNoApplyGroupPolicyAceCount +Checks whether every collected GPO has an explicit allow entry for **Apply Group +Policy**. A missing entry is a finding; generic administrative rights do not count +as an explicit application entry. This read-only check assesses a preventive ACL +setting and does not calculate effective permissions for each user or computer. - Counts the number of GPOs missing the "Apply Group Policy" ACE. - -#### Why This Test Matters -- Detective control: counts GPOs missing the Apply Group Policy ACE which governs policy application. +Here, "explicit" means a specific **Apply Group Policy** right rather than generic +rights. The check also accepts an inherited entry when it applies to the GPO itself; +it excludes inherit-only entries. It does not require that every qualifying ACE +was added directly to the GPO. #### Control Type -**Operational** +**Detective** + +#### Why This Test Matters + +An explicit application entry is one part of how policy scope is represented in +the ACL. If intended recipients lack application rights, required security +settings may not be delivered to them. The entry's absence may indicate that the GPO is not configured for intended +recipients, but does not alone establish effective policy application. An unused +policy or an intentionally different design may also lack the entry. #### Security Recommendation -- Ensure the ACE is present on necessary GPOs or document why it is absent. + +Review the intended security filtering and application scope for each finding. +Grant **Apply Group Policy** only to principals that should receive the policy; +do not add a broad grant or a generic administrative entry to satisfy the check. #### How the Test Works -- Evaluates GPO reports for HasApplyGroupPolicyAce, counts missing ACE occurrences, and provides a sample list. + +- Requires Windows for security-descriptor parsing and checks + `HasApplyGroupPolicyAce` in each collected report. +- A missing explicit allow entry fails. Generic administrative grants do not + satisfy this specific check, and the result is not an effective-access + calculation. +- An empty report set, unreadable permissions, or incomplete collection is an + error, not a clean result. Findings are listed by GPO. + +#### Remediation action + +1. In **Group Policy Management**, inspect each listed GPO's **Scope** > + **Security Filtering** and **Delegation** > **Advanced** settings. +2. Add an explicit **Apply Group Policy** grant only for intended recipients. If + the GPO is intentionally unused, document that decision and consider its + disposition rather than granting access solely to clear the finding. #### Related Tests -- `Test-MtAdGpoNoApplyGroupPolicyAceDetails`. + +- [AD-GPOREP-03 — GPOs should include Authenticated Users permissions](https://maester.dev/docs/tests/AD-GPOREP-03) (`Test-MtAdGpoNoAuthenticatedUsersCount`) assesses a selected read-principal entry; this test checks the application entry separately. +- [AD-GPOREP-06 — GPOs should include Domain Computers or Authenticated Users permissions](https://maester.dev/docs/tests/AD-GPOREP-06) (`Test-MtAdGpoNoDomainComputersCount`) assesses selected read-principal entries; this test checks the explicit application entry separately. +- [AD-GPOL-01 — GPOs with enabled links should be investigated](https://maester.dev/docs/tests/AD-GPOL-01) (`Test-MtAdGpoLinkedCount`) inventories enabled links; a link alone does not establish that a policy applies to every target. #### 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..06354e8ef7 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-10.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOREP-10.ps1 @@ -1,75 +1,51 @@ -<# #> -function Test-MtAdGpoNoApplyGroupPolicyAceCount { +function Test-MtAdGpoNoApplyGroupPolicyAceCount { <# .SYNOPSIS - Counts the number of GPOs missing the "Apply Group Policy" ACE. + Checks that every GPO has an explicit 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. + Fails when a GPO has no explicit application entry and lists affected policies. + This does not calculate effective access for every target principal. .EXAMPLE - Test-MtAdGpoNoApplyGroupPolicyAceCount + Invoke-MtTest -Id 'AD-GPOREP-10' - 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. + Fails when a GPO has no explicit Apply Group Policy allow entry. .LINK - https://maester.dev/docs/commands/Test-MtAdGpoNoApplyGroupPolicyAceCount + https://maester.dev/docs/tests/AD-GPOREP-10 #> [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', - Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), - Author = 'soulemike' + 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'), + Platform = 'Windows', + Author = 'soulemike' )] [CmdletBinding()] [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 - } - - $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 + $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.' } + $details = @($missing | Sort-Object Name | ForEach-Object { [pscustomobject]@{ Name = $_.Name; ApplicationEntry = 'Not present' } }) + $message = if ($missing.Count -eq 0) { "Well done. All $($reports.Count) GPOs have 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." } + $result = Format-MtAdGpoResult -Summary $message -Metrics ([ordered]@{ 'Total GPOs' = $reports.Count; 'GPOs without Apply Group Policy entries' = $missing.Count }) -Details $details -Properties Name, ApplicationEntry -Headers GPO, 'Apply Group Policy entry' + Add-MtTestResultDetail -Result $result + 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..75419c7778 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-12.md +++ b/tests/ad/gpo-state/Test.AD-GPOREP-12.md @@ -1,34 +1,58 @@ -Disabled GPO links represent a potential security and operational concern in Active Directory environments: +Inventories disabled GPO link entries, including links that are both disabled and +enforced. Counts are link entries, not distinct GPOs. This read-only inventory +returns an informational **Investigate** result; it does not decide whether a +disabled link is appropriate or change link state. -- **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 +#### Control Type -#### Security Recommendation +**Operational** — informational inventory + +#### Why This Test Matters -Regularly review disabled GPO links and either: +A disabled link does not apply that GPO through that link, but the policy may be +linked elsewhere or received through another part of the hierarchy. Disabled +links can be intentional exceptions or temporary changes that need review. The +inventory provides policy and container context without asserting a policy gap. + +#### Security Recommendation -- 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 +Review disabled links with their policy owners. Confirm intended scope and +inheritance before enabling, removing, or retaining a link, and document approved +exceptions. #### 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) +When malformed targets make `GPOLinksComplete` false, only observed parsed-link +counts are reported. The partial inventory remains **Investigate**, and zero known +disabled links is not presented as proof that all links are enabled. -The gPLink attribute is parsed to determine the state of each link. +- Reads the cached GPO link and policy inventory and counts link entries by + enabled or disabled state. +- Reports each disabled link with its GPO and linked container. Links that are + both disabled and enforced remain included in the disabled count. +- Missing link or GPO collection, or an unknown link state, is an error. A + successful inventory with no disabled links still returns **Investigate**. +- `AD-GPOL-02` uses the same inventory but retains its default **Info/Passed** + outcome. Neither result judges an individual link's risk. + +#### Remediation action + +1. In **Group Policy Management**, locate each listed domain, OU, or site and + review its disabled links with the policy owner. +2. Re-enable links that should apply, remove obsolete links, and document + intentional exceptions. Confirm intended scope and inherited policy before + changing a link. #### Related Tests -- `Test-MtAdGpoEnforcedCount` - Counts enforced GPO links -- `Test-MtAdGpoLinkedCount` - Counts distinct GPOs with links -- `Test-MtAdGpoUnlinkedCount` - Identifies GPOs with no links +- [AD-GPOL-02 — Disabled GPO link inventory](https://maester.dev/docs/tests/AD-GPOL-02) (`Test-MtCheckADGPOL02`) reports the same disabled-link inventory as Passed rather than Investigate. +- [AD-GPOL-01 — GPOs with enabled links should be investigated](https://maester.dev/docs/tests/AD-GPOL-01) (`Test-MtAdGpoLinkedCount`) inventories enabled links. +- [AD-GPOL-03 — Direct GPO link coverage should be investigated](https://maester.dev/docs/tests/AD-GPOL-03) (`Test-MtAdGpoUnlinkedTargetCount`) inventories direct link coverage across targets. +- [AD-GPOREP-14 — GPOs with enforced links should be investigated](https://maester.dev/docs/tests/AD-GPOREP-14) (`Test-MtAdGpoEnforcementCount`) inventories policies with enforced links. + +#### Related 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..d5608fb740 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-12.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOREP-12.ps1 @@ -1,29 +1,35 @@ function Test-MtCheckADGPOREP12 { <# .SYNOPSIS - GPO disabled link count should be retrievable + Inventories disabled GPO links. .DESCRIPTION - Runs the shared check Test-MtAdGpoDisabledLinkCount. + Uses Test-MtAdGpoDisabledLinkCount to count disabled links and list their policies and containers for review. + + .EXAMPLE + Invoke-MtTest -Id 'AD-GPOREP-12' + + Inventories disabled GPO links and their containers for review, not as a failure. + + .LINK + https://maester.dev/docs/tests/AD-GPOREP-12 #> [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', - Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), - Author = 'soulemike' + 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' )] [CmdletBinding()] [OutputType([bool])] param() - $result = Test-MtAdGpoDisabledLinkCount - if ($null -eq $result) { return $null } - return $result + return Test-MtAdGpoDisabledLinkCount -Investigate } 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 -} diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-14.md b/tests/ad/gpo-state/Test.AD-GPOREP-14.md index 0c55128645..f0603d2f0d 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-14.md +++ b/tests/ad/gpo-state/Test.AD-GPOREP-14.md @@ -1,26 +1,60 @@ -#### Test-MtAdGpoEnforcementCount +Inventories distinct GPOs that have at least one enforced link. The informational +**Investigate** result is not a pass/fail judgement about enforcement. This +read-only inventory does not change links or assess whether an override is +appropriate. - Counts the number of GPOs that have enforced GPO links. +#### Control Type -#### Why This Test Matters -- Detective control: counts GPOs with enforced links which indicates explicit policy delivery is configured. +**Operational** — informational inventory -#### Control Type +#### Why This Test Matters -**Operational** +Enforcement overrides **Block Inheritance**; it does not block inheritance. +Knowing which policies use enforced links helps reviewers understand where an +inheritance override exists. An unintended override can apply settings to OUs whose +design relies on blocking ordinary inherited policies. Enforcement may be intentional, so its presence alone +does not establish risk or justify removing the flag. #### Security Recommendation -- Ensure enforcement aligns with security policy; adjust as needed for least privilege and correct policy propagation. + +This inventory counts configured enforcement flags, including flags on disabled +links. Only enabled links actively apply policy and override Block Inheritance; +review link state before interpreting a configured flag as an active override. + +Review each enforced link's owner, target, and policy purpose. Confirm that the +override matches the intended design and document why it is needed before making +any change to link enforcement. #### How the Test Works -- Fetches GPO state, filters for HasEnforcement, and reports total GPOs, number with enforcement, and the ratio. + +- Uses the cached GPO and link inventories to count distinct GPOs with one or more + enforced links, rather than counting individual links. +- A policy with no links is known to have no enforced link when the inventory + confirms that state. `GPOLinksComplete = false` prevents an absent parsed match + from being treated as conclusive. A known configured flag still proves presence. + Missing or incomplete link data otherwise remains unknown. +- Reports policies with enforced or unknown state. Failed GPO metadata collection + is an error; unknown enforcement remains visible in the **Investigate** result. +- `AD-GPOL-04` evaluates individual enforced links and fails when any are found; + this test inventories policies and always reports for investigation. + +#### Remediation action + +Review each listed policy's owner, enforced link, target, and settings in **Group +Policy Management**. Confirm that the override is required by the policy design +before changing it. If it is not required, assess effects on inheritance and use +the normal change process to remove the enforced flag; do not disable enforcement +blindly. Investigate any unknown enforcement state. #### Related Tests -- `Test-MtAdGpoEnforcementCount`. + +- [AD-GPOL-04 — GPO links should not use enforcement](https://maester.dev/docs/tests/AD-GPOL-04) (`Test-MtAdGpoEnforcedCount`) evaluates individual enforced link entries and fails when any are found. +- [AD-GPOL-05 — OUs should not block Group Policy inheritance](https://maester.dev/docs/tests/AD-GPOL-05) (`Test-MtAdGpoBlockedInheritanceCount`) inventories OUs that block inheritance. +- [AD-GPOREP-12 — Review disabled GPO links](https://maester.dev/docs/tests/AD-GPOREP-12) (`Test-MtCheckADGPOREP12`) inventories disabled links, including links that may also be enforced. #### 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-14.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-14.ps1 index 54027b7cb3..0e538c3525 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-14.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOREP-14.ps1 @@ -1,72 +1,60 @@ -<# #> -function Test-MtAdGpoEnforcementCount { +function Test-MtAdGpoEnforcementCount { <# .SYNOPSIS - Counts the number of GPOs that have enforced GPO links. + Inventories GPOs that have at least one enforced link. .DESCRIPTION - This test retrieves Active Directory Group Policy state information using Get-MtADGpoState, - then counts how many returned GPO reports indicate enforced links. + Counts policies, not link entries. Enforcement overrides Block Inheritance; + unknown link data remains visible rather than being counted as not enforced. .EXAMPLE - Test-MtAdGpoEnforcementCount + Invoke-MtTest -Id 'AD-GPOREP-14' - Returns $true if GPO report data is accessible, $false otherwise. - The test result includes the number of GPOs with enforced links. + Inventories GPOs with enforced links and unknown enforcement for investigation. .LINK - https://maester.dev/docs/commands/Test-MtAdGpoEnforcementCount + https://maester.dev/docs/tests/AD-GPOREP-14 #> [MaesterTest( - Id = 'AD-GPOREP-14', - Title = 'GPO enforcement 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' + Id = 'AD-GPOREP-14', + Title = 'GPOs with enforced links 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-MtAdGpoEnforcementCount" - $gpoState = Get-MtADGpoState - Write-Verbose "Retrieved AD state" - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting gpo enforcement 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 - $enforcedCount = @($gpoReportsArray | Where-Object { [int]$_.Enforcement -gt 0 }).Count - - $testResult = $true - $enforcedPercentage = if ($totalCount -gt 0) { [Math]::Round(($enforcedCount / $totalCount) * 100, 2) } else { 0 } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total GPOs | $totalCount |" + "`n" - $result += "| GPOs with enforced links | $enforcedCount |" + "`n" - $result += "| Enforced ratio | $enforcedPercentage% |" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory GPOs have been analyzed for enforced links. $enforcedCount out of $totalCount GPO(s) have enforced link(s).`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdGpoEnforcementCount" - return $testResult + $state = Get-MtADGpoState + if ($null -eq $state -or $null -eq $state.GPOs) { throw 'GPO metadata could not be collected; enforcement cannot be inventoried.' } + $gpos = @($state.GPOs | Where-Object { $null -ne $_ }) + $linksComplete = Test-MtAdGpoLinksComplete -State $state + # A null aggregate in GPOReports can mean an unlinked GPO, not a failed read. + # The cached normalized link collection distinguishes known no-links from unknown. + $rows = @(foreach ($gpo in $gpos) { + $assessment = 'Unknown' + if ($null -ne $state.GPOLinks -and -not [string]::IsNullOrWhiteSpace([string]$gpo.Id)) { + $links = @($state.GPOLinks | Where-Object { ([string]$_.GpoGuid).Trim('{}') -eq ([string]$gpo.Id).Trim('{}') }) + if (@($links | Where-Object { $true -eq $_.IsEnforced }).Count -gt 0) { $assessment = 'Enforced link present' } + elseif ($linksComplete -and @($links | Where-Object { $null -eq $_.IsEnforced }).Count -eq 0) { $assessment = 'No enforced links' } + } + [pscustomobject]@{ Name = $gpo.DisplayName; Enforcement = $assessment } + }) + $enforced = @($rows | Where-Object Enforcement -EQ 'Enforced link present') + $unknown = @($rows | Where-Object Enforcement -EQ 'Unknown') + $details = @($enforced + $unknown | Sort-Object Name) + $summary = if ($enforced.Count -eq 0 -and $unknown.Count -eq 0) { 'No collected GPO has an enforced link.' } + elseif ($unknown.Count -eq $gpos.Count) { 'Link enforcement could not be determined for any collected GPO.' } + elseif ($enforced.Count -eq 0) { 'No enforced links were found among evaluated GPOs.' } + else { "$($enforced.Count) of $($gpos.Count) GPOs have enforced links. Review their scope and inheritance overrides." } + if ($unknown.Count -gt 0) { $summary += " Link enforcement is unknown for $($unknown.Count) GPOs." } + $result = Format-MtAdGpoResult -Summary $summary -Metrics ([ordered]@{ 'Total GPOs' = $gpos.Count; 'GPOs with enforced links' = $enforced.Count; 'GPOs with unknown enforcement' = $unknown.Count }) -Details $details -Properties Name, Enforcement -Headers GPO, 'Link enforcement' + Add-MtTestResultDetail -Result $result -Investigate + return $true } diff --git a/tests/ad/gpo-state/Test.AD-GPOREP-15.md b/tests/ad/gpo-state/Test.AD-GPOREP-15.md index babf93248d..51a6442512 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-15.md +++ b/tests/ad/gpo-state/Test.AD-GPOREP-15.md @@ -1,26 +1,50 @@ -#### Test-MtAdGpoVersionMismatchCount - - Counts the number of GPOs with a version mismatch. - -#### Why This Test Matters -- Detective control: flags GPOs that have a version mismatch which could affect policy consistency across machines. +Checks whether each GPO's Active Directory version matches its SYSVOL `GPT.INI` +version. A mismatch fails the test and can indicate inconsistent policy state. +This is a read-only diagnostic of collected versions; it does not repair either +copy or establish the cause of a mismatch. #### Control Type **Detective** +#### Why This Test Matters + +Group Policy stores policy information in Active Directory and SYSVOL. A version +mismatch can point to replication or policy deployment problems, leaving collected +directory and file-system state inconsistent. Clients can then receive stale or +inconsistent settings, including security controls. The result identifies the two +reported versions but does not determine which copy is authoritative. + #### Security Recommendation -- Review mismatched GPOs and align versions with baseline configurations. + +Investigate each mismatch and verify replication and access to the relevant +`GPT.INI` before making changes. Use the established recovery process to restore +consistent policy state rather than manually changing a version value in isolation. #### How the Test Works -- Pulls GPO state, filters HasVersionMismatch, counts total/mismatched and computes a mismatch ratio. + +- Compares each collected GPO's directory version with its SYSVOL `GPT.INI` + version. +- A difference fails and is reported with both version values. Matching collected + versions pass this comparison; they do not certify the policy's settings. +- Missing version data, an empty report set, or a report count that differs from + the GPO inventory is an error, not a clean result. + +#### Remediation action + +1. In **Group Policy Management**, identify each listed GPO and verify its + directory and SYSVOL versions, including access to `GPT.INI`. +2. Diagnose replication and collection issues, then resolve inconsistent policy + files and directory metadata through the normal recovery process. Re-run the + check after replication completes. #### Related Tests -- `Test-MtAdGpoVersionMismatchDetails`. + +- [AD-GPO-01 — GPO inventory should be investigated](https://maester.dev/docs/tests/AD-GPO-01) (`Test-MtAdGpoTotalCount`) inventories the GPO population for context; it does not assess version consistency. #### 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..6ad7eb2e0f 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-15.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOREP-15.ps1 @@ -1,74 +1,53 @@ -<# #> -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. + Lists policies with differing directory and GPT.INI versions; incomplete comparisons are errors. .EXAMPLE - Test-MtAdGpoVersionMismatchCount + Invoke-MtTest -Id 'AD-GPOREP-15' - Returns $true if GPO report data is accessible, $false otherwise. - The test result includes the number of GPOs with version mismatch. + Fails when directory and SYSVOL versions differ for a GPO. .LINK - https://maester.dev/docs/commands/Test-MtAdGpoVersionMismatchCount + https://maester.dev/docs/tests/AD-GPOREP-15 #> [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', + 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' + Mitre = 'None', + Service = 'ActiveDirectory', + Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), + Author = 'soulemike' )] [CmdletBinding()] [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 - } - - $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 + $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 + }) + 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 }) + $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." } + $result = Format-MtAdGpoResult -Summary $message -Metrics ([ordered]@{ 'Total GPOs' = $reports.Count; 'GPOs with version mismatches' = $mismatched.Count }) -Details @($mismatched | Sort-Object Name) -Properties Name, DirectoryVersion, SysvolVersion -Headers GPO, 'Directory version', 'SYSVOL version' + Add-MtTestResultDetail -Result $result + 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..d2e7bcbd55 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-17.md +++ b/tests/ad/gpo-state/Test.AD-GPOREP-17.md @@ -1,26 +1,55 @@ -#### Test-MtAdGpoCpasswordFoundCount - - Counts the number of GPOs that contain a cpassword. - -#### Why This Test Matters -- Detective control: counts GPOs containing a cpassword which indicates potential credential exposure. +Scans collected GPO files for Group Policy Preferences `cpassword` values and +default passwords in preferences or security templates. Any detected secret fails +the test. The read-only scan reports presence without exposing credential values; +it does not remove secrets or rotate credentials. #### Control Type **Detective** +#### Why This Test Matters + +The `cpassword` value is recoverable, and Microsoft notes that any authenticated +user can retrieve and decrypt passwords stored in Group Policy Preferences. Other +detected default passwords also represent exposed credentials. Treat findings as +critical and rotate affected credentials, including privileged ones; deleting a +stored value alone does not invalidate a credential that may already be known. + #### Security Recommendation -- Review cpassword occurrences and rotate credentials or secure storage as needed. + +Remove password-bearing settings from GPO files and rotate every affected +credential. Use a supported secret-management mechanism instead of storing +passwords in preferences or security templates. Applying the MS14-025 update does +not remove legacy `cpassword` values already stored in SYSVOL. #### How the Test Works -- Retrieves GPO state, filters for CpasswordFound, and reports totals and percentage of GPOs with cpasswords. + +- Scans collected GPO files for `cpassword` and default-password indicators in + preferences or security templates. +- Either finding type on a policy is enough to fail the test. A policy is counted + once even if both indicators are present; details show flags, not secret values. +- An incomplete scan with no findings is an error, not a clean pass. If findings + exist, the test fails and reports scan incompleteness. Missing reports, an + empty report set, or an inventory/report count mismatch is an error. +- A clean result means no such passwords were found in the completed scan; it + does not certify other GPO settings. + +#### Remediation action + +1. In **Group Policy Management**, locate each listed GPO and remove + password-bearing preferences or security-template settings from SYSVOL. +2. Rotate every credential stored there, including credentials for privileged + accounts. Then move secret handling to a supported mechanism and rescan all + GPOs; do not rely on removing the XML value alone. #### Related Tests -- `Test-MtAdGpoCpasswordFoundDetails`. + +- [AD-GPOREP-01 — No GPO should have an empty permissions list](https://maester.dev/docs/tests/AD-GPOREP-01) (`Test-MtAdGpoNoPermissionsCount`) assesses whether GPO permission entries are present; it does not determine which users can effectively read a secret-bearing file. #### 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 (MS14-025)](https://learn.microsoft.com/security-updates/securitybulletins/2014/ms14-025) +- [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-17.ps1 b/tests/ad/gpo-state/Test.AD-GPOREP-17.ps1 index 93ee88bc5b..88a66002c6 100644 --- a/tests/ad/gpo-state/Test.AD-GPOREP-17.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOREP-17.ps1 @@ -1,75 +1,60 @@ -<# #> -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. + Flags either Group Policy Preferences cpassword or default passwords, including cases with only one finding type. Never includes credential values. .EXAMPLE - Test-MtAdGpoCpasswordFoundCount + Invoke-MtTest -Id 'AD-GPOREP-17' - Returns $true if GPO report data is accessible, $false otherwise. - The test result includes the number of GPOs with cpassword present. + Fails when scanned GPO files expose cpassword or default passwords. .LINK - https://maester.dev/docs/commands/Test-MtAdGpoCpasswordFoundCount + https://maester.dev/docs/tests/AD-GPOREP-17 #> [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', + 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.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' + 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-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 + }) + $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 }) + if ($found.Count -eq 0 -and $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 + $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 affected credentials." } + if ($incomplete.Count -gt 0) { $message += " Scanning was incomplete for $($incomplete.Count) GPOs." } + $result = Format-MtAdGpoResult -Summary $message -Metrics ([ordered]@{ 'Total GPOs' = $reports.Count; 'GPOs exposing passwords' = $found.Count; 'GPOs with cpassword' = $cpassword.Count; 'GPOs with default passwords' = $defaultPassword.Count; 'GPOs with incomplete scans' = $incomplete.Count }) -Details @($found | Sort-Object Name) -Properties Name, CpasswordFound, DefaultPasswordFound -Headers GPO, 'cpassword present', 'Default password present' + Add-MtTestResultDetail -Result $result + 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 -} diff --git a/tests/ad/gpo-state/Test.AD-GPOS-01.md b/tests/ad/gpo-state/Test.AD-GPOS-01.md deleted file mode 100644 index 18cd1363df..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOS-01.md +++ /dev/null @@ -1,26 +0,0 @@ -#### Test-MtAdGpoStateTotalCount - - Counts the total number of Group Policy Objects (GPOs) returned by Get-MtADGpoState. - -#### Why This Test Matters -- Operational control: provides a quick overview of the total GPOs present in the AD state to gauge scope. - -#### Control Type - -**Operational** - -#### Security Recommendation -- Use as a baseline metric; no remediation required unless counts look unexpectedly abnormal. - -#### How the Test Works -- Calls Get-MtADGpoState, counts non-null GPOs in the GPOs collection, and reports a Markdown table with a single Total GPOs value. - -#### Related Tests -- `Test-MtAdGpoStateTotalCount` is the primary reference. - -#### Related links -- [Microsoft Learn - Group Policy overview](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-GPOS-01.ps1 b/tests/ad/gpo-state/Test.AD-GPOS-01.ps1 deleted file mode 100644 index f3b9f6c7f1..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOS-01.ps1 +++ /dev/null @@ -1,68 +0,0 @@ -<# #> -function Test-MtAdGpoStateTotalCount { - <# - .SYNOPSIS - Counts the total number of Group Policy Objects (GPOs) returned by Get-MtADGpoState. - - .DESCRIPTION - This test retrieves Active Directory GPO state data using Get-MtADGpoState and counts the total - number of GPO entries present in the returned state. - - .EXAMPLE - Test-MtAdGpoStateTotalCount - - Returns $true if GPO state data is accessible, $false otherwise. - The test result includes the total number of returned GPOs. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoStateTotalCount - #> - [MaesterTest( - Id = 'AD-GPOS-01', - Title = 'GPO state total 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-MtAdGpoStateTotalCount" - $gpoState = Get-MtADGpoState - Write-Verbose "Retrieved AD state" - - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting gpo state total count" - - $gpos = $gpoState.GPOs - if ($null -eq $gpos) { - Add-MtTestResultDetail -Result 'Unable to retrieve Active Directory Group Policy Objects (GPOs) from Get-MtADGpoState.' - return $false - } - - $totalCount = @($gpos | Where-Object { $null -ne $_ }).Count - - $testResult = $true - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total GPOs (state) | $totalCount |" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory GPO state has been analyzed. The domain contains $totalCount GPO(s) (state view).`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdGpoStateTotalCount" - return $testResult -} diff --git a/tests/ad/gpo-state/Test.AD-GPOS-02.md b/tests/ad/gpo-state/Test.AD-GPOS-02.md index c8e17ac6cb..e392655a01 100644 --- a/tests/ad/gpo-state/Test.AD-GPOS-02.md +++ b/tests/ad/gpo-state/Test.AD-GPOS-02.md @@ -1,26 +1,38 @@ -#### Test-MtAdGpoWmiFilterCount - - Counts the number of GPOs that have a non-empty WMI filter. +Inventories GPOs with non-empty WMI filter references and reports those references. The **Investigate** result is informational: WMI filters affect policy targeting, but their presence alone is not a security finding. #### Why This Test Matters -- Operational control: counts GPOs that have a non-empty WMI filter to gauge policy scoping across the environment. + +WMI filters can constrain which computers receive a linked GPO. A poorly scoped filter can exclude intended computers from required security settings, and an inefficient query can delay policy processing. Reviewing their use and intended scope can help identify those issues. A filter reference by itself does not show that its query is incorrect or that a policy is applied inappropriately. #### Control Type -**Operational** +**Operational** — this test inventories filter references for review; it does not evaluate their security or validate policy application. #### Security Recommendation -- Review configure WMI filters to ensure correct targeting and minimize unnecessary exposure. + +- Review each filter's query and intended scope with its owner. +- Confirm that linked policies target the intended computers and users. +- Revise or remove a filter only after checking the effect on policy targeting and following the normal change process. #### How the Test Works -- Gets GPO state, computes the number of GPOs with a non-empty WmiFilter, and reports totals and ratios. + +The test reads the collected GPO inventory and counts entries whose `WmiFilter` reference is non-empty. It reports the total GPO count and the count with filter references, and lists the associated GPO and reference when filters are found. When none are found, the summary says so without an empty details table. Successful collection returns **Investigate**, whether or not references are found; failed GPO inventory collection is an error. + +This check looks only for a non-empty reference. It does not parse or validate the full WMI query, establish whether the referenced filter is available, or determine which systems receive the policy. The collector cannot distinguish an attribute that was not returned from one that was returned blank, so an empty reference is not complete audit proof that no filter exists. + +#### Remediation action + +Review each reported filter's query and intended scope with its owner. Confirm that linked policies target the intended computers and users, and assess query behavior and performance. Remove or revise filters only through the normal policy change process. #### Related Tests -- `Test-MtAdGpoWmiFilterDetails`. + +- [AD-GPOL-01 — GPOs with enabled links should be investigated](https://maester.dev/docs/tests/AD-GPOL-01) (`Test-MtAdGpoLinkedCount`) inventories GPOs with enabled links, one part of policy targeting. +- [AD-GPOS-04 — Disabled GPO settings should be investigated](https://maester.dev/docs/tests/AD-GPOS-04) (`Test-MtAdGpoSettingsDisabledCount`) inventories disabled user or computer settings separately from WMI filter references. +- [AD-GPOREP-10 — GPOs should have an Apply Group Policy allow entry](https://maester.dev/docs/tests/AD-GPOREP-10) (`Test-MtAdGpoNoApplyGroupPolicyAceCount`) checks explicit Apply Group Policy entries, another aspect of policy targeting. #### 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-GPOS-02.ps1 b/tests/ad/gpo-state/Test.AD-GPOS-02.ps1 index 7cbad37fe6..4029483932 100644 --- a/tests/ad/gpo-state/Test.AD-GPOS-02.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOS-02.ps1 @@ -1,79 +1,42 @@ -<# #> -function Test-MtAdGpoWmiFilterCount { +function Test-MtAdGpoWmiFilterCount { <# .SYNOPSIS - Counts the number of GPOs that have a non-empty WMI filter. + Inventories GPOs with WMI filters, including their filter references. .DESCRIPTION - This test retrieves Active Directory GPO state data using Get-MtADGpoState and counts how many - returned GPOs have a configured WmiFilter value. + Combines counts and details for non-empty WMI filter references. The inventory + requires investigation, not a pass/fail judgement on targeting. .EXAMPLE - Test-MtAdGpoWmiFilterCount + Invoke-MtTest -Id 'AD-GPOS-02' - Returns $true if GPO state data is accessible, $false otherwise. - The test result includes counts of WMI-filtered vs total GPOs. + Inventories WMI filter references for investigation without judging their targeting. .LINK - https://maester.dev/docs/commands/Test-MtAdGpoWmiFilterCount + https://maester.dev/docs/tests/AD-GPOS-02 #> [MaesterTest( - Id = 'AD-GPOS-02', - Title = 'WMI filter 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' + Id = 'AD-GPOS-02', + Title = 'GPO WMI filters 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-MtAdGpoWmiFilterCount" - $gpoState = Get-MtADGpoState - Write-Verbose "Retrieved AD state" - - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting gpo wmi filter count" - - $gpos = $gpoState.GPOs - if ($null -eq $gpos) { - Add-MtTestResultDetail -Result 'Unable to retrieve Active Directory Group Policy Objects (GPOs) from Get-MtADGpoState.' - return $false - } - - $gposArray = @($gpos | Where-Object { $null -ne $_ }) - $totalCount = $gposArray.Count - - $wmiFiltered = $gposArray | Where-Object { - $wf = $_.WmiFilter - -not [string]::IsNullOrWhiteSpace([string]$wf) - } - - $wmiFilterCount = @($wmiFiltered).Count - $testResult = $true - - $wmiPercentage = if ($totalCount -gt 0) { [Math]::Round(($wmiFilterCount / $totalCount) * 100, 2) } else { 0 } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total GPOs (state) | $totalCount |" + "`n" - $result += "| GPOs with WMI Filter | $wmiFilterCount |" + "`n" - $result += "| WMI Filter ratio | $wmiPercentage% |" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory GPOs have been analyzed for WMI filters. $wmiFilterCount out of $totalCount GPO(s) have a WMI filter configured.`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdGpoWmiFilterCount" - return $testResult + $state = Get-MtADGpoState + if ($null -eq $state -or $null -eq $state.GPOs) { throw 'GPO metadata could not be collected; WMI filters cannot be inventoried.' } + $gpos = @($state.GPOs | Where-Object { $null -ne $_ }) + $filtered = @($gpos | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_.WmiFilter) } | Sort-Object DisplayName) + $summary = if ($filtered.Count -eq 0) { 'No collected GPO has a WMI filter reference.' } else { "$($filtered.Count) of $($gpos.Count) GPOs have WMI filter references. Review targeting and filter performance." } + $result = Format-MtAdGpoResult -Summary $summary -Metrics ([ordered]@{ 'Total GPOs' = $gpos.Count; 'GPOs with WMI filters' = $filtered.Count }) -Details $filtered -Properties DisplayName, Id, WmiFilter -Headers GPO, Id, 'WMI filter' + Add-MtTestResultDetail -Result $result -Investigate + return $true } diff --git a/tests/ad/gpo-state/Test.AD-GPOS-03.md b/tests/ad/gpo-state/Test.AD-GPOS-03.md deleted file mode 100644 index 721412f0fc..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOS-03.md +++ /dev/null @@ -1,26 +0,0 @@ -#### Test-MtAdGpoWmiFilterDetails - - Returns details of GPOs with a WMI filter configuration. - -#### Why This Test Matters -- Detective control: detects GPOs with a non-empty WMI filter, which can influence policy scope per machine. - -#### Control Type - -**Operational** - -#### Security Recommendation -- Review WMI-filtered GPOs to ensure filters are intentional and correctly scoped. - -#### How the Test Works -- Retrieves GPO state, filters for Gpos with a non-empty WmiFilter, and renders a Markdown table with details. - -#### Related Tests -- `Test-MtAdGpoWmiFilterCount`. - -#### 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-GPOS-03.ps1 b/tests/ad/gpo-state/Test.AD-GPOS-03.ps1 deleted file mode 100644 index 95a8d81afc..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOS-03.ps1 +++ /dev/null @@ -1,94 +0,0 @@ -<# #> -function Test-MtAdGpoWmiFilterDetails { - <# - .SYNOPSIS - Returns details of GPOs that have a non-empty WMI filter. - - .DESCRIPTION - This test retrieves Active Directory GPO state data using Get-MtADGpoState and returns a markdown - table listing all GPOs whose WmiFilter property is configured. - - .EXAMPLE - Test-MtAdGpoWmiFilterDetails - - Returns $true if GPO state data is accessible, $false otherwise. - The test result includes a markdown table of GPO WMI filter configuration. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoWmiFilterDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-GPOS-03', - Title = 'WMI filter 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-MtAdGpoWmiFilterDetails" - $gpoState = Get-MtADGpoState - Write-Verbose "Retrieved AD state" - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting gpo wmi filter details" - - $gpos = $gpoState.GPOs - if ($null -eq $gpos) { - Add-MtTestResultDetail -Result 'Unable to retrieve Active Directory Group Policy Objects (GPOs) from Get-MtADGpoState.' - return $false - } - - $gposArray = @($gpos | Where-Object { $null -ne $_ }) - - $wmiFiltered = $gposArray | Where-Object { - $wf = $_.WmiFilter - -not [string]::IsNullOrWhiteSpace([string]$wf) - } - - $wmiFilteredCount = @($wmiFiltered).Count - $testResult = $true - - $table = "| GPO DisplayName | Id | GpoStatus | WmiFilter | Owner |" + "`n" - $table += '| --- | --- | --- | --- | --- |' + "`n" - - foreach ($gpo in @($wmiFiltered | Sort-Object -Property DisplayName)) { - $displayName = [string]$gpo.DisplayName - $displayName = $displayName -replace '\|', '\\|' - - $id = [string]$gpo.Id - $owner = if ($null -ne $gpo.Owner) { [string]$gpo.Owner } else { '' } - $owner = $owner -replace '\|', '\\|' - - $status = if ($null -ne $gpo.GpoStatus) { $gpo.GpoStatus } else { '' } - $wmiFilter = [string]$gpo.WmiFilter - $wmiFilter = $wmiFilter -replace '\|', '\\|' - - $table += "| $displayName | $id | $status | $wmiFilter | $owner |" + "`n" - } - - $recommendation = if ($wmiFilteredCount -gt 0) { - "GPO WMI filter details were returned ($wmiFilteredCount). Review these filters to ensure they are still intended." - } else { - '✅ No GPOs with WMI filter 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-MtAdGpoWmiFilterDetails" - return $testResult -} diff --git a/tests/ad/gpo-state/Test.AD-GPOS-04.md b/tests/ad/gpo-state/Test.AD-GPOS-04.md index 5dee734d9d..b36ae5995f 100644 --- a/tests/ad/gpo-state/Test.AD-GPOS-04.md +++ b/tests/ad/gpo-state/Test.AD-GPOS-04.md @@ -1,26 +1,42 @@ -#### Test-MtAdGpoSettingsDisabledCount - - Counts GPOs where settings are disabled (AllDisabled, UserDisabled, or ComputerDisabled). +Inventories GPOs with disabled settings, separating **all settings disabled**, **user settings disabled**, and **computer settings disabled**. These categories are disjoint. Unknown or unrecognized statuses are reported separately and are not counted as enabled. The **Investigate** result does not judge whether a disabled category is appropriate. #### Why This Test Matters -- Detective control: checks how many GPOs have disabled settings (AllDisabled, UserDisabled, ComputerDisabled). + +GPO status indicates which part of a policy is configured as disabled. Accidentally disabling a category can prevent its intended security settings from being applied. Disabling an unused category can also be deliberate and appropriate. The inventory supports owner review but does not label every disabled setting a security problem. #### Control Type -**Operational** +**Operational** — this test inventories policy status for investigation; it does not evaluate whether disabled settings are appropriate. #### Security Recommendation -- Review disabled settings to confirm they are intentional and document exceptions if needed. + +- Confirm with the policy owner whether each disabled category is intentional and documented. +- Review policy scope and change history before enabling settings, since doing so may affect users or computers. +- Investigate unknown status values rather than treating them as enabled or assuming they indicate a disabled policy. #### How the Test Works -- Counts GPOs whose GpoStatus maps to a disabled state and reports totals and ratios. + +The test maps known GPO status values to four categories: `0` = all settings disabled, `1` = user settings disabled, `2` = computer settings disabled, and `3` = all settings enabled. The three disabled categories are mutually exclusive. Unrecognized or missing values are labeled **Unknown**, reported separately, and never counted as enabled. + +The result reports total GPOs, counts for each disabled category, and the unknown-status count. It lists policies with disabled or unknown status when any exist and does not render an empty details table otherwise. Successful collection always returns **Investigate**; unavailable GPO inventory is an error. + +These rules apply to the collected `GpoStatus` value. The collector currently maps +an absent directory `flags` attribute to the enabled status, so this inventory is +not proof that every underlying LDAP attribute was returned. + +#### Remediation action + +Review each listed policy with its owner and confirm whether its disabled settings or unknown status are intentional. Check the policy's scope and change history before enabling settings; document approved exceptions. Investigate unknown status through inventory or data-quality review rather than guessing the intended state. #### Related Tests -- `Test-MtAdGpoAllSettingsDisabledDetails` and `Test-MtAdGpoSettingsDisabledCount`. + +- [AD-GPO-01 — GPO inventory should be investigated](https://maester.dev/docs/tests/AD-GPO-01) (`Test-MtAdGpoTotalCount`) reports the total GPO inventory for context. +- [AD-GPOS-02 — GPO WMI filters should be investigated](https://maester.dev/docs/tests/AD-GPOS-02) (`Test-MtAdGpoWmiFilterCount`) inventories GPOs with WMI filter references, a separate policy attribute. +- [AD-GPOREP-12 — Review disabled GPO links](https://maester.dev/docs/tests/AD-GPOREP-12) (`Test-MtCheckADGPOREP12`) inventories disabled links; link state and disabled policy settings are separate conditions. #### 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-GPOS-04.ps1 b/tests/ad/gpo-state/Test.AD-GPOS-04.ps1 index 88b50927c4..b8112eb014 100644 --- a/tests/ad/gpo-state/Test.AD-GPOS-04.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOS-04.ps1 @@ -1,101 +1,64 @@ -<# #> -function Test-MtAdGpoSettingsDisabledCount { +function Test-MtAdGpoSettingsDisabledCount { <# .SYNOPSIS - Counts GPOs where settings are disabled (AllDisabled, UserDisabled, or ComputerDisabled). + Inventories disabled user, computer or both GPO settings. .DESCRIPTION - This test retrieves Active Directory GPO state data using Get-MtADGpoState and counts how many - returned GPOs have GpoStatus values indicating disabled settings. - - GpoStatus mapping: - - 0 = AllDisabled - - 1 = UserDisabled - - 2 = ComputerDisabled - - 3 = AllEnabled + Combines category counts and policy details. Numeric and named statuses are + matched exactly; unknown statuses remain visible and never count as enabled. .EXAMPLE - Test-MtAdGpoSettingsDisabledCount + Invoke-MtTest -Id 'AD-GPOS-04' - Returns $true if GPO state data is accessible, $false otherwise. - The test result includes disabled vs total GPO counts. + Inventories disabled settings and unknown statuses for investigation. .LINK - https://maester.dev/docs/commands/Test-MtAdGpoSettingsDisabledCount + https://maester.dev/docs/tests/AD-GPOS-04 #> [MaesterTest( - Id = 'AD-GPOS-04', - Title = 'Disabled GPO settings 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' + Id = 'AD-GPOS-04', + Title = 'Disabled GPO settings 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-MtAdGpoSettingsDisabledCount" - $gpoState = Get-MtADGpoState - Write-Verbose "Retrieved AD state" - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting gpo settings disabled count" - - $gpos = $gpoState.GPOs - if ($null -eq $gpos) { - Add-MtTestResultDetail -Result 'Unable to retrieve Active Directory Group Policy Objects (GPOs) from Get-MtADGpoState.' - return $false - } - - function Convert-GpoStatusToInt { - param([object]$Status) - - if ($null -eq $Status) { return $null } - - $s = [string]$Status - if ($s -match '^\s*(\d+)\s*$') { return [int]$Matches[1] } - switch -Regex ($s) { - 'AllDisabled' { return 0 } - 'UserDisabled' { return 1 } - 'ComputerDisabled' { return 2 } - 'AllEnabled' { return 3 } - } - - return $null + $state = Get-MtADGpoState + if ($null -eq $state -or $null -eq $state.GPOs) { throw 'GPO metadata could not be collected; disabled settings cannot be inventoried.' } + $rows = @(foreach ($gpo in @($state.GPOs | Where-Object { $null -ne $_ })) { + $status = switch -Regex (([string]$gpo.GpoStatus).Trim()) { + '^(0|AllDisabled|AllSettingsDisabled)$' { 'All settings disabled'; break } + '^(1|UserDisabled|UserSettingsDisabled)$' { 'User settings disabled'; break } + '^(2|ComputerDisabled|ComputerSettingsDisabled)$' { 'Computer settings disabled'; break } + '^(3|AllEnabled|AllSettingsEnabled)$' { 'All settings enabled'; break } + default { 'Unknown' } + } + [pscustomobject]@{ Name = $gpo.DisplayName; Id = $gpo.Id; Status = $status } + }) + $disabled = @($rows | Where-Object { $_.Status -notin 'All settings enabled', 'Unknown' }) + $unknown = @($rows | Where-Object Status -EQ 'Unknown') + $summary = if ($disabled.Count -eq 0 -and $unknown.Count -eq 0) { 'No collected GPO has disabled user or computer settings.' } + elseif ($unknown.Count -eq $rows.Count) { 'Settings status could not be determined for any collected GPO.' } + elseif ($disabled.Count -eq 0) { 'No disabled settings were found among evaluated GPOs.' } + else { "$($disabled.Count) of $($rows.Count) GPOs have disabled settings. Review whether each disabled category is intentional." } + if ($unknown.Count -gt 0) { $summary += " Settings status is unknown for $($unknown.Count) GPOs." } + $metrics = [ordered]@{ + 'Total GPOs' = $rows.Count + 'GPOs with disabled settings' = $disabled.Count + 'Only user settings disabled' = @($rows | Where-Object Status -EQ 'User settings disabled').Count + 'Only computer settings disabled' = @($rows | Where-Object Status -EQ 'Computer settings disabled').Count + 'All settings disabled' = @($rows | Where-Object Status -EQ 'All settings disabled').Count + 'GPOs with unknown status' = $unknown.Count } - - $gposArray = @($gpos | Where-Object { $null -ne $_ }) - $totalCount = $gposArray.Count - - $disabledGpos = foreach ($gpo in $gposArray) { - $statusInt = Convert-GpoStatusToInt -Status $gpo.GpoStatus - if ($null -ne $statusInt -and $statusInt -in 0,1,2) { $gpo } - } - - $disabledCount = @($disabledGpos).Count - $testResult = $true - - $disabledPercentage = if ($totalCount -gt 0) { [Math]::Round(($disabledCount / $totalCount) * 100, 2) } else { 0 } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total GPOs (state) | $totalCount |" + "`n" - $result += "| GPOs with disabled settings | $disabledCount |" + "`n" - $result += "| Disabled ratio | $disabledPercentage% |" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory GPOs have been analyzed for disabled settings. $disabledCount out of $totalCount GPO(s) have disabled settings (GpoStatus 0, 1, or 2).`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdGpoSettingsDisabledCount" - return $testResult + $result = Format-MtAdGpoResult -Summary $summary -Metrics $metrics -Details @($disabled + $unknown | Sort-Object Name) -Properties Name, Id, Status -Headers GPO, Id, 'Settings status' + Add-MtTestResultDetail -Result $result -Investigate + return $true } diff --git a/tests/ad/gpo-state/Test.AD-GPOS-05.md b/tests/ad/gpo-state/Test.AD-GPOS-05.md deleted file mode 100644 index e86e11cfb2..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOS-05.md +++ /dev/null @@ -1,26 +0,0 @@ -#### Test-MtAdGpoComputerSettingsDisabledDetails - - Returns details of GPOs where computer settings are disabled. - -#### Why This Test Matters -- Detective control: lists GPOs where computer settings are disabled which can affect machine-level policy delivery. - -#### Control Type - -**Operational** - -#### Security Recommendation -- Review computer-disabled GPOs and confirm they are intentional. - -#### How the Test Works -- Analyzes GPO state to extract GpoStatus ComputerDisabled details and renders a detailed table. - -#### Related Tests -- `Test-MtAdGpoComputerSettingsDisabledDetails`. - -#### 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-GPOS-05.ps1 b/tests/ad/gpo-state/Test.AD-GPOS-05.ps1 deleted file mode 100644 index e1e465f70f..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOS-05.ps1 +++ /dev/null @@ -1,114 +0,0 @@ -<# #> -function Test-MtAdGpoComputerSettingsDisabledDetails { - <# - .SYNOPSIS - Returns details of GPOs where computer settings are disabled. - - .DESCRIPTION - This test retrieves Active Directory GPO state data using Get-MtADGpoState and returns a markdown - table listing GPOs with GpoStatus indicating computer settings are disabled. - - GpoStatus mapping: - - 0 = AllDisabled - - 1 = UserDisabled - - 2 = ComputerDisabled - - 3 = AllEnabled - - .EXAMPLE - Test-MtAdGpoComputerSettingsDisabledDetails - - Returns $true if GPO state data is accessible, $false otherwise. - The test result includes a markdown table with the computer-disabled GPOs. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoComputerSettingsDisabledDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-GPOS-05', - Title = 'Computer disabled GPO settings 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-MtAdGpoComputerSettingsDisabledDetails" - $gpoState = Get-MtADGpoState - Write-Verbose "Retrieved AD state" - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting gpo computer settings disabled details" - - $gpos = $gpoState.GPOs - if ($null -eq $gpos) { - Add-MtTestResultDetail -Result 'Unable to retrieve Active Directory Group Policy Objects (GPOs) from Get-MtADGpoState.' - return $false - } - - function Convert-GpoStatusToInt { - param([object]$Status) - - if ($null -eq $Status) { return $null } - $s = [string]$Status - if ($s -match '^\s*(\d+)\s*$') { return [int]$Matches[1] } - switch -Regex ($s) { - 'AllDisabled' { return 0 } - 'UserDisabled' { return 1 } - 'ComputerDisabled' { return 2 } - 'AllEnabled' { return 3 } - } - return $null - } - - $gposArray = @($gpos | Where-Object { $null -ne $_ }) - - $computerDisabled = foreach ($gpo in $gposArray) { - $statusInt = Convert-GpoStatusToInt -Status $gpo.GpoStatus - if ($null -ne $statusInt -and $statusInt -eq 2) { $gpo } - } - - $computerDisabledCount = @($computerDisabled).Count - $testResult = $true - - $table = "| GPO DisplayName | Id | GpoStatus | WmiFilter | Owner |" + "`n" - $table += '| --- | --- | --- | --- | --- |' + "`n" - - foreach ($gpo in @($computerDisabled | Sort-Object -Property DisplayName)) { - $displayName = [string]$gpo.DisplayName - $displayName = $displayName -replace '\|', '\\|' - $id = [string]$gpo.Id - $status = if ($null -ne $gpo.GpoStatus) { $gpo.GpoStatus } else { '' } - $wmiFilter = [string]$gpo.WmiFilter - $wmiFilter = $wmiFilter -replace '\|', '\\|' - $owner = if ($null -ne $gpo.Owner) { [string]$gpo.Owner } else { '' } - $owner = $owner -replace '\|', '\\|' - - $table += "| $displayName | $id | $status | $wmiFilter | $owner |" + "`n" - } - - $recommendation = if ($computerDisabledCount -gt 0) { - "GPOs with computer settings disabled were returned ($computerDisabledCount).` -Review these GPOs to ensure computer-side policy delivery is intentionally disabled." - } else { - '✅ No GPOs with computer settings disabled 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-MtAdGpoComputerSettingsDisabledDetails" - return $testResult -} diff --git a/tests/ad/gpo-state/Test.AD-GPOS-06.md b/tests/ad/gpo-state/Test.AD-GPOS-06.md deleted file mode 100644 index d6f9e56279..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOS-06.md +++ /dev/null @@ -1,26 +0,0 @@ -#### Test-MtAdGpoUserSettingsDisabledDetails - - Returns details of GPOs where user settings are disabled. - -#### Why This Test Matters -- Detective control: looks for GPOs where user settings are disabled, which can impact user policy delivery. - -#### Control Type - -**Operational** - -#### Security Recommendation -- Review user-disabled GPOs and confirm whether disabling is intentional per policy. - -#### How the Test Works -- Gets GPO state, filters for reports where the UserDisabled status is true and renders a details table including display name and status. - -#### Related Tests -- `Test-MtAdGpoUserSettingsDisabledDetails` (self reference for template clarity). - -#### 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-GPOS-06.ps1 b/tests/ad/gpo-state/Test.AD-GPOS-06.ps1 deleted file mode 100644 index ece5637a84..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOS-06.ps1 +++ /dev/null @@ -1,113 +0,0 @@ -<# #> -function Test-MtAdGpoUserSettingsDisabledDetails { - <# - .SYNOPSIS - Returns details of GPOs where user settings are disabled. - - .DESCRIPTION - This test retrieves Active Directory GPO state data using Get-MtADGpoState and returns a markdown - table listing GPOs with GpoStatus indicating user settings are disabled. - - GpoStatus mapping: - - 0 = AllDisabled - - 1 = UserDisabled - - 2 = ComputerDisabled - - 3 = AllEnabled - - .EXAMPLE - Test-MtAdGpoUserSettingsDisabledDetails - - Returns $true if GPO state data is accessible, $false otherwise. - The test result includes a markdown table with the user-disabled GPOs. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoUserSettingsDisabledDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-GPOS-06', - Title = 'User disabled GPO settings 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-MtAdGpoUserSettingsDisabledDetails" - $gpoState = Get-MtADGpoState - Write-Verbose "Retrieved AD state" - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting gpo user settings disabled details" - - $gpos = $gpoState.GPOs - if ($null -eq $gpos) { - Add-MtTestResultDetail -Result 'Unable to retrieve Active Directory Group Policy Objects (GPOs) from Get-MtADGpoState.' - return $false - } - - function Convert-GpoStatusToInt { - param([object]$Status) - - if ($null -eq $Status) { return $null } - $s = [string]$Status - if ($s -match '^\s*(\d+)\s*$') { return [int]$Matches[1] } - switch -Regex ($s) { - 'AllDisabled' { return 0 } - 'UserDisabled' { return 1 } - 'ComputerDisabled' { return 2 } - 'AllEnabled' { return 3 } - } - return $null - } - - $gposArray = @($gpos | Where-Object { $null -ne $_ }) - - $userDisabled = foreach ($gpo in $gposArray) { - $statusInt = Convert-GpoStatusToInt -Status $gpo.GpoStatus - if ($null -ne $statusInt -and $statusInt -eq 1) { $gpo } - } - - $userDisabledCount = @($userDisabled).Count - $testResult = $true - - $table = "| GPO DisplayName | Id | GpoStatus | WmiFilter | Owner |" + "`n" - $table += '| --- | --- | --- | --- | --- |' + "`n" - - foreach ($gpo in @($userDisabled | Sort-Object -Property DisplayName)) { - $displayName = [string]$gpo.DisplayName - $displayName = $displayName -replace '\|', '\\|' - $id = [string]$gpo.Id - $status = if ($null -ne $gpo.GpoStatus) { $gpo.GpoStatus } else { '' } - $wmiFilter = [string]$gpo.WmiFilter - $wmiFilter = $wmiFilter -replace '\|', '\\|' - $owner = if ($null -ne $gpo.Owner) { [string]$gpo.Owner } else { '' } - $owner = $owner -replace '\|', '\\|' - - $table += "| $displayName | $id | $status | $wmiFilter | $owner |" + "`n" - } - - $recommendation = if ($userDisabledCount -gt 0) { - "GPOs with user settings disabled were returned ($userDisabledCount).`nReview these GPOs to ensure user-side policy delivery is intentionally disabled." - } else { - '✅ No GPOs with user settings disabled 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-MtAdGpoUserSettingsDisabledDetails" - return $testResult -} diff --git a/tests/ad/gpo-state/Test.AD-GPOS-07.md b/tests/ad/gpo-state/Test.AD-GPOS-07.md deleted file mode 100644 index 55f4d5f87f..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOS-07.md +++ /dev/null @@ -1,26 +0,0 @@ -#### Test-MtAdGpoAllSettingsDisabledDetails - - Returns details of GPOs where all settings are disabled. - -#### Why This Test Matters -- Detective control: lists GPOs where all settings are disabled which can be a sign of misconfiguration or excessive restriction. - -#### Control Type - -**Operational** - -#### Security Recommendation -- Review fully disabled GPOs; decide whether to re-enable or remove them. - -#### How the Test Works -- Identifies GPOs with GpoStatus AllDisabled and renders a detailed MD table of those GPOs. - -#### Related Tests -- `Test-MtAdGpoAllSettingsDisabledDetails` is the current test; other related tests include state-wide counts. - -#### 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-GPOS-07.ps1 b/tests/ad/gpo-state/Test.AD-GPOS-07.ps1 deleted file mode 100644 index 8a5b7f3648..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOS-07.ps1 +++ /dev/null @@ -1,112 +0,0 @@ -<# #> -function Test-MtAdGpoAllSettingsDisabledDetails { - <# - .SYNOPSIS - Returns details of GPOs where all settings are disabled. - - .DESCRIPTION - This test retrieves Active Directory GPO state data using Get-MtADGpoState and returns a markdown - table listing GPOs with GpoStatus indicating all settings are disabled. - - GpoStatus mapping: - - 0 = AllDisabled - - 1 = UserDisabled - - 2 = ComputerDisabled - - 3 = AllEnabled - - .EXAMPLE - Test-MtAdGpoAllSettingsDisabledDetails - - Returns $true if GPO state data is accessible, $false otherwise. - The test result includes a markdown table with the fully-disabled GPOs. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoAllSettingsDisabledDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-GPOS-07', - Title = 'All disabled GPO settings 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-MtAdGpoAllSettingsDisabledDetails" - $gpoState = Get-MtADGpoState - Write-Verbose "Retrieved AD state" - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting gpo all settings disabled details" - - $gpos = $gpoState.GPOs - if ($null -eq $gpos) { - Add-MtTestResultDetail -Result 'Unable to retrieve Active Directory Group Policy Objects (GPOs) from Get-MtADGpoState.' - return $false - } - - function Convert-GpoStatusToInt { - param([object]$Status) - if ($null -eq $Status) { return $null } - $s = [string]$Status - if ($s -match '^\s*(\d+)\s*$') { return [int]$Matches[1] } - switch -Regex ($s) { - 'AllDisabled' { return 0 } - 'UserDisabled' { return 1 } - 'ComputerDisabled' { return 2 } - 'AllEnabled' { return 3 } - } - return $null - } - - $gposArray = @($gpos | Where-Object { $null -ne $_ }) - - $allDisabled = foreach ($gpo in $gposArray) { - $statusInt = Convert-GpoStatusToInt -Status $gpo.GpoStatus - if ($null -ne $statusInt -and $statusInt -eq 0) { $gpo } - } - - $allDisabledCount = @($allDisabled).Count - $testResult = $true - - $table = "| GPO DisplayName | Id | GpoStatus | WmiFilter | Owner |" + "`n" - $table += '| --- | --- | --- | --- | --- |' + "`n" - - foreach ($gpo in @($allDisabled | Sort-Object -Property DisplayName)) { - $displayName = [string]$gpo.DisplayName - $displayName = $displayName -replace '\|', '\\|' - $id = [string]$gpo.Id - $status = if ($null -ne $gpo.GpoStatus) { $gpo.GpoStatus } else { '' } - $wmiFilter = [string]$gpo.WmiFilter - $wmiFilter = $wmiFilter -replace '\|', '\\|' - $owner = if ($null -ne $gpo.Owner) { [string]$gpo.Owner } else { '' } - $owner = $owner -replace '\|', '\\|' - - $table += "| $displayName | $id | $status | $wmiFilter | $owner |" + "`n" - } - - $recommendation = if ($allDisabledCount -gt 0) { - "GPOs with all settings disabled were returned ($allDisabledCount). Review whether these GPOs should be re-enabled or removed." - } else { - '✅ No GPOs with all settings disabled 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-MtAdGpoAllSettingsDisabledDetails" - return $testResult -} diff --git a/tests/ad/gpo-state/Test.AD-GPOS-08.md b/tests/ad/gpo-state/Test.AD-GPOS-08.md index 1958afaf15..820de947c2 100644 --- a/tests/ad/gpo-state/Test.AD-GPOS-08.md +++ b/tests/ad/gpo-state/Test.AD-GPOS-08.md @@ -1,26 +1,38 @@ -#### Test-MtAdGpoOwnerDistinctCount - - Counts the number of distinct GPO owners. +Inventories distinct known owner identities across collected GPOs and groups policies by owner. Blank or missing owner values are reported as unknown, not counted as a distinct known owner. The **Investigate** result is informational: owner count alone does not establish whether ownership is appropriate or access is unauthorized. #### Why This Test Matters -- Operational control: assesses diversity of GPO owners which can highlight unusual configurations or omissions. + +Identifiable ownership helps administrators review policy purpose, maintenance, and delegated management. Ownership can influence permission management; inappropriate ownership or delegation can permit unauthorized policy changes. Unknown ownership can make accountability harder, while multiple owners may be appropriate in a larger environment. The number of owners by itself does not demonstrate excessive access or poor control. #### Control Type -**Operational** +**Operational** — this test inventories ownership information for review; it does not assess or change GPO permissions. #### Security Recommendation -- If many owners are identical or blank, review GPO creation practices to ensure proper ownership. + +- Keep ownership and delegation current so policy changes have an accountable reviewer. +- Resolve blank or unrecognized ownership where possible, while distinguishing unknown data from known owners. +- Review the permissions governing GPO management separately; an owner count alone does not prove who can change a policy. #### How the Test Works -- Retrieves GPO state, extracts Owner fields, computes distinct non-empty owners, and reports the count. + +The test groups collected GPOs by non-empty `Owner` values and reports the number of distinct known owner identities, the policy count for each, and associated policy names. GPOs with blank or missing owner values are grouped under unknown ownership and listed separately; they are not counted as an additional known owner. If the collector cannot translate an owner SID to a name, it retains the SID and counts it as a known identity. A counted SID does not establish that the account still exists or is an appropriate owner. + +If no GPOs are returned, the summary says so without an empty details table. Failed GPO inventory collection is an error. The test does not inspect permissions, validate whether an owner is authorized, or decide whether the number of owners is appropriate. It always returns **Investigate** when collection succeeds. + +#### Remediation action + +Review each known owner and the policies assigned to them. Resolve unknown ownership where possible, and confirm that ownership and delegation are current and appropriate for each policy. If access is a concern, review GPO permissions directly rather than inferring authorization from this count. #### Related Tests -- `Test-MtAdGpoOwnerDetails` - summarizes owners per GPOs. + +- [AD-GPO-01 — GPO inventory should be investigated](https://maester.dev/docs/tests/AD-GPO-01) (`Test-MtAdGpoTotalCount`) reports the total GPO inventory for context. +- [AD-GPO-02 — GPOs should be modified within the configured age limit](https://maester.dev/docs/tests/AD-GPO-02) (`Test-MtAdGpoStale`) identifies policies whose last modification exceeds the configured age limit. +- [AD-GPOREP-09 — GPOs should not inherit permission entries](https://maester.dev/docs/tests/AD-GPOREP-09) (`Test-MtAdGpoInheritedPermissionsCount`) checks inherited permission entries, which can affect GPO delegation. #### 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-GPOS-08.ps1 b/tests/ad/gpo-state/Test.AD-GPOS-08.ps1 index 953f1a331d..67409fa137 100644 --- a/tests/ad/gpo-state/Test.AD-GPOS-08.ps1 +++ b/tests/ad/gpo-state/Test.AD-GPOS-08.ps1 @@ -1,76 +1,48 @@ -<# #> -function Test-MtAdGpoOwnerDistinctCount { +function Test-MtAdGpoOwnerDistinctCount { <# .SYNOPSIS - Counts the number of distinct GPO owners. + Inventories distinct GPO owners and the policies owned by each. .DESCRIPTION - This test retrieves Active Directory GPO state data using Get-MtADGpoState and counts the number of - distinct (non-empty) Owner values found across returned GPO objects. + Combines the owner count and grouped details. Unresolved owners are listed + separately and are not counted as an additional known owner. .EXAMPLE - Test-MtAdGpoOwnerDistinctCount + Invoke-MtTest -Id 'AD-GPOS-08' - Returns $true if GPO state data is accessible, $false otherwise. - The test result includes the distinct owner count. + Inventories GPO owners and unresolved ownership for investigation. .LINK - https://maester.dev/docs/commands/Test-MtAdGpoOwnerDistinctCount + https://maester.dev/docs/tests/AD-GPOS-08 #> [MaesterTest( - Id = 'AD-GPOS-08', - Title = 'GPO owner distinct count 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' + Id = 'AD-GPOS-08', + Title = 'GPO owners 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-MtAdGpoOwnerDistinctCount" - $gpoState = Get-MtADGpoState - Write-Verbose "Retrieved AD state" - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting gpo owner distinct count" - - $gpos = $gpoState.GPOs - if ($null -eq $gpos) { - Add-MtTestResultDetail -Result 'Unable to retrieve Active Directory Group Policy Objects (GPOs) from Get-MtADGpoState.' - return $false - } - - $gposArray = @($gpos | Where-Object { $null -ne $_ }) - - $owners = $gposArray | - ForEach-Object { - $o = $_.Owner - if (-not [string]::IsNullOrWhiteSpace([string]$o)) { [string]$o } - } | - Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) } | - Select-Object -Unique - - $distinctOwnerCount = @($owners).Count - $testResult = $true - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Distinct GPO owner count | $distinctOwnerCount |" + "`n" - Write-Verbose "Counts computed" - - $testResultMarkdown = "Active Directory GPO owners have been analyzed. There are $distinctOwnerCount distinct owner(s).`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - Write-Verbose "Completed Test-MtAdGpoOwnerDistinctCount" - return $testResult + $state = Get-MtADGpoState + if ($null -eq $state -or $null -eq $state.GPOs) { throw 'GPO metadata could not be collected; owners cannot be inventoried.' } + $gpos = @($state.GPOs | Where-Object { $null -ne $_ }) + $known = @($gpos | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_.Owner) } | Group-Object Owner | Sort-Object Name) + $unknown = @($gpos | Where-Object { [string]::IsNullOrWhiteSpace([string]$_.Owner) }) + $details = @(foreach ($group in $known) { + [pscustomobject]@{ Owner = $group.Name; Count = $group.Count; Policies = ($group.Group.DisplayName | Sort-Object) -join ', ' } + }) + if ($unknown.Count -gt 0) { $details += [pscustomobject]@{ Owner = $null; Count = $unknown.Count; Policies = ($unknown.DisplayName | Sort-Object) -join ', ' } } + $summary = if ($gpos.Count -eq 0) { 'No GPOs were returned; no owners can be listed.' } else { "The $($gpos.Count) collected GPOs have $($known.Count) distinct known owners. Review ownership and delegation." } + if ($unknown.Count -gt 0) { $summary += " Owners could not be resolved for $($unknown.Count) GPOs." } + $result = Format-MtAdGpoResult -Summary $summary -Metrics ([ordered]@{ 'Total GPOs' = $gpos.Count; 'Distinct known owners' = $known.Count; 'GPOs with unknown owners' = $unknown.Count }) -Details $details -Properties Owner, Count, Policies -Headers Owner, 'GPO count', GPOs + Add-MtTestResultDetail -Result $result -Investigate + return $true } diff --git a/tests/ad/gpo-state/Test.AD-GPOS-09.md b/tests/ad/gpo-state/Test.AD-GPOS-09.md deleted file mode 100644 index de293612d6..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOS-09.md +++ /dev/null @@ -1,26 +0,0 @@ -#### Test-MtAdGpoOwnerDetails - - Returns details of GPO owners, including how many GPOs each owner has. - -#### Why This Test Matters -- Operational value: summarizes GPO owners and how many GPOs each owner has, revealing ownership distribution. - -#### Control Type - -**Operational** - -#### Security Recommendation -- Ensure ownership aligns with policy and stewardship; adjust ownership for orphaned or unclear GPOs. - -#### How the Test Works -- Retrieves GPO state, groups GPOs by Owner, and renders a table with owner and GPO counts. - -#### Related Tests -- `Test-MtAdGpoOwnerDistinctCount`. - -#### 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-GPOS-09.ps1 b/tests/ad/gpo-state/Test.AD-GPOS-09.ps1 deleted file mode 100644 index 85b5374158..0000000000 --- a/tests/ad/gpo-state/Test.AD-GPOS-09.ps1 +++ /dev/null @@ -1,97 +0,0 @@ -<# #> -function Test-MtAdGpoOwnerDetails { - <# - .SYNOPSIS - Returns details of GPO owners, including how many GPOs each owner has. - - .DESCRIPTION - This test retrieves Active Directory GPO state data using Get-MtADGpoState and returns a markdown - table summarizing GPO owners. Owners are grouped by the GPO Owner property. - - .EXAMPLE - Test-MtAdGpoOwnerDetails - - Returns $true if GPO state data is accessible, $false otherwise. - The test result includes a markdown table with owner counts. - - .LINK - https://maester.dev/docs/commands/Test-MtAdGpoOwnerDetails - #> - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Clarity in using plural')] - [MaesterTest( - Id = 'AD-GPOS-09', - Title = 'GPO owner 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-MtAdGpoOwnerDetails" - $gpoState = Get-MtADGpoState - Write-Verbose "Retrieved AD state" - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - Write-Verbose "Filtering/counting gpo owner details" - - $gpos = $gpoState.GPOs - if ($null -eq $gpos) { - Add-MtTestResultDetail -Result 'Unable to retrieve Active Directory Group Policy Objects (GPOs) from Get-MtADGpoState.' - return $false - } - - $gposArray = @($gpos | Where-Object { $null -ne $_ }) - - $rows = $gposArray | - ForEach-Object { - $ownerValue = $_.Owner - if ([string]::IsNullOrWhiteSpace([string]$ownerValue)) { return $null } - [PSCustomObject]@{ - Owner = [string]$ownerValue - DisplayName = [string]$_.DisplayName - } - } | - Where-Object { $null -ne $_ } | - Group-Object -Property Owner - - $ownerGroups = @($rows) - $ownerGroupCount = $ownerGroups.Count - $testResult = $true - - $table = "| Owner | GPO Count | GPO DisplayNames |" + "`n" - $table += '| --- | --- | --- |' + "`n" - - foreach ($group in ($ownerGroups | Sort-Object -Property Count -Descending)) { - $owner = [string]$group.Name - $owner = $owner -replace '\|', '\\|' - - $displayNames = @($group.Group | ForEach-Object { [string]$_.DisplayName } | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) - $displayNamesJoined = ($displayNames | Sort-Object | ForEach-Object { $_ -replace '\|', '\\|' }) -join ', ' - - $table += "| $owner | $($group.Count) | $displayNamesJoined |" + "`n" - } - - $recommendation = if ($ownerGroupCount -gt 0) { - "GPO owner details were returned for $ownerGroupCount distinct owner(s)." - } else { - '✅ No GPO owner values 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-MtAdGpoOwnerDetails" - return $testResult -} diff --git a/tests/ad/gpo/Test.AD-GPO-01.md b/tests/ad/gpo/Test.AD-GPO-01.md index 279b9881d9..01fb15ab79 100644 --- a/tests/ad/gpo/Test.AD-GPO-01.md +++ b/tests/ad/gpo/Test.AD-GPO-01.md @@ -1,32 +1,38 @@ -Understanding the total number of Group Policy Objects (GPOs) in your Active Directory environment is crucial for several security and operational reasons: +Inventories the total number of Group Policy Objects (GPOs) returned from Active Directory. The **Investigate** result is intentional: the count is a starting point for understanding policy inventory, not a security finding. -- **Policy Sprawl**: A large number of GPOs can indicate policy sprawl, making it difficult to manage and troubleshoot policy conflicts -- **Performance Impact**: Each GPO adds processing overhead during user logon and computer startup -- **Security Complexity**: More GPOs mean more potential attack surfaces if any contain misconfigurations -- **Audit Requirements**: Compliance frameworks often require understanding of policy scope and distribution +#### Why This Test Matters + +An inventory helps administrators understand how much policy configuration they maintain and gives context for reviews of scope, ownership, and purpose. A large or growing number of GPOs can make policy maintenance and conflict analysis harder, but the count alone does not show that a policy is redundant, unsafe, or effective on a particular computer or user. #### Control Type -**Operational** +**Operational** — this test reports an inventory metric for review; it does not assess a security requirement or alter configuration. #### Security Recommendation -Regularly audit your GPO inventory and consolidate redundant or overlapping policies. Consider: - -- Merging GPOs with similar settings -- Removing unused or obsolete GPOs -- Documenting the purpose of each GPO -- Implementing a naming convention for better organization +- Keep a documented purpose and accountable owner for each GPO. +- Review scope and settings before consolidating policies; similar names do not mean their scope or contents are interchangeable. +- Retire a GPO only after confirming it is no longer needed and following the normal backup and change process. #### How the Test Works -This test retrieves all Group Policy Objects from Active Directory and counts the total number. It uses the Get-MtADGpoState function to access cached GPO data. +The test reads the collected GPO inventory and counts the returned GPO records. It reports the total and adds an **Investigate** result even when the collection is empty; in that case, the summary explicitly says that no GPOs were returned. If the inventory itself could not be retrieved, the test errors rather than treating missing data as an empty directory. + +The result does not inspect policy settings, links, application, or whether two policies can safely be combined. + +#### Remediation action + +Review the inventory and confirm each policy's owner, purpose, and intended scope. Investigate apparent duplicates with their owners, and consolidate only policies with compatible settings and scope. Archive or remove a policy only after confirming it is no longer needed. #### Related Tests -- `Test-MtAdGpoUnlinkedCount` - Identifies GPOs that are not linked to any location -- `Test-MtAdGpoCreatedBefore2020Count` - Identifies potentially outdated GPOs -- `Test-MtAdGpoLinkedCount` - Counts GPOs that are actively linked +- [AD-GPO-02 — GPOs should be modified within the configured age limit](https://maester.dev/docs/tests/AD-GPO-02) (`Test-MtAdGpoStale`) reviews modification age for the inventoried GPOs. +- [AD-GPO-04 — GPOs should have at least one link](https://maester.dev/docs/tests/AD-GPO-04) (`Test-MtAdGpoUnlinkedCount`) identifies inventoried GPOs without collected link references. +- [AD-GPOL-01 — GPOs with enabled links should be investigated](https://maester.dev/docs/tests/AD-GPOL-01) (`Test-MtAdGpoLinkedCount`) counts inventoried GPOs with enabled links. + +#### Related 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/Test.AD-GPO-01.ps1 b/tests/ad/gpo/Test.AD-GPO-01.ps1 index b07ee29bd1..7dce8396df 100644 --- a/tests/ad/gpo/Test.AD-GPO-01.ps1 +++ b/tests/ad/gpo/Test.AD-GPO-01.ps1 @@ -1,71 +1,41 @@ function Test-MtAdGpoTotalCount { <# .SYNOPSIS - Counts the total number of Group Policy Objects in Active Directory. + Inventories the total number of GPOs for investigation. .DESCRIPTION - This test retrieves the total count of Group Policy Objects (GPOs) in the Active Directory domain. - Knowing the total number of GPOs helps administrators understand the scope of policy management - and identify potential areas for consolidation or cleanup. + Counts cached GPO metadata. An inventory count is not a security verdict; + missing collection is an error, not an empty successful inventory. .EXAMPLE - Test-MtAdGpoTotalCount + Invoke-MtTest -Id 'AD-GPO-01' - Returns $true if GPO data is accessible, $false otherwise. - The test result includes the total count of GPOs. + Inventories GPOs for investigation rather than making a pass/fail security judgement. .LINK - https://maester.dev/docs/commands/Test-MtAdGpoTotalCount + https://maester.dev/docs/tests/AD-GPO-01 #> [MaesterTest( - Id = 'AD-GPO-01', - Title = 'GPO total count should be retrievable', - 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' + Id = 'AD-GPO-01', + Title = 'GPO inventory 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-MtAdGpoTotalCount" - - # 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 - - # Count total GPOs - $totalCount = ($gpos | Measure-Object).Count - - # Test passes only if we successfully retrieved the GPO dataset - $testResult = $null -ne $gpos - - # Generate markdown results - if ($testResult) { - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total GPOs | $totalCount |" + "`n" - - $testResultMarkdown = "Active Directory Group Policy Objects have been analyzed. The domain contains $totalCount GPO(s).`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - } else { - $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 - - return $testResult + $state = Get-MtADGpoState + if ($null -eq $state -or $null -eq $state.GPOs) { throw 'The GPO inventory could not be retrieved.' } + $count = @($state.GPOs | Where-Object { $null -ne $_ }).Count + $summary = if ($count -eq 0) { 'No GPOs were returned in the collected inventory.' } else { "The collected inventory contains $count GPOs. Review policy inventory and ownership." } + $result = Format-MtAdGpoResult -Summary $summary -Metrics ([ordered]@{ 'Total GPOs' = $count }) + Add-MtTestResultDetail -Result $result -Investigate + return $true } diff --git a/tests/ad/gpo/Test.AD-GPO-02.md b/tests/ad/gpo/Test.AD-GPO-02.md index be1132b58b..2dce213fc3 100644 --- a/tests/ad/gpo/Test.AD-GPO-02.md +++ b/tests/ad/gpo/Test.AD-GPO-02.md @@ -1,28 +1,43 @@ -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 whether each GPO's last modification is within the configured age limit, which defaults to five calendar years. The test fails if any modification date is older than that limit. A modification exactly at the cutoff passes. This is a maintenance indicator, not proof that a policy is insecure. -Tracking the count of GPOs created before 2020 helps you quickly identify areas that may benefit from review and modernization. +#### Why This Test Matters + +Policies that have not changed for a long time may preserve obsolete settings or assumptions that no longer match the current security baseline. Stable policies can also be intentional. Reviewing older policies can reveal those settings or undocumented dependencies before a planned change; age by itself does not establish a security or operational defect. #### Control Type -**Detective** +**Detective** — the test identifies policies outside the configured modification-age limit for review. It does not update or remove them. #### 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. +- Review stale policies with their owners and compare their settings and scope with current requirements. +- Treat the modification date as a review signal, not as a quality score or reason to make an unnecessary edit. +- Confirm policy dependencies and intended application before changing or retiring a GPO. #### How the Test Works -This test retrieves GPO state from Active Directory using **Get-MtADGpoState** (it uses `$gpoState.GPOs`). +The test compares each collected GPO's `ModificationTime` with the current UTC date minus `MaximumModificationAgeYears` (five years by default). A modification exactly on the UTC cutoff is within the limit. It reports the total, stale count, cutoff, and each policy's creation and modification dates and assessment. An old creation date alone does not fail a recently modified GPO. + +An empty or unavailable GPO inventory, or a missing modification date, causes an error because age cannot be assessed. The source modification timestamp is LDAP `whenChanged`, which is specific to the queried domain controller and can reflect metadata or ACL changes as well as policy changes. It is not a complete history of policy-setting changes. + +Configure `MaximumModificationAgeYears` under `TestSettings` > `Parameters` for `AD-GPO-02` in +`maester-config.json`, or pass it through `Invoke-MtTest -Parameter`. -It then filters all GPOs where the `CreationTime` is earlier than **January 1st, 2020** and reports the resulting count. +#### Remediation action + +1. In **Group Policy Management**, review stale policies with their owners and compare their settings and scope with current requirements. +2. Update a policy only where review identifies a real need, then verify intended scope and behavior. Archive or remove policies only after confirming they are no longer required. +3. Do not make an unrelated edit merely to refresh the modification timestamp. #### 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 should be investigated](https://maester.dev/docs/tests/AD-GPO-01) (`Test-MtAdGpoTotalCount`) reports the total GPO inventory for context. +- [AD-GPO-04 — GPOs should have at least one link](https://maester.dev/docs/tests/AD-GPO-04) (`Test-MtAdGpoUnlinkedCount`) identifies GPOs without collected link references; it does not assess modification age. +- [AD-GPOL-01 — GPOs with enabled links should be investigated](https://maester.dev/docs/tests/AD-GPOL-01) (`Test-MtAdGpoLinkedCount`) inventories GPOs with enabled links. + +#### Related 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/Test.AD-GPO-02.ps1 b/tests/ad/gpo/Test.AD-GPO-02.ps1 index e9ceff5ad0..edfdce6b06 100644 --- a/tests/ad/gpo/Test.AD-GPO-02.ps1 +++ b/tests/ad/gpo/Test.AD-GPO-02.ps1 @@ -1,75 +1,72 @@ -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 last modification is older than + MaximumModificationAgeYears (five calendar years by default). Reports creation and modification + dates together; an old creation date alone does not cause failure. .EXAMPLE - Test-MtAdGpoCreatedBefore2020Count + Invoke-MtTest -Id 'AD-GPO-02' + + Checks whether any GPO was last modified more than five calendar years ago. - Returns $true if GPO data is accessible, $false otherwise. + .EXAMPLE + Invoke-MtTest -Id 'AD-GPO-02' -Parameter @{ MaximumModificationAgeYears = 3 } - The test result includes the count of GPOs created before 2020. + Uses a three-year modification-age limit instead of the five-year default. .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', - 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' + Id = 'AD-GPO-02', + Title = 'GPOs should be modified within the configured age limit', + 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-MtAdGpoCreatedBefore2020Count" + param( + # Maximum age of a GPO's last modification, in calendar years. + [ValidateRange(1, 100)] + [int] $MaximumModificationAgeYears = 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.Count -eq 0) { throw 'The GPO inventory is empty; modification age cannot be assessed.' } + 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.' - } - - # Generate markdown results - Add-MtTestResultDetail -Result $testResultMarkdown - - return $testResult + # LDAP modification dates are UTC; keep the clock and calendar-year cutoff in UTC too. + $cutoffDate = ([DateTimeOffset](Get-Date)).UtcDateTime.AddYears(-$MaximumModificationAgeYears) + $stale = @($gpos | Where-Object { [datetime]$_.ModificationTime -lt $cutoffDate }) + $details = @(foreach ($gpo in ($gpos | Sort-Object DisplayName)) { + [pscustomobject]@{ + Name = $gpo.DisplayName + Created = if ($null -ne $gpo.CreationTime) { ([datetime]$gpo.CreationTime).ToString('yyyy-MM-dd HH:mm:ss') } else { $null } + Modified = ([datetime]$gpo.ModificationTime).ToString('yyyy-MM-dd HH:mm:ss') + Assessment = if ([datetime]$gpo.ModificationTime -lt $cutoffDate) { 'Stale' } else { 'Within limit' } + } + }) + $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 $MaximumModificationAgeYears years. Age is a hygiene indicator, not proof of insecure settings." } + $result = Format-MtAdGpoResult -Summary $message -Metrics ([ordered]@{ 'Total GPOs' = $gpos.Count; 'Stale GPOs' = $stale.Count; 'Modification cutoff' = $cutoffDate.ToString('yyyy-MM-dd HH:mm:ss') }) -Details $details -Properties Name, Created, Modified, Assessment -Headers GPO, Created, Modified, Assessment + Add-MtTestResultDetail -Result $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..79da80f46e 100644 --- a/tests/ad/gpo/Test.AD-GPO-04.md +++ b/tests/ad/gpo/Test.AD-GPO-04.md @@ -1,35 +1,42 @@ -Unlinked (or orphaned) Group Policy Objects (GPOs) exist in Active Directory but are not linked to any OU, domain, or site. While they may look harmless, they can still create operational and security risk: +Identifies GPOs whose identifiers do not appear in collected domain, OU, or site `gPLink` values. It counts references to a GPO whether a link is enabled or disabled; it does not determine whether settings are actively applied. An unlinked GPO may be intentionally retained and is not, by itself, a vulnerability. -- **Resource and operational overhead**: Unused GPOs add clutter and can increase administrative effort. -- **Accidental exposure**: An unlinked GPO can be mistakenly linked later, suddenly applying unknown settings to users or computers. -- **Harder incident investigation**: Policy behavior becomes harder to reason about when unused GPOs remain in the environment. +#### Why This Test Matters + +An unlinked policy can add inventory and maintenance overhead. If it is mistakenly linked later, unreviewed or obsolete settings can unexpectedly reach users or computers. Finding one is a prompt to verify its purpose and lifecycle, not evidence that the policy is exploitable or must be removed. #### Control Type -**Detective** +**Detective** — the test detects GPOs with no collected link reference and reports them for review; it does not make a configuration change. #### Security Recommendation -After verification, **remove unlinked GPOs** to reduce risk and simplify policy management: - -- Confirm the GPO’s purpose (documentation, change history, owners). -- Verify it is not required for any special-case deployment path. -- If you are confident it is unused, remove it (or archive it) and ensure backups/restore requirements are met. -- Restrict who can create/link GPOs to prevent accidental re-introduction. +- Keep the purpose and owner of retained, unlinked GPOs documented. +- Before removal, confirm that the policy is not retained for a planned deployment, recovery, or other approved use. +- Review link scope and state separately; the presence of a link reference does not establish that the policy applies. #### How the Test Works -This test retrieves Active Directory Group Policy state data using `Get-MtADGpoState` and: +The test compares each collected GPO identifier with GUID references from collected domain, OU, and site `gPLink` data. Disabled links count as references, as do references whose policy application is not established by this test. It reports total, linked, and unlinked GPO counts and lists unlinked policies when any are found. + +Any GPO without a collected link reference fails the test. It passes when all collected GPOs have at least one reference, without asserting that those links are enabled or effective. + +Missing GPO or link collection, an incomplete parsed link map, or a GPO without an identifier causes an error rather than a clean result. A skipped malformed target could otherwise make a linked policy appear unlinked. The test does not calculate resultant policy or determine whether any referenced GPO is enabled or effective. -1. Uses the cached list of GPOs (`$gpoState.GPOs`). -2. Extracts GPO link references from the collected `GPOLinks` (via `gPLink`). -3. Counts GPOs whose IDs are not referenced by any collected `gPLink` entry. +#### Remediation action + +1. In **Group Policy Management**, review each listed GPO's owner, purpose, backup, and change history. +2. If it is no longer needed, archive or remove it under the normal change process. Otherwise document why it is unlinked and retain it. +3. Do not infer a security gap or remove a policy solely because it has no link. #### Related Tests -- `Test-MtAdGpoTotalCount` - Counts the total number of GPOs -- `Test-MtAdGpoLinkedCount` - Identifies GPOs that are actively linked -- `Test-MtAdGpoCreatedBefore2020Count` - Identifies potentially outdated GPOs +- [AD-GPO-01 — GPO inventory should be investigated](https://maester.dev/docs/tests/AD-GPO-01) (`Test-MtAdGpoTotalCount`) reports the total GPO inventory for context. +- [AD-GPOL-01 — GPOs with enabled links should be investigated](https://maester.dev/docs/tests/AD-GPOL-01) (`Test-MtAdGpoLinkedCount`) counts distinct GPOs with an enabled link, unlike this test's reference check. +- [AD-GPOL-03 — Direct GPO link coverage should be investigated](https://maester.dev/docs/tests/AD-GPOL-03) (`Test-MtAdGpoUnlinkedTargetCount`) inventories targets without a direct link rather than GPOs without any collected link reference. + +#### Related 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/Test.AD-GPO-04.ps1 b/tests/ad/gpo/Test.AD-GPO-04.ps1 index e9a6ca2b13..2af43857cf 100644 --- a/tests/ad/gpo/Test.AD-GPO-04.ps1 +++ b/tests/ad/gpo/Test.AD-GPO-04.ps1 @@ -1,131 +1,61 @@ function Test-MtAdGpoUnlinkedCount { <# .SYNOPSIS - Counts Active Directory GPOs that are not linked to any OU, domain, or site. + Checks that every GPO has a link to a domain, OU or site. .DESCRIPTION - This test identifies "orphaned" (unlinked) Group Policy Objects (GPOs) that exist in Active Directory - but are not linked to any OU, domain, or site. Unlinked GPOs can consume administrative and processing - resources while providing no effective policy. + Compares GPO identifiers with collected link references, including disabled + links. Settings status does not establish whether a GPO is linked. .EXAMPLE - Test-MtAdGpoUnlinkedCount + Invoke-MtTest -Id 'AD-GPO-04' - Returns $true if unlinked GPOs were not found, $false if orphaned/unlinked GPOs exist. + Fails when a GPO has no link to a domain, OU or site, including disabled links. .LINK - https://maester.dev/docs/commands/Test-MtAdGpoUnlinkedCount + https://maester.dev/docs/tests/AD-GPO-04 #> [MaesterTest( - Id = 'AD-GPO-04', - Title = 'Unlinked GPO count should be compliant', - Product = 'ad', - Feature = 'group-policy', - Area = 'infrastructure', - ResourceType = 'GroupPolicy', - Severity = 'Low', - UserImpact = 'Low', + Id = 'AD-GPO-04', + Title = 'GPOs should have at least one link', + 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' + Mitre = 'None', + Service = 'ActiveDirectory', + Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), + Author = 'soulemike' )] [CmdletBinding()] [OutputType([bool])] param() - - Write-Verbose "Starting Test-MtAdGpoUnlinkedCount" - - # 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 + $state = Get-MtADGpoState + if ($null -eq $state -or $null -eq $state.GPOs -or $null -eq $state.GPOLinks) { throw 'GPO metadata or links were not retrieved; unlinked GPOs cannot be assessed.' } + if (-not (Test-MtAdGpoLinksComplete -State $state)) { throw 'GPO link collection is incomplete; missing links cannot be assessed conclusively.' } + $gpos = @($state.GPOs | Where-Object { $null -ne $_ }) + $linkedIds = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase) + foreach ($link in @($state.GPOLinks | Where-Object { $null -ne $_ })) { + if ($null -ne $link.GpoGuid) { $null = $linkedIds.Add(([string]$link.GpoGuid).Trim('{}')) } + foreach ($match in [regex]::Matches([string]$link.GpLink, '\{([0-9a-fA-F-]{36})\}')) { $null = $linkedIds.Add($match.Groups[1].Value) } } - - $gpos = $gpoState.GPOs - $totalCount = ($gpos | Measure-Object).Count - - # Collect GPO IDs that appear in GPOLinks (gPLink) across the collected AD containers. - # Get-MtADGpoState currently retrieves GPOLinks from Configuration naming context (sites-related searchbase). - $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 + $unlinked = @(foreach ($gpo in $gpos) { + if ([string]::IsNullOrWhiteSpace([string]$gpo.Id)) { throw 'A GPO has no identifier; its links cannot be assessed.' } + if (-not $linkedIds.Contains(([string]$gpo.Id).Trim('{}'))) { $gpo } + }) + $details = @(foreach ($gpo in @($unlinked | Sort-Object DisplayName)) { + [pscustomobject]@{ + Name = $gpo.DisplayName + Created = if ($null -ne $gpo.CreationTime) { ([datetime]$gpo.CreationTime).ToString('yyyy-MM-dd HH:mm:ss') } else { $null } + Modified = if ($null -ne $gpo.ModificationTime) { ([datetime]$gpo.ModificationTime).ToString('yyyy-MM-dd HH:mm:ss') } else { $null } } - - # 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 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 } - - # 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 - } - } - - $unlinkedCount = ($unlinkedGpos | Measure-Object).Count - $linkedCount = $totalCount - $unlinkedCount - - # Sample names for operator visibility - $sampleLimit = 5 - $sampleUnlinked = $unlinkedGpos | Select-Object -First $sampleLimit - $sampleNames = @($sampleUnlinked | ForEach-Object { - if ($_.DisplayName) { $_.DisplayName } else { $_.Id } - }) - $sampleNamesText = ($sampleNames | Where-Object { $_ }) -join ', ' - if ($unlinkedCount -gt $sampleLimit -and $sampleNamesText) { - $sampleNamesText += " (showing first $sampleLimit)" - } - - # Security intent: pass only when no unlinked/orphaned GPOs exist. - $testResult = $unlinkedCount -eq 0 - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total GPOs | $totalCount |" + "`n" - $result += "| Linked GPOs | $linkedCount |" + "`n" - $result += "| Unlinked GPOs | $unlinkedCount |" + "`n" - if ($unlinkedCount -gt 0 -and $sampleNamesText) { - $result += "| Sample Unlinked GPOs | $sampleNamesText |" + "`n" - } - - if ($testResult) { - $testResultMarkdown = "✅ Unlinked/orphaned GPOs have not been found. Active Directory Group Policy Objects have been analyzed successfully.`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%" - } - $testResultMarkdown = $testResultMarkdown -replace "%TestResult%", $result - - Add-MtTestResultDetail -Result $testResultMarkdown - return $testResult + }) + $pass = $unlinked.Count -eq 0 + $summary = if ($pass) { 'Well done. No unlinked GPOs were found.' } else { "$($unlinked.Count) of $($gpos.Count) GPOs have no links. Review their purpose and archive or remove obsolete policies after verification." } + $result = Format-MtAdGpoResult -Summary $summary -Metrics ([ordered]@{ 'Total GPOs' = $gpos.Count; 'Linked GPOs' = $gpos.Count - $unlinked.Count; 'Unlinked GPOs' = $unlinked.Count }) -Details $details -Properties Name, Created, Modified -Headers GPO, Created, Modified + Add-MtTestResultDetail -Result $result + return $pass } 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..2b7014fa57 100644 --- a/tests/ad/gpo/Test.AD-GPOL-01.md +++ b/tests/ad/gpo/Test.AD-GPOL-01.md @@ -1,37 +1,42 @@ -Linked Group Policy Objects (GPOs) are actively applying settings to users and/or computers across your Active Directory environment. +Inventories distinct GPOs that have at least one enabled link and reports them against the collected GPO inventory. The **Investigate** result is informational: an enabled link does not establish that a policy is effective for any particular user or computer. -For security assessments, it is important to understand the scope of actively linked (and therefore applying) policies. This test helps you: +#### Why This Test Matters -- Identify the ratio of active vs unused policies -- Spot environments where many GPOs exist but only a subset are actually applied -- Prioritize review/cleanup efforts based on real policy exposure +Link inventory helps administrators understand where policies are configured to be considered. Comparing enabled-link counts with the full inventory can support scope and lifecycle reviews, but neither a low nor high count proves that policy coverage is deficient or excessive. #### Control Type -**Operational** +**Operational** — this test provides a view of configured links for investigation; it does not judge policy effectiveness or enforce a control. #### Security Recommendation -- **Review linked (active) GPOs regularly**: Linked policies can change security posture immediately when modified. -- **Audit unused/unlinked GPOs**: Large numbers of unused policies can indicate mismanagement and increase the risk of accidental changes. -- **Use the linked ratio**: A low linked ratio might indicate policy sprawl or a backlog of orphaned policies. +- Review enabled links against intended policy scope and ownership. +- Evaluate effective policy separately: security filtering, WMI filters, inheritance, and policy processing affect application. +- Check before enabling or removing links, since either change can alter which users or computers receive settings. #### How the Test Works -This test retrieves GPO state from Active Directory using **Get-MtADGpoState** (it uses `$gpoState.GPOs` and `$gpoState.GPOLinks`). +If a malformed link makes the parsed map incomplete, known enabled-link matches +are still listed, but the count of GPOs without enabled links is **Unknown**. The +summary explicitly marks this as a partial inventory rather than a clean result. -It then: +The test uses collected GPO and link data, identifies link entries with enabled state, and counts each distinct GPO once when it has at least one enabled link. It reports total GPOs, the count with enabled links, and the count without them; GPOs with enabled links are listed when present. -1. Parses `gPLink` values to identify **enabled** (0) and **enforced** (2) link entries. -2. Counts distinct GPO GUIDs that have at least one enabled link. -3. Compares linked GPO count vs total GPO count and reports both metrics in Markdown. +Missing inventory or link data, an unknown GPO identifier, or an unknown link state causes an error. The test does not evaluate security filtering, WMI query results, inheritance, or resultant policy. An enabled link is not proof of application. + +#### Remediation action + +Review policies with and without enabled links against their intended scope. Before enabling, removing, or consolidating a link, check the target, disabled links, security filtering, WMI filters, inheritance, ownership, and expected policy processing. Confirm any change in the relevant deployment scope. #### Related Tests -- `Test-MtAdGpoTotalCount` - Total GPO inventory -- `Test-MtAdGpoUnlinkedCount` - GPOs not linked anywhere -- `Test-MtAdGpoCreatedBefore2020Count` - Potentially legacy GPOs -- `Test-MtAdGpoChangedBefore2020Count` - Potentially stale GPOs +- [AD-GPO-01 — GPO inventory should be investigated](https://maester.dev/docs/tests/AD-GPO-01) (`Test-MtAdGpoTotalCount`) reports the total GPO inventory for context. +- [AD-GPO-04 — GPOs should have at least one link](https://maester.dev/docs/tests/AD-GPO-04) (`Test-MtAdGpoUnlinkedCount`) identifies GPOs without any collected link reference, including disabled references. +- [AD-GPOL-02 — Disabled GPO link inventory](https://maester.dev/docs/tests/AD-GPOL-02) (`Test-MtCheckADGPOL02`) inventories disabled link entries rather than distinct GPOs with enabled links. + +#### Related 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/Test.AD-GPOL-01.ps1 b/tests/ad/gpo/Test.AD-GPOL-01.ps1 index 9f2d1bd8b6..3913a5efd5 100644 --- a/tests/ad/gpo/Test.AD-GPOL-01.ps1 +++ b/tests/ad/gpo/Test.AD-GPOL-01.ps1 @@ -1,95 +1,55 @@ function Test-MtAdGpoLinkedCount { <# .SYNOPSIS - Counts distinct GPOs that have at least one enabled link (active GPOs). + Inventories GPOs with at least one enabled link. .DESCRIPTION - This test retrieves Active Directory GPO state information using Get-MtADGpoState, then counts distinct - Group Policy Objects (GPOs) that have at least one enabled link. - - Understanding the scope of actively linked (and therefore applying) policies is important for security - assessments. Comparing total GPOs vs linked GPOs helps identify the ratio of active vs unused policies. + Uses normalized cached links. An enabled link does not prove effective policy + application: security filtering, WMI filters and policy processing also matter. .EXAMPLE - Test-MtAdGpoLinkedCount + Invoke-MtTest -Id 'AD-GPOL-01' - Returns $true if GPO data is accessible, $false otherwise. + Inventories enabled links for investigation without claiming effective policy application. .LINK - https://maester.dev/docs/commands/Test-MtAdGpoLinkedCount + https://maester.dev/docs/tests/AD-GPOL-01 #> [MaesterTest( - Id = 'AD-GPOL-01', - Title = 'GPO linked 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' + Id = 'AD-GPOL-01', + Title = 'GPOs with enabled links 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-MtAdGpoLinkedCount" - - $gpoState = Get-MtADGpoState - - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $gpos = $gpoState.GPOs - $totalCount = if ($null -ne $gpos) { ($gpos | Measure-Object).Count } else { 0 } - - # gPLink syntax includes entries like: - # [LDAP://...CN={GPO-GUID},...;0] -> enabled - # [LDAP://...CN={GPO-GUID},...;1] -> disabled - # [LDAP://...CN={GPO-GUID},...;2] -> enforced - $linkedGuidSet = [System.Collections.Generic.HashSet[string]]::new() - - $gpoLinks = $gpoState.GPOLinks - if ($null -ne $gpoLinks) { - foreach ($linkObj in $gpoLinks) { - $gPLinkValue = $linkObj.gPLink - if ([string]::IsNullOrEmpty($gPLinkValue)) { - continue - } - - $pattern = '\[\s*LDAP://[^\]]*?\{(?[0-9a-fA-F-]{36})\}[^\]]*?;\s*(?\d)\s*\]' - $regexMatches = [regex]::Matches([string]$gPLinkValue, $pattern) - - foreach ($match in $regexMatches) { - $guid = $match.Groups['guid'].Value - $status = [int]$match.Groups['status'].Value - - # 0 = enabled, 2 = enforced. Count both as active links. - if ($status -in 0, 2) { - [void]$linkedGuidSet.Add($guid) - } - } - } + $state = Get-MtADGpoState + if ($null -eq $state -or $null -eq $state.GPOs -or $null -eq $state.GPOLinks) { throw 'GPO metadata or links could not be collected; enabled links cannot be inventoried.' } + $gpos = @($state.GPOs | Where-Object { $null -ne $_ }) + if (@($gpos | Where-Object { [string]::IsNullOrWhiteSpace([string]$_.Id) }).Count -gt 0) { throw 'One or more GPO identifiers are unknown; enabled links cannot be inventoried.' } + $links = @($state.GPOLinks | Where-Object { $null -ne $_ }) + $linksComplete = Test-MtAdGpoLinksComplete -State $state + if (@($links | Where-Object { $null -eq $_.IsDisabled -or [string]::IsNullOrWhiteSpace([string]$_.GpoGuid) }).Count -gt 0) { throw 'One or more GPO links have unknown state or target.' } + $enabledIds = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase) + foreach ($link in @($links | Where-Object { $false -eq $_.IsDisabled })) { $null = $enabledIds.Add(([string]$link.GpoGuid).Trim('{}')) } + $linked = @($gpos | Where-Object { $enabledIds.Contains(([string]$_.Id).Trim('{}')) } | Sort-Object DisplayName) + $summary = if ($linked.Count -eq 0) { 'No collected GPO has an enabled link.' } else { "$($linked.Count) of $($gpos.Count) GPOs have at least one enabled link. Enabled links alone do not establish effective policy application." } + $withoutEnabled = $gpos.Count - $linked.Count + if (-not $linksComplete) { + $summary = "Partial link inventory: $($linked.Count) GPOs have known enabled links. Some links could not be parsed, so absence of an enabled link is unknown." + $withoutEnabled = $null } - - $linkedCount = $linkedGuidSet.Count - $linkedPercentage = if ($totalCount -gt 0) { [math]::Round(($linkedCount / $totalCount) * 100, 2) } else { 0 } - - $testResult = $true - - $resultTable = "| Metric | Value |" + "`n" - $resultTable += "| --- | --- |" + "`n" - $resultTable += "| Total GPOs | $totalCount |" + "`n" - $resultTable += "| Linked GPOs (Active) | $linkedCount |" + "`n" - $resultTable += "| Linked Ratio | $linkedPercentage% |" + "`n" - - $testResultMarkdown = "Active Directory Group Policy Objects have been analyzed. The domain contains $totalCount GPO(s); $linkedCount GPO(s) are linked and active across at least one scope (domain, OU, or site).`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $resultTable - - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate - return $testResult + $metrics = [ordered]@{ 'Total GPOs' = $gpos.Count; 'GPOs with enabled links' = $linked.Count; 'GPOs without enabled links' = $withoutEnabled } + if (-not $linksComplete) { $metrics['Link collection complete'] = $false } + $result = Format-MtAdGpoResult -Summary $summary -Metrics $metrics -Details $linked -Properties DisplayName, Id -Headers GPO, Id + Add-MtTestResultDetail -Result $result -Investigate + return $true } diff --git a/tests/ad/gpo/Test.AD-GPOL-02.md b/tests/ad/gpo/Test.AD-GPOL-02.md index 00bdc213ce..dacefd5946 100644 --- a/tests/ad/gpo/Test.AD-GPOL-02.md +++ b/tests/ad/gpo/Test.AD-GPOL-02.md @@ -1,34 +1,43 @@ -Disabled GPO links represent a potential security and operational concern in Active Directory environments: +Inventories disabled GPO link entries. It reports total, enabled, and disabled link counts and lists disabled links when present. A disabled link may be intentional; this inventory does not decide whether a policy should apply or whether a disabled link is a security gap. -- **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 +#### Why This Test Matters -#### Security Recommendation +Disabled links can reflect a deliberate design, a temporary change, or an action that was not revisited. Knowing where they are helps owners check policy intent and avoid confusion during troubleshooting or review. Their presence alone does not establish risk. + +#### Control Type -Regularly review disabled GPO links and either: +**Operational** — this is an inventory of disabled links, not an assessment of whether each should be enabled. -- 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 +#### Security Recommendation + +- Document the reason and owner for disabled links that are intentionally retained. +- Confirm desired scope and inherited policy before re-enabling or removing a link. +- Treat the inventory as a review aid; do not change a link solely to clear the listing. #### 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) +Malformed targets leave a partial parsed-link inventory. In that case, this check +reports **Investigate** rather than Passed; observed counts do not establish the +complete enabled/disabled state of all links. + +The test calls the shared disabled-link inventory, which reads collected GPO and link data and counts link entries by enabled or disabled state. It reports total, enabled, and disabled links and lists the associated GPO and linked container when disabled entries exist. A link that is both disabled and enforced remains part of the disabled-link inventory. -The gPLink attribute is parsed to determine the state of each link. +Missing GPO or link collection, or an unknown link state, causes an error. When collection succeeds, this test retains its default **Info/Passed** outcome even when disabled links are found. [AD-GPOREP-12](https://maester.dev/docs/tests/AD-GPOREP-12) uses the same inventory with an **Investigate** outcome; neither result assigns risk to an individual link. + +#### Remediation action + +1. In **Group Policy Management**, locate each listed domain, OU, or site and review its disabled links with the policy owner. +2. Re-enable links that should apply, remove obsolete links, and document intentional exceptions. Check inherited policy, filtering, and intended scope before changing a link. #### Related Tests -- `Test-MtAdGpoEnforcedCount` - Counts enforced GPO links -- `Test-MtAdGpoLinkedCount` - Counts distinct GPOs with links -- `Test-MtAdGpoUnlinkedCount` - Identifies GPOs with no links +- [AD-GPOL-01 — GPOs with enabled links should be investigated](https://maester.dev/docs/tests/AD-GPOL-01) (`Test-MtAdGpoLinkedCount`) inventories GPOs with enabled links. +- [AD-GPOL-04 — GPO links should not use enforcement](https://maester.dev/docs/tests/AD-GPOL-04) (`Test-MtAdGpoEnforcedCount`) checks whether individual link entries are enforced. +- [AD-GPOREP-12 — Review disabled GPO links](https://maester.dev/docs/tests/AD-GPOREP-12) (`Test-MtCheckADGPOREP12`) presents the disabled-link inventory with an Investigate outcome. + +#### Related 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/Test.AD-GPOL-02.ps1 b/tests/ad/gpo/Test.AD-GPOL-02.ps1 index be45c20106..0ecb823f5f 100644 --- a/tests/ad/gpo/Test.AD-GPOL-02.ps1 +++ b/tests/ad/gpo/Test.AD-GPOL-02.ps1 @@ -1,29 +1,35 @@ function Test-MtCheckADGPOL02 { <# .SYNOPSIS - Disabled GPO link count should be retrievable + Inventories disabled GPO links without making a risk judgement. .DESCRIPTION Runs the shared check Test-MtAdGpoDisabledLinkCount. + + .EXAMPLE + Invoke-MtTest -Id 'AD-GPOL-02' + + Inventories disabled GPO links for review without treating them as a failure. + + .LINK + https://maester.dev/docs/tests/AD-GPOL-02 #> [MaesterTest( - Id = 'AD-GPOL-02', - Title = 'Disabled GPO link count should be retrievable', - 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' + Id = 'AD-GPOL-02', + Title = 'Disabled GPO link inventory', + 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() - $result = Test-MtAdGpoDisabledLinkCount - if ($null -eq $result) { return $null } - return $result + return Test-MtAdGpoDisabledLinkCount } diff --git a/tests/ad/gpo/Test.AD-GPOL-03.md b/tests/ad/gpo/Test.AD-GPOL-03.md index 18020d2d4c..5376d9e43e 100644 --- a/tests/ad/gpo/Test.AD-GPOL-03.md +++ b/tests/ad/gpo/Test.AD-GPOL-03.md @@ -1,37 +1,38 @@ -Active Directory targets (OUs, the domain root, and sites) without any Group Policy links may indicate incomplete security policy coverage. +Inventories direct GPO link coverage across collected OUs, the domain root, and sites. It counts and lists targets without a direct link and always returns **Investigate**. A target without a direct link may receive policy through inheritance, so the result does not establish an effective-policy gap. -When a target has no GPO links, security and configuration baselines may not be applied consistently—creating gaps that attackers or misconfigurations can exploit. +#### Why This Test Matters + +Direct-link coverage provides context for understanding directory policy layout and identifying targets whose intended policy path may need explanation. However, an OU, domain, or site without a direct link is not necessarily missing security policy: settings may flow from a parent or another applicable scope. #### Control Type -**Operational** +**Operational** — the test reports direct-link inventory for review. It does not determine whether security requirements are effectively met. #### Security Recommendation -Investigate any unlinked targets and remediate the policy coverage gap: +- Compare the listed targets with the documented policy design and intended scope. +- Assess inherited policy and resultant application before concluding that a target has a coverage gap. +- Avoid adding direct links merely to make every target appear linked; unnecessary links can change policy processing. -- 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. +#### How the Test Works -Unlinked targets can represent missing or outdated configurations, so treat results as potential security configuration gaps. +The test counts collected OUs, the domain root, and sites, then looks for GPO GUID references in each target's `gPLink` value. A GUID reference counts as a direct link even if the link is disabled or refers to a GPO that is not resolved here. It reports linked and unlinked target counts and lists targets without a direct reference. -#### How the Test Works +The test does not evaluate link state, resolve every reference to an existing policy, or calculate resultant policy. Missing domain/OU collection causes an error. If only site collection is unavailable, the OU and domain metrics remain available, site counts are **Unknown**, and the result explicitly identifies a partial inventory. The result receives **Investigate**, whether or not unlinked targets are found. -This test uses `Get-MtADGpoState` (and its cached `GPOLinks`/AD data) and: +#### Remediation action -1. Enumerates all OUs using `Get-ADOrganizationalUnit`. -2. Reads the `gPLink` value for the domain root. -3. Identifies site link objects from `Get-MtADGpoState` (`$gpoState.SiteContainers`). -4. Counts each target whose `gPLink` value contains no GPO GUID references (i.e., no GPO links). +Review each target without a direct link against the intended design, including parent links, inheritance blocking, link state, and policy scope. Add a direct link only when that design requires it. If coverage remains unclear, verify effective policy through the appropriate policy assessment rather than inferring a gap from this inventory. #### 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 — GPOs should have at least one link](https://maester.dev/docs/tests/AD-GPO-04) (`Test-MtAdGpoUnlinkedCount`) identifies GPOs without collected link references; this test instead inventories targets without direct links. +- [AD-GPOL-01 — GPOs with enabled links should be investigated](https://maester.dev/docs/tests/AD-GPOL-01) (`Test-MtAdGpoLinkedCount`) inventories distinct GPOs with enabled links. +- [AD-GPOL-05 — OUs should not block Group Policy inheritance](https://maester.dev/docs/tests/AD-GPOL-05) (`Test-MtAdGpoBlockedInheritanceCount`) reports OUs that block inheritance, which affects how policy can flow to targets. + +#### Related 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/Test.AD-GPOL-03.ps1 b/tests/ad/gpo/Test.AD-GPOL-03.ps1 index f9734c0be5..003ff19df9 100644 --- a/tests/ad/gpo/Test.AD-GPOL-03.ps1 +++ b/tests/ad/gpo/Test.AD-GPOL-03.ps1 @@ -1,180 +1,57 @@ function Test-MtAdGpoUnlinkedTargetCount { <# .SYNOPSIS - Counts AD targets (OUs, domains, sites) that do not have any GPO links. + Inventories direct GPO link coverage 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 OUs, the domain root and sites without + direct GUID references. Inherited policy can apply without a direct link. .EXAMPLE - Test-MtAdGpoUnlinkedTargetCount + Invoke-MtTest -Id 'AD-GPOL-03' - 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. + Lists targets without direct links for investigation, not as proof of missing policy. .LINK - https://maester.dev/docs/commands/Test-MtAdGpoUnlinkedTargetCount + https://maester.dev/docs/tests/AD-GPOL-03 #> [MaesterTest( - Id = 'AD-GPOL-03', - Title = 'GPO unlinked target count should be compliant', - Product = 'ad', - Feature = 'group-policy', - Area = 'infrastructure', - ResourceType = 'OrganizationalUnit', - Severity = 'Low', - UserImpact = 'Low', - ImplementationCost = 'Medium', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), - Author = 'soulemike' + Id = 'AD-GPOL-03', + Title = 'Direct GPO link coverage should be investigated', + 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() - - Write-Verbose "Starting Test-MtAdGpoUnlinkedTargetCount" - - # 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 - } - - function Test-MtGpoLinkPresent { - param( - [Parameter(Mandatory = $false)] - [object]$gPLinkValue - ) - - if ($null -eq $gPLinkValue) { - return $false - } - - $text = [string]$gPLinkValue - if ([string]::IsNullOrWhiteSpace($text)) { - return $false - } - - # gPLink contains one or more entries like: - # LDAP://...CN={GPO-GUID},...;0 - return [regex]::IsMatch($text, '\{[0-9a-fA-F-]{36}\}') - } - - # Collect targets without any GPO links - $unlinkedOus = @() - $unlinkedDomains = @() - $unlinkedSites = @() - - # OUs - $ous = @($gpoState.LinkContainers | Where-Object { @($_.ObjectClass) -contains 'organizationalUnit' }) - foreach ($ou in $ous) { - if (-not (Test-MtGpoLinkPresent -gPLinkValue $ou.GpLink)) { - $unlinkedOus += $ou - } - } - - # Domain root - $domainObj = $gpoState.LinkContainers | Where-Object { @($_.ObjectClass) -contains 'domainDNS' } | Select-Object -First 1 - if ($null -ne $domainObj -and -not (Test-MtGpoLinkPresent -gPLinkValue $domainObj.GpLink)) { - $unlinkedDomains = @($domainObj) - } - - # Sites (siteLink objects) - $siteContainers = $gpoState.SiteContainers - $siteLinks = @() - if ($null -ne $siteContainers) { - foreach ($obj in @($siteContainers)) { - $objectClass = $obj.ObjectClass - - if ($null -eq $objectClass) { - continue - } - - if (@($objectClass) -contains 'site') { - $siteLinks += $obj - } - } - } - - foreach ($siteLink in @($siteLinks)) { - $siteLinkValue = $null - if ($siteLink.PSObject.Properties.Match('gPLink')) { - $siteLinkValue = $siteLink.gPLink - } - - if (-not (Test-MtGpoLinkPresent -gPLinkValue $siteLinkValue)) { - $unlinkedSites += $siteLink - } - } - - $totalOus = if ($null -ne $ous) { ($ous | Measure-Object).Count } else { 0 } - $totalDomains = if ($null -ne $domainObj) { 1 } else { 0 } - $totalSites = @($siteLinks).Count - - $unlinkedCountOus = @($unlinkedOus).Count - $unlinkedCountDomains = @($unlinkedDomains).Count - $unlinkedCountSites = @($unlinkedSites).Count - - $totalUnlinkedTargets = $unlinkedCountOus + $unlinkedCountDomains + $unlinkedCountSites - $testResult = $totalUnlinkedTargets -eq 0 - - # Sample unlinked targets - $sampleLimit = 5 - $sample = @() - $sample += @($unlinkedOus | Sort-Object DistinguishedName | Select-Object -First $sampleLimit | ForEach-Object { - 'OU: ' + [string]$_.DistinguishedName - }) - - if ($sample.Count -lt $sampleLimit -and $unlinkedDomains.Count -gt 0) { - $sample += @('Domain: ' + [string]$unlinkedDomains[0].DistinguishedName) - } - - if ($sample.Count -lt $sampleLimit -and $unlinkedSites.Count -gt 0) { - $remaining = $sampleLimit - $sample.Count - $sample += @($unlinkedSites | Sort-Object DistinguishedName | Select-Object -First $remaining | ForEach-Object { - 'SiteLink: ' + [string]$_.DistinguishedName + $state = Get-MtADGpoState + if ($null -eq $state -or $null -eq $state.LinkContainers) { throw 'Domain or OU GPO link containers were not retrieved.' } + $ous = @($state.LinkContainers | Where-Object { @($_.ObjectClass) -contains 'organizationalUnit' }) + $domain = @($state.LinkContainers | Where-Object { @($_.ObjectClass) -contains 'domainDNS' } | Select-Object -First 1) + $sites = @($state.SiteContainers | Where-Object { @($_.ObjectClass) -contains 'site' }) + $sitesAvailable = $null -ne $state.SiteContainers + $withoutLinks = { -not [regex]::IsMatch([string]$_.GpLink, '\{[0-9a-fA-F-]{36}\}') } + $unlinkedOus = @($ous | Where-Object $withoutLinks) + $unlinkedDomains = @($domain | Where-Object $withoutLinks) + $unlinkedSites = @($sites | Where-Object $withoutLinks) + $details = @(foreach ($target in @($unlinkedOus) + @($unlinkedDomains) + @($unlinkedSites)) { + [pscustomobject]@{ Kind = @($target.ObjectClass)[-1]; DistinguishedName = $target.DistinguishedName } }) - } - - $sampleText = ($sample | Where-Object { $_ }) -join ', ' - if ($totalUnlinkedTargets -gt $sampleLimit -and $sampleText) { - $sampleText += " (showing first $sampleLimit)" - } - - $result = "| Metric | Value |" + "`n" - $result += "| --- | --- |" + "`n" - $result += "| Total OUs | $totalOus |" + "`n" - $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 += "| Total Unlinked Targets | $totalUnlinkedTargets |" + "`n" - if ($sampleText) { - # Avoid breaking markdown tables when DNs contain pipes - # Use [regex]::Escape to properly escape the pipe character for regex replacement - $safeSampleText = $sampleText -replace '\|', '|' - $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%" - } - - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result - - Add-MtTestResultDetail -Result $testResultMarkdown - return $testResult + $summary = if ($details.Count -eq 0) { 'No collected target lacks a direct GPO link. Review effective policy separately; a direct link is not proof of policy application.' } + else { "$($details.Count) target(s) have no direct links. Investigate inherited policy; absence of a direct link is not proof of missing security policy." } + $siteCount = if ($sitesAvailable) { $sites.Count } else { $null } + $unlinkedSiteCount = if ($sitesAvailable) { $unlinkedSites.Count } else { $null } + $totalWithoutLinks = if ($sitesAvailable) { $details.Count } else { $null } + if (-not $sitesAvailable) { $summary = "Partial inventory: site data is unavailable. OU and domain metrics remain available; $($details.Count) known targets have no direct links. Review inherited policy separately." } + $metrics = [ordered]@{ 'Total OUs' = $ous.Count; 'Unlinked OUs' = $unlinkedOus.Count; 'OUs with direct links' = $ous.Count - $unlinkedOus.Count; 'Total domains' = $domain.Count; 'Domains without direct links' = $unlinkedDomains.Count; 'Total sites' = $siteCount; 'Sites without direct links' = $unlinkedSiteCount; 'Targets without direct links' = $totalWithoutLinks } + $result = Format-MtAdGpoResult -Summary $summary -Metrics $metrics -Details @($details | Sort-Object Kind, DistinguishedName) -Properties Kind, DistinguishedName -Headers 'Target type', 'Distinguished name' + Add-MtTestResultDetail -Result $result -Investigate + return $true } diff --git a/tests/ad/gpo/Test.AD-GPOL-04.md b/tests/ad/gpo/Test.AD-GPOL-04.md index 75aef9d0a2..a69975aebf 100644 --- a/tests/ad/gpo/Test.AD-GPOL-04.md +++ b/tests/ad/gpo/Test.AD-GPOL-04.md @@ -1,31 +1,38 @@ -Enforced Group Policy Object (GPO) links are special link entries that **block inheritance** from being overridden at lower levels (for example, by child OUs). +Checks individual GPO link entries for configured **Enforced** flags. It passes when no configured flags are found and fails when any are found, including on disabled links. Enabled enforced links override **Block Inheritance** at lower levels; disabled links do not apply and therefore do not actively override inheritance. A finding is a hygiene prompt to review the configured flag, not an instruction to disable intentional enforcement. -This can be a powerful mechanism for security baselines, but it also increases the chance that a critical policy unintentionally becomes “sticky” across the domain. +#### Why This Test Matters + +An enforced parent link can continue to apply settings where a lower-level OU blocks inheritance. This can be important by design, but may also make a policy's reach broader than administrators expect. Reviewing enforced links helps make that behavior understood and intentional; enforcement alone does not show that a policy is unsafe. #### Control Type -**Detective** +**Detective** — this check fails when any collected link is enforced, to prompt review. It does not change the link or decide whether the override is justified. #### Security Recommendation -- **Enforced GPOs override inheritance blocking**: any configuration enforced at a higher scope can still apply even if child OUs attempt to disable inheritance. -- **Use enforced links sparingly**: reserve them for critical security policies that must apply everywhere. -- **Review enforced policies regularly**: confirm the GPO’s purpose and ownership, and ensure the enforced settings remain aligned with current security requirements. +- Review every enforced link's owner, target, policy purpose, and settings. +- Confirm that the override is required and that its effect on lower-level containers is understood. +- Do not remove enforcement solely to obtain a passing result; assess policy behavior and intended inheritance first. #### How the Test Works -This test retrieves Active Directory GPO state from `Get-MtADGpoState` (using `$gpoState.GPOLinks`) and: +The test examines each collected GPO link entry and counts entries with `IsEnforced` set to true. It passes if the count is zero and fails if one or more flags are configured. It separately reports enabled enforcement overrides, disabled flagged links, and flagged links with unknown enabled/disabled state. Details include the GPO ID, container, and link state. This preserves the configured-flag rule rather than silently exempting disabled flags. + +Missing link collection or unknown enforcement state causes an error. An incomplete parsed link map cannot prove the absence of configured flags; known configured flags remain findings. This check counts link entries, unlike [AD-GPOREP-14](https://maester.dev/docs/tests/AD-GPOREP-14), which reports distinct GPOs with configured enforcement flags and always returns **Investigate**. Neither result determines whether enforcement is appropriate. + +#### Remediation action -1. Examines each collected link object for the `Enforced` property. -2. Counts link entries where `Enforced` is `$true`. -3. Reports the enforced link count and the enforced ratio in Markdown. +Review each enforced link's purpose, owner, target, and settings in **Group Policy Management**. Confirm whether the override is required by the policy design before changing it. If it is not required, assess the effect on inheritance and remove the enforced flag through the normal change process; do not disable enforcement blindly. #### Related Tests -- `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-GPOL-05 — OUs should not block Group Policy inheritance](https://maester.dev/docs/tests/AD-GPOL-05) (`Test-MtAdGpoBlockedInheritanceCount`) reports OUs whose inheritance blocks may be overridden by enforced links. +- [AD-GPOL-02 — Disabled GPO link inventory](https://maester.dev/docs/tests/AD-GPOL-02) (`Test-MtCheckADGPOL02`) inventories disabled link entries, a separate link state. +- [AD-GPOREP-14 — GPOs with enforced links should be investigated](https://maester.dev/docs/tests/AD-GPOREP-14) (`Test-MtAdGpoEnforcementCount`) inventories distinct GPOs with enforced links rather than assessing each link entry for failure. + +#### Related 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/Test.AD-GPOL-04.ps1 b/tests/ad/gpo/Test.AD-GPOL-04.ps1 index 38b40fe2e2..f36c19a822 100644 --- a/tests/ad/gpo/Test.AD-GPOL-04.ps1 +++ b/tests/ad/gpo/Test.AD-GPOL-04.ps1 @@ -1,88 +1,62 @@ function Test-MtAdGpoEnforcedCount { <# .SYNOPSIS - Counts enforced GPO links (links that block inheritance). + Checks that GPO links are not enforced. .DESCRIPTION - This test retrieves Active Directory GPO link state information using Get-MtADGpoState and then counts - how many GPO link entries are marked as **Enforced**. - - Enforced GPO links cannot be blocked by child OUs, which means security-related policies can apply - everywhere even when lower-level inheritance would normally disable them. + Passes when no configured enforcement flags exist, fails when any exist. + Enabled enforced links override Block Inheritance; disabled links do not apply. + Review intentional enforcement before changing it. .EXAMPLE - Test-MtAdGpoEnforcedCount + Invoke-MtTest -Id 'AD-GPOL-04' - Returns $true when no enforced GPO links are detected, $false when enforced GPO links exist. + Fails when any GPO link is enforced; review intended inheritance overrides. .LINK - https://maester.dev/docs/commands/Test-MtAdGpoEnforcedCount + https://maester.dev/docs/tests/AD-GPOL-04 #> [MaesterTest( - Id = 'AD-GPOL-04', - Title = 'Enforced GPO link count should be retrievable', - 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' + Id = 'AD-GPOL-04', + Title = 'GPO links should not use enforcement', + 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-MtAdGpoEnforcedCount" - - $gpoState = Get-MtADGpoState - - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $gpoLinks = $gpoState.GPOLinks - - $totalLinks = if ($null -ne $gpoLinks) { ($gpoLinks | Measure-Object).Count } else { 0 } - - $enforcedCount = 0 - if ($null -ne $gpoLinks) { - foreach ($linkObj in $gpoLinks) { - if ($null -eq $linkObj) { - continue + $state = Get-MtADGpoState + if ($null -eq $state -or $null -eq $state.GPOLinks) { throw 'GPO links could not be collected; enforcement cannot be assessed.' } + $links = @($state.GPOLinks | Where-Object { $null -ne $_ }) + if (@($links | Where-Object { $null -eq $_.IsEnforced }).Count -gt 0) { throw 'One or more GPO link enforcement states are unknown.' } + $enforced = @($links | Where-Object { $true -eq $_.IsEnforced } | Sort-Object DistinguishedName, GpoGuid) + $linksComplete = Test-MtAdGpoLinksComplete -State $state + if ($enforced.Count -eq 0 -and -not $linksComplete) { throw 'GPO link collection is incomplete; absence of enforcement cannot be assessed.' } + $active = @($enforced | Where-Object { $false -eq $_.IsDisabled }) + $disabled = @($enforced | Where-Object { $true -eq $_.IsDisabled }) + $unknownState = @($enforced | Where-Object { $null -eq $_.IsDisabled }) + $details = @(foreach ($link in $enforced) { + [pscustomobject]@{ + Id = $link.GpoGuid + Container = $link.DistinguishedName + State = if ($null -eq $link.IsDisabled) { 'Unknown' } elseif ($link.IsDisabled) { 'Disabled' } else { 'Enabled' } } - - # Get-MtADGpoState surfaces an Enforced property on link objects. - if ($null -ne $linkObj.Enforced -and [bool]$linkObj.Enforced) { - $enforcedCount++ - } - } - } - - $enforcedPercentage = if ($totalLinks -gt 0) { [math]::Round(($enforcedCount / $totalLinks) * 100, 2) } else { 0 } - - # Security intent: flag environments that use enforced links (they override inheritance blocking). - $testResult = $enforcedCount -eq 0 - - $resultTable = "| Metric | Value |" + "`n" - $resultTable += "| --- | --- |" + "`n" - $resultTable += "| Total GPO link entries | $totalLinks |" + "`n" - $resultTable += "| Enforced GPO link entries | $enforcedCount |" + "`n" - $resultTable += "| Enforced link ratio | $enforcedPercentage% |" + "`n" - - if ($testResult) { - $recommendation = "✅ No enforced GPO links (inheritance-blocking links) were detected. Active Directory Group Policy Objects have been analyzed successfully." - } - else { - $recommendation = "⚠️ Enforced GPO links were detected ($enforcedCount). Enforced links override inheritance blocking at child OUs, so they can significantly impact security posture. Review and use enforced links sparingly for critical policies that must apply everywhere." - } - - $testResultMarkdown = "$recommendation`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $resultTable - - Add-MtTestResultDetail -Result $testResultMarkdown - return $testResult + }) + $pass = $enforced.Count -eq 0 + $summary = if ($pass) { 'Well done. No configured enforcement flags were found.' } + else { "$($enforced.Count) GPO links have configured enforcement flags; $($active.Count) are enabled overrides. Disabled links do not actively override inheritance. Review configured enforcement before changing it." } + if ($unknownState.Count -gt 0) { $summary += " Enabled/disabled state is unknown for $($unknownState.Count) flagged links." } + if (-not $linksComplete) { $summary += ' Link collection is incomplete; additional enforcement flags may exist.' } + $result = Format-MtAdGpoResult -Summary $summary -Metrics ([ordered]@{ 'Collected GPO links' = $links.Count; 'Enforced GPO links' = $enforced.Count; 'Enabled enforcement overrides' = $active.Count; 'Disabled links with enforcement flags' = $disabled.Count; 'Flagged links with unknown state' = $unknownState.Count; 'Link collection complete' = $linksComplete }) -Details $details -Properties Id, Container, State -Headers 'GPO Id', 'Linked container', 'Link state' + Add-MtTestResultDetail -Result $result + return $pass } diff --git a/tests/ad/gpo/Test.AD-GPOL-05.md b/tests/ad/gpo/Test.AD-GPOL-05.md index 715bdff073..e9c32fc9b8 100644 --- a/tests/ad/gpo/Test.AD-GPOL-05.md +++ b/tests/ad/gpo/Test.AD-GPOL-05.md @@ -1,35 +1,38 @@ -GPO inheritance blocking controls whether settings from parent Organizational Units (OUs) flow down to child OUs. -When inheritance is blocked on an OU, policies from higher-level scopes won’t apply as expected. +Checks whether any collected OU has `gpOptions` equal to `1`, which blocks Group Policy inheritance. It fails when one or more OUs block inheritance and passes when none do. Blocking inheritance is not by itself proof of a security gap: enforced parent links still apply. -For security assessments, this matters because inheritance blocking can create **security gaps**: +#### Why This Test Matters -- **Parent OU policies won’t apply** to the affected OUs. -- Security baselines can become inconsistent across the directory. -- “Sticky” configurations at lower levels can persist unnoticed. +An inheritance block can prevent settings from parent-linked GPOs from flowing to child OUs and may therefore be important to understand when evaluating policy scope. It may also be a deliberate exception. Knowing which OUs use it helps owners verify that the resulting configuration matches directory design. #### Control Type -**Operational** +**Detective** — this test identifies OUs that block inheritance for review; it does not remove the block or establish whether required settings are missing. #### Security Recommendation -- **Review blocked inheritance regularly**: confirm each OU blocking inheritance has a documented business/technical justification. -- **Ensure compensating controls exist**: if parent policies won’t apply, equivalent security settings must be configured directly where needed. -- **Monitor and alert on changes**: inheritance blocking is often changed unintentionally during OU restructuring or delegation work. +- Document the reason and owner for each OU that blocks inheritance. +- Verify required settings through effective policy review, including any enforced parent links and local or directly linked policies. +- Change inheritance only after assessing its effects on the OU and its descendants. #### How the Test Works -This test retrieves Organizational Units (OUs) from Active Directory using: +The test examines collected OU link-container data and checks `gpOptions`. A value of `1` indicates blocked inheritance; an unset value uses the default behavior, with inheritance enabled, and is not treated as unknown. The test reports the total OU count and the number that block inheritance, listing affected OUs when present. -1. `Get-ADOrganizationalUnit -Filter * -Properties gpOptions` -2. Counts OUs where **`gpOptions -eq 1`** (where `gpOptions` indicates GPO inheritance blocking). -3. Reports the total OU count, the number of blocked OUs, and the blocked ratio in Markdown. +The test fails if one or more OUs block inheritance and passes if none do. Failure to collect OU/link-container data causes an error rather than a clean result. Enforced parent links still apply across a lower-level inheritance block. + +#### Remediation action + +Review each listed OU with its owner and confirm the business or technical reason for blocking inheritance. Verify that required security settings are otherwise applied, including settings from enforced parent links. Remove the block only after assessing policy scope and the effect on the OU and its child OUs. #### Related Tests -- `Test-MtAdGpoEnforcedCount` - Counts enforced (inheritance-blocking) link entries -- `Test-MtAdGpoLinkedCount` - Counts GPOs actively linked to apply settings -- `Test-MtAdGpoUnlinkedCount` - Identifies unlinked/orphaned GPOs +- [AD-GPOL-03 — Direct GPO link coverage should be investigated](https://maester.dev/docs/tests/AD-GPOL-03) (`Test-MtAdGpoUnlinkedTargetCount`) inventories targets without a direct GPO link. +- [AD-GPOL-04 — GPO links should not use enforcement](https://maester.dev/docs/tests/AD-GPOL-04) (`Test-MtAdGpoEnforcedCount`) reviews enforced links that override inheritance blocking. +- [AD-GPOL-01 — GPOs with enabled links should be investigated](https://maester.dev/docs/tests/AD-GPOL-01) (`Test-MtAdGpoLinkedCount`) inventories GPOs with enabled links. + +#### Related 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/Test.AD-GPOL-05.ps1 b/tests/ad/gpo/Test.AD-GPOL-05.ps1 index 254c3dfed3..fb8c9d1761 100644 --- a/tests/ad/gpo/Test.AD-GPOL-05.ps1 +++ b/tests/ad/gpo/Test.AD-GPOL-05.ps1 @@ -1,113 +1,45 @@ function Test-MtAdGpoBlockedInheritanceCount { <# .SYNOPSIS - Counts targets blocking GPO inheritance. + Checks that OUs do not block GPO inheritance. .DESCRIPTION - This test retrieves Active Directory Organizational Units (OUs) and counts how many targets - are configured to block Group Policy Object (GPO) inheritance. - - Blocked inheritance is set on OUs via the `gpOptions` attribute. - When `gpOptions -eq 1`, GPO inheritance is blocked for that OU. - - Blocking inheritance can create security gaps because settings from parent OUs won't apply. - Policies can become “sticky” at lower levels, so blocked inheritance should be monitored and - justified. + Fails when gpOptions equals 1 on an OU. An unset gpOptions attribute uses the + default (inheritance enabled); failed container collection is not a clean pass. .EXAMPLE - Test-MtAdGpoBlockedInheritanceCount + Invoke-MtTest -Id 'AD-GPOL-05' - Returns $true when no OUs are blocking GPO inheritance, $false when blocked inheritance is present. - The test result includes the blocked OU count. + Fails when a collected OU blocks Group Policy inheritance. .LINK - https://maester.dev/docs/commands/Test-MtAdGpoBlockedInheritanceCount + https://maester.dev/docs/tests/AD-GPOL-05 #> [MaesterTest( - Id = 'AD-GPOL-05', - Title = 'GPO blocked inheritance count should be compliant', - Product = 'ad', - Feature = 'group-policy', - Area = 'infrastructure', - ResourceType = 'OrganizationalUnit', - Severity = 'Medium', - UserImpact = 'Low', + Id = 'AD-GPOL-05', + Title = 'OUs should not block Group Policy inheritance', + Product = 'ad', + Feature = 'group-policy', + Area = 'infrastructure', + ResourceType = 'OrganizationalUnit', + Severity = 'Low', + UserImpact = 'Low', ImplementationCost = 'Medium', - Mitre = 'None', - Service = 'ActiveDirectory', - Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), - Author = 'soulemike' + Mitre = 'None', + Service = 'ActiveDirectory', + Permission = ('ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty', 'ActiveDirectory:File:SYSVOL:Read'), + Author = 'soulemike' )] [CmdletBinding()] [OutputType([bool])] param() - - Write-Verbose "Starting Test-MtAdGpoBlockedInheritanceCount" - - # Get AD GPO state data (uses cached data if available) - $gpoState = $null - $gpoState = Get-MtADGpoState - -# If unable to retrieve AD data, skip the test - if ($null -eq $gpoState) { - Add-MtTestResultDetail -SkippedBecause NotConnectedActiveDirectory - return $null - } - - $ous = @($gpoState.LinkContainers | Where-Object { @($_.ObjectClass) -contains 'organizationalUnit' }) - - $ouCount = ($ous | Measure-Object).Count - - $blockedOus = @() - $blockedOus = @( - foreach ($ou in $ous) { - $gpOptionsValue = $ou.gpOptions - if ($null -eq $gpOptionsValue) { - continue - } - - # gpOptions: 1 = blocked inheritance - if ([int]$gpOptionsValue -eq 1) { - $ou - } - } - ) - - $blockedCount = ($blockedOus | Measure-Object).Count - $blockedPercentage = if ($ouCount -gt 0) { [math]::Round(($blockedCount / $ouCount) * 100, 2) } else { 0 } - - # Security intent: pass only when no OU is blocking GPO inheritance. - $testResult = $blockedCount -eq 0 - - $sampleLimit = 5 - $sampleBlocked = $blockedOus | Select-Object -First $sampleLimit - $sampleNames = @($sampleBlocked | ForEach-Object { - if ($_.Name) { $_.Name } else { $_.DistinguishedName } - }) - $sampleNamesText = ($sampleNames | Where-Object { $_ }) -join ', ' - if ($blockedCount -gt $sampleLimit -and $sampleNamesText) { - $sampleNamesText += " (showing first $sampleLimit)" - } - - $resultTable = "| Metric | Value |" + "`n" - $resultTable += "| --- | --- |" + "`n" - $resultTable += "| Total OUs | $ouCount |" + "`n" - $resultTable += "| OUs Blocking Inheritance | $blockedCount |" + "`n" - $resultTable += "| Blocked Ratio | $blockedPercentage% |" + "`n" - if ($blockedCount -gt 0 -and $sampleNamesText) { - $resultTable += "| Sample Blocked OUs | $sampleNamesText |" + "`n" - } - - if ($testResult) { - $recommendation = "✅ GPO inheritance blocking was not detected on any OU. Active Directory Group Policy Objects have been analyzed successfully." - } - else { - $recommendation = "⚠️ GPO inheritance blocking was detected on $blockedCount OU(s). Blocked inheritance can create security gaps because policies from parent OUs won't apply. Review and justify these OU configurations." - } - - $testResultMarkdown = "$recommendation`n`n%TestResult%" - $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $resultTable - - Add-MtTestResultDetail -Result $testResultMarkdown - return $testResult + $state = Get-MtADGpoState + if ($null -eq $state -or $null -eq $state.LinkContainers) { throw 'GPO link containers could not be collected; inheritance blocking cannot be assessed.' } + $ous = @($state.LinkContainers | Where-Object { @($_.ObjectClass) -contains 'organizationalUnit' }) + $blocked = @($ous | Where-Object { $null -ne $_.GpOptions -and [int]$_.GpOptions -eq 1 } | Sort-Object DistinguishedName) + $pass = $blocked.Count -eq 0 + $summary = if ($pass) { 'Well done. No collected OU blocks Group Policy inheritance.' } else { "$($blocked.Count) of $($ous.Count) OUs block Group Policy inheritance. Review and justify these exceptions; enforced parent links still apply." } + $result = Format-MtAdGpoResult -Summary $summary -Metrics ([ordered]@{ 'Total OUs' = $ous.Count; 'OUs blocking inheritance' = $blocked.Count }) -Details $blocked -Properties DistinguishedName -Headers OU + Add-MtTestResultDetail -Result $result + return $pass } 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 -} diff --git a/website/docs/advanced/active-directory.md b/website/docs/advanced/active-directory.md index 234ff2d34e..e6a0461bb3 100644 --- a/website/docs/advanced/active-directory.md +++ b/website/docs/advanced/active-directory.md @@ -9,7 +9,7 @@ sidebar: - Version: 3.0 - Methodology: Extracted from `[MaesterTest] Permission` attribute on each AD test -- Total tests: 270 +- Total tests: 252 - Format: `::` The permission model documents the exact minimum permissions each built-in AD test requires. It does not describe human role names (e.g., Domain Admin); it describes the technical permission a test needs to retrieve its data. @@ -123,13 +123,13 @@ 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 Tests (22 tests) | 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-01 through AD-GPO-02 and AD-GPO-04; AD-GPOL-01 through AD-GPOL-05; AD-GPOREP-01, 03, 05-07, 09-10, 12, 14-15 and 17; AD-GPOS-02, AD-GPOS-04 and AD-GPOS-08 | `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. | -**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. +**Summary:** 62 of 252 AD tests (about 25%) require privileges beyond a standard authenticated user. The remaining 190 tests can run with standard Domain User LDAP read access. ## Category Summary @@ -151,10 +151,10 @@ A standard **authenticated user** (Domain User) can read most LDAP attributes on | `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` | -| `gpos` | AD-GPOS-01 through AD-GPOS-09 | `ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty`, `ActiveDirectory:File:SYSVOL:Read` | +| `gpo` | AD-GPO-01 through AD-GPO-02, and AD-GPO-04 | `ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty`, `ActiveDirectory:File:SYSVOL:Read` | +| `gpol` | AD-GPOL-01 through AD-GPOL-05 | `ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty`, `ActiveDirectory:File:SYSVOL:Read` | +| `gporep` (Group Policy settings) | AD-GPOREP-01, 03, 05-07, 09-10, 12, 14-15, and 17 | `ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty`, `ActiveDirectory:File:SYSVOL:Read` | +| `gpos` | AD-GPOS-02, AD-GPOS-04, and AD-GPOS-08 | `ActiveDirectory:Ldap:groupPolicyContainer.gPCFileSysPath:ReadProperty`, `ActiveDirectory:File:SYSVOL:Read` | | `grp` | AD-GRP-01 through AD-GRP-10 | `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` | @@ -170,6 +170,31 @@ A standard **authenticated user** (Domain User) can read most LDAP attributes on | `trust` | AD-TRUST-01 through AD-TRUST-07 | `ActiveDirectory:Ldap:trustedDomain:ReadProperty` | | `user` | AD-USER-01 through AD-USER-29 | `ActiveDirectory:Ldap:user:ReadProperty` | +## Retired GPO test IDs + +The consolidated tests keep the surviving ID; retired IDs no longer have standalone tests. Update `TestSettings`, ID-based selections and exclusions that name them. Historical `-Tag` and `-ExcludeTag` selectors redirect to the consolidated checks through the generated legacy-tag table; this does not migrate parameter or severity overrides. + +| Retired ID | Consolidated into | +|---|---| +| AD-GPO-03 | AD-GPO-02 | +| AD-GPO-05 | AD-GPO-04 | +| AD-GPOS-01 | AD-GPO-01 | +| AD-GPOS-03 | AD-GPOS-02 | +| AD-GPOS-05, AD-GPOS-06, AD-GPOS-07 | AD-GPOS-04 | +| AD-GPOS-09 | AD-GPOS-08 | +| 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-19, AD-GPOREP-20 | AD-GPOREP-17 | + +The Group Policy consolidation reduces these checks from 28 to 22. Retired GPO IDs no longer have standalone tests; the mappings above preserve their legacy-tag destinations. + +`AD-GPOL-04` retains its no-enforced-links pass/fail rule with a default severity of **Low**. Review any configuration that deliberately overrides its earlier **Info** severity. + ## Known Misleading Outcomes The following behaviors can hide incomplete access. They are documented here so operators do not misinterpret empty or partial results as proof of a clean configuration. @@ -180,7 +205,7 @@ The following behaviors can hide incomplete access. They are documented here so ### 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. +An empty GPO inventory is not, by itself, proof of a complete audit: it may be a legitimate empty result or reflect an unreadable or incomplete query. Interpret it with collection status and the specific test's result. Failed metadata, link, or report collection remains unavailable (`null`), rather than being treated as an empty successful collection. The collector also records directory and SYSVOL version details; a missing XML scan or failed SYSVOL/report collection is not evidence that the scanned policy is clean. LDAP access alone does not prove policy files were read. ### DNS tests (AD-DNS-*) diff --git a/website/scripts/tests/retired-test-redirects.test.mjs b/website/scripts/tests/retired-test-redirects.test.mjs new file mode 100644 index 0000000000..b9f16db5b6 --- /dev/null +++ b/website/scripts/tests/retired-test-redirects.test.mjs @@ -0,0 +1,46 @@ +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; + +test('retired native tests redirect to their surviving checks without removing URL-contract entries', async () => { + const previous = process.cwd(); + const fixture = mkdtempSync(join(tmpdir(), 'maester-redirects-')); + const source = new URL('../../src/lib/redirects.mjs', import.meta.url); + const registry = readFileSync(new URL('../../../build/golden/native-test-replacements.psd1', import.meta.url), 'utf8'); + const replacements = Object.fromEntries([...registry.matchAll(/'([^']+)'\s*=\s*'([^']+)'/g)].map((match) => [match[1], match[2]])); + const contract = readFileSync(new URL('../../src/data/url-contract.txt', import.meta.url), 'utf8'); + try { + mkdirSync(join(fixture, 'src/data'), { recursive: true }); + mkdirSync(join(fixture, 'blog'), { recursive: true }); + mkdirSync(join(fixture, 'dist/docs/tests'), { recursive: true }); + writeFileSync(join(fixture, 'src/data/test-catalog.json'), JSON.stringify({ Tests: [], TestReplacements: replacements })); + writeFileSync(join(fixture, 'src/data/versions.json'), JSON.stringify({ commands: {} })); + writeFileSync(join(fixture, 'src/data/url-contract.txt'), contract); + writeFileSync(join(fixture, 'blog/authors.yml'), ''); + for (const replacement of new Set(Object.values(replacements))) { + writeFileSync(join(fixture, `dist/docs/tests/${replacement}.html`), 'survivor'); + } + process.chdir(fixture); + const { buildRedirects } = await import(source.href + '?retired-test-fixture'); + const rules = buildRedirects(join(fixture, 'dist')); + assert.ok(rules.includes('/docs/tests/AD-GPOREP-16 /docs/tests/AD-GPOREP-15 301')); + assert.ok(rules.includes('/docs/tests/AD-GPOS-01 /docs/tests/AD-GPO-01 301')); + assert.ok(rules.includes('/docs/next/* /docs/:splat 301')); + const redirects = new Map(rules.map((line) => line.split(/\s+/).slice(0, 2))); + let verified = 0; + for (const path of contract.split('\n').map((line) => line.trim())) { + const id = path.match(/^\/docs\/(?:next\/)?tests\/([^/]+)$/)?.[1]; + if (!replacements[id]) continue; + const current = path.replace(/^\/docs\/next\//, '/docs/'); + assert.equal(redirects.get(current), `/docs/tests/${replacements[id]}`, path); + verified++; + } + assert.ok(verified >= 36, 'real contract must exercise the retired AD test URLs in both URL trees'); + assert.equal(readFileSync(join(fixture, 'src/data/url-contract.txt'), 'utf8'), contract); + } finally { + process.chdir(previous); + rmSync(fixture, { recursive: true, force: true }); + } +}); diff --git a/website/src/data/test-builder.json b/website/src/data/test-builder.json index 2b025d35ea..8542c340a9 100644 --- a/website/src/data/test-builder.json +++ b/website/src/data/test-builder.json @@ -18464,6 +18464,11 @@ "type": "int", "tests": 4 }, + { + "name": "MaximumModificationAgeYears", + "type": "int", + "tests": 1 + }, { "name": "MaximumPasswordAgeDays", "type": "int", diff --git a/website/src/lib/redirects.mjs b/website/src/lib/redirects.mjs index 3af41f8de7..680223d77e 100644 --- a/website/src/lib/redirects.mjs +++ b/website/src/lib/redirects.mjs @@ -30,6 +30,11 @@ export function buildRedirects(dist) { const catalog = JSON.parse(readFileSync(join(websiteRoot, 'src/data/test-catalog.json'), 'utf8')); const versions = JSON.parse(readFileSync(join(websiteRoot, 'src/data/versions.json'), 'utf8')); const testByFunction = new Map(catalog.Tests.filter((t) => t.FunctionName).map((t) => [t.FunctionName, t.Id])); + // Consolidated native checks retain their historical test URLs, including /docs/next + // through the preview-tree rule below. The replacement registry is exported with the catalog. + for (const [retired, replacement] of Object.entries(catalog.TestReplacements ?? {})) { + add(`/docs/tests/${retired}`, `/docs/tests/${replacement}`); + } for (const name of Object.keys(versions.commands)) { if (exists(`/docs/commands/${name}`)) continue; const test = testByFunction.get(name); @@ -133,4 +138,3 @@ export function redirects() { }, }; } -