diff --git a/build/golden/Export-MtLegacyTagTable.ps1 b/build/golden/Export-MtLegacyTagTable.ps1 index 33da8e4eff..4609761d1e 100644 --- a/build/golden/Export-MtLegacyTagTable.ps1 +++ b/build/golden/Export-MtLegacyTagTable.ps1 @@ -8,10 +8,11 @@ -Tag CA, -Tag CIS, -ExcludeTag MS.AAD.3.5 and every other 2.x tag keep selecting the same tests, the module ships a table that maps each 2.x tag to the IDs of the built-in tests that carried it. - The table is derived from two frozen files and nothing else, so the output never changes with tests/: + The table is derived from two frozen files and explicit native test replacements: powershell/tests/fixtures/golden/tags-and-blocks.json the tags of every built-in test in 2.x - powershell/tests/fixtures/golden/tags-3.0-preview.json tags the 3.0 previews added (for example AI) + powershell/tests/fixtures/golden/tags-3.0-preview.json tags the 3.0 previews added (for example AI) + build/golden/native-test-replacements.psd1 intentional renames and consolidations Rules: - A tag is matched case-insensitively; the table keeps the first spelling of the snapshot. @@ -22,7 +23,8 @@ obvious one ($Replacements below, and -Severity for Severity:). The engine names it in the warning it writes when a run selects through the tag. - Tests added after 3.0 are not in the table. The file is generated once and is not edited by hand; + Tests added after 3.0 are not in the table unless they explicitly replace a historical check. + The file is regenerated when native replacements change and is never edited by hand; powershell/tests/functions/golden/Golden.Tests.ps1 checks that it is what this script produces. .EXAMPLE @@ -49,10 +51,8 @@ $ErrorActionPreference = 'Stop' $RepoRoot = (Resolve-Path -Path $RepoRoot).Path $fixtures = Join-Path $RepoRoot 'powershell/tests/fixtures/golden' -# 2.x IDs that have another ID in 3.0. -$RenamedIds = @{ - 'MT1060' = 'MT.1060' # The drift family: four Its per folder in 2.x, one native family in 3.0. -} +# Explicit replacements, never a dynamic filter that could hide an accidental test deletion. +$RenamedIds = Import-PowerShellDataFile -LiteralPath (Join-Path $RepoRoot 'build/golden/native-test-replacements.psd1') # The typed selector that takes the place of a tag. Only tags with an obvious one are listed. $Replacements = [ordered]@{ diff --git a/build/golden/native-test-replacements.psd1 b/build/golden/native-test-replacements.psd1 new file mode 100644 index 0000000000..4933c07f31 --- /dev/null +++ b/build/golden/native-test-replacements.psd1 @@ -0,0 +1,95 @@ +@{ + # Explicit native test consolidations. Frozen 2.x tags select these surviving checks. + 'MT1060' = 'MT.1060' + 'AD-CFG-01' = 'AD-FOR-03' + 'AD-CFG-04' = 'AD-FEAT-01' + 'AD-CFG-05' = 'AD-FOR-04' + 'AD-COMP-02' = 'AD-DCOMP-06' + 'AD-COMP-09' = 'AD-DCOMP-01' + 'AD-COMP-10' = 'AD-DCOMP-03' + 'AD-DACL-04' = 'AD-DACL-03' + 'AD-DACL-06' = 'AD-DACL-05' + 'AD-DACL-08' = 'AD-DACL-07' + 'AD-DACL-10' = 'AD-DACL-09' + 'AD-DACL-12' = 'AD-DACL-11' + 'AD-DACL-13' = 'AD-DACL-11' + 'AD-DACL-16' = 'AD-DACL-15' + 'AD-DACL-18' = 'AD-DACL-17' + 'AD-DCOMP-02' = 'AD-DCOMP-01' + 'AD-DCOMP-05' = 'AD-DCOMP-04' + 'AD-DCOMP-09' = 'AD-DCOMP-08' + 'AD-FEAT-02' = 'AD-FEAT-01' + 'AD-GMC-03' = 'AD-GMC-02' + 'AD-GMC-05' = 'AD-GMC-04' + 'AD-GMC-07' = 'AD-GMC-06' + 'AD-GMC-09' = 'AD-GMC-08' + 'AD-GMC-11' = 'AD-GMC-10' + 'AD-GPO-03' = 'AD-GPO-02' + 'AD-GPO-05' = 'AD-GPO-04' + 'AD-GPOL-06' = 'AD-GPOL-03' + 'AD-GPOREP-02' = 'AD-GPOREP-01' + 'AD-GPOREP-04' = 'AD-GPOREP-03' + 'AD-GPOREP-08' = 'AD-GPOREP-07' + 'AD-GPOREP-11' = 'AD-GPOREP-10' + 'AD-GPOREP-13' = 'AD-GPOREP-12' + 'AD-GPOREP-16' = 'AD-GPOREP-15' + 'AD-GPOREP-18' = 'AD-GPOREP-17' + 'AD-GPOREP-19' = 'AD-GPOREP-17' + 'AD-GPOREP-20' = 'AD-GPOREP-17' + 'AD-GRP-07' = 'AD-GRP-06' + 'AD-GRP-09' = 'AD-GRP-08' + 'AD-GRP-10' = 'AD-GRP-08' + 'AD-ROOTDSE-02' = 'AD-ROOTDSE-01' + 'AD-SCH-02' = 'AD-SCH-01' + 'AD-SCH-04' = 'AD-SCH-03' + 'AD-SPN-02' = 'AD-SPN-01' + 'AD-SPN-04' = 'AD-SPN-03' + 'AD-SPN-08' = 'AD-SPN-07' + 'AD-SPN-10' = 'AD-SPN-09' + 'AD-SPN-13' = 'AD-SPN-12' + 'AD-TRUST-04' = 'AD-TRUST-03' + 'AD-TRUST-05' = 'AD-TRUST-01' + 'AD-TRUST-07' = 'AD-TRUST-06' + 'AD-USER-14' = 'AD-SPN-06' + # Second AD consolidation batch. + 'AD-CFG-14' = 'AD-CFG-13' + 'AD-CFG-16' = 'AD-CFG-15' + 'AD-CFG-17' = 'AD-CFG-15' + 'AD-CFG-18' = 'AD-CFG-15' + 'AD-CFG-19' = 'AD-CFG-15' + 'AD-CFG-24' = 'AD-CFG-23' + 'AD-FGPP-02' = 'AD-FGPP-01' + 'AD-FGPP-03' = 'AD-FGPP-01' + 'AD-FGPP-04' = 'AD-FGPP-01' + 'AD-PWDPOL-02' = 'AD-PWDPOL-01' + 'AD-PWDPOL-03' = 'AD-PWDPOL-01' + 'AD-PWDPOL-04' = 'AD-PWDPOL-01' + 'AD-PWDPOL-05' = 'AD-PWDPOL-01' + 'AD-PWDPOL-06' = 'AD-PWDPOL-01' + 'AD-PWDPOL-07' = 'AD-PWDPOL-01' + 'AD-SITE-03' = 'AD-SITE-02' + 'AD-SITE-05' = 'AD-SITE-04' + 'AD-SUB-01' = 'AD-SITE-04' + 'AD-SUB-02' = 'AD-SITE-04' + 'AD-SUB-05' = 'AD-SUB-04' + 'AD-SUB-07' = 'AD-SUB-06' + 'AD-SUB-09' = 'AD-SUB-08' + 'AD-SUB-10' = 'AD-SUB-08' + 'AD-SUB-11' = 'AD-SITE-04' + 'AD-OU-05' = 'AD-OU-04' + 'AD-USER-17' = 'AD-USER-16' + 'AD-USER-18' = 'AD-USER-16' + 'AD-USER-21' = 'AD-USER-20' + 'AD-USER-23' = 'AD-USER-22' + 'AD-USER-24' = 'AD-USER-22' + 'AD-USER-25' = 'AD-USER-22' + 'AD-USER-27' = 'AD-USER-26' + 'AD-USER-28' = 'AD-USER-05' + 'AD-USER-29' = 'AD-USER-05' + 'AD-DC-06' = 'AD-DC-05' + 'AD-DC-08' = 'AD-DC-07' + 'AD-DCD-02' = 'AD-DCD-01' + 'AD-DOM-06' = 'AD-DOM-05' + 'AD-DOM-08' = 'AD-DOM-07' + 'AD-FORS-02' = 'AD-FORS-01' +} diff --git a/powershell/assets/Maester.LegacyTags.json b/powershell/assets/Maester.LegacyTags.json index 2ba8db3c4b..fe1c0e7f75 100644 --- a/powershell/assets/Maester.LegacyTags.json +++ b/powershell/assets/Maester.LegacyTags.json @@ -16,11 +16,8 @@ "Tag": "AD", "Replacement": "-Product ad", "Tests": [ - "AD-CFG-01", "AD-CFG-02", "AD-CFG-03", - "AD-CFG-04", - "AD-CFG-05", "AD-CFG-06", "AD-CFG-07", "AD-CFG-08", @@ -29,66 +26,43 @@ "AD-CFG-11", "AD-CFG-12", "AD-CFG-13", - "AD-CFG-14", "AD-CFG-15", - "AD-CFG-16", - "AD-CFG-17", - "AD-CFG-18", - "AD-CFG-19", "AD-CFG-20", "AD-CFG-21", "AD-CFG-22", "AD-CFG-23", - "AD-CFG-24", "AD-COMP-01", - "AD-COMP-02", "AD-COMP-03", "AD-COMP-04", "AD-COMP-05", "AD-COMP-06", "AD-COMP-07", "AD-COMP-08", - "AD-COMP-09", - "AD-COMP-10", "AD-DACL-01", "AD-DACL-02", "AD-DACL-03", - "AD-DACL-04", "AD-DACL-05", - "AD-DACL-06", "AD-DACL-07", - "AD-DACL-08", "AD-DACL-09", - "AD-DACL-10", "AD-DACL-11", - "AD-DACL-12", - "AD-DACL-13", "AD-DACL-14", "AD-DACL-15", - "AD-DACL-16", "AD-DACL-17", - "AD-DACL-18", "AD-DC-01", "AD-DC-02", "AD-DC-03", "AD-DC-04", "AD-DC-05", - "AD-DC-06", "AD-DC-07", - "AD-DC-08", "AD-DCD-01", - "AD-DCD-02", "AD-DCD-03", "AD-DCD-04", "AD-DCOMP-01", - "AD-DCOMP-02", "AD-DCOMP-03", "AD-DCOMP-04", - "AD-DCOMP-05", "AD-DCOMP-06", "AD-DCOMP-07", "AD-DCOMP-08", - "AD-DCOMP-09", "AD-DFSR-01", "AD-DNS-01", "AD-DNS-02", @@ -114,67 +88,43 @@ "AD-DOM-03", "AD-DOM-04", "AD-DOM-05", - "AD-DOM-06", "AD-DOM-07", - "AD-DOM-08", "AD-DOMS-01", "AD-FEAT-01", - "AD-FEAT-02", "AD-FGPP-01", - "AD-FGPP-02", - "AD-FGPP-03", - "AD-FGPP-04", "AD-FOR-01", "AD-FOR-02", "AD-FOR-03", "AD-FOR-04", "AD-FORS-01", - "AD-FORS-02", "AD-FORS-03", "AD-FORS-04", "AD-GCHG-01", "AD-GMC-01", "AD-GMC-02", - "AD-GMC-03", "AD-GMC-04", - "AD-GMC-05", "AD-GMC-06", - "AD-GMC-07", "AD-GMC-08", - "AD-GMC-09", "AD-GMC-10", - "AD-GMC-11", "AD-GPO-01", "AD-GPO-02", - "AD-GPO-03", "AD-GPO-04", - "AD-GPO-05", "AD-GPOL-01", "AD-GPOL-02", "AD-GPOL-03", "AD-GPOL-04", "AD-GPOL-05", - "AD-GPOL-06", "AD-GPOREP-01", - "AD-GPOREP-02", "AD-GPOREP-03", - "AD-GPOREP-04", "AD-GPOREP-05", "AD-GPOREP-06", "AD-GPOREP-07", - "AD-GPOREP-08", "AD-GPOREP-09", "AD-GPOREP-10", - "AD-GPOREP-11", "AD-GPOREP-12", - "AD-GPOREP-13", "AD-GPOREP-14", "AD-GPOREP-15", - "AD-GPOREP-16", "AD-GPOREP-17", - "AD-GPOREP-18", - "AD-GPOREP-19", - "AD-GPOREP-20", "AD-GPOS-01", "AD-GPOS-02", "AD-GPOS-03", @@ -190,10 +140,7 @@ "AD-GRP-04", "AD-GRP-05", "AD-GRP-06", - "AD-GRP-07", "AD-GRP-08", - "AD-GRP-09", - "AD-GRP-10", "AD-KRBTGT-01", "AD-KRBTGT-02", "AD-KRBTGT-03", @@ -202,61 +149,34 @@ "AD-OU-02", "AD-OU-03", "AD-OU-04", - "AD-OU-05", "AD-PRINT-01", "AD-PWDPOL-01", - "AD-PWDPOL-02", - "AD-PWDPOL-03", - "AD-PWDPOL-04", - "AD-PWDPOL-05", - "AD-PWDPOL-06", - "AD-PWDPOL-07", "AD-REPL-01", "AD-REPL-02", "AD-ROOTDSE-01", - "AD-ROOTDSE-02", "AD-ROOTDSE-03", "AD-SCH-01", - "AD-SCH-02", "AD-SCH-03", - "AD-SCH-04", "AD-SCH-05", "AD-SITE-01", "AD-SITE-02", - "AD-SITE-03", "AD-SITE-04", - "AD-SITE-05", "AD-SPN-01", - "AD-SPN-02", "AD-SPN-03", - "AD-SPN-04", "AD-SPN-05", "AD-SPN-06", "AD-SPN-07", - "AD-SPN-08", "AD-SPN-09", - "AD-SPN-10", "AD-SPN-11", "AD-SPN-12", - "AD-SPN-13", - "AD-SUB-01", - "AD-SUB-02", "AD-SUB-03", "AD-SUB-04", - "AD-SUB-05", "AD-SUB-06", - "AD-SUB-07", "AD-SUB-08", - "AD-SUB-09", - "AD-SUB-10", - "AD-SUB-11", "AD-TRUST-01", "AD-TRUST-02", "AD-TRUST-03", - "AD-TRUST-04", - "AD-TRUST-05", "AD-TRUST-06", - "AD-TRUST-07", "AD-USER-01", "AD-USER-02", "AD-USER-03", @@ -270,47 +190,574 @@ "AD-USER-11", "AD-USER-12", "AD-USER-13", - "AD-USER-14", "AD-USER-15", "AD-USER-16", - "AD-USER-17", - "AD-USER-18", "AD-USER-19", "AD-USER-20", - "AD-USER-21", "AD-USER-22", - "AD-USER-23", - "AD-USER-24", - "AD-USER-25", - "AD-USER-26", - "AD-USER-27", - "AD-USER-28", - "AD-USER-29" + "AD-USER-26" + ] + }, + { + "Tag": "AD-CFG-01", + "Tests": [ + "AD-FOR-03" + ] + }, + { + "Tag": "AD-CFG-04", + "Tests": [ + "AD-FEAT-01" + ] + }, + { + "Tag": "AD-CFG-05", + "Tests": [ + "AD-FOR-04" + ] + }, + { + "Tag": "AD-CFG-14", + "Tests": [ + "AD-CFG-13" + ] + }, + { + "Tag": "AD-CFG-16", + "Tests": [ + "AD-CFG-15" + ] + }, + { + "Tag": "AD-CFG-17", + "Tests": [ + "AD-CFG-15" + ] + }, + { + "Tag": "AD-CFG-18", + "Tests": [ + "AD-CFG-15" + ] + }, + { + "Tag": "AD-CFG-19", + "Tests": [ + "AD-CFG-15" + ] + }, + { + "Tag": "AD-CFG-24", + "Tests": [ + "AD-CFG-23" + ] + }, + { + "Tag": "AD-COMP-02", + "Tests": [ + "AD-DCOMP-06" + ] + }, + { + "Tag": "AD-COMP-09", + "Tests": [ + "AD-DCOMP-01" + ] + }, + { + "Tag": "AD-COMP-10", + "Tests": [ + "AD-DCOMP-03" + ] + }, + { + "Tag": "AD-DACL-04", + "Tests": [ + "AD-DACL-03" + ] + }, + { + "Tag": "AD-DACL-06", + "Tests": [ + "AD-DACL-05" + ] + }, + { + "Tag": "AD-DACL-08", + "Tests": [ + "AD-DACL-07" + ] + }, + { + "Tag": "AD-DACL-10", + "Tests": [ + "AD-DACL-09" + ] + }, + { + "Tag": "AD-DACL-12", + "Tests": [ + "AD-DACL-11" + ] + }, + { + "Tag": "AD-DACL-13", + "Tests": [ + "AD-DACL-11" + ] + }, + { + "Tag": "AD-DACL-16", + "Tests": [ + "AD-DACL-15" + ] + }, + { + "Tag": "AD-DACL-18", + "Tests": [ + "AD-DACL-17" + ] + }, + { + "Tag": "AD-DC-06", + "Tests": [ + "AD-DC-05" + ] + }, + { + "Tag": "AD-DC-08", + "Tests": [ + "AD-DC-07" + ] + }, + { + "Tag": "AD-DCD-02", + "Tests": [ + "AD-DCD-01" + ] + }, + { + "Tag": "AD-DCOMP-02", + "Tests": [ + "AD-DCOMP-01" + ] + }, + { + "Tag": "AD-DCOMP-05", + "Tests": [ + "AD-DCOMP-04" + ] + }, + { + "Tag": "AD-DCOMP-09", + "Tests": [ + "AD-DCOMP-08" + ] + }, + { + "Tag": "AD-DOM-06", + "Tests": [ + "AD-DOM-05" + ] + }, + { + "Tag": "AD-DOM-08", + "Tests": [ + "AD-DOM-07" + ] + }, + { + "Tag": "AD-FEAT-02", + "Tests": [ + "AD-FEAT-01" + ] + }, + { + "Tag": "AD-FGPP-02", + "Tests": [ + "AD-FGPP-01" + ] + }, + { + "Tag": "AD-FGPP-03", + "Tests": [ + "AD-FGPP-01" + ] + }, + { + "Tag": "AD-FGPP-04", + "Tests": [ + "AD-FGPP-01" + ] + }, + { + "Tag": "AD-FORS-02", + "Tests": [ + "AD-FORS-01" + ] + }, + { + "Tag": "AD-GMC-03", + "Tests": [ + "AD-GMC-02" + ] + }, + { + "Tag": "AD-GMC-05", + "Tests": [ + "AD-GMC-04" + ] + }, + { + "Tag": "AD-GMC-07", + "Tests": [ + "AD-GMC-06" + ] + }, + { + "Tag": "AD-GMC-09", + "Tests": [ + "AD-GMC-08" + ] + }, + { + "Tag": "AD-GMC-11", + "Tests": [ + "AD-GMC-10" + ] + }, + { + "Tag": "AD-GPO-03", + "Tests": [ + "AD-GPO-02" + ] + }, + { + "Tag": "AD-GPO-05", + "Tests": [ + "AD-GPO-04" + ] + }, + { + "Tag": "AD-GPOL-06", + "Tests": [ + "AD-GPOL-03" + ] + }, + { + "Tag": "AD-GPOREP-02", + "Tests": [ + "AD-GPOREP-01" + ] + }, + { + "Tag": "AD-GPOREP-04", + "Tests": [ + "AD-GPOREP-03" + ] + }, + { + "Tag": "AD-GPOREP-08", + "Tests": [ + "AD-GPOREP-07" + ] + }, + { + "Tag": "AD-GPOREP-11", + "Tests": [ + "AD-GPOREP-10" + ] + }, + { + "Tag": "AD-GPOREP-13", + "Tests": [ + "AD-GPOREP-12" + ] + }, + { + "Tag": "AD-GPOREP-16", + "Tests": [ + "AD-GPOREP-15" + ] + }, + { + "Tag": "AD-GPOREP-18", + "Tests": [ + "AD-GPOREP-17" + ] + }, + { + "Tag": "AD-GPOREP-19", + "Tests": [ + "AD-GPOREP-17" + ] + }, + { + "Tag": "AD-GPOREP-20", + "Tests": [ + "AD-GPOREP-17" + ] + }, + { + "Tag": "AD-GRP-07", + "Tests": [ + "AD-GRP-06" + ] + }, + { + "Tag": "AD-GRP-09", + "Tests": [ + "AD-GRP-08" + ] + }, + { + "Tag": "AD-GRP-10", + "Tests": [ + "AD-GRP-08" + ] + }, + { + "Tag": "AD-OU-05", + "Tests": [ + "AD-OU-04" + ] + }, + { + "Tag": "AD-PWDPOL-02", + "Tests": [ + "AD-PWDPOL-01" + ] + }, + { + "Tag": "AD-PWDPOL-03", + "Tests": [ + "AD-PWDPOL-01" + ] + }, + { + "Tag": "AD-PWDPOL-04", + "Tests": [ + "AD-PWDPOL-01" + ] + }, + { + "Tag": "AD-PWDPOL-05", + "Tests": [ + "AD-PWDPOL-01" + ] + }, + { + "Tag": "AD-PWDPOL-06", + "Tests": [ + "AD-PWDPOL-01" + ] + }, + { + "Tag": "AD-PWDPOL-07", + "Tests": [ + "AD-PWDPOL-01" + ] + }, + { + "Tag": "AD-ROOTDSE-02", + "Tests": [ + "AD-ROOTDSE-01" + ] + }, + { + "Tag": "AD-SCH-02", + "Tests": [ + "AD-SCH-01" + ] + }, + { + "Tag": "AD-SCH-04", + "Tests": [ + "AD-SCH-03" + ] + }, + { + "Tag": "AD-SITE-03", + "Tests": [ + "AD-SITE-02" + ] + }, + { + "Tag": "AD-SITE-05", + "Tests": [ + "AD-SITE-04" + ] + }, + { + "Tag": "AD-SPN-02", + "Tests": [ + "AD-SPN-01" + ] + }, + { + "Tag": "AD-SPN-04", + "Tests": [ + "AD-SPN-03" + ] + }, + { + "Tag": "AD-SPN-08", + "Tests": [ + "AD-SPN-07" + ] + }, + { + "Tag": "AD-SPN-10", + "Tests": [ + "AD-SPN-09" + ] + }, + { + "Tag": "AD-SPN-13", + "Tests": [ + "AD-SPN-12" + ] + }, + { + "Tag": "AD-SUB-01", + "Tests": [ + "AD-SITE-04" + ] + }, + { + "Tag": "AD-SUB-02", + "Tests": [ + "AD-SITE-04" + ] + }, + { + "Tag": "AD-SUB-05", + "Tests": [ + "AD-SUB-04" + ] + }, + { + "Tag": "AD-SUB-07", + "Tests": [ + "AD-SUB-06" + ] + }, + { + "Tag": "AD-SUB-09", + "Tests": [ + "AD-SUB-08" + ] + }, + { + "Tag": "AD-SUB-10", + "Tests": [ + "AD-SUB-08" + ] + }, + { + "Tag": "AD-SUB-11", + "Tests": [ + "AD-SITE-04" + ] + }, + { + "Tag": "AD-TRUST-04", + "Tests": [ + "AD-TRUST-03" + ] + }, + { + "Tag": "AD-TRUST-05", + "Tests": [ + "AD-TRUST-01" + ] + }, + { + "Tag": "AD-TRUST-07", + "Tests": [ + "AD-TRUST-06" + ] + }, + { + "Tag": "AD-USER-14", + "Tests": [ + "AD-SPN-06" + ] + }, + { + "Tag": "AD-USER-17", + "Tests": [ + "AD-USER-16" + ] + }, + { + "Tag": "AD-USER-18", + "Tests": [ + "AD-USER-16" + ] + }, + { + "Tag": "AD-USER-21", + "Tests": [ + "AD-USER-20" + ] + }, + { + "Tag": "AD-USER-23", + "Tests": [ + "AD-USER-22" + ] + }, + { + "Tag": "AD-USER-24", + "Tests": [ + "AD-USER-22" + ] + }, + { + "Tag": "AD-USER-25", + "Tests": [ + "AD-USER-22" + ] + }, + { + "Tag": "AD-USER-27", + "Tests": [ + "AD-USER-26" + ] + }, + { + "Tag": "AD-USER-28", + "Tests": [ + "AD-USER-05" + ] + }, + { + "Tag": "AD-USER-29", + "Tests": [ + "AD-USER-05" ] }, { "Tag": "AD.Computer", "Tests": [ "AD-COMP-01", - "AD-COMP-02", "AD-COMP-03", "AD-COMP-04", "AD-COMP-05", "AD-COMP-06", "AD-COMP-07", "AD-COMP-08", - "AD-COMP-09", - "AD-COMP-10" + "AD-DCOMP-01", + "AD-DCOMP-03", + "AD-DCOMP-06" ] }, { "Tag": "AD.Config", "Tests": [ - "AD-CFG-01", "AD-CFG-02", "AD-CFG-03", - "AD-CFG-04", - "AD-CFG-05", "AD-CFG-06", "AD-CFG-07", "AD-CFG-08", @@ -319,17 +766,14 @@ "AD-CFG-11", "AD-CFG-12", "AD-CFG-13", - "AD-CFG-14", "AD-CFG-15", - "AD-CFG-16", - "AD-CFG-17", - "AD-CFG-18", - "AD-CFG-19", "AD-CFG-20", "AD-CFG-21", "AD-CFG-22", "AD-CFG-23", - "AD-CFG-24" + "AD-FEAT-01", + "AD-FOR-03", + "AD-FOR-04" ] }, { @@ -338,21 +782,13 @@ "AD-DACL-01", "AD-DACL-02", "AD-DACL-03", - "AD-DACL-04", "AD-DACL-05", - "AD-DACL-06", "AD-DACL-07", - "AD-DACL-08", "AD-DACL-09", - "AD-DACL-10", "AD-DACL-11", - "AD-DACL-12", - "AD-DACL-13", "AD-DACL-14", "AD-DACL-15", - "AD-DACL-16", - "AD-DACL-17", - "AD-DACL-18" + "AD-DACL-17" ] }, { @@ -387,9 +823,7 @@ "AD-DOM-03", "AD-DOM-04", "AD-DOM-05", - "AD-DOM-06", "AD-DOM-07", - "AD-DOM-08", "AD-DOMS-01" ] }, @@ -401,11 +835,8 @@ "AD-DC-03", "AD-DC-04", "AD-DC-05", - "AD-DC-06", "AD-DC-07", - "AD-DC-08", "AD-DCD-01", - "AD-DCD-02", "AD-DCD-03", "AD-DCD-04" ] @@ -418,7 +849,6 @@ "AD-FOR-03", "AD-FOR-04", "AD-FORS-01", - "AD-FORS-02", "AD-FORS-03", "AD-FORS-04" ] @@ -432,11 +862,9 @@ { "Tag": "AD.GMC", "Tests": [ - "AD-GMC-07", + "AD-GMC-06", "AD-GMC-08", - "AD-GMC-09", - "AD-GMC-10", - "AD-GMC-11" + "AD-GMC-10" ] }, { @@ -444,40 +872,28 @@ "Tests": [ "AD-GPO-01", "AD-GPO-02", - "AD-GPO-03", "AD-GPO-04", - "AD-GPO-05", "AD-GPOL-01", "AD-GPOL-02", "AD-GPOL-03", "AD-GPOL-04", - "AD-GPOL-05", - "AD-GPOL-06" + "AD-GPOL-05" ] }, { "Tag": "AD.GPOState", "Tests": [ "AD-GPOREP-01", - "AD-GPOREP-02", "AD-GPOREP-03", - "AD-GPOREP-04", "AD-GPOREP-05", "AD-GPOREP-06", "AD-GPOREP-07", - "AD-GPOREP-08", "AD-GPOREP-09", "AD-GPOREP-10", - "AD-GPOREP-11", "AD-GPOREP-12", - "AD-GPOREP-13", "AD-GPOREP-14", "AD-GPOREP-15", - "AD-GPOREP-16", "AD-GPOREP-17", - "AD-GPOREP-18", - "AD-GPOREP-19", - "AD-GPOREP-20", "AD-GPOS-01", "AD-GPOS-02", "AD-GPOS-03", @@ -495,25 +911,17 @@ "AD-GCHG-01", "AD-GMC-01", "AD-GMC-02", - "AD-GMC-03", "AD-GMC-04", - "AD-GMC-05", "AD-GMC-06", - "AD-GMC-07", "AD-GMC-08", - "AD-GMC-09", "AD-GMC-10", - "AD-GMC-11", "AD-GRP-01", "AD-GRP-02", "AD-GRP-03", "AD-GRP-04", "AD-GRP-05", "AD-GRP-06", - "AD-GRP-07", - "AD-GRP-08", - "AD-GRP-09", - "AD-GRP-10" + "AD-GRP-08" ] }, { @@ -522,24 +930,14 @@ "AD-OU-01", "AD-OU-02", "AD-OU-03", - "AD-OU-04", - "AD-OU-05" + "AD-OU-04" ] }, { "Tag": "AD.PasswordPolicy", "Tests": [ "AD-FGPP-01", - "AD-FGPP-02", - "AD-FGPP-03", - "AD-FGPP-04", - "AD-PWDPOL-01", - "AD-PWDPOL-02", - "AD-PWDPOL-03", - "AD-PWDPOL-04", - "AD-PWDPOL-05", - "AD-PWDPOL-06", - "AD-PWDPOL-07" + "AD-PWDPOL-01" ] }, { @@ -553,11 +951,9 @@ "Tests": [ "AD-DFSR-01", "AD-FEAT-01", - "AD-FEAT-02", "AD-REPL-01", "AD-REPL-02", "AD-ROOTDSE-01", - "AD-ROOTDSE-02", "AD-ROOTDSE-03" ] }, @@ -565,9 +961,7 @@ "Tag": "AD.Schema", "Tests": [ "AD-SCH-01", - "AD-SCH-02", "AD-SCH-03", - "AD-SCH-04", "AD-SCH-05" ] }, @@ -575,14 +969,11 @@ "Tag": "AD.Security", "Tests": [ "AD-DCOMP-01", - "AD-DCOMP-02", "AD-DCOMP-03", "AD-DCOMP-04", - "AD-DCOMP-05", "AD-DCOMP-06", "AD-DCOMP-07", "AD-DCOMP-08", - "AD-DCOMP-09", "AD-KRBTGT-01", "AD-KRBTGT-02", "AD-KRBTGT-03", @@ -594,38 +985,24 @@ "Tests": [ "AD-SITE-01", "AD-SITE-02", - "AD-SITE-03", "AD-SITE-04", - "AD-SITE-05", - "AD-SUB-01", - "AD-SUB-02", "AD-SUB-03", "AD-SUB-04", - "AD-SUB-05", "AD-SUB-06", - "AD-SUB-07", - "AD-SUB-08", - "AD-SUB-09", - "AD-SUB-10", - "AD-SUB-11" + "AD-SUB-08" ] }, { "Tag": "AD.SPN", "Tests": [ "AD-SPN-01", - "AD-SPN-02", "AD-SPN-03", - "AD-SPN-04", "AD-SPN-05", "AD-SPN-06", "AD-SPN-07", - "AD-SPN-08", "AD-SPN-09", - "AD-SPN-10", "AD-SPN-11", - "AD-SPN-12", - "AD-SPN-13" + "AD-SPN-12" ] }, { @@ -634,15 +1011,13 @@ "AD-TRUST-01", "AD-TRUST-02", "AD-TRUST-03", - "AD-TRUST-04", - "AD-TRUST-05", - "AD-TRUST-06", - "AD-TRUST-07" + "AD-TRUST-06" ] }, { "Tag": "AD.User", "Tests": [ + "AD-SPN-06", "AD-USER-01", "AD-USER-02", "AD-USER-03", @@ -656,22 +1031,12 @@ "AD-USER-11", "AD-USER-12", "AD-USER-13", - "AD-USER-14", "AD-USER-15", "AD-USER-16", - "AD-USER-17", - "AD-USER-18", "AD-USER-19", "AD-USER-20", - "AD-USER-21", "AD-USER-22", - "AD-USER-23", - "AD-USER-24", - "AD-USER-25", - "AD-USER-26", - "AD-USER-27", - "AD-USER-28", - "AD-USER-29" + "AD-USER-26" ] }, { diff --git a/powershell/internal/checks/ad/ad/Assert-MtAdUserAccountControl.ps1 b/powershell/internal/checks/ad/ad/Assert-MtAdUserAccountControl.ps1 new file mode 100644 index 0000000000..7cefa6f8f3 --- /dev/null +++ b/powershell/internal/checks/ad/ad/Assert-MtAdUserAccountControl.ps1 @@ -0,0 +1,7 @@ +function Assert-MtAdUserAccountControl { + [CmdletBinding()] + param([object[]] $Users) + + $missing = @($Users | Where-Object { $null -eq $_.UserAccountControl }) + if ($missing.Count) { throw "UserAccountControl is unavailable for $($missing.Count) users; cannot treat missing flags as clear." } +} diff --git a/powershell/internal/checks/ad/ad/ConvertTo-MtAdConfigurationInventoryCell.ps1 b/powershell/internal/checks/ad/ad/ConvertTo-MtAdConfigurationInventoryCell.ps1 new file mode 100644 index 0000000000..18b1ec193e --- /dev/null +++ b/powershell/internal/checks/ad/ad/ConvertTo-MtAdConfigurationInventoryCell.ps1 @@ -0,0 +1,8 @@ +function ConvertTo-MtAdConfigurationInventoryCell { + [CmdletBinding()] + [OutputType([string])] + param($Value) + + if ($null -eq $Value -or [string]::IsNullOrWhiteSpace([string]$Value)) { return '—' } + return [System.Net.WebUtility]::HtmlEncode(([string]$Value -replace '\r\n|\r|\n', ' ')).Replace('|', '|') +} diff --git a/powershell/internal/checks/ad/ad/Format-MtAdSiteInventoryValue.ps1 b/powershell/internal/checks/ad/ad/Format-MtAdSiteInventoryValue.ps1 new file mode 100644 index 0000000000..7fc4d66a67 --- /dev/null +++ b/powershell/internal/checks/ad/ad/Format-MtAdSiteInventoryValue.ps1 @@ -0,0 +1,9 @@ +function Format-MtAdSiteInventoryValue { + [CmdletBinding()] + [OutputType([string])] + param($Value) + + if ($null -eq $Value -or [string]::IsNullOrWhiteSpace([string]$Value)) { return '—' } + $text = [string]$Value -replace '[\r\n]+', ' ' + return [System.Net.WebUtility]::HtmlEncode($text).Replace('|', '|') +} diff --git a/powershell/internal/checks/ad/ad/Format-MtAdSummaryTable.ps1 b/powershell/internal/checks/ad/ad/Format-MtAdSummaryTable.ps1 new file mode 100644 index 0000000000..4d356afc72 --- /dev/null +++ b/powershell/internal/checks/ad/ad/Format-MtAdSummaryTable.ps1 @@ -0,0 +1,15 @@ +function Format-MtAdSummaryTable { + <# + .SYNOPSIS + Formats ordered scalar assessment metrics as an escaped Markdown table. + #> + [CmdletBinding()] + [OutputType([string])] + param([Parameter(Mandatory)] [System.Collections.IDictionary] $Values) + + $rows = @('| Metric | Value |', '| --- | --- |') + foreach ($name in $Values.Keys) { + $rows += '| {0} | {1} |' -f (Format-MtAdSiteInventoryValue $name), (Format-MtAdSiteInventoryValue $Values[$name]) + } + return $rows -join "`n" +} diff --git a/powershell/internal/checks/ad/ad/Format-MtAdUserSecurityTable.ps1 b/powershell/internal/checks/ad/ad/Format-MtAdUserSecurityTable.ps1 new file mode 100644 index 0000000000..74cb5a930a --- /dev/null +++ b/powershell/internal/checks/ad/ad/Format-MtAdUserSecurityTable.ps1 @@ -0,0 +1,19 @@ +function Format-MtAdUserSecurityTable { + [CmdletBinding()] + param( + [object[]] $Rows, + [string[]] $Columns + ) + + $lines = @() + $lines += '| ' + ($Columns -join ' | ') + ' |' + $lines += '| ' + (($Columns | ForEach-Object { '---' }) -join ' | ') + ' |' + foreach ($row in $Rows) { + $values = foreach ($column in $Columns) { + $value = $row.$column + if ($null -eq $value) { 'Unknown' } else { ([string]$value -replace '\|', '\|' -replace '[\r\n]+', ' ') } + } + $lines += '| ' + ($values -join ' | ') + ' |' + } + return ($lines -join "`n") +} diff --git a/powershell/internal/checks/ad/ad/Get-MtAdCertificateInventory.ps1 b/powershell/internal/checks/ad/ad/Get-MtAdCertificateInventory.ps1 new file mode 100644 index 0000000000..c0b95aa787 --- /dev/null +++ b/powershell/internal/checks/ad/ad/Get-MtAdCertificateInventory.ps1 @@ -0,0 +1,51 @@ +function Get-MtAdCertificateInventory { + [CmdletBinding()] + [OutputType([object[]])] + param( + [Parameter(Mandatory)] $Configuration + ) + + $rows = @() + $roles = @( + @{ Name = 'Enterprise CA'; Property = 'EnterpriseCAs' }, + @{ Name = 'Trusted root'; Property = 'TrustedRootCAs' }, + @{ Name = 'Intermediate'; Property = 'IntermediateCAs' }, + @{ Name = 'NTAuth'; Property = 'NtAuthCertificates' } + ) + foreach ($role in $roles) { + foreach ($entry in @($Configuration.($role.Property))) { + $raw = $entry.cACertificate + # A single DER certificate is a byte array, not an array of certificates. + $values = [System.Collections.Generic.List[object]]::new() + if ($raw -is [byte[]] -or $raw -is [string]) { + $values.Add($raw) + } elseif ($null -ne $raw) { + foreach ($value in $raw) { $values.Add($value) } + } + foreach ($value in $values) { + if ($null -eq $value) { continue } + $bytes = if ($value -is [byte[]]) { $value } elseif ($value -is [string]) { + try { [Convert]::FromBase64String($value) } catch { throw "Invalid certificate encoding for $($role.Name) $($entry.Name)." } + } else { throw "Unsupported certificate value for $($role.Name) $($entry.Name)." } + try { + $cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new([byte[]]$bytes) + $rows += [pscustomobject]@{ + Role = $role.Name + Name = [string]$entry.Name + Subject = $cert.Subject + Issuer = $cert.Issuer + NotBefore = $cert.NotBefore.ToString('yyyy-MM-dd') + NotAfter = $cert.NotAfter.ToString('yyyy-MM-dd') + Thumbprint = $cert.Thumbprint + Status = if ($cert.NotAfter -lt (Get-Date)) { 'Expired (review)' } elseif ($cert.NotBefore -gt (Get-Date)) { 'Not yet valid (review)' } else { 'Within validity dates' } + } + } catch { + throw "Unable to parse public certificate for $($role.Name) $($entry.Name)." + } finally { + if ($null -ne $cert) { $cert.Dispose(); $cert = $null } + } + } + } + } + return $rows +} diff --git a/powershell/internal/checks/ad/ad/Get-MtAdConfigurationInventory.ps1 b/powershell/internal/checks/ad/ad/Get-MtAdConfigurationInventory.ps1 new file mode 100644 index 0000000000..36968f9372 --- /dev/null +++ b/powershell/internal/checks/ad/ad/Get-MtAdConfigurationInventory.ps1 @@ -0,0 +1,17 @@ +function Get-MtAdConfigurationInventory { + [CmdletBinding()] + param( + [Parameter(Mandatory)] $State, + [Parameter(Mandatory)] [string[]] $Required + ) + + if ($null -eq $State -or $null -eq $State.Configuration) { + throw 'Active Directory configuration data is unavailable.' + } + foreach ($name in $Required) { + if ($null -eq $State.Configuration.PSObject.Properties[$name] -or $null -eq $State.Configuration.$name) { + throw "Active Directory configuration $name data is unavailable." + } + } + return $State.Configuration +} diff --git a/powershell/internal/checks/ad/ad/Get-MtAdConfigurationInventorySiteLinkTransport.ps1 b/powershell/internal/checks/ad/ad/Get-MtAdConfigurationInventorySiteLinkTransport.ps1 new file mode 100644 index 0000000000..54b36c353f --- /dev/null +++ b/powershell/internal/checks/ad/ad/Get-MtAdConfigurationInventorySiteLinkTransport.ps1 @@ -0,0 +1,20 @@ +function Get-MtAdConfigurationInventorySiteLinkTransport { + [CmdletBinding()] + param([Parameter(Mandatory)] $Configuration) + + $rows = @() + foreach ($link in @($Configuration.SiteLinks)) { + $match = [regex]::Match([string]$link.DistinguishedName, '(?i)^CN=(?:\\.|[^,])+,CN=(IP|SMTP),CN=Inter-Site Transports,') + $transport = if ($match.Success) { $match.Groups[1].Value } else { '' } + if ($transport -notin @('IP', 'SMTP')) { throw "Unknown site link transport for $($link.Name): $($link.DistinguishedName)." } + $rows += [pscustomobject]@{ + Name = $link.Name + Transport = $transport.ToUpperInvariant() + Cost = $link.cost + Interval = $link.ReplicationFrequencyInMinutes + Sites = (@($link.siteList | Where-Object { $null -ne $_ }) -join ', ') + DistinguishedName = $link.DistinguishedName + } + } + return $rows +} diff --git a/powershell/internal/checks/ad/ad/Get-MtAdDomainControllerRelease.ps1 b/powershell/internal/checks/ad/ad/Get-MtAdDomainControllerRelease.ps1 new file mode 100644 index 0000000000..cfd5dbbacf --- /dev/null +++ b/powershell/internal/checks/ad/ad/Get-MtAdDomainControllerRelease.ps1 @@ -0,0 +1,23 @@ +function Get-MtAdDomainControllerRelease { + [CmdletBinding()] + param([Parameter(Mandatory)] $Controller) + + if ($Controller.CollectionError) { throw "DC metadata incomplete for $($Controller.Name): $($Controller.CollectionError)" } + $name = [string]$Controller.OperatingSystem + $version = [string]$Controller.OperatingSystemVersion + $byName = if ($name -match '(?i)Windows\s+(?:Server\s+)?(2025|2022|2019|2016|2012|2008|2003|2000)\b') { [int]$Matches[1] } else { $null } + $byBuild = if ($version -match '(?:^|\D)(26100|20348|17763|14393|9600|9200|7601|7600|6003|6002|6001|6000|3790|2195)(?:\D|$)') { + switch ($Matches[1]) { + '26100' { 2025 }; '20348' { 2022 }; '17763' { 2019 }; '14393' { 2016 } + { $_ -in '9600', '9200' } { 2012 } + { $_ -in '7601', '7600', '6003', '6002', '6001', '6000' } { 2008 } + '3790' { 2003 }; '2195' { 2000 } + } + } else { $null } + if ($null -ne $byName -and $null -ne $byBuild -and $byName -ne $byBuild) { + throw "Conflicting OS metadata for $($Controller.Name): $name / $version." + } + $release = if ($null -ne $byBuild) { $byBuild } else { $byName } + if ($null -eq $release) { throw "Unclassified DC OS for $($Controller.Name): $name / $version." } + return $release +} diff --git a/powershell/internal/checks/ad/ad/Get-MtAdDomainControllersInScope.ps1 b/powershell/internal/checks/ad/ad/Get-MtAdDomainControllersInScope.ps1 new file mode 100644 index 0000000000..61b3f8a059 --- /dev/null +++ b/powershell/internal/checks/ad/ad/Get-MtAdDomainControllersInScope.ps1 @@ -0,0 +1,22 @@ +function Get-MtAdDomainControllersInScope { + [CmdletBinding()] + [OutputType([object[]])] + param([Parameter(Mandatory)] $State) + + $dn = [string]$State.Domain.DistinguishedName + if (-not $dn -or $null -eq $State.DomainControllers) { throw 'Connected domain DN or DC inventory is unavailable.' } + $scopedControllers = @($State.DomainControllers | Where-Object { + $reference = [string]$_.ServerReference + if ($reference) { + $referenceDomain = ([regex]::Matches($reference, '(?i)(?:^|,)DC=[^,]+') | ForEach-Object { $_.Value.TrimStart(',') }) -join ',' + $referenceDomain -ieq $dn + } else { + $dns = [string]$_.DnsHostName + $root = [string]$State.Domain.DnsRoot + if (-not $dns -or -not $root) { throw "Cannot scope DC $($_.Name) to the connected domain." } + $dot = $dns.IndexOf('.') + $dot -gt 0 -and $dns.Substring($dot + 1) -ieq $root + } + }) + return $scopedControllers +} diff --git a/powershell/internal/checks/ad/ad/Get-MtAdDomainNameFindings.ps1 b/powershell/internal/checks/ad/ad/Get-MtAdDomainNameFindings.ps1 new file mode 100644 index 0000000000..cab9654787 --- /dev/null +++ b/powershell/internal/checks/ad/ad/Get-MtAdDomainNameFindings.ps1 @@ -0,0 +1,28 @@ +function Get-MtAdDomainNameFindings { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Internal helper returns a collection of domain-name findings.')] + [CmdletBinding()] + param([Parameter(Mandatory)] $Forest, [ValidateSet('Dns', 'Netbios')] [string] $Kind) + + $partitions = @($Forest.DomainPartitions) + if ($partitions.Count -eq 0 -or @($Forest.Domains).Count -ne $partitions.Count) { + throw 'Complete forest domain partition metadata is required to validate names.' + } + $findings = [System.Collections.Generic.List[string]]::new() + foreach ($partition in $partitions) { + if (-not $partition.DistinguishedName -or -not $partition.DnsRoot -or -not $partition.NetBIOSName) { + throw 'A forest domain partition has missing DN, DNS root or NetBIOS name.' + } + $name = if ($Kind -eq 'Dns') { [string]$partition.DnsRoot } else { [string]$partition.NetBIOSName } + if ($Kind -eq 'Dns') { + try { $ascii = [System.Globalization.IdnMapping]::new().GetAscii($name) } catch { $ascii = '' } + $valid = $ascii.Length -le 253 -and $ascii.Length -gt 0 + foreach ($label in @($ascii -split '\.')) { + if ($label.Length -gt 63 -or $label -cnotmatch '^[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$') { $valid = $false } + } + } else { + $valid = $name.Length -le 15 -and $name.Length -gt 0 -and $name -notmatch '[\\/:*?"<>|\.]' -and $name -notmatch '^\s|\s$' + } + if (-not $valid) { $findings.Add("$name ($($partition.DistinguishedName))") } + } + return $findings.ToArray() +} diff --git a/powershell/internal/checks/ad/ad/Get-MtAdFsmoPlacement.ps1 b/powershell/internal/checks/ad/ad/Get-MtAdFsmoPlacement.ps1 new file mode 100644 index 0000000000..e5d71d97ef --- /dev/null +++ b/powershell/internal/checks/ad/ad/Get-MtAdFsmoPlacement.ps1 @@ -0,0 +1,60 @@ +function Get-MtAdFsmoPlacement { + [CmdletBinding()] + param([Parameter(Mandatory)] $State) + + $forest = $State.Forest + $domain = $State.Domain + if (-not $forest.RootDomain -or -not $forest.RootDomainDistinguishedName -or + -not $domain.DistinguishedName -or @($State.DomainControllers).Count -eq 0 -or + @($forest.Domains).Count -eq 0) { throw 'Incomplete forest, domain or DC inventory for FSMO placement.' } + + $rootDomain = $domain + if ($domain.DistinguishedName -ine $forest.RootDomainDistinguishedName) { + $rootState = Get-MtADDomainState -ComputerName $forest.RootDomain -Categories @('Domain') + $rootDomain = $rootState.Domain + if (-not $rootDomain -or $rootDomain.DistinguishedName -ine $forest.RootDomainDistinguishedName) { + throw 'Cannot obtain the forest root domain PDC owner from the cached root-domain snapshot.' + } + } + + $owners = [ordered]@{ + Schema = $forest.SchemaOwnerDistinguishedName + DomainNaming = $forest.DomainNamingOwnerDistinguishedName + RootPdc = $rootDomain.PdcOwnerDistinguishedName + Pdc = $domain.PdcOwnerDistinguishedName + Rid = $domain.RidOwnerDistinguishedName + Infrastructure = $domain.InfrastructureOwnerDistinguishedName + } + $issues = [System.Collections.Generic.List[string]]::new() + foreach ($role in $owners.Keys) { + if ([string]::IsNullOrWhiteSpace([string]$owners[$role]) -or $owners[$role] -notmatch '(?i)^CN=NTDS Settings,CN=') { + throw "Missing or invalid NTDS Settings DN for $role; hostname fallback is not safe." + } + $matching = @($State.DomainControllers | Where-Object { $_.DistinguishedName -ieq $owners[$role] }) + if ($matching.Count -ne 1) { throw "Cannot map $role owner to exactly one inventoried DC: $($owners[$role])." } + if ($null -eq $matching[0].IsReadOnly) { throw "Incomplete read-only status for $role owner." } + if ($matching[0].IsReadOnly) { $issues.Add("Read-only DC is recorded as $role owner.") } + } + if ($owners.Schema -ine $owners.RootPdc) { $issues.Add('Schema Master is not on the forest-root PDC.') } + if ($owners.DomainNaming -ine $owners.RootPdc) { $issues.Add('Domain Naming Master is not on the forest-root PDC.') } + if ($owners.Rid -ine $owners.Pdc) { $issues.Add('RID Master is not on the connected domain PDC.') } + + $multiDomain = @($forest.Domains).Count -gt 1 + $domainDcs = @(Get-MtAdDomainControllersInScope -State $State) + if ($domainDcs.Count -eq 0) { throw 'Connected-domain DC scope is unavailable for Infrastructure Master placement.' } + $allGc = @($domainDcs | Where-Object { $null -eq $_.IsGlobalCatalog }).Count -eq 0 -and + @($domainDcs | Where-Object { $_.IsGlobalCatalog -eq $false }).Count -eq 0 + $recycle = @($State.OptionalFeatures | Where-Object { $_.Name -eq 'Recycle Bin Feature' }) + if ($multiDomain -and -not $allGc) { + if ($recycle.Count -ne 1 -or $null -eq $recycle[0].IsEnabled) { throw 'Recycle Bin state unavailable for the Infrastructure Master GC exception.' } + if ($recycle[0].IsEnabled -eq $false) { + if (@($domainDcs | Where-Object { $null -eq $_.IsGlobalCatalog }).Count -gt 0) { + throw 'Unknown connected-domain DC GC status prevents determining whether the all-GC Infrastructure Master exception applies.' + } + $infra = @($State.DomainControllers | Where-Object { $_.DistinguishedName -ieq $owners.Infrastructure })[0] + if ($null -eq $infra.IsGlobalCatalog) { throw 'Infrastructure Master GC state unavailable.' } + if ($infra.IsGlobalCatalog) { $issues.Add('Infrastructure Master is a GC in a multi-domain forest with non-GCs and Recycle Bin disabled.') } + } + } + return [pscustomobject]@{ Owners = $owners; Issues = @($issues); AllGlobalCatalogs = $allGc } +} diff --git a/powershell/internal/checks/ad/ad/Get-MtAdFunctionalLevelAssessment.ps1 b/powershell/internal/checks/ad/ad/Get-MtAdFunctionalLevelAssessment.ps1 new file mode 100644 index 0000000000..73388c502d --- /dev/null +++ b/powershell/internal/checks/ad/ad/Get-MtAdFunctionalLevelAssessment.ps1 @@ -0,0 +1,34 @@ +function Get-MtAdFunctionalLevelAssessment { + [CmdletBinding()] + param( + [Parameter(Mandatory)] $State, + [ValidateSet('Domain', 'Forest')] [string] $Scope + ) + + $controllers = @($State.DomainControllers) + if ($controllers.Count -eq 0 -or $null -eq $State.$Scope) { + throw "$Scope functional level cannot be assessed without the directory object and complete DC inventory." + } + foreach ($dc in $controllers) { + if ($dc.CollectionError) { throw "DC metadata incomplete for $($dc.Name): $($dc.CollectionError)" } + } + $releases = @($controllers | ForEach-Object { Get-MtAdDomainControllerRelease -Controller $_ }) + for ($i = 0; $i -lt $controllers.Count; $i++) { + $supported = $controllers[$i].SupportedLevelValue + $expected = switch ($releases[$i]) { + 2025 { @(10) }; { $_ -in 2016, 2019, 2022 } { @(7) } + 2012 { @(5, 6) }; 2008 { @(3, 4) }; 2003 { @(2) }; 2000 { @(0) } + } + if ($null -eq $supported -or [string]$supported -notmatch '^(0|2|3|4|5|6|7|10)$' -or [int]$supported -notin $expected) { + throw "Missing or inconsistent supported functional level for DC $($controllers[$i].Name)." + } + } + $raw = if ($Scope -eq 'Domain') { $State.Domain.DomainLevelValue } else { $State.Forest.ForestLevelValue } + if ($null -eq $raw -or [string]$raw -notmatch '^(0|[1-9][0-9]*)$') { + throw "$Scope msDS-Behavior-Version is missing or invalid; the display mode is not authoritative." + } + $level = [int]$raw + if ($level -notin @(0, 1, 2, 3, 4, 5, 6, 7, 10)) { throw "Unknown $Scope functional level $level." } + $target = ($controllers | Measure-Object -Property SupportedLevelValue -Minimum).Minimum + return [pscustomobject]@{ Current = $level; Target = $target; Releases = $releases } +} diff --git a/powershell/internal/checks/ad/ad/Get-MtAdOrganizationalUnitOverview.ps1 b/powershell/internal/checks/ad/ad/Get-MtAdOrganizationalUnitOverview.ps1 new file mode 100644 index 0000000000..8bcb2d3819 --- /dev/null +++ b/powershell/internal/checks/ad/ad/Get-MtAdOrganizationalUnitOverview.ps1 @@ -0,0 +1,25 @@ +function Get-MtAdOrganizationalUnitOverview { + [CmdletBinding()] + [OutputType([object[]], [pscustomobject])] + param([Parameter(Mandatory)] $State, [switch] $IncludeChildren) + + $ous = Get-MtAdStateCollection -State $State -Name OrganizationalUnits + foreach ($ou in $ous) { + if ([string]::IsNullOrWhiteSpace($ou.DistinguishedName) -or [string]::IsNullOrWhiteSpace($ou.Name)) { + throw 'An organizational unit has missing Name or DistinguishedName metadata.' + } + } + if (-not $IncludeChildren) { return $ous } + $users = Get-MtAdStateCollection -State $State -Name Users + $groups = Get-MtAdStateCollection -State $State -Name Groups + $computers = Get-MtAdStateCollection -State $State -Name Computers + # An escaped comma is part of an RDN, not a DN component separator. + $children = @{} + foreach ($object in @($ous) + @($users) + @($groups) + @($computers)) { + $dn = [string]$object.DistinguishedName + if ([string]::IsNullOrWhiteSpace($dn)) { throw 'A directory object has missing DistinguishedName metadata.' } + $parent = $dn -replace '^(?:\\.|[^,])+,', '' + if ($parent -ne $dn) { $children[$parent] = $true } + } + return [PSCustomObject]@{ Ous = $ous; WithoutSelectedDirectChildren = @($ous | Where-Object { -not $children.ContainsKey([string]$_.DistinguishedName) }) } +} diff --git a/powershell/internal/checks/ad/ad/Get-MtAdPasswordPolicyUsage.ps1 b/powershell/internal/checks/ad/ad/Get-MtAdPasswordPolicyUsage.ps1 new file mode 100644 index 0000000000..fa0c60a655 --- /dev/null +++ b/powershell/internal/checks/ad/ad/Get-MtAdPasswordPolicyUsage.ps1 @@ -0,0 +1,39 @@ +function Get-MtAdPasswordPolicyUsage { + <# + .SYNOPSIS + Counts visible enabled users by their computed resultant fine-grained policy DN. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param([Parameter(Mandatory)] $Users, [Parameter(Mandatory)] $Policies) + + $counts = @{} + foreach ($policy in @($Policies)) { + if ([string]::IsNullOrWhiteSpace([string]$policy.DistinguishedName)) { + throw 'A fine-grained password policy has no distinguished name.' + } + if ($null -eq $policy.PSObject.Properties['MsDsPsoAppliesTo'] -or $null -eq $policy.PSObject.Properties['MsDsPasswordSettingsPrecedence']) { + throw "Fine-grained password policy '$($policy.DistinguishedName)' lacks direct targets or precedence metadata." + } + $counts[[string]$policy.DistinguishedName] = 0 + } + $enabledCount = 0 + $defaultCount = 0 + foreach ($user in @($Users)) { + if ($null -eq $user.PSObject.Properties['Enabled'] -or $null -eq $user.Enabled) { + throw 'User Enabled field is missing; cannot establish policy usage.' + } + if (-not $user.Enabled) { continue } + $enabledCount++ + if ($null -eq $user.PSObject.Properties['ResultantPasswordPolicyDN']) { + throw "ResultantPasswordPolicyDN is missing for enabled user '$($user.Name)'." + } + $dn = [string]$user.ResultantPasswordPolicyDN + if ([string]::IsNullOrWhiteSpace($dn)) { $defaultCount++; continue } + if (-not $counts.ContainsKey($dn)) { + throw "Resultant password policy '$dn' for user '$($user.Name)' is absent from the collected PSO inventory." + } + $counts[$dn]++ + } + return [pscustomobject]@{ Counts = $counts; EnabledCount = $enabledCount; DefaultCount = $defaultCount } +} diff --git a/powershell/internal/checks/ad/ad/Get-MtAdSiteSubnetOverview.ps1 b/powershell/internal/checks/ad/ad/Get-MtAdSiteSubnetOverview.ps1 new file mode 100644 index 0000000000..f75c188339 --- /dev/null +++ b/powershell/internal/checks/ad/ad/Get-MtAdSiteSubnetOverview.ps1 @@ -0,0 +1,63 @@ +function Get-MtAdSiteSubnetOverview { + [CmdletBinding()] + param( + [Parameter(Mandatory)] $State, + [switch] $Sites, + [switch] $Subnets, + [switch] $Controllers + ) + + $siteEntries = @() + $subnetEntries = @() + $controllerEntries = @() + if ($Sites) { $siteEntries = Get-MtAdStateCollection -State $State -Name ReplicationSites } + if ($Subnets) { $subnetEntries = Get-MtAdStateCollection -State $State -Name Subnets } + if ($Controllers) { $controllerEntries = Get-MtAdStateCollection -State $State -Name DomainControllers } + $siteByDn = @{} + foreach ($site in $siteEntries) { + if ([string]::IsNullOrWhiteSpace($site.DistinguishedName) -or [string]::IsNullOrWhiteSpace($site.Name)) { + throw 'A replication site has missing Name or DistinguishedName metadata.' + } + $siteByDn[[string]$site.DistinguishedName] = $site + } + + $withSubnet = @{} + $orphaned = @($subnetEntries | Where-Object { [string]::IsNullOrWhiteSpace($_.SiteObject) }) + foreach ($subnet in $subnetEntries) { + if ([string]::IsNullOrWhiteSpace($subnet.Name) -or [string]::IsNullOrWhiteSpace($subnet.DistinguishedName)) { + throw 'A subnet has missing Name or DistinguishedName metadata.' + } + if (-not [string]::IsNullOrWhiteSpace($subnet.SiteObject) -and $Sites) { + if ($siteByDn.ContainsKey([string]$subnet.SiteObject)) { + $withSubnet[[string]$subnet.SiteObject] = $true + } else { + $orphaned += $subnet + } + } + } + + $withDc = @{} + if ($Controllers) { + foreach ($dc in $controllerEntries) { + if ([string]::IsNullOrWhiteSpace($dc.Site) -or [string]::IsNullOrWhiteSpace($dc.SiteDistinguishedName)) { + throw 'A domain controller has missing Site or SiteDistinguishedName metadata; site coverage cannot be determined.' + } + if (-not $siteByDn.ContainsKey([string]$dc.SiteDistinguishedName)) { + throw "Domain controller site DN '$($dc.SiteDistinguishedName)' does not match any retrieved replication site." + } + if ($dc.Site -ine $siteByDn[[string]$dc.SiteDistinguishedName].Name) { + throw "Domain controller site name '$($dc.Site)' does not match the site at '$($dc.SiteDistinguishedName)'." + } + $withDc[[string]$dc.SiteDistinguishedName] = $true + } + } + + return [PSCustomObject]@{ + Sites = $siteEntries + Subnets = $subnetEntries + SitesWithSubnets = @($siteEntries | Where-Object { $withSubnet.ContainsKey([string]$_.DistinguishedName) }) + SitesWithoutSubnets = @($siteEntries | Where-Object { -not $withSubnet.ContainsKey([string]$_.DistinguishedName) }) + OrphanedSubnets = @($orphaned) + SitesWithoutDcs = @($siteEntries | Where-Object { -not $withDc.ContainsKey([string]$_.DistinguishedName) }) + } +} diff --git a/powershell/internal/checks/ad/ad/Get-MtAdStateCollection.ps1 b/powershell/internal/checks/ad/ad/Get-MtAdStateCollection.ps1 new file mode 100644 index 0000000000..d512245832 --- /dev/null +++ b/powershell/internal/checks/ad/ad/Get-MtAdStateCollection.ps1 @@ -0,0 +1,30 @@ +function Get-MtAdStateCollection { + <# + .SYNOPSIS + Reads a required collection from a dictionary or object AD snapshot. + #> + [CmdletBinding()] + [OutputType([object[]])] + param( + [Parameter(Mandatory)] [AllowNull()] [object] $State, + [Parameter(Mandatory)] [string] $Name + ) + + $present = $false + $value = $null + if ($null -ne $State) { + if ($State -is [System.Collections.IDictionary]) { + $present = $State.Contains($Name) + if ($present) { $value = $State[$Name] } + } else { + $property = $State.PSObject.Properties[$Name] + $present = $null -ne $property + if ($present) { $value = $property.Value } + } + } + if (-not $present -or $null -eq $value) { + throw "Active Directory $Name data is unavailable." + } + # Preserve an empty collected array as a value, rather than emitting no output. + return ,@($value) +} diff --git a/powershell/internal/checks/ad/ad/Get-MtAdSubnetInventory.ps1 b/powershell/internal/checks/ad/ad/Get-MtAdSubnetInventory.ps1 new file mode 100644 index 0000000000..f6963218a5 --- /dev/null +++ b/powershell/internal/checks/ad/ad/Get-MtAdSubnetInventory.ps1 @@ -0,0 +1,44 @@ +function Get-MtAdSubnetInventory { + [CmdletBinding()] + [OutputType([object[]])] + param([Parameter(Mandatory)] $State) + + $subnets = Get-MtAdStateCollection -State $State -Name Subnets + $entries = foreach ($subnet in $subnets) { + $cidr = [string]$subnet.Name + if ([string]::IsNullOrWhiteSpace($subnet.DistinguishedName)) { + throw "Subnet '$cidr' has missing DistinguishedName metadata." + } + if ($cidr -notmatch '^([^/]+)/([0-9]{1,3})$') { + throw "Invalid subnet CIDR '$cidr'." + } + $addressText = $Matches[1] + $prefix = [int]$Matches[2] + $address = $null + if (-not [System.Net.IPAddress]::TryParse($addressText, [ref]$address) -or + $addressText -match '%' -or + ($address.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork -and $addressText -notmatch '^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$') -or + $address.AddressFamily -notin @([System.Net.Sockets.AddressFamily]::InterNetwork, [System.Net.Sockets.AddressFamily]::InterNetworkV6)) { + throw "Invalid subnet address '$cidr'." + } + $ipv4 = $address.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork + if ($prefix -gt $(if ($ipv4) { 32 } else { 128 })) { + throw "Invalid subnet prefix '$cidr'." + } + $bytes = $address.GetAddressBytes() + $private = $ipv4 -and (($bytes[0] -eq 10) -or ($bytes[0] -eq 172 -and $bytes[1] -ge 16 -and $bytes[1] -le 31) -or ($bytes[0] -eq 192 -and $bytes[1] -eq 168)) + [PSCustomObject]@{ + Subnet = $subnet + Cidr = $cidr + Address = $address + Prefix = $prefix + IsIpv4 = $ipv4 + IsRfc1918 = $private + # A range belongs wholly to RFC1918 only if its prefix covers no addresses outside the block. + IsRfc1918Subset = $private -and (($bytes[0] -eq 10 -and $prefix -ge 8) -or + ($bytes[0] -eq 172 -and $bytes[1] -ge 16 -and $bytes[1] -le 31 -and $prefix -ge 12) -or + ($bytes[0] -eq 192 -and $bytes[1] -eq 168 -and $prefix -ge 16)) + } + } + return @($entries) +} diff --git a/powershell/internal/checks/ad/ad/Get-MtAdUserPathFindings.ps1 b/powershell/internal/checks/ad/ad/Get-MtAdUserPathFindings.ps1 new file mode 100644 index 0000000000..f239cb231f --- /dev/null +++ b/powershell/internal/checks/ad/ad/Get-MtAdUserPathFindings.ps1 @@ -0,0 +1,32 @@ +function Get-MtAdUserPathFindings { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Internal helper returns a collection of path findings.')] + [CmdletBinding()] + param([object[]] $Users, [string[]] $ApprovedPathPrefixes) + + foreach ($user in $Users) { + foreach ($field in @('HomeDirectory', 'ProfilePath', 'ScriptPath')) { + $path = [string]$user.$field + if ([string]::IsNullOrWhiteSpace($path)) { continue } + $normalized = $path.Replace('/', '\').TrimEnd('\') + $reason = $null + if ($normalized -match '(^|\\)\.\.(\\|$)') { $reason = 'Parent traversal (reject)' } + elseif ($field -eq 'ScriptPath' -and $normalized -notmatch '^(\\\\|[A-Za-z]:\\)') { + $reason = 'Relative NETLOGON script: review (not failed)' + } else { + $approved = $false + foreach ($prefix in $ApprovedPathPrefixes) { + if ([string]::IsNullOrWhiteSpace($prefix)) { continue } + $base = $prefix.Replace('/', '\').TrimEnd('\') + if ($base -match '(^|\\)\.\.(\\|$)') { throw "Approved prefix contains traversal: $prefix" } + if ($base -notmatch '^(\\\\[^\\]+\\[^\\]+|[A-Za-z]:\\)') { throw "Approved prefix must be an absolute UNC or drive path: $prefix" } + if ($normalized.Equals($base, [StringComparison]::OrdinalIgnoreCase) -or + $normalized.StartsWith($base + '\', [StringComparison]::OrdinalIgnoreCase)) { $approved = $true; break } + } + if (-not $approved) { $reason = 'Unapproved path' } + } + if ($null -ne $reason) { + [pscustomobject]@{ SamAccountName = $user.SamAccountName; Field = $field; Path = $path; Finding = $reason } + } + } + } +} diff --git a/powershell/internal/checks/ad/ad/Invoke-MtAdConfigurationInventoryReport.ps1 b/powershell/internal/checks/ad/ad/Invoke-MtAdConfigurationInventoryReport.ps1 new file mode 100644 index 0000000000..2d555e553b --- /dev/null +++ b/powershell/internal/checks/ad/ad/Invoke-MtAdConfigurationInventoryReport.ps1 @@ -0,0 +1,89 @@ +function Invoke-MtAdConfigurationInventoryReport { + [CmdletBinding()] + [OutputType([bool])] + param([Parameter(Mandatory)][ValidateSet('EnterpriseCAs', 'Templates', 'Certificates', 'CDP', 'NTAuth', 'SiteLinks')][string] $Kind) + + $required = switch ($Kind) { + 'EnterpriseCAs' { @('EnterpriseCAs') } + 'Templates' { @('EnterpriseCAs', 'CertificateTemplates', 'EnrollmentTemplates') } + 'Certificates' { @('EnterpriseCAs', 'TrustedRootCAs', 'IntermediateCAs') } + 'CDP' { @('CrlDistributionPoints') } + 'NTAuth' { @('NtAuthCertificates') } + 'SiteLinks' { @('SiteLinks') } + } + $config = Get-MtAdConfigurationInventory -State (Get-MtADDomainState -Categories @('Configuration')) -Required $required + $lines = [System.Collections.Generic.List[string]]::new() + switch ($Kind) { + 'EnterpriseCAs' { + $cas = @($config.EnterpriseCAs) + $lines.Add("Enterprise CAs: $($cas.Count). Review the published templates and host names below.") + $lines.Add('| CA | DNS host | Published templates |') + $lines.Add('| --- | --- | --- |') + foreach ($ca in $cas) { + $templates = @($ca.certificateTemplates | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) }) + $lines.Add("| $(ConvertTo-MtAdConfigurationInventoryCell $ca.Name) | $(ConvertTo-MtAdConfigurationInventoryCell $ca.dNSHostName) | $(ConvertTo-MtAdConfigurationInventoryCell ($templates -join ', ')) |") + } + } + 'Templates' { + $templates = @($config.CertificateTemplates) + $published = @($config.EnrollmentTemplates | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) } | Sort-Object -Unique) + $known = @{} + foreach ($template in $templates) { $known[[string]$template.Name] = $true } + $unknown = @($published | Where-Object { -not $known.ContainsKey([string]$_) }) + $lines.Add("Template objects: $($templates.Count); distinct published names: $($published.Count); published names without a template object: $($unknown.Count).") + $lines.Add('| Template CN | Display name | Publishing CAs |') + $lines.Add('| --- | --- | --- |') + foreach ($template in $templates) { + $publishers = @($config.EnterpriseCAs | Where-Object { @($_.certificateTemplates) -contains $template.Name } | ForEach-Object { $_.Name }) + $lines.Add("| $(ConvertTo-MtAdConfigurationInventoryCell $template.Name) | $(ConvertTo-MtAdConfigurationInventoryCell $template.displayName) | $(ConvertTo-MtAdConfigurationInventoryCell ($publishers -join ', ')) |") + } + foreach ($name in $unknown) { + $publishers = @($config.EnterpriseCAs | Where-Object { @($_.certificateTemplates) -contains $name } | ForEach-Object { $_.Name }) + $lines.Add("| $(ConvertTo-MtAdConfigurationInventoryCell $name) (unknown template) | — | $(ConvertTo-MtAdConfigurationInventoryCell ($publishers -join ', ')) |") + } + } + 'Certificates' { + $certs = @(Get-MtAdCertificateInventory -Configuration $config) + $lines.Add("Enterprise CA objects: $(@($config.EnterpriseCAs).Count); trusted root objects: $(@($config.TrustedRootCAs).Count); intermediate objects: $(@($config.IntermediateCAs).Count); public certificate entries: $($certs.Count). A certificate in multiple roles appears once per role.") + $lines.Add('| Role | Object | Subject | Issuer | Valid from | Valid to | Thumbprint | Observation |') + $lines.Add('| --- | --- | --- | --- | --- | --- | --- | --- |') + foreach ($cert in $certs) { + $lines.Add("| $(ConvertTo-MtAdConfigurationInventoryCell $cert.Role) | $(ConvertTo-MtAdConfigurationInventoryCell $cert.Name) | $(ConvertTo-MtAdConfigurationInventoryCell $cert.Subject) | $(ConvertTo-MtAdConfigurationInventoryCell $cert.Issuer) | $($cert.NotBefore) | $($cert.NotAfter) | $($cert.Thumbprint) | $($cert.Status) |") + } + } + 'CDP' { + $entries = @($config.CrlDistributionPoints) + $lines.Add("CRL distribution point objects: $($entries.Count). This is an inventory, not a CRL validity or reachability check.") + $lines.Add('| Name | Distinguished name | CRL published |') + $lines.Add('| --- | --- | --- |') + foreach ($entry in $entries) { + $present = if ($null -ne $entry.certificateRevocationList -and @($entry.certificateRevocationList).Count -gt 0) { 'Yes' } else { 'No' } + $lines.Add("| $(ConvertTo-MtAdConfigurationInventoryCell $entry.Name) | $(ConvertTo-MtAdConfigurationInventoryCell $entry.DistinguishedName) | $present |") + } + } + 'NTAuth' { + $certs = @(Get-MtAdCertificateInventory -Configuration $config) + $ntAuth = @($certs | Where-Object { $_.Role -eq 'NTAuth' }) + $lines.Add("NTAuth objects: $(@($config.NtAuthCertificates).Count); public certificates: $($ntAuth.Count). Expiry observations require review and do not fail this inventory.") + $lines.Add('| Object | Subject | Issuer | Valid from | Valid to | Thumbprint | Observation |') + $lines.Add('| --- | --- | --- | --- | --- | --- | --- |') + foreach ($cert in $ntAuth) { + $lines.Add("| $(ConvertTo-MtAdConfigurationInventoryCell $cert.Name) | $(ConvertTo-MtAdConfigurationInventoryCell $cert.Subject) | $(ConvertTo-MtAdConfigurationInventoryCell $cert.Issuer) | $($cert.NotBefore) | $($cert.NotAfter) | $($cert.Thumbprint) | $($cert.Status) |") + } + } + 'SiteLinks' { + $links = @(Get-MtAdConfigurationInventorySiteLinkTransport -Configuration $config) + $ip = @($links | Where-Object { $_.Transport -eq 'IP' }).Count + $smtp = @($links | Where-Object { $_.Transport -eq 'SMTP' }).Count + $lines.Add("Site links: $($links.Count); IP: $ip; SMTP: $smtp. Transport is identified by the parent DN, not cost or replication interval.") + $lines.Add('| Link | Transport | Cost | Replication interval (minutes) | Sites | Distinguished name |') + $lines.Add('| --- | --- | --- | --- | --- | --- |') + foreach ($link in $links) { + $lines.Add("| $(ConvertTo-MtAdConfigurationInventoryCell $link.Name) | $($link.Transport) | $(ConvertTo-MtAdConfigurationInventoryCell $link.Cost) | $(ConvertTo-MtAdConfigurationInventoryCell $link.Interval) | $(ConvertTo-MtAdConfigurationInventoryCell $link.Sites) | $(ConvertTo-MtAdConfigurationInventoryCell $link.DistinguishedName) |") + } + } + } + if ($lines.Count -eq 0) { throw 'Inventory report could not be generated.' } + Add-MtTestResultDetail -Result ($lines -join "`n") -Investigate + return $true +} diff --git a/powershell/internal/checks/ad/ad/Test-MtAdPasswordPolicyConfiguration.ps1 b/powershell/internal/checks/ad/ad/Test-MtAdPasswordPolicyConfiguration.ps1 new file mode 100644 index 0000000000..acb45546c3 --- /dev/null +++ b/powershell/internal/checks/ad/ad/Test-MtAdPasswordPolicyConfiguration.ps1 @@ -0,0 +1,94 @@ +function Test-MtAdPasswordPolicyConfiguration { + <# + .SYNOPSIS + Evaluates normalized default-domain or fine-grained password policy fields. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] $Policy, + [Alias('Profile')][ValidateSet('CurrentNist', 'LegacyRotation')][string] $ConfigurationProfile = 'CurrentNist', + [ValidateRange(0, 255)][int] $MinimumLength = 0, + [ValidateRange(0, 255)][int] $MinimumHistory = 24, + [ValidateRange(1, 3650)][int] $MaximumAgeDays = 90, + [ValidateRange(1, 1000)][int] $MaximumLockoutThreshold = 10, + [ValidateRange(1, 10080)][int] $MinimumLockoutMinutes = 15, + [ValidateRange(1, 10080)][int] $MinimumResetMinutes = 15, + [string[]] $Fields = @('PwdHistoryLength', 'MaxPwdAge', 'MinPwdAge', 'MinPwdLength', 'ComplexityEnabled', 'ReversibleEncryptionEnabled', 'LockoutDuration', 'LockoutThreshold', 'LockoutObservationWindow') + ) + + if ($null -eq $Policy) { throw 'Password policy data is missing.' } + $expectedLength = if ($MinimumLength -eq 0) { if ($ConfigurationProfile -eq 'CurrentNist') { 15 } else { 14 } } else { $MinimumLength } + $rows = [System.Collections.Generic.List[string]]::new() + $passed = $true + $investigate = $false + foreach ($field in $Fields) { + $property = $Policy.PSObject.Properties[$field] + if ($null -eq $property -or $null -eq $property.Value) { + throw "Password policy field '$field' is missing; cannot evaluate it." + } + $value = $property.Value + $status = 'Pass' + $expected = '' + switch ($field) { + 'PwdHistoryLength' { + $expected = "At least $MinimumHistory (Microsoft baseline; not a NIST requirement)" + if ([int]$value -lt $MinimumHistory) { $status = 'Fail' } + } + 'MinPwdLength' { + $expected = "At least $expectedLength characters" + if ([int]$value -lt $expectedLength) { $status = 'Fail' } + } + 'MaxPwdAge' { + if ($value -isnot [timespan]) { throw "Password policy field '$field' must be a TimeSpan." } + $days = [math]::Abs($value.TotalDays) + $value = "$days days" + if ($ConfigurationProfile -eq 'CurrentNist') { + $expected = '0 days (no forced periodic expiration)' + if ($days -ne 0) { $status = 'Fail' } + } else { + $expected = "1 to $MaximumAgeDays days (organization-selected legacy rotation)" + if ($days -eq 0 -or $days -gt $MaximumAgeDays) { $status = 'Fail' } + } + } + 'MinPwdAge' { + if ($value -isnot [timespan]) { throw "Password policy field '$field' must be a TimeSpan." } + $value = "$([math]::Abs($value.TotalDays)) days" + $expected = 'Observation only; not a password strength or rotation requirement' + $status = 'Observe' + } + 'ComplexityEnabled' { + if ($value -isnot [bool]) { throw "Password policy field '$field' must be a Boolean." } + $expected = if ($ConfigurationProfile -eq 'CurrentNist') { 'Observation only; verify blocklist before changing composition rules' } else { 'Enabled (legacy profile)' } + if ($ConfigurationProfile -eq 'CurrentNist') { $status = 'Observe' } elseif (-not $value) { $status = 'Fail' } + } + 'ReversibleEncryptionEnabled' { + if ($value -isnot [bool]) { throw "Password policy field '$field' must be a Boolean." } + $expected = 'Disabled' + if ($value) { $status = 'Fail' } + } + 'LockoutThreshold' { + $expected = "1 to $MaximumLockoutThreshold attempts (Microsoft baseline, not NIST 100-attempt ceiling)" + if ([int]$value -lt 1 -or [int]$value -gt $MaximumLockoutThreshold) { $status = 'Fail' } + } + 'LockoutDuration' { + if ($value -isnot [timespan]) { throw "Password policy field '$field' must be a TimeSpan." } + $minutes = [math]::Abs($value.TotalMinutes) + $value = if ($minutes -eq 0) { '0 (until administrator unlocks)' } else { "$minutes minutes" } + $expected = "0 (manual unlock) or at least $MinimumLockoutMinutes minutes" + if ($minutes -ne 0 -and $minutes -lt $MinimumLockoutMinutes) { $status = 'Fail' } + } + 'LockoutObservationWindow' { + if ($value -isnot [timespan]) { throw "Password policy field '$field' must be a TimeSpan." } + $minutes = [math]::Abs($value.TotalMinutes) + $value = "$minutes minutes" + $expected = "At least $MinimumResetMinutes minutes" + if ($minutes -lt $MinimumResetMinutes) { $status = 'Fail' } + } + default { throw "Unsupported password policy field '$field'." } + } + if ($status -eq 'Fail') { $passed = $false } + $rows.Add("| $field | $value | $expected | $status |") | Out-Null + } + return [pscustomobject]@{ Passed = $passed; Investigate = $investigate; Rows = @($rows); Profile = $ConfigurationProfile } +} diff --git a/powershell/internal/checks/ad/ad/Test-MtAdUserOrdinaryIdentity.ps1 b/powershell/internal/checks/ad/ad/Test-MtAdUserOrdinaryIdentity.ps1 new file mode 100644 index 0000000000..546a20c47f --- /dev/null +++ b/powershell/internal/checks/ad/ad/Test-MtAdUserOrdinaryIdentity.ps1 @@ -0,0 +1,13 @@ +function Test-MtAdUserOrdinaryIdentity { + [CmdletBinding()] + [OutputType([bool])] + param([object] $User) + + if ($User.IsCriticalSystemObject -eq $true -or $null -ne $User.SecondaryKrbtgtNumber -or + @($User.KrbtgtLinkBacklinks | Where-Object { $null -ne $_ }).Count -gt 0 -or + $User.SamAccountName -like 'krbtgt_AzureAD*') { return $false } + $sid = if ($User.Sid -is [string]) { $User.Sid } else { [string]$User.Sid.Value } + if ([string]::IsNullOrWhiteSpace($sid)) { throw 'User SID is unavailable; protected-account exclusions cannot be established.' } + if ($sid -match '-(500|501|502|503)$') { return $false } + return $true +} diff --git a/powershell/internal/services/ad/Test-MtAdDomainControllerAccount.ps1 b/powershell/internal/services/ad/Test-MtAdDomainControllerAccount.ps1 new file mode 100644 index 0000000000..9648e13ac3 --- /dev/null +++ b/powershell/internal/services/ad/Test-MtAdDomainControllerAccount.ps1 @@ -0,0 +1,38 @@ +function Test-MtAdDomainControllerAccount { + <# + .SYNOPSIS + Identifies a DC account from the collected directory server inventory. + + .DESCRIPTION + Uses serverReference distinguished names, with DNS fallback only for inventory + entries lacking serverReference. A claimed DC primary group is not DC evidence. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [object] $Account, + + [Parameter(Mandatory)] + [object[]] $DomainControllers + ) + + if ([string]::IsNullOrWhiteSpace([string]$Account.DistinguishedName)) { + throw 'Account distinguished name is unavailable; DC identity cannot be verified.' + } + if (@($Account.ObjectClass | Where-Object { $_ -in 'msDS-ManagedServiceAccount', 'msDS-GroupManagedServiceAccount', 'msDS-DelegatedManagedServiceAccount' }).Count -gt 0) { + return $false + } + foreach ($dc in $DomainControllers) { + if (-not $dc.ServerReference -and -not $dc.DnsHostName) { + throw 'DC inventory lacks serverReference and DNS identity; DC exclusions cannot be verified.' + } + if ($dc.ServerReference) { + if ([string]$dc.ServerReference -eq [string]$Account.DistinguishedName) { return $true } + } + elseif ($Account.DnsHostName -and ([string]$dc.DnsHostName).TrimEnd('.') -eq ([string]$Account.DnsHostName).TrimEnd('.')) { + return $true + } + } + return $false +} diff --git a/powershell/internal/services/ad/protocol/ConvertFrom-MtLdapValue.ps1 b/powershell/internal/services/ad/protocol/ConvertFrom-MtLdapValue.ps1 index 92192b89c0..065a94b11f 100644 --- a/powershell/internal/services/ad/protocol/ConvertFrom-MtLdapValue.ps1 +++ b/powershell/internal/services/ad/protocol/ConvertFrom-MtLdapValue.ps1 @@ -58,6 +58,8 @@ 'minpwdage', 'lockoutduration', 'msds-lockoutduration', + 'lockoutobservationwindow', + 'msds-lockoutobservationwindow', 'msds-maximumpasswordage', 'msds-minimumpasswordage' ) @@ -107,7 +109,7 @@ } } - if ($NormalizedAttributeName -in @('iscriticalsystemobject', 'enabledconnection', 'msds-passwordcomplexityenabled', 'msds-isrodc')) { + if ($NormalizedAttributeName -in @('iscriticalsystemobject', 'enabledconnection', 'msds-passwordcomplexityenabled', 'msds-passwordreversibleencryptionenabled', 'msds-isrodc')) { $convertedBoolean = $false if ([bool]::TryParse($InputValue, [ref]$convertedBoolean)) { return $convertedBoolean @@ -162,7 +164,7 @@ if ($Value -is [byte[]]) { switch ($normalizedAttributeName) { - { $_ -in @('objectsid', 'sidhistory', 'securityidentifier') } { + { $_ -in @('objectsid', 'sidhistory', 'securityidentifier', 'ms-ds-creatorsid') } { try { return New-Object System.Security.Principal.SecurityIdentifier -ArgumentList $Value, 0 } @@ -206,7 +208,7 @@ } if ($Value -is [System.Security.Principal.SecurityIdentifier]) { - if ($normalizedAttributeName -in @('objectsid', 'sidhistory', 'securityidentifier')) { + if ($normalizedAttributeName -in @('objectsid', 'sidhistory', 'securityidentifier', 'ms-ds-creatorsid')) { return $Value } @@ -225,7 +227,7 @@ return [int]$Value } - if ($normalizedAttributeName -in @('maxpwdage', 'minpwdage', 'lockoutduration', 'msds-lockoutduration', 'msds-maximumpasswordage', 'msds-minimumpasswordage')) { + if ($normalizedAttributeName -in @('maxpwdage', 'minpwdage', 'lockoutduration', 'lockoutobservationwindow', 'msds-lockoutduration', 'msds-lockoutobservationwindow', 'msds-maximumpasswordage', 'msds-minimumpasswordage')) { $intervalValue = [long]$Value if ($intervalValue -eq [long]::MinValue) { return [timespan]::Zero diff --git a/powershell/internal/services/ad/queries/Get-MtLdapComputer.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapComputer.ps1 index 8b6b46a2e3..8a1a8dccf6 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapComputer.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapComputer.ps1 @@ -9,8 +9,9 @@ ) if ([string]::IsNullOrWhiteSpace($SearchBase)) { $SearchBase = (Get-MtLdapRootDse -Connection $Connection).DefaultNamingContext } - $attributes = @('distinguishedName', 'name', 'sAMAccountName', 'userAccountControl', 'operatingSystem', 'operatingSystemVersion', 'dNSHostName', 'whenCreated', 'whenChanged', 'lastLogonTimestamp', 'pwdLastSet', 'servicePrincipalName', 'primaryGroupID', 'objectSid', 'isCriticalSystemObject', 'managedBy', 'sIDHistory') - $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter '(objectClass=computer)' -Attributes $attributes) + $attributes = @('distinguishedName', 'name', 'sAMAccountName', 'userAccountControl', 'operatingSystem', 'operatingSystemVersion', 'dNSHostName', 'whenCreated', 'whenChanged', 'lastLogonTimestamp', 'pwdLastSet', 'servicePrincipalName', 'primaryGroupID', 'objectSid', 'isCriticalSystemObject', 'managedBy', 'sIDHistory', 'msDS-AllowedToDelegateTo', 'msDS-AllowedToActOnBehalfOfOtherIdentity', 'mS-DS-CreatorSID') + # Managed service accounts derive from computer but are not workstation/server inventory. + $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter '(&(objectClass=computer)(!(|(objectClass=msDS-ManagedServiceAccount)(objectClass=msDS-GroupManagedServiceAccount)(objectClass=msDS-DelegatedManagedServiceAccount))))' -Attributes $attributes) return @($entries | ForEach-Object { $uac = if ($null -ne $_.userAccountControl) { ConvertFrom-MtLdapUserAccountControl -UserAccountControl ([int]$_.userAccountControl) } else { $null } [PSCustomObject]@{ @@ -20,6 +21,10 @@ PasswordLastSet = $_.pwdLastSet; PasswordExpired = if ($null -ne $uac) { $uac.PasswordExpired } else { $null }; PasswordNeverExpires = if ($null -ne $uac) { $uac.DontExpirePassword } else { $null } PasswordNotRequired = if ($null -ne $uac) { $uac.PasswordNotRequired } else { $null }; TrustedForDelegation = if ($null -ne $uac) { $uac.TrustedForDelegation } else { $null } TrustedToAuthForDelegation = if ($null -ne $uac) { $uac.TrustedToAuthForDelegation } else { $null }; ServicePrincipalName = [string[]]@($_.servicePrincipalName | Where-Object { $null -ne $_ }) + AllowedToDelegateTo = [string[]]@($_.'msDS-AllowedToDelegateTo' | Where-Object { $null -ne $_ }) + HasResourceBasedConstrainedDelegation = $null -ne $_.'msDS-AllowedToActOnBehalfOfOtherIdentity' + CreatorSid = $_.'mS-DS-CreatorSID' + 'mS-DS-CreatorSID' = $_.'mS-DS-CreatorSID' PrimaryGroupId = $_.primaryGroupID; Sid = $_.objectSid; UserAccountControl = [int]$_.userAccountControl IsCriticalSystemObject = if ($null -ne $_.isCriticalSystemObject) { [bool]$_.isCriticalSystemObject } else { $null }; ManagedBy = [string]$_.managedBy; SidHistory = @($_.sIDHistory | Where-Object { $null -ne $_ }) } diff --git a/powershell/internal/services/ad/queries/Get-MtLdapConfigurationContainer.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapConfigurationContainer.ps1 index ef341ea54b..800aa0a2db 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapConfigurationContainer.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapConfigurationContainer.ps1 @@ -55,10 +55,21 @@ $siteLinks = @($rawSiteLinks | ForEach-Object { $replInterval = if ($null -ne $_.replInterval) { [int]$_.replInterval } else { $null } $_ | Add-Member -NotePropertyName ReplicationFrequencyInMinutes -NotePropertyValue $replInterval -Force + $transport = if ([string]$_.DistinguishedName -match '(?i),CN=(IP|SMTP),CN=Inter-Site Transports,') { $matches[1].ToUpperInvariant() } else { $null } + $_ | Add-Member -NotePropertyName TransportName -NotePropertyValue $transport -Force $_ }) - $dhcp = Invoke-ConfigurationSearchSafe -RelativeSearchBase 'CN=NetServices,CN=Services' -Scope OneLevel -Filter '(|(objectClass=dhcpClass)(objectClass=dhcpServer)(objectClass=serviceConnectionPoint))' -Attributes ($commonAttributes + @('serviceBindingInformation', 'keywords')) + $dhcpObjects = Invoke-ConfigurationSearchSafe -RelativeSearchBase 'CN=NetServices,CN=Services' -Scope OneLevel -Filter '(objectClass=dhcpClass)' -Attributes ($commonAttributes + @('dhcpServers')) + # MS-DHCPE: authorization entries are dhcpServers values, not one server per object. + $dhcp = @(foreach ($registration in @($dhcpObjects | ForEach-Object { $_.dhcpServers } | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) } | Sort-Object -Unique)) { + $match = [regex]::Match([string]$registration, '^i(?[^$]+)\$rcn=(?[^$]*)\$f(?[^$]*)\$s(?[^$]*)\$$', [System.Text.RegularExpressions.RegexOptions]::IgnoreCase) + [pscustomobject]@{ + DnsName = if ($match.Success) { $match.Groups['server'].Value } else { 'Unknown (unrecognized registration format)' } + IPAddress = if ($match.Success) { $match.Groups['ip'].Value } else { $null } + RegistrationParsed = $match.Success + } + }) $authN = Invoke-ConfigurationSearchSafe -RelativeSearchBase 'CN=AuthN Policy Configuration,CN=Services' -Scope Subtree -Filter '(objectClass=*)' -Attributes ($commonAttributes + @('msDS-ServiceAllowedToAuthenticateFrom', 'msDS-ServiceAllowedToAuthenticateTo')) @@ -77,13 +88,13 @@ $policies = Invoke-ConfigurationSearchSafe -RelativeSearchBase 'CN=Query Policies,CN=Directory Service,CN=Windows NT,CN=Services' -Scope OneLevel -Filter '(objectClass=queryPolicy)' -Attributes ($commonAttributes + @('lDAPAdminLimits')) - $directoryService = Invoke-ConfigurationSearchSafe -RelativeSearchBase 'CN=Directory Service,CN=Windows NT,CN=Services' -Scope Base -Filter '(objectClass=nTDSService)' -Attributes @('tombstoneLifetime', 'dSHeuristics', 'sPNMappings') | Select-Object -First 1 + $directoryService = Invoke-ConfigurationSearchSafe -RelativeSearchBase 'CN=Directory Service,CN=Windows NT,CN=Services' -Scope Base -Filter '(objectClass=*)' -Attributes @('distinguishedName', 'tombstoneLifetime', 'dSHeuristics', 'sPNMappings') | Select-Object -First 1 # Use safe search so a NoSuchObject error (common when KDS has never been used) returns @() # rather than throwing and nulling the entire Configuration category $kds = Invoke-ConfigurationSearchSafe -RelativeSearchBase 'CN=Master Root Keys,CN=Group Key Distribution Service,CN=Services' -Scope OneLevel -Filter '(objectClass=msKds-ProvRootKey)' -Attributes ($commonAttributes + @('msKds-CreateTime', 'msKds-DomainID')) - $activation = Invoke-ConfigurationSearchSafe -RelativeSearchBase 'CN=Activation Objects,CN=Microsoft SPP,CN=Services' -Scope OneLevel -Filter '(|(objectClass=msImaging-PSP)(objectClass=serviceConnectionPoint))' -Attributes ($commonAttributes + @('keywords', 'serviceBindingInformation')) + $activation = Invoke-ConfigurationSearchSafe -RelativeSearchBase 'CN=Activation Objects,CN=Microsoft SPP,CN=Services' -Scope OneLevel -Filter '(objectClass=msSPP-ActivationObject)' -Attributes $commonAttributes $enrollmentTemplates = [string[]]@($enterprise | ForEach-Object { @($_.certificateTemplates) } | Sort-Object -Unique) @@ -92,8 +103,9 @@ TrustedRootCAs = @($trustedRoots); IntermediateCAs = @($intermediate); EnterpriseCAs = @($enterprise); CertificateTemplates = @($templates) EnrollmentTemplates = $enrollmentTemplates; CrlDistributionPoints = @($cdp); NtAuthCertificates = @($ntAuth); LdapQueryPolicies = @($policies) TombstoneLifetime = if ($null -ne $directoryService) { $directoryService.tombstoneLifetime } else { $null } + DirectoryServiceRetrieved = $null -ne $directoryService DsHeuristics = if ($null -ne $directoryService) { $directoryService.dSHeuristics } else { $null } - SpnMappings = if ($null -ne $directoryService) { @($directoryService.sPNMappings | Where-Object { $null -ne $_ }) } else { @() } + SpnMappings = if ($null -ne $directoryService) { @($directoryService.sPNMappings | Where-Object { $null -ne $_ }) } else { $null } KdsRootKeys = @($kds); ActivationObjects = @($activation) } } diff --git a/powershell/internal/services/ad/queries/Get-MtLdapDomain.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapDomain.ps1 index 16d6130788..0d394ac3db 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapDomain.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapDomain.ps1 @@ -36,7 +36,7 @@ $SearchBase = $rootDse.DefaultNamingContext } - $attributes = @('distinguishedName', 'name', 'objectSid', 'lockoutDuration', 'lockoutThreshold', 'maxPwdAge', 'minPwdAge', 'minPwdLength', 'ms-DS-MachineAccountQuota', 'pwdProperties', 'pwdHistoryLength', 'rIDAvailablePool', 'objectVersion', 'whenCreated', 'whenChanged', 'msDS-Behavior-Version', 'fSMORoleOwner', 'msDS-AllowedDNSSuffixes') + $attributes = @('distinguishedName', 'name', 'objectSid', 'lockoutDuration', 'lockoutThreshold', 'lockOutObservationWindow', 'maxPwdAge', 'minPwdAge', 'minPwdLength', 'ms-DS-MachineAccountQuota', 'pwdProperties', 'pwdHistoryLength', 'objectVersion', 'whenCreated', 'whenChanged', 'msDS-Behavior-Version', 'fSMORoleOwner', 'msDS-AllowedDNSSuffixes', 'msDS-LogonTimeSyncInterval') $entry = Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Base -Filter '(objectClass=domainDNS)' -Attributes $attributes -PageSize 0 | Select-Object -First 1 if ($null -eq $entry) { return $null @@ -46,9 +46,9 @@ $crossRef = $crossRefs | Where-Object { $_.nCName -eq $SearchBase } | Select-Object -First 1 $infrastructure = Invoke-MtLdapSearch -Connection $Connection -SearchBase "CN=Infrastructure,$SearchBase" -Scope Base -Filter '(objectClass=infrastructureUpdate)' -Attributes @('fSMORoleOwner') -PageSize 0 | Select-Object -First 1 - $ridManager = Invoke-MtLdapSearch -Connection $Connection -SearchBase ('CN=RID Manager$,CN=System,' + $SearchBase) -Scope Base -Filter '(objectClass=rIDManager)' -Attributes @('fSMORoleOwner') -PageSize 0 | Select-Object -First 1 + $ridManager = Invoke-MtLdapSearch -Connection $Connection -SearchBase ('CN=RID Manager$,CN=System,' + $SearchBase) -Scope Base -Filter '(objectClass=rIDManager)' -Attributes @('fSMORoleOwner', 'rIDAvailablePool') -PageSize 0 | Select-Object -First 1 $domainModeNames = @('Windows2000Domain', 'Windows2003InterimDomain', 'Windows2003Domain', 'Windows2008Domain', 'Windows2008R2Domain', 'Windows2012Domain', 'Windows2012R2Domain', 'Windows2016Domain') - $domainModeValue = [int]$entry.'msDS-Behavior-Version' + $domainModeValue = if ($null -ne $entry.'msDS-Behavior-Version') { [int]$entry.'msDS-Behavior-Version' } else { $null } return [PSCustomObject]@{ DistinguishedName = [string]$entry.DistinguishedName @@ -57,19 +57,29 @@ DomainSID = $entry.objectSid LockoutDuration = $entry.lockoutDuration LockoutThreshold = $entry.lockoutThreshold + LockoutObservationWindow = $entry.lockOutObservationWindow MaxPwdAge = $entry.maxPwdAge MinPwdAge = $entry.minPwdAge MinPwdLength = $entry.minPwdLength MsDsMachineAccountQuota = $entry.'ms-DS-MachineAccountQuota' PwdProperties = $entry.pwdProperties + ComplexityEnabled = if ($null -ne $entry.pwdProperties) { ([int]$entry.pwdProperties -band 1) -ne 0 } else { $null } + ReversibleEncryptionEnabled = if ($null -ne $entry.pwdProperties) { ([int]$entry.pwdProperties -band 16) -ne 0 } else { $null } + PasswordExpirationDisabled = if ($null -ne $entry.maxPwdAge) { $entry.maxPwdAge -eq [timespan]::Zero } else { $null } + LockoutRequiresAdminUnlock = if ($null -ne $entry.lockoutDuration) { $entry.lockoutDuration -eq [timespan]::Zero } else { $null } PwdHistoryLength = $entry.pwdHistoryLength - RIDAvailablePool = $entry.rIDAvailablePool + RIDAvailablePool = $ridManager.rIDAvailablePool ObjectVersion = $entry.objectVersion WhenCreated = $entry.whenCreated WhenChanged = $entry.whenChanged DnsRoot = ConvertFrom-DomainDistinguishedName -DistinguishedName $SearchBase Forest = ConvertFrom-DomainDistinguishedName -DistinguishedName $rootDse.RootDomainNamingContext - DomainMode = if ($domainModeValue -ge 0 -and $domainModeValue -lt $domainModeNames.Count) { $domainModeNames[$domainModeValue] } else { $domainModeValue } + DomainMode = if ($domainModeValue -eq 10) { 'Windows2025Domain' } elseif ($null -ne $domainModeValue -and $domainModeValue -ge 0 -and $domainModeValue -lt $domainModeNames.Count) { $domainModeNames[$domainModeValue] } else { $domainModeValue } + DomainLevelValue = $domainModeValue + PdcOwnerDistinguishedName = [string]$entry.fSMORoleOwner + RidOwnerDistinguishedName = [string]$ridManager.fSMORoleOwner + InfrastructureOwnerDistinguishedName = [string]$infrastructure.fSMORoleOwner + LogonTimeSyncIntervalDays = $entry.'msDS-LogonTimeSyncInterval' InfrastructureMaster = Resolve-FsmoOwner -OwnerDistinguishedName ([string]$infrastructure.fSMORoleOwner) PDCEmulator = Resolve-FsmoOwner -OwnerDistinguishedName ([string]$entry.fSMORoleOwner) RIDMaster = Resolve-FsmoOwner -OwnerDistinguishedName ([string]$ridManager.fSMORoleOwner) diff --git a/powershell/internal/services/ad/queries/Get-MtLdapDomainController.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapDomainController.ps1 index 97f417105c..f83c7c0479 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapDomainController.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapDomainController.ps1 @@ -10,30 +10,51 @@ ) $searchBase = "CN=Sites,$ConfigurationNamingContext" - $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $searchBase -Scope Subtree -Filter '(objectClass=nTDSDSA)' -Attributes @('distinguishedName', 'name', 'options', 'invocationId')) + $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $searchBase -Scope Subtree -Filter '(objectClass=nTDSDSA)' -Attributes @('distinguishedName', 'name', 'objectClass', 'options', 'invocationId', 'msDS-Behavior-Version', 'msDS-isRODC')) + $siteNames = @{} return @($entries | ForEach-Object { - $serverDn = $_.DistinguishedName -replace '^[^,]+,', '' + $serverDn = $_.DistinguishedName -replace '^(?:\\.|[^,])+,', '' # Extract site name from DN: CN=,CN=Servers,CN=,CN=Sites,... $site = $null - $parts = $serverDn -split ',CN=Sites,', 2 - if ($parts.Count -eq 2) { - $siteParts = $parts[0] -split ',CN=Servers,', 2 - if ($siteParts.Count -eq 2) { - $site = $siteParts[1] -replace '^CN=', '' + $siteDn = $null + $collectionError = $null + if ($serverDn -match '(?i),CN=Servers,(?.+)$') { + $siteDn = $matches['siteDn'] + if (-not $siteNames.ContainsKey($siteDn)) { + try { + $siteEntry = Invoke-MtLdapSearch -Connection $Connection -SearchBase $siteDn -Scope Base -Filter '(objectClass=site)' -Attributes @('name') -PageSize 0 | Select-Object -First 1 + $siteNames[$siteDn] = if ($null -ne $siteEntry) { [string]$siteEntry.name } else { $null } + } + catch { $siteNames[$siteDn] = $null } } + $site = $siteNames[$siteDn] } - $server = Invoke-MtLdapSearch -Connection $Connection -SearchBase $serverDn -Scope Base -Filter '(objectClass=server)' -Attributes @('name', 'dNSHostName', 'serverReference') -PageSize 0 | Select-Object -First 1 + $server = $null + try { + $server = Invoke-MtLdapSearch -Connection $Connection -SearchBase $serverDn -Scope Base -Filter '(objectClass=server)' -Attributes @('name', 'dNSHostName', 'serverReference') -PageSize 0 | Select-Object -First 1 + } + catch { $collectionError = 'DC server metadata could not be read from the selected directory target.' } + if ($null -eq $server) { $collectionError = 'DC server metadata was not returned by the selected directory target.' } # Query computer object for operatingSystem and RODC status $operatingSystem = $null - $isReadOnly = $false + $operatingSystemVersion = $null + $isReadOnly = if ($null -ne $_.'msDS-isRODC') { [bool]$_.'msDS-isRODC' } elseif (@($_.objectClass) -contains 'nTDSDSARO') { $true } elseif (@($_.objectClass) -contains 'nTDSDSA') { $false } else { $null } if (-not [string]::IsNullOrWhiteSpace($server.serverReference)) { - $computer = Invoke-MtLdapSearch -Connection $Connection -SearchBase $server.serverReference -Scope Base -Filter '(objectClass=computer)' -Attributes @('operatingSystem', 'msDS-IsRODC') -PageSize 0 | Select-Object -First 1 - $operatingSystem = $computer.operatingSystem - $isReadOnly = if ($null -ne $computer.'msDS-IsRODC') { [bool]$computer.'msDS-IsRODC' } else { $false } + try { + $computer = Invoke-MtLdapSearch -Connection $Connection -SearchBase $server.serverReference -Scope Base -Filter '(objectClass=computer)' -Attributes @('operatingSystem', 'operatingSystemVersion', 'msDS-IsRODC') -PageSize 0 | Select-Object -First 1 + if ($null -eq $computer) { $collectionError = 'DC computer metadata was not returned; cross-domain visibility may be incomplete.' } + else { + $operatingSystem = $computer.operatingSystem + $operatingSystemVersion = $computer.operatingSystemVersion + if ($null -eq $isReadOnly -and $null -ne $computer.'msDS-IsRODC') { $isReadOnly = [bool]$computer.'msDS-IsRODC' } + } + } + catch { $collectionError = 'DC computer metadata could not be read; cross-domain visibility may be incomplete.' } } + elseif ($null -eq $collectionError) { $collectionError = 'DC serverReference is unavailable; computer metadata cannot be resolved.' } $optionsValue = if ($null -ne $_.options) { [int]$_.options } else { 0 } @@ -45,11 +66,16 @@ Options = $_.options InvocationId = $_.invocationId Site = $site + SiteDistinguishedName = $siteDn OperatingSystem = [string]$operatingSystem + OperatingSystemVersion = [string]$operatingSystemVersion + SupportedLevelValue = if ($null -ne $_.'msDS-Behavior-Version') { [int]$_.'msDS-Behavior-Version' } else { $null } IsGlobalCatalog = [bool]($optionsValue -band 0x1) IsReadOnly = $isReadOnly - LdapPort = 389 - SslPort = 636 + LdapPort = $null + SslPort = $null + PortEvidence = 'Not measured' + CollectionError = $collectionError } }) } diff --git a/powershell/internal/services/ad/queries/Get-MtLdapFineGrainedPasswordPolicy.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapFineGrainedPasswordPolicy.ps1 index 59fd5fa584..f1adf24e36 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapFineGrainedPasswordPolicy.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapFineGrainedPasswordPolicy.ps1 @@ -9,12 +9,16 @@ ) if ([string]::IsNullOrWhiteSpace($SearchBase)) { $SearchBase = (Get-MtLdapRootDse -Connection $Connection).DefaultNamingContext } - $attributes = @('distinguishedName', 'name', 'msDS-PasswordSettingsPrecedence', 'msDS-LockoutDuration', 'msDS-LockoutThreshold', 'msDS-MaximumPasswordAge', 'msDS-MinimumPasswordAge', 'msDS-MinimumPasswordLength', 'msDS-PasswordComplexityEnabled', 'msDS-PasswordHistoryLength', 'msDS-PSOAppliesTo') + $attributes = @('distinguishedName', 'name', 'msDS-PasswordSettingsPrecedence', 'msDS-LockoutDuration', 'msDS-LockoutThreshold', 'msDS-LockoutObservationWindow', 'msDS-MaximumPasswordAge', 'msDS-MinimumPasswordAge', 'msDS-MinimumPasswordLength', 'msDS-PasswordComplexityEnabled', 'msDS-PasswordReversibleEncryptionEnabled', 'msDS-PasswordHistoryLength', 'msDS-PSOAppliesTo') $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter '(objectClass=msDS-PasswordSettings)' -Attributes $attributes) return @($entries | ForEach-Object { [PSCustomObject]@{ DistinguishedName = [string]$_.DistinguishedName; Name = [string]$_.name; MsDsPasswordSettingsPrecedence = $_.'msDS-PasswordSettingsPrecedence' LockoutDuration = $_.'msDS-LockoutDuration'; LockoutThreshold = $_.'msDS-LockoutThreshold'; MaxPwdAge = $_.'msDS-MaximumPasswordAge' MinPwdAge = $_.'msDS-MinimumPasswordAge'; MinPwdLength = $_.'msDS-MinimumPasswordLength'; PwdProperties = $_.'msDS-PasswordComplexityEnabled' + ComplexityEnabled = $_.'msDS-PasswordComplexityEnabled'; ReversibleEncryptionEnabled = $_.'msDS-PasswordReversibleEncryptionEnabled' + LockoutObservationWindow = $_.'msDS-LockoutObservationWindow' + PasswordExpirationDisabled = if ($null -ne $_.'msDS-MaximumPasswordAge') { $_.'msDS-MaximumPasswordAge' -eq [timespan]::Zero } else { $null } + LockoutRequiresAdminUnlock = if ($null -ne $_.'msDS-LockoutDuration') { $_.'msDS-LockoutDuration' -eq [timespan]::Zero } else { $null } PwdHistoryLength = $_.'msDS-PasswordHistoryLength'; MsDsPsoAppliesTo = @($_.'msDS-PSOAppliesTo' | Where-Object { $null -ne $_ }) } }) } diff --git a/powershell/internal/services/ad/queries/Get-MtLdapForest.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapForest.ps1 index 38fcadd55c..7a218b2a72 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapForest.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapForest.ps1 @@ -38,7 +38,7 @@ }) $rootPartition = $domainPartitions | Where-Object { $_.nCName -eq $rootDse.RootDomainNamingContext } | Select-Object -First 1 $forestModeNames = @('Windows2000Forest', 'Windows2003InterimForest', 'Windows2003Forest', 'Windows2008Forest', 'Windows2008R2Forest', 'Windows2012Forest', 'Windows2012R2Forest', 'Windows2016Forest') - $forestModeValue = [int]$rootDse.ForestFunctionality + $forestModeValue = if ($null -ne $rootDse.ForestFunctionality) { [int]$rootDse.ForestFunctionality } else { $null } $fallbackRootDomain = (([regex]::Matches($rootDse.RootDomainNamingContext, '(?i)(?:^|,)DC=([^,]+)') | ForEach-Object { $_.Groups[1].Value }) -join '.') $crossForestReferences = @($partitions | Where-Object { @@ -59,9 +59,14 @@ return [PSCustomObject]@{ RootDomain = if ($null -ne $rootPartition) { [string]$rootPartition.dnsRoot } else { $fallbackRootDomain } Domains = [string[]]@($domainPartitions | ForEach-Object { $_.dnsRoot } | Sort-Object -Unique) - ForestMode = if ($forestModeValue -ge 0 -and $forestModeValue -lt $forestModeNames.Count) { $forestModeNames[$forestModeValue] } else { $forestModeValue } + ForestMode = if ($forestModeValue -eq 10) { 'Windows2025Forest' } elseif ($null -ne $forestModeValue -and $forestModeValue -ge 0 -and $forestModeValue -lt $forestModeNames.Count) { $forestModeNames[$forestModeValue] } else { $forestModeValue } + ForestLevelValue = $forestModeValue + RootDomainDistinguishedName = [string]$rootDse.RootDomainNamingContext + DomainPartitions = @($domainPartitions | ForEach-Object { [pscustomobject]@{ DistinguishedName = [string]$_.nCName; DnsRoot = [string]$_.dnsRoot; NetBIOSName = [string]$_.nETBIOSName } }) SchemaMaster = Resolve-FsmoOwner -OwnerDistinguishedName ([string]$schemaFsmo.fSMORoleOwner) DomainNamingMaster = Resolve-FsmoOwner -OwnerDistinguishedName ([string]$partitionsContainer.fSMORoleOwner) + SchemaOwnerDistinguishedName = [string]$schemaFsmo.fSMORoleOwner + DomainNamingOwnerDistinguishedName = [string]$partitionsContainer.fSMORoleOwner UPNSuffixes = [string[]]@(@($partitionsContainer.uPNSuffixes) | Where-Object { $null -ne $_ }) SPNSuffixes = [string[]]@(@($partitionsContainer.'msDS-SPNSuffixes') | Where-Object { $null -ne $_ }) CrossForestReferences = $crossForestReferences diff --git a/powershell/internal/services/ad/queries/Get-MtLdapOptionalFeature.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapOptionalFeature.ps1 index 647e45386f..232f4ff488 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapOptionalFeature.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapOptionalFeature.ps1 @@ -12,5 +12,5 @@ $searchBase = "CN=Optional Features,CN=Directory Service,CN=Windows NT,CN=Services,$ConfigurationNamingContext" $attributes = @('distinguishedName', 'name', 'msDS-OptionalFeatureGUID', 'msDS-EnabledFeatureBL', 'msDS-RequiredForestBehaviorVersion') $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $searchBase -Scope Subtree -Filter '(objectClass=msDS-OptionalFeature)' -Attributes $attributes) - return @($entries | ForEach-Object { [PSCustomObject]@{ Name = [string]$_.name; DistinguishedName = [string]$_.DistinguishedName; FeatureGUID = $_.'msDS-OptionalFeatureGUID'; IsEnabled = (@($_.'msDS-EnabledFeatureBL' | Where-Object { $null -ne $_ }).Count -gt 0); RequiredForestBehaviorVersion = $_.'msDS-RequiredForestBehaviorVersion' } }) + return @($entries | ForEach-Object { [PSCustomObject]@{ Name = [string]$_.name; DistinguishedName = [string]$_.DistinguishedName; FeatureGUID = $_.'msDS-OptionalFeatureGUID'; IsEnabled = (@($_.'msDS-EnabledFeatureBL' | Where-Object { $null -ne $_ }).Count -gt 0); EnabledScopes = [string[]]@($_.'msDS-EnabledFeatureBL' | Where-Object { $null -ne $_ }); RequiredForestBehaviorVersion = $_.'msDS-RequiredForestBehaviorVersion' } }) } diff --git a/powershell/internal/services/ad/queries/Get-MtLdapPrinter.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapPrinter.ps1 index 3f7077edd9..bb484f9474 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapPrinter.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapPrinter.ps1 @@ -9,6 +9,6 @@ ) if ([string]::IsNullOrWhiteSpace($SearchBase)) { $SearchBase = (Get-MtLdapRootDse -Connection $Connection).DefaultNamingContext } - $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter '(objectClass=printQueue)' -Attributes @('distinguishedName', 'name', 'serverName', 'location')) - return @($entries | ForEach-Object { [PSCustomObject]@{ DistinguishedName = [string]$_.DistinguishedName; Name = [string]$_.name; ServerName = [string]$_.serverName; Location = [string]$_.location } }) + $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter '(objectClass=printQueue)' -Attributes @('distinguishedName', 'name', 'serverName', 'location', 'description')) + return @($entries | ForEach-Object { [PSCustomObject]@{ DistinguishedName = [string]$_.DistinguishedName; Name = [string]$_.name; ServerName = [string]$_.serverName; Location = [string]$_.location; Description = [string]$_.description } }) } diff --git a/powershell/internal/services/ad/queries/Get-MtLdapReplicationSite.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapReplicationSite.ps1 index b6ac800456..b6d875aa6a 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapReplicationSite.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapReplicationSite.ps1 @@ -10,5 +10,5 @@ ) $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase "CN=Sites,$ConfigurationNamingContext" -Scope Subtree -Filter '(objectClass=site)' -Attributes @('distinguishedName', 'name')) - return @($entries | ForEach-Object { [PSCustomObject]@{ Name = [string]$_.name; DistinguishedName = [string]$_.DistinguishedName } }) + return @($entries | ForEach-Object { [PSCustomObject]@{ Name = [string]$_.name; DistinguishedName = [string]$_.DistinguishedName; ObjectClass = @('site') } }) } diff --git a/powershell/internal/services/ad/queries/Get-MtLdapSchemaObject.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapSchemaObject.ps1 index 37b603f4c2..3fca785fea 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapSchemaObject.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapSchemaObject.ps1 @@ -9,6 +9,6 @@ [string] $SchemaNamingContext ) - $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SchemaNamingContext -Scope Subtree -Filter '(objectClass=*)' -Attributes @('distinguishedName', 'name', 'objectClass', 'whenCreated', 'objectVersion')) - return @($entries | ForEach-Object { [PSCustomObject]@{ DistinguishedName = [string]$_.DistinguishedName; Name = [string]$_.name; ObjectClass = @($_.objectClass | Where-Object { $null -ne $_ }); WhenCreated = $_.whenCreated; ObjectVersion = $_.objectVersion } }) + $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SchemaNamingContext -Scope Subtree -Filter '(objectClass=*)' -Attributes @('distinguishedName', 'name', 'lDAPDisplayName', 'objectClass', 'whenCreated', 'objectVersion')) + return @($entries | ForEach-Object { [PSCustomObject]@{ DistinguishedName = [string]$_.DistinguishedName; Name = [string]$_.name; LdapDisplayName = [string]$_.lDAPDisplayName; ObjectClass = @($_.objectClass | Where-Object { $null -ne $_ }); WhenCreated = $_.whenCreated; ObjectVersion = $_.objectVersion } }) } diff --git a/powershell/internal/services/ad/queries/Get-MtLdapServiceAccount.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapServiceAccount.ps1 index 4a60f57a4a..01870d6947 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapServiceAccount.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapServiceAccount.ps1 @@ -9,7 +9,17 @@ ) if ([string]::IsNullOrWhiteSpace($SearchBase)) { $SearchBase = (Get-MtLdapRootDse -Connection $Connection).DefaultNamingContext } - $attributes = @('distinguishedName', 'name', 'sAMAccountName', 'dNSHostName', 'whenCreated', 'whenChanged', 'objectSid') - $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter '(objectClass=msDS-GroupManagedServiceAccount)' -Attributes $attributes) - return @($entries | ForEach-Object { [PSCustomObject]@{ DistinguishedName = [string]$_.DistinguishedName; Name = [string]$_.name; SamAccountName = [string]$_.sAMAccountName; DnsHostName = [string]$_.dNSHostName; Created = $_.whenCreated; Modified = $_.whenChanged; Sid = $_.objectSid } }) + $attributes = @('distinguishedName', 'name', 'sAMAccountName', 'dNSHostName', 'whenCreated', 'whenChanged', 'objectSid', 'objectClass', 'msDS-DelegatedMSAState', 'userAccountControl', 'msDS-AllowedToDelegateTo', 'msDS-AllowedToActOnBehalfOfOtherIdentity') + $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter '(|(objectClass=msDS-ManagedServiceAccount)(objectClass=msDS-GroupManagedServiceAccount)(objectClass=msDS-DelegatedManagedServiceAccount))' -Attributes $attributes) + return @($entries | ForEach-Object { + $uac = if ($null -ne $_.userAccountControl) { ConvertFrom-MtLdapUserAccountControl -UserAccountControl ([int]$_.userAccountControl) } else { $null } + [PSCustomObject]@{ + DistinguishedName = [string]$_.DistinguishedName; Name = [string]$_.name; SamAccountName = [string]$_.sAMAccountName; DnsHostName = [string]$_.dNSHostName + Created = $_.whenCreated; Modified = $_.whenChanged; Sid = $_.objectSid; ObjectClass = @($_.objectClass); DelegatedMsaState = $_.'msDS-DelegatedMSAState' + TrustedForDelegation = if ($null -ne $uac) { $uac.TrustedForDelegation } else { $null } + TrustedToAuthForDelegation = if ($null -ne $uac) { $uac.TrustedToAuthForDelegation } else { $null } + AllowedToDelegateTo = [string[]]@($_.'msDS-AllowedToDelegateTo' | Where-Object { $null -ne $_ }) + HasResourceBasedConstrainedDelegation = $null -ne $_.'msDS-AllowedToActOnBehalfOfOtherIdentity' + } + }) } diff --git a/powershell/internal/services/ad/queries/Get-MtLdapUser.ps1 b/powershell/internal/services/ad/queries/Get-MtLdapUser.ps1 index 4828b3735b..2624ea12ba 100644 --- a/powershell/internal/services/ad/queries/Get-MtLdapUser.ps1 +++ b/powershell/internal/services/ad/queries/Get-MtLdapUser.ps1 @@ -9,7 +9,7 @@ ) if ([string]::IsNullOrWhiteSpace($SearchBase)) { $SearchBase = (Get-MtLdapRootDse -Connection $Connection).DefaultNamingContext } - $attributes = @('distinguishedName', 'name', 'sAMAccountName', 'userAccountControl', 'adminCount', 'homeDirectory', 'badPasswordTime', 'lastLogonTimestamp', 'lockoutTime', 'logonHours', 'userWorkstations', 'managedBy', 'manager', 'pwdLastSet', 'profilePath', 'scriptPath', 'objectSid', 'sIDHistory', 'servicePrincipalName', 'whenCreated', 'whenChanged', 'isCriticalSystemObject') + $attributes = @('distinguishedName', 'name', 'sAMAccountName', 'userAccountControl', 'adminCount', 'homeDirectory', 'badPasswordTime', 'lastLogonTimestamp', 'lockoutTime', 'logonHours', 'userWorkstations', 'managedBy', 'manager', 'pwdLastSet', 'profilePath', 'scriptPath', 'objectSid', 'sIDHistory', 'servicePrincipalName', 'whenCreated', 'whenChanged', 'isCriticalSystemObject', 'primaryGroupID', 'msDS-ResultantPSO', 'msDS-SecondaryKrbTgtNumber', 'msDS-KrbTgtLinkBL', 'msDS-AllowedToDelegateTo', 'msDS-AllowedToActOnBehalfOfOtherIdentity') $entries = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $SearchBase -Scope Subtree -Filter '(&(objectClass=user)(!(objectClass=computer)))' -Attributes $attributes) return @($entries | ForEach-Object { $uac = if ($null -ne $_.userAccountControl) { ConvertFrom-MtLdapUserAccountControl -UserAccountControl ([int]$_.userAccountControl) } else { $null } @@ -21,6 +21,14 @@ ManagedBy = [string]$_.managedBy; Manager = [string]$_.manager; PasswordExpired = if ($null -ne $uac) { $uac.PasswordExpired } else { $null }; PasswordLastSet = $_.pwdLastSet PasswordNeverExpires = if ($null -ne $uac) { $uac.DontExpirePassword } else { $null }; PasswordNotRequired = if ($null -ne $uac) { $uac.PasswordNotRequired } else { $null }; ProfilePath = [string]$_.profilePath ScriptPath = [string]$_.scriptPath; Sid = $_.objectSid; SidHistory = @($_.sIDHistory | Where-Object { $null -ne $_ }); ServicePrincipalName = [string[]]@($_.servicePrincipalName | Where-Object { $null -ne $_ }) + PrimaryGroupId = $_.primaryGroupID + ResultantPasswordPolicyDN = if ($null -ne $_.'msDS-ResultantPSO') { [string]$_.'msDS-ResultantPSO' } else { $null } + ResultantPasswordPolicyAttributeReturned = -not [string]::IsNullOrWhiteSpace([string]$_.'msDS-ResultantPSO') + SecondaryKrbtgtNumber = $_.'msDS-SecondaryKrbTgtNumber' + KrbtgtLinkBacklinks = @($_.'msDS-KrbTgtLinkBL' | Where-Object { $null -ne $_ }) + ReversibleEncryptionEnabled = if ($null -ne $_.userAccountControl) { ([int]$_.userAccountControl -band 0x80) -ne 0 } else { $null } + AllowedToDelegateTo = [string[]]@($_.'msDS-AllowedToDelegateTo' | Where-Object { $null -ne $_ }) + HasResourceBasedConstrainedDelegation = $null -ne $_.'msDS-AllowedToActOnBehalfOfOtherIdentity' TrustedForDelegation = if ($null -ne $uac) { $uac.TrustedForDelegation } else { $null }; TrustedToAuthForDelegation = if ($null -ne $uac) { $uac.TrustedToAuthForDelegation } else { $null }; UseDESKeyOnly = if ($null -ne $uac) { $uac.UseDesKeyOnly } else { $null } UserAccountControl = if ($null -ne $_.userAccountControl) { [int]$_.userAccountControl } else { $null }; Created = $_.whenCreated; Modified = $_.whenChanged; IsCriticalSystemObject = if ($null -ne $_.isCriticalSystemObject) { [bool]$_.isCriticalSystemObject } else { $null } } diff --git a/powershell/internal/services/ad/transport/Get-MtSysvolContent.ps1 b/powershell/internal/services/ad/transport/Get-MtSysvolContent.ps1 index 8777578f30..a91b1eb0d2 100644 --- a/powershell/internal/services/ad/transport/Get-MtSysvolContent.ps1 +++ b/powershell/internal/services/ad/transport/Get-MtSysvolContent.ps1 @@ -797,7 +797,9 @@ function Get-MtSysvolContent { $gppXml.Add((ConvertFrom-MtSysvolGppXml -Content (& $invokeAdapter 'ReadText' $TimeoutSeconds) -RelativePath $path)) } catch { - Write-Verbose "Could not parse SYSVOL XML file '$path': $($_.Exception.Message)" + # Parser/transport errors may contain file contents. Do not expose those + # values or return a clean scan after skipping an unreadable XML file. + throw "SYSVOL XML file '$path' could not be fully assessed; the password scan is incomplete." } } elseif ($path -match '(?i)(^|/)GptTmpl\.inf$') { diff --git a/powershell/public/services/ad/Get-MtADDomainState.ps1 b/powershell/public/services/ad/Get-MtADDomainState.ps1 index 7f42bb3893..42180f5cf9 100644 --- a/powershell/public/services/ad/Get-MtADDomainState.ps1 +++ b/powershell/public/services/ad/Get-MtADDomainState.ps1 @@ -495,7 +495,7 @@ } } Schema = @{ - Properties = @('SchemaObjects', 'SchemaContainer', 'LapsInstalled') + Properties = @('SchemaObjects', 'SchemaContainer', 'LapsInstalled', 'WindowsLapsInstalled', 'DelegatedMsaSupported') Dependencies = @() Collector = { $result = [ordered]@{} @@ -503,6 +503,10 @@ $result['SchemaObjects'] = $schemaObjects $result['SchemaContainer'] = $schemaObjects | Where-Object { $_.DistinguishedName -eq $protocolRootDse.SchemaNamingContext } | Select-Object -First 1 $result['LapsInstalled'] = [bool]($schemaObjects | Where-Object { $_.Name -eq 'ms-Mcs-AdmPwd' } | Select-Object -First 1) + # Schema availability only: never retrieve password attribute values. + $schemaNames = @($schemaObjects | ForEach-Object { if ($_.LdapDisplayName) { $_.LdapDisplayName } else { $_.Name } }) + $result['WindowsLapsInstalled'] = ($schemaNames -contains 'msLAPS-Password') -and ($schemaNames -contains 'msLAPS-PasswordExpirationTime') + $result['DelegatedMsaSupported'] = $schemaNames -contains 'msDS-DelegatedManagedServiceAccount' return $result } } @@ -625,6 +629,8 @@ SchemaContainer = $null Printers = @() LapsInstalled = $false + WindowsLapsInstalled = $false + DelegatedMsaSupported = $false DaclEntries = @() FineGrainedPasswordPolicies = @() } diff --git a/powershell/public/services/ad/Get-MtADGpoState.ps1 b/powershell/public/services/ad/Get-MtADGpoState.ps1 index fcf944230e..7dcd3e4e0d 100644 --- a/powershell/public/services/ad/Get-MtADGpoState.ps1 +++ b/powershell/public/services/ad/Get-MtADGpoState.ps1 @@ -103,6 +103,7 @@ } catch { Write-Verbose "Could not collect GPO metadata: $($_.Exception.Message)" + $gpoState['GPOs'] = $null } $parsedGpoLinks = [System.Collections.Generic.List[object]]::new() @@ -199,9 +200,12 @@ $hasDenyAce = [bool]($access | Where-Object { $_.AccessControlType -eq 'Deny' } | Select-Object -First 1) $hasApplyGroupPolicyAce = [bool]($access | Where-Object { $_.AccessControlType -eq 'Allow' -and - (([string]$_.ObjectType -eq $applyGroupPolicyGuid) -or + [string]$_.AceFlags -notmatch 'InheritOnly' -and + (([string]$_.ActiveDirectoryRights -match 'GenericAll') -or ([string]$_.ActiveDirectoryRights -match 'ApplyGroupPolicy') -or - (([string]$_.ActiveDirectoryRights -match 'ExtendedRight') -and ([string]$_.ObjectType -eq $applyGroupPolicyGuid))) + (([string]$_.ActiveDirectoryRights -match 'ExtendedRight') -and + (([string]$_.ObjectType -eq $applyGroupPolicyGuid) -or + ([string]$_.ObjectType -eq [guid]::Empty.ToString())))) } | Select-Object -First 1) } @@ -234,13 +238,18 @@ } $hasVersionMismatch = $null + $sysvolVersion = $null $cpasswordFound = $null $defaultPasswordFound = $null $errors = [System.Collections.Generic.List[object]]::new() try { Write-Verbose "Collecting SYSVOL content for GPO '$gpoGuid'" $sysvolContent = Get-MtSysvolContent -Operation Connect -GpoGuid $gpoGuid + if ($null -eq $sysvolContent -or $null -eq $sysvolContent.CpasswordFound -or $null -eq $sysvolContent.DefaultPasswordFound) { + throw 'SYSVOL content scanning did not return a complete result.' + } if ($null -ne $sysvolContent.GptIni -and $null -ne $sysvolContent.GptIni.Version) { + $sysvolVersion = [long]$sysvolContent.GptIni.Version $hasVersionMismatch = [long]$gpo.VersionNumber -ne [long]$sysvolContent.GptIni.Version } $cpasswordFound = [bool]$sysvolContent.CpasswordFound @@ -263,6 +272,8 @@ Name = $gpo.DisplayName DisabledLinks = if ($null -ne $gpoLinks) { @($gpoLinks | Where-Object { $_.IsDisabled }).Count } else { $null } HasVersionMismatch = $hasVersionMismatch + DirectoryVersion = $gpo.VersionNumber + SysvolVersion = $sysvolVersion CpasswordFound = $cpasswordFound DefaultPasswordFound = $defaultPasswordFound HasApplyGroupPolicyAce = $hasApplyGroupPolicyAce @@ -282,7 +293,7 @@ } catch { Write-Verbose "Could not build GPO reports: $($_.Exception.Message)" - $gpoState['GPOReports'] = @() + $gpoState['GPOReports'] = $null } $__MtSession.ADCache[$cacheKey] = $gpoState diff --git a/powershell/tests/ad/transport/Get-MtSysvolContent.Tests.ps1 b/powershell/tests/ad/transport/Get-MtSysvolContent.Tests.ps1 index 63da610348..752adb7bc0 100644 --- a/powershell/tests/ad/transport/Get-MtSysvolContent.Tests.ps1 +++ b/powershell/tests/ad/transport/Get-MtSysvolContent.Tests.ps1 @@ -129,6 +129,34 @@ Describe 'Get-MtSysvolContent transport contract' { } } + It 'does not return a clean password scan when an XML file is malformed or unreadable' -ForEach @( + @{ Windows = $true; ReadFailure = $false } + @{ Windows = $false; ReadFailure = $false } + @{ Windows = $true; ReadFailure = $true } + @{ Windows = $false; ReadFailure = $true } + ) { + $script:readFailure = $ReadFailure + $script:useWindowsAdapter = $Windows + Mock Test-MtSysvolWindowsPlatform -ModuleName Maester { $script:useWindowsAdapter } + $adapterMock = { + if ($Operation -eq 'List') { + return [PSCustomObject]@{ RelativePath = 'Machine/Preferences/Groups/Groups.xml'; Name = 'Groups.xml'; Length = 50 } + } + if ($Operation -eq 'ReadText') { + if ($script:readFailure) { throw 'read failed SECRET-MUST-NOT-PRINT' } + return '`nname") | Should -Be 'bad|<script> name' + } + + It 'includes unknown published names instead of silently omitting them' { + Mock Get-MtADDomainState -ModuleName Maester { [pscustomobject]@{ Configuration = [pscustomobject]@{ CertificateTemplates = @([pscustomobject]@{ Name = 'Known'; displayName = 'Known' }); EnrollmentTemplates = @('Known', 'Unknown'); EnterpriseCAs = @([pscustomobject]@{ Name = 'CA'; certificateTemplates = @('Known', 'Unknown') }) } } } + Mock Add-MtTestResultDetail -ModuleName Maester { $script:detail = $Result } + Invoke-MtAdConfigurationInventoryReport -Kind Templates | Should -BeTrue + $script:detail | Should -Match 'unknown template' + $script:detail | Should -Match 'published names without a template object: 1' + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + } + + It 'reports a valid empty optional certificate container as an inventory' { + Mock Get-MtADDomainState -ModuleName Maester { [pscustomobject]@{ Configuration = [pscustomobject]@{ EnterpriseCAs = @(); TrustedRootCAs = @(); IntermediateCAs = @() } } } + Mock Add-MtTestResultDetail -ModuleName Maester { $script:detail = $Result } + Invoke-MtAdConfigurationInventoryReport -Kind Certificates | Should -BeTrue + $script:detail | Should -Match 'public certificate entries: 0' + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + } + + It 'renders the shared Enterprise CA assessment with CA and template context' { + Mock Get-MtADDomainState -ModuleName Maester { + [pscustomobject]@{ Configuration = [pscustomobject]@{ EnterpriseCAs = @( + [pscustomobject]@{ Name = 'CA|one'; dNSHostName = 'ca.example.com'; certificateTemplates = @('User', 'Machine') } + ) } } + } + Mock Add-MtTestResultDetail -ModuleName Maester { $script:detail = $Result } + Invoke-MtAdConfigurationInventoryReport -Kind EnterpriseCAs | Should -BeTrue + $script:detail | Should -Match 'Enterprise CAs: 1' + $script:detail | Should -Match 'CA|one \| ca.example.com \| User, Machine' + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + } + + It 'does not mistake a missing published template list for an empty one' { + Mock Get-MtADDomainState -ModuleName Maester { [pscustomobject]@{ Configuration = [pscustomobject]@{ EnterpriseCAs = @(); CertificateTemplates = @() } } } + { Invoke-MtAdConfigurationInventoryReport -Kind Templates } | Should -Throw '*EnrollmentTemplates data is unavailable*' + } +} diff --git a/powershell/tests/functions/ADCollectorQueries.Tests.ps1 b/powershell/tests/functions/ADCollectorQueries.Tests.ps1 new file mode 100644 index 0000000000..a185940001 --- /dev/null +++ b/powershell/tests/functions/ADCollectorQueries.Tests.ps1 @@ -0,0 +1,157 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'AD query normalization for consolidated checks' { + BeforeEach { + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { } + } + + It 'uses schema LDAP display names rather than common names' { + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { + [pscustomobject]@{ name = 'ms-LAPS-Password'; lDAPDisplayName = 'msLAPS-Password'; objectClass = @('attributeSchema') } + } + InModuleScope Maester { + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') + try { + $objects = @(Get-MtLdapSchemaObject -Connection $connection -SchemaNamingContext 'CN=Schema,CN=Configuration,DC=example,DC=com') + $objects[0].Name | Should -Be 'ms-LAPS-Password' + $objects[0].LdapDisplayName | Should -Be 'msLAPS-Password' + } + finally { $connection.Dispose() } + } + Should -Invoke Invoke-MtLdapSearch -ModuleName Maester -ParameterFilter { $Attributes -contains 'lDAPDisplayName' } + } + + It 'collects all three managed service account classes without requesting passwords' { + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { + [pscustomobject]@{ name = 'Delegated'; objectClass = @('computer', 'msDS-DelegatedManagedServiceAccount'); 'msDS-DelegatedMSAState' = 2; userAccountControl = 17301504; 'msDS-AllowedToDelegateTo' = @('HTTP/managed'); 'msDS-AllowedToActOnBehalfOfOtherIdentity' = [byte[]]@(1, 2, 3) } + } + InModuleScope Maester { + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') + try { + $accounts = @(Get-MtLdapServiceAccount -Connection $connection -SearchBase 'DC=example,DC=com') + $accounts[0].ObjectClass | Should -Contain 'msDS-DelegatedManagedServiceAccount' + $accounts[0].DelegatedMsaState | Should -Be 2 + $accounts[0].TrustedForDelegation | Should -BeTrue + $accounts[0].TrustedToAuthForDelegation | Should -BeTrue + $accounts[0].AllowedToDelegateTo | Should -Contain 'HTTP/managed' + $accounts[0].HasResourceBasedConstrainedDelegation | Should -BeTrue + } + finally { $connection.Dispose() } + } + Should -Invoke Invoke-MtLdapSearch -ModuleName Maester -ParameterFilter { + $Filter -match 'msDS-ManagedServiceAccount' -and $Filter -match 'msDS-GroupManagedServiceAccount' -and $Filter -match 'msDS-DelegatedManagedServiceAccount' -and + @($Attributes | Where-Object { $_ -match '^(msDS-ManagedPassword|msDS-ManagedPasswordId|msDS-ManagedPasswordPreviousId)$' }).Count -eq 0 + } + } + + It 'reports classic KCD targets and RBCD descriptor presence separately' { + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { + [pscustomobject]@{ name = 'Client'; userAccountControl = 4096; 'msDS-AllowedToDelegateTo' = @('HTTP/service.example.com'); 'msDS-AllowedToActOnBehalfOfOtherIdentity' = [byte[]]@(1, 2, 3) } + } + InModuleScope Maester { + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') + try { + $computers = @(Get-MtLdapComputer -Connection $connection -SearchBase 'DC=example,DC=com') + $computers[0].AllowedToDelegateTo | Should -Contain 'HTTP/service.example.com' + $computers[0].HasResourceBasedConstrainedDelegation | Should -BeTrue + $computers[0].PSObject.Properties.Name | Should -Not -Contain 'msDS-AllowedToActOnBehalfOfOtherIdentity' + } + finally { $connection.Dispose() } + } + } + + It 'retains enabled optional feature scopes' { + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { + [pscustomobject]@{ name = 'Recycle Bin Feature'; 'msDS-EnabledFeatureBL' = @('CN=Partitions,CN=Configuration,DC=example,DC=com') } + } + InModuleScope Maester { + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') + try { + $features = @(Get-MtLdapOptionalFeature -Connection $connection -ConfigurationNamingContext 'CN=Configuration,DC=example,DC=com') + $features[0].IsEnabled | Should -BeTrue + $features[0].EnabledScopes | Should -HaveCount 1 + } + finally { $connection.Dispose() } + } + } + + It 'normalizes binary CreatorSid as a SID rather than UTF-8 text' { + InModuleScope Maester { + $sid = ConvertFrom-MtLdapValue -AttributeName 'mS-DS-CreatorSID' -Value ([byte[]]@(1, 1, 0, 0, 0, 0, 0, 5, 11, 0, 0, 0)) + $sid.Value | Should -Be 'S-1-5-11' + } + } + + It 'retains the actual creator SID attribute alongside its compatibility alias' { + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { + [pscustomobject]@{ name = 'Computer'; 'mS-DS-CreatorSID' = [pscustomobject]@{ Value = 'S-1-5-11' } } + } + InModuleScope Maester { + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') + try { + $computer = @(Get-MtLdapComputer -Connection $connection -SearchBase 'DC=example,DC=com')[0] + $computer.'mS-DS-CreatorSID'.Value | Should -Be 'S-1-5-11' + $computer.CreatorSid.Value | Should -Be $computer.'mS-DS-CreatorSID'.Value + } finally { $connection.Dispose() } + } + } + + It 'distinguishes a missing Directory Service object from unset attributes' { + InModuleScope Maester { + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') + try { + $config = Get-MtLdapConfigurationContainer -Connection $connection -ConfigurationNamingContext 'CN=Configuration,DC=example,DC=com' + $config.DirectoryServiceRetrieved | Should -BeFalse + $config.SpnMappings | Should -BeNullOrEmpty + } + finally { $connection.Dispose() } + } + } + + It 'counts DHCP authorization values rather than dhcpClass container objects' { + Mock -ModuleName Maester Invoke-MtLdapSearch -RemoveParameterType Connection { + [pscustomobject]@{ name = 'DhcpRoot'; dhcpServers = @('i192.0.2.1$rcn=dhcp1.example.com$f0$sdhcp1.example.com$', 'i192.0.2.2$rcn=dhcp2.example.com$f0$sdhcp2.example.com$', 'unrecognized entry') } + } -ParameterFilter { $Filter -eq '(objectClass=dhcpClass)' } + InModuleScope Maester { + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') + try { + $config = Get-MtLdapConfigurationContainer -Connection $connection -ConfigurationNamingContext 'CN=Configuration,DC=example,DC=com' + $config.DhcpServers | Should -HaveCount 3 + @($config.DhcpServers | Where-Object RegistrationParsed) | Should -HaveCount 2 + $config.DhcpServers.DnsName | Should -Contain 'dhcp1.example.com' + $config.DhcpServers.IPAddress | Should -Contain '192.0.2.2' + } + finally { $connection.Dispose() } + } + } + + It 'requests the actual AD-based activation schema class' { + InModuleScope Maester { + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('localhost') + try { $null = Get-MtLdapConfigurationContainer -Connection $connection -ConfigurationNamingContext 'CN=Configuration,DC=example,DC=com' } + finally { $connection.Dispose() } + } + Should -Invoke Invoke-MtLdapSearch -ModuleName Maester -ParameterFilter { $Filter -eq '(objectClass=msSPP-ActivationObject)' } + } +} + +Describe 'Windows LAPS readiness accepts the production dictionary state' { + BeforeEach { + Mock -ModuleName Maester Get-MtADDomainState { + [ordered]@{ + WindowsLapsInstalled = $true + SchemaObjects = @( + [pscustomobject]@{ Name = 'ms-LAPS-Password'; LdapDisplayName = 'msLAPS-Password' } + [pscustomobject]@{ Name = 'ms-LAPS-Password-Expiration-Time'; LdapDisplayName = 'msLAPS-PasswordExpirationTime' } + ) + } + } + Mock -ModuleName Maester Add-MtTestResultDetail { } + } + + It 'passes with an ordered dictionary, not only a PSCustomObject fixture' { + InModuleScope Maester { Test-MtAdLapsInstalledStatus | Should -BeTrue } + } +} diff --git a/powershell/tests/functions/ADComputerChecks.Tests.ps1 b/powershell/tests/functions/ADComputerChecks.Tests.ps1 new file mode 100644 index 0000000000..674b46c006 --- /dev/null +++ b/powershell/tests/functions/ADComputerChecks.Tests.ps1 @@ -0,0 +1,168 @@ +Describe 'Active Directory computer inventory checks' { + BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name @( + 'Test-MtAdComputerUnconstrainedDelegationCount' + 'Test-MtAdComputerNonDcConstrainedDelegationCount' + 'Test-MtAdComputerOperatingSystemCount' + 'Test-MtAdComputerPerOUAverage' + 'Test-MtAdComputerCreatorSidCount' + 'Test-MtAdComputerInDefaultContainer' + 'Test-MtAdComputerNonStandardGroup' + ) + } + + BeforeEach { + $script:Details = $null + $script:AdComputerState = [PSCustomObject]@{ + Computers = @( + [PSCustomObject]@{ Name = 'dc1'; DistinguishedName = 'CN=dc1,OU=Domain Controllers,DC=example,DC=com'; DnsHostName = 'dc1.example.com'; PrimaryGroupId = 516; Enabled = $true; TrustedForDelegation = $true; TrustedToAuthForDelegation = $false; AllowedToDelegateTo = @(); HasResourceBasedConstrainedDelegation = $false; OperatingSystem = 'Server' } + [PSCustomObject]@{ Name = 'app|one'; DistinguishedName = 'CN=app\,one,OU=Servers|Prod,DC=example,DC=com'; DnsHostName = 'app.example.com'; PrimaryGroupId = 515; Enabled = $true; TrustedForDelegation = $false; TrustedToAuthForDelegation = $true; AllowedToDelegateTo = @('HTTP/backend|one'); HasResourceBasedConstrainedDelegation = $true; OperatingSystem = '' } + [PSCustomObject]@{ Name = 'client'; DistinguishedName = 'CN=client,OU=Clients,DC=example,DC=com'; DnsHostName = 'client.example.com'; PrimaryGroupId = 515; Enabled = $true; TrustedForDelegation = $false; TrustedToAuthForDelegation = $false; AllowedToDelegateTo = @(); HasResourceBasedConstrainedDelegation = $false; OperatingSystem = 'Client' } + ) + DomainControllers = @([PSCustomObject]@{ Name = 'dc1'; ServerReference = 'CN=dc1,OU=Domain Controllers,DC=example,DC=com'; DnsHostName = 'dc1.example.com' }) + ServiceAccounts = @() + } + Mock -ModuleName Maester Get-MtADDomainState { $script:AdComputerState } + Mock -ModuleName Maester Add-MtTestResultDetail { param($Result, [switch] $Investigate) $script:Details = [PSCustomObject]@{ Text = $Result; Investigate = $Investigate.IsPresent } } + } + + It 'excludes DCs and uses only non-DC computers as the unconstrained percentage denominator' { + Test-MtAdComputerUnconstrainedDelegationCount | Should -BeTrue + $script:Details.Text | Should -BeLike '*| Total Non-DC Computers | 2 |*' + $script:Details.Text | Should -BeLike '*| Non-DC Percentage with Unconstrained Delegation | 0% |*' + + $script:AdComputerState.Computers[1].TrustedForDelegation = $true + Test-MtAdComputerUnconstrainedDelegationCount | Should -BeFalse + $script:Details.Text | Should -BeLike '*| Non-DC Percentage with Unconstrained Delegation | 50% |*' + $script:Details.Text | Should -Match 'app\\\|one' + } + + It 'inventories classic KCD, protocol transition, and RBCD descriptor presence independently' { + Test-MtAdComputerNonDcConstrainedDelegationCount | Should -BeTrue + $script:Details.Investigate | Should -BeTrue + $script:Details.Text | Should -BeLike '*| Non-DC Accounts with Classic KCD Target SPNs | 1 |*' + $script:Details.Text | Should -BeLike '*| Non-DC Accounts with Protocol Transition Flag | 1 |*' + $script:Details.Text | Should -BeLike '*| Non-DC Accounts with RBCD Descriptor Present | 1 |*' + $script:Details.Text | Should -BeLike '*| Distinct Non-DC Accounts with One or More Indicators | 1 |*' + $script:Details.Text | Should -Match 'HTTP/backend\\\|one' + + $script:AdComputerState.Computers[1].TrustedToAuthForDelegation = $false + $script:AdComputerState.Computers[2].HasResourceBasedConstrainedDelegation = $true + Test-MtAdComputerNonDcConstrainedDelegationCount | Should -BeTrue + $script:Details.Text | Should -BeLike '*| Non-DC Accounts with Classic KCD Target SPNs | 1 |*' + $script:Details.Text | Should -BeLike '*| Non-DC Accounts with Protocol Transition Flag | 0 |*' + $script:Details.Text | Should -BeLike '*| Non-DC Accounts with RBCD Descriptor Present | 2 |*' + $script:Details.Text | Should -BeLike '*| Distinct Non-DC Accounts with One or More Indicators | 2 |*' + } + + It 'does not treat missing delegation metadata as a clean result' { + $script:AdComputerState.Computers[1].PSObject.Properties.Remove('AllowedToDelegateTo') + { Test-MtAdComputerNonDcConstrainedDelegationCount } | Should -Throw '*Required delegation fields*' + $script:AdComputerState.Computers[1].TrustedForDelegation = $null + { Test-MtAdComputerUnconstrainedDelegationCount } | Should -Throw '*flag is missing*' + } + + It 'does not treat unknown RBCD descriptor presence as false' { + $script:AdComputerState.Computers[1].HasResourceBasedConstrainedDelegation = $null + { Test-MtAdComputerNonDcConstrainedDelegationCount } | Should -Throw '*Required delegation fields*' + } + + It 'excludes RODCs by server inventory and DCs by DNS fallback, not a claimed primary group' { + $script:AdComputerState.Computers += [PSCustomObject]@{ Name = 'rodc-other'; DistinguishedName = 'CN=rodc-other,DC=example,DC=com'; DnsHostName = 'rodc-other.example.com'; PrimaryGroupId = 521; TrustedForDelegation = $true; TrustedToAuthForDelegation = $true; AllowedToDelegateTo = @('HTTP/dc'); HasResourceBasedConstrainedDelegation = $true } + $script:AdComputerState.Computers += [PSCustomObject]@{ Name = 'dc-alias'; DistinguishedName = 'CN=dc-alias,DC=example,DC=com'; DnsHostName = 'SECOND.example.com'; PrimaryGroupId = 515; TrustedForDelegation = $true; TrustedToAuthForDelegation = $true; AllowedToDelegateTo = @('HTTP/dc'); HasResourceBasedConstrainedDelegation = $true } + $script:AdComputerState.DomainControllers += [PSCustomObject]@{ Name = 'different-short-name'; ServerReference = ''; DnsHostName = 'second.EXAMPLE.com' } + $script:AdComputerState.DomainControllers += [PSCustomObject]@{ Name = 'rodc-other'; ServerReference = 'CN=rodc-other,DC=example,DC=com'; DnsHostName = 'rodc-other.example.com' } + + Test-MtAdComputerUnconstrainedDelegationCount | Should -BeTrue + $script:Details.Text | Should -BeLike '*| Total Non-DC Computers | 2 |*' + Test-MtAdComputerNonDcConstrainedDelegationCount | Should -BeTrue + $script:Details.Text | Should -BeLike '*| Total Non-DC Computers | 2 |*' + } + + It 'counts unknown operating systems without suggesting OS support or patch status' { + Test-MtAdComputerOperatingSystemCount | Should -BeTrue + $script:Details.Investigate | Should -BeTrue + $script:Details.Text | Should -BeLike '*| Computers without OS Data | 1 |*' + $script:Details.Text | Should -BeLike '*| Unknown OS | 1 | 33.33% of all computers |*' + } + + It 'escapes container cells and supplies a heading for the top five table' { + Test-MtAdComputerPerOUAverage | Should -BeTrue + $script:Details.Investigate | Should -BeTrue + $script:Details.Text | Should -Match '\| Container \| Computer Count \|' + $script:Details.Text | Should -Match 'OU=Servers\\\|Prod' + } + + It 'does not report missing CreatorSid collection as zero CreatorSids' { + Test-MtAdComputerCreatorSidCount | Should -BeNullOrEmpty + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $SkippedBecause -eq 'Error' } + $script:Details.Text | Should -BeLike '*mS-DS-CreatorSID LDAP attribute*' + } + + It 'fails when an enabled computer is a child of the default Computers container' { + $script:AdComputerState.Computers[2].DistinguishedName = 'CN=client,CN=Computers,DC=example,DC=com' + Test-MtAdComputerInDefaultContainer | Should -BeFalse + $script:Details.Text | Should -BeLike '*| In Default Computers Container | 1 |*' + } + + It 'counts optional CreatorSid metadata rather than treating its presence as a security failure' { + foreach ($computer in $script:AdComputerState.Computers) { + $computer | Add-Member -NotePropertyName 'mS-DS-CreatorSID' -NotePropertyValue $null + } + $script:AdComputerState.Computers[1].'mS-DS-CreatorSID' = 'S-1-5-21-1-2-3-1100' + Test-MtAdComputerCreatorSidCount | Should -BeTrue + $script:Details.Investigate | Should -BeTrue + $script:Details.Text | Should -BeLike '*| Computers with CreatorSid | 1 |*' + } + + It 'recognizes escaped commas in the computer name without counting an OU named Computers' { + $script:AdComputerState.Computers[1].DistinguishedName = 'CN=app\,one,CN=Computers,DC=example,DC=com' + $script:AdComputerState.Computers[2].DistinguishedName = 'CN=client,OU=Computers,DC=example,DC=com' + Test-MtAdComputerInDefaultContainer | Should -BeFalse + $script:Details.Text | Should -BeLike '*| In Default Computers Container | 1 |*' + } + + It 'does not exclude a non-DC account claiming primary group ' -ForEach @(@{ Group = 516 }, @{ Group = 521 }) { + $script:AdComputerState.Computers[2].PrimaryGroupId = $Group + $script:AdComputerState.Computers[2].TrustedForDelegation = $true + Test-MtAdComputerUnconstrainedDelegationCount | Should -BeFalse + $script:Details.Text | Should -BeLike '*| Total Non-DC Computers | 2 |*' + $script:Details.Text | Should -BeLike '*| Non-DC Computers Claiming DC Primary Groups | 1 |*' + Test-MtAdComputerNonStandardGroup | Should -BeFalse + $script:Details.Text | Should -Match 'client' + } + + It 'does not accept a forged DNS name when the DC inventory has serverReference' { + $script:AdComputerState.Computers[2].DnsHostName = 'dc1.example.com' + $script:AdComputerState.Computers[2].TrustedForDelegation = $true + Test-MtAdComputerUnconstrainedDelegationCount | Should -BeFalse + } + + It 'includes delegation on without adding it to device percentages' -ForEach @( + @{ Class = 'msDS-ManagedServiceAccount' } + @{ Class = 'msDS-GroupManagedServiceAccount' } + @{ Class = 'msDS-DelegatedManagedServiceAccount' } + ) { + $script:AdComputerState.ServiceAccounts = @([PSCustomObject]@{ + Name = 'Managed service'; DistinguishedName = 'CN=Managed,DC=example,DC=com' + ObjectClass = @('computer', $Class); TrustedForDelegation = $true + TrustedToAuthForDelegation = $true; AllowedToDelegateTo = @('HTTP/managed') + HasResourceBasedConstrainedDelegation = $true + }) + Test-MtAdComputerUnconstrainedDelegationCount | Should -BeFalse + $script:Details.Text | Should -BeLike '*| Managed Service Accounts with Unconstrained Delegation | 1 |*' + $script:Details.Text | Should -BeLike '*| Non-DC Percentage with Unconstrained Delegation | 0% |*' + Test-MtAdComputerNonDcConstrainedDelegationCount | Should -BeTrue + $script:Details.Text | Should -BeLike '*| Non-DC Accounts with Classic KCD Target SPNs | 2 |*' + $script:Details.Text | Should -Match 'Managed service' + } + + It 'errors when the managed account inventory or delegation flags are unavailable' { + $script:AdComputerState.ServiceAccounts = $null + { Test-MtAdComputerUnconstrainedDelegationCount } | Should -Throw '*inventories*' + $script:AdComputerState.ServiceAccounts = @([PSCustomObject]@{ Name = 'Unknown'; TrustedForDelegation = $null }) + { Test-MtAdComputerUnconstrainedDelegationCount } | Should -Throw '*flag is missing*' + } +} diff --git a/powershell/tests/functions/ADConfigurationChecks.Tests.ps1 b/powershell/tests/functions/ADConfigurationChecks.Tests.ps1 new file mode 100644 index 0000000000..c74f61c546 --- /dev/null +++ b/powershell/tests/functions/ADConfigurationChecks.Tests.ps1 @@ -0,0 +1,123 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name Test-MtAdTombstoneLifetime, Test-MtAdDsHeuristicsCount, Test-MtAdSpnMappings, Test-MtAdRecycleBinStatus, Test-MtAdOptionalFeatureCount, Test-MtAdKdsRootKeysCount +} + +Describe 'AD configuration, forest and optional-feature checks' { + BeforeEach { + $script:detail = $null + $script:state = [PSCustomObject]@{ + Forest = [PSCustomObject]@{ Name = 'example.test'; ForestMode = 'Windows2016Forest' } + Configuration = [PSCustomObject]@{ + DirectoryServiceRetrieved = $true + TombstoneLifetime = 180 + DsHeuristics = $null + SpnMappings = @('HOST=HTTP') + KdsRootKeys = @([PSCustomObject]@{ 'msKds-CreateTime' = [datetime]'2024-01-01' }) + } + OptionalFeatures = @( + [PSCustomObject]@{ Name = 'Recycle Bin Feature'; IsEnabled = $true; EnabledScopes = @('CN=Partitions,CN=Configuration,DC=example,DC=test') } + [PSCustomObject]@{ Name = 'Other Feature'; IsEnabled = $false; EnabledScopes = @() } + ) + } + Mock Get-MtADDomainState -ModuleName Maester { $script:state } + Mock Add-MtTestResultDetail -ModuleName Maester { $script:detail = $Result } + } + + It 'reports an explicitly configured 180-day tombstone lifetime, not the default' { + Test-MtAdTombstoneLifetime | Should -BeTrue + $script:detail | Should -Match 'Configured tombstoneLifetime \| 180 days' + $script:detail | Should -Match 'Effective tombstone lifetime \| 180 days' + $script:detail | Should -Match 'default \(60 days\) \| False' + $script:detail | Should -Match 'Advisory status \| ✅ Meets advisory' + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + } + + It 'reports 60 days as the effective lifetime only when the attribute is unset' { + $script:state.Configuration.TombstoneLifetime = $null + Test-MtAdTombstoneLifetime | Should -BeTrue + $script:detail | Should -Match 'Configured tombstoneLifetime \| Not set' + $script:detail | Should -Match 'Effective tombstone lifetime \| 60 days' + $script:detail | Should -Match 'default \(60 days\) \| True' + $script:detail | Should -Match 'Advisory status \| ⚠️ Below advisory' + Test-MtAdTombstoneLifetime -RecommendedMinimumDays 30 | Should -BeTrue + $script:detail | Should -Match 'Advisory status \| ✅ Meets advisory' + } + + It 'errors rather than assuming a default if the Directory Service object is missing' { + $script:state.Configuration.DirectoryServiceRetrieved = $false + $script:state.Configuration.TombstoneLifetime = $null + { Test-MtAdTombstoneLifetime } | Should -Throw '*Directory Service object*' + { Test-MtAdDsHeuristicsCount } | Should -Throw '*Directory Service object*' + { Test-MtAdSpnMappings } | Should -Throw '*Directory Service object*' + } + + It 'errors on invalid tombstone values rather than treating them as advisory-only findings' -ForEach @( + @{ Value = 0 } + @{ Value = -1 } + @{ Value = 'invalid' } + ) { + $script:state.Configuration.TombstoneLifetime = $Value + { Test-MtAdTombstoneLifetime } | Should -Throw + } + + It 'investigates unset dSHeuristics without treating it as an inventory error' { + Test-MtAdDsHeuristicsCount | Should -BeTrue + $script:detail | Should -Match 'not set' + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Exactly 1 -ParameterFilter { $Investigate } + } + + It 'fails when Recycle Bin exists but is not enabled' { + $script:state.OptionalFeatures[0].IsEnabled = $false + Test-MtAdRecycleBinStatus | Should -BeFalse + $script:detail | Should -Match 'not enabled' + } + + It 'combines available and enabled counts with feature scope details' { + Test-MtAdOptionalFeatureCount | Should -BeTrue + $script:detail | Should -Match 'Available optional features \| 2' + $script:detail | Should -Match 'Enabled optional features \| 1' + $script:detail | Should -Match 'Recycle Bin Feature \| True \| CN=Partitions' + $script:detail | Should -Match 'Other Feature \| False \| None' + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Exactly 1 -ParameterFilter { $Investigate } + } + + It 'errors when an optional feature is missing enabled-scope data' { + $script:state.OptionalFeatures[0].PSObject.Properties.Remove('EnabledScopes') + { Test-MtAdOptionalFeatureCount } | Should -Throw '*scopes were not collected*' + } + + It 'fails for zero KDS root keys rather than assuming gMSAs are unused' { + $script:state.Configuration.KdsRootKeys = @() + Test-MtAdKdsRootKeysCount -KeyInventoryReadAccessConfirmed $true | Should -BeFalse + $script:detail | Should -Match 'No KDS root keys' + } + + It 'investigates the documented two-key case with a single boolean return' { + $script:state.Configuration.KdsRootKeys += [PSCustomObject]@{ 'msKds-CreateTime' = [datetime]'2025-01-01' } + Test-MtAdKdsRootKeysCount -KeyInventoryReadAccessConfirmed $true | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Exactly 1 -ParameterFilter { $Investigate } + $script:detail | Should -Not -Match 'Recommended Count' + } + + It 'does not silently omit a KDS key with unavailable creation metadata' { + $script:state.Configuration.KdsRootKeys += [PSCustomObject]@{ Name = 'Unreadable metadata' } + { Test-MtAdKdsRootKeysCount } | Should -Throw '*inventory is incomplete*' + } + + It 'investigates zero visible keys unless complete read access was confirmed' { + $script:state.Configuration.KdsRootKeys = @() + Test-MtAdKdsRootKeysCount | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Exactly 1 -ParameterFilter { $Investigate } + $script:detail | Should -Match 'not proof that keys are missing' + $script:detail | Should -Not -Match 'create a third' + } + + It 'does not recommend another key from an unconfirmed two-key inventory' { + $script:state.Configuration.KdsRootKeys += [PSCustomObject]@{ 'msKds-CreateTime' = [datetime]'2025-01-01' } + Test-MtAdKdsRootKeysCount | Should -BeTrue + $script:detail | Should -Match 'complete inventory is not confirmed' + $script:detail | Should -Not -Match 'create a third' + } +} diff --git a/powershell/tests/functions/ADDaclConsolidation.Tests.ps1 b/powershell/tests/functions/ADDaclConsolidation.Tests.ps1 new file mode 100644 index 0000000000..e4ceb8f9ca --- /dev/null +++ b/powershell/tests/functions/ADDaclConsolidation.Tests.ps1 @@ -0,0 +1,67 @@ +Describe 'Consolidated Active Directory DACL inventory' { + BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name @( + 'Test-MtAdDaclConflictObjectCount' + 'Test-MtAdDaclDenyAceCount' + 'Test-MtAdDaclDistinctIdentityCount' + 'Test-MtAdDaclPrivilegedAllowAceCount' + 'Test-MtAdDaclPrivilegedExtendedRightCount' + 'Test-MtAdDaclUnresolvedSidCount' + 'Test-MtAdDaclInheritedObjectTypeCount' + ) + $script:Entries = @( + [PSCustomObject]@{ ObjectDN = 'CN=Dup\0ACNF:123,DC=example,DC=com'; ObjectClass = 'user'; ObjectName = 'Dup'; AccessControlType = 'Allow'; ActiveDirectoryRights = 'GenericAll'; IdentityReference = 'S-1-5-21-1-2-3-99'; ObjectType = [guid]::Empty.ToString(); InheritedObjectType = '11111111-1111-1111-1111-111111111111' } + [PSCustomObject]@{ ObjectDN = 'CN=Dup\0ACNF:123,DC=example,DC=com'; ObjectClass = 'user'; ObjectName = 'Dup'; AccessControlType = 'Allow'; ActiveDirectoryRights = 'ReadProperty, ExtendedRight'; IdentityReference = 'EXAMPLE\Admin'; ObjectType = '00299570-246d-11d0-a768-00aa006e0529'; InheritedObjectType = '11111111-1111-1111-1111-111111111111' } + [PSCustomObject]@{ ObjectDN = 'OU=Other,DC=example,DC=com'; ObjectClass = 'organizationalUnit'; ObjectName = 'Other'; AccessControlType = 'Deny'; ActiveDirectoryRights = 'ExtendedRight'; IdentityReference = 'EXAMPLE\Admin'; ObjectType = '00299570-246d-11d0-a768-00aa006e0529'; InheritedObjectType = [guid]::Empty.ToString() } + ) + } + + BeforeEach { + $script:Detail = $null + Mock -ModuleName Maester Test-MtAdDaclPlatformSupported { $true } + Mock -ModuleName Maester Get-MtADDomainState { [PSCustomObject]@{ DaclEntries = $script:Entries } } + Mock -ModuleName Maester Add-MtTestResultDetail { param($Result) $script:Detail = $Result } + } + + It 'keeps counts and object details together for conflict objects and deny ACEs' { + Test-MtAdDaclConflictObjectCount | Should -BeTrue + $script:Detail | Should -BeLike '*| Conflict Objects In DACL Data | 1 |*' + $script:Detail | Should -BeLike '*| CN=Dup* | user | 2 |*' + Test-MtAdDaclDenyAceCount | Should -BeTrue + $script:Detail | Should -BeLike '*| Deny ACEs | 1 |*' + $script:Detail | Should -BeLike '*| Other | organizationalUnit | OU=Other,DC=example,DC=com | EXAMPLE\Admin | 1 |*' + } + + It 'reports identity distribution and distinct counts in one result' { + Test-MtAdDaclDistinctIdentityCount | Should -BeTrue + $script:Detail | Should -BeLike '*| Distinct identities | 2 |*' + $script:Detail | Should -BeLike '*| EXAMPLE\Admin | 2 | 2 | 1 | 1 |*' + } + + It 'includes privileged allow objects and named extended-right identities without counting deny grants' { + Test-MtAdDaclPrivilegedAllowAceCount | Should -BeTrue + $script:Detail | Should -BeLike '*| Privileged allow ACEs | 2 |*' + $script:Detail | Should -BeLike '*| Dup | user | 2 | 2 | ExtendedRight, GenericAll |*' + Test-MtAdDaclPrivilegedExtendedRightCount | Should -BeTrue + $script:Detail | Should -BeLike '*| ExtendedRight allow ACEs | 1 |*' + $script:Detail | Should -BeLike '*| EXAMPLE\Admin | Reset Password | 1 |*' + } + + It 'includes unresolved SID and inheritance-target breakdowns' { + Test-MtAdDaclUnresolvedSidCount | Should -BeTrue + $script:Detail | Should -BeLike '*| Distinct Unresolved SIDs | 1 |*' + $script:Detail | Should -BeLike '*| CN=Dup* | 1 | S-1-5-21-1-2-3-99 |*' + Test-MtAdDaclInheritedObjectTypeCount | Should -BeTrue + $script:Detail | Should -BeLike '*| Distinct InheritedObjectType GUIDs | 1 |*' + $script:Detail | Should -BeLike '*| 11111111-1111-1111-1111-111111111111 | 2 | 1 |*' + } + + It 'does not report an inventory from missing DACL data' { + Mock -ModuleName Maester Get-MtADDomainState { [PSCustomObject]@{ DaclEntries = $null } } + foreach ($check in @('Test-MtAdDaclConflictObjectCount', 'Test-MtAdDaclDenyAceCount', 'Test-MtAdDaclDistinctIdentityCount', 'Test-MtAdDaclPrivilegedAllowAceCount', 'Test-MtAdDaclPrivilegedExtendedRightCount', 'Test-MtAdDaclUnresolvedSidCount', 'Test-MtAdDaclInheritedObjectTypeCount')) { + { & $check } | Should -Throw '*DACL data is unavailable*' + } + } +} diff --git a/powershell/tests/functions/ADDomainForestBatch.Tests.ps1 b/powershell/tests/functions/ADDomainForestBatch.Tests.ps1 new file mode 100644 index 0000000000..f9285639dd --- /dev/null +++ b/powershell/tests/functions/ADDomainForestBatch.Tests.ps1 @@ -0,0 +1,253 @@ +BeforeAll { + . "$PSScriptRoot/../../internal/checks/ad/ad/Get-MtAdDomainControllerRelease.ps1" + . "$PSScriptRoot/../../internal/checks/ad/ad/Get-MtAdFunctionalLevelAssessment.ps1" + . "$PSScriptRoot/../../internal/checks/ad/ad/Get-MtAdDomainControllersInScope.ps1" + . "$PSScriptRoot/../../internal/checks/ad/ad/Get-MtAdDomainNameFindings.ps1" + . "$PSScriptRoot/../../internal/checks/ad/ad/Get-MtAdFsmoPlacement.ps1" +} + +Describe 'Native AD domain and forest results' { + BeforeAll { Import-Module "$PSScriptRoot/../../Maester.psd1" -Force } + BeforeEach { + $script:batchDetail = $null + $script:batchState = [pscustomobject]@{ + Domain = [pscustomobject]@{ + DistinguishedName = 'DC=example,DC=com'; DnsRoot = 'example.com'; DomainLevelValue = 10 + } + Forest = [pscustomobject]@{ + ForestLevelValue = 10; Domains = @('example.com', 'child.example.com') + } + DomainControllers = @([pscustomobject]@{ + Name = 'root'; DnsHostName = 'root.example.com' + ServerReference = 'CN=root,CN=Domain Controllers,DC=example,DC=com' + OperatingSystem = 'Windows Server 2025'; OperatingSystemVersion = '10.0 (26100)' + SupportedLevelValue = 10; IsGlobalCatalog = $true + }) + } + Mock -ModuleName Maester Get-MtADDomainState { $script:batchState } + Mock -ModuleName Maester Add-MtTestResultDetail { $script:batchDetail = $Result; return } + } + + It 'excludes other-domain DCs and fails DOM-01 and FOR-01 only on incompatible connected-domain support' { + $script:batchState.DomainControllers += [pscustomobject]@{ + Name = 'child'; DnsHostName = 'child.child.example.com' + ServerReference = 'CN=child,CN=Domain Controllers,DC=child,DC=example,DC=com' + OperatingSystem = 'Windows Server 2022'; OperatingSystemVersion = '10.0 (20348)' + SupportedLevelValue = 7; IsGlobalCatalog = $true + } + InModuleScope Maester { Test-MtAdForestFunctionalLevel | Should -BeTrue } + $script:batchDetail | Should -Match '\| Other-domain DCs excluded \| 1 \|' + $script:batchState.DomainControllers.Count | Should -Be 2 + $script:batchState.DomainControllers[1].ServerReference = 'CN=child,CN=Domain Controllers,DC=example,DC=com' + InModuleScope Maester { + Test-MtAdDomainFunctionalLevel | Should -BeFalse + Test-MtAdForestFunctionalLevel | Should -BeFalse + } + $script:batchDetail | Should -Match 'exceeds connected-domain DC support' + $script:batchState.Domain.DomainLevelValue = 7 + $script:batchState.Forest.ForestLevelValue = 7 + InModuleScope Maester { + Test-MtAdDomainFunctionalLevel | Should -BeTrue + Test-MtAdForestFunctionalLevel | Should -BeTrue + } + } + + It 'counts only connected-domain DCs even when child DNS names have the parent suffix' { + $script:batchState.DomainControllers += [pscustomobject]@{ + Name = 'child'; DnsHostName = 'child.child.example.com' + ServerReference = 'CN=child,CN=Domain Controllers,DC=child,DC=example,DC=com' + } + InModuleScope Maester { Test-MtAdDomainControllerCount } + $script:batchDetail | Should -Match 'has 1 inventoried DC' + $script:batchDetail | Should -Not -Match 'child' + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + } + + It 'excludes foreign-domain lookup errors but rejects unknown connected-domain OS metadata' { + $script:batchState.DomainControllers += [pscustomobject]@{ + Name = 'foreign'; DnsHostName = 'foreign.child.example.com' + ServerReference = 'CN=foreign,CN=Domain Controllers,DC=child,DC=example,DC=com' + OperatingSystem = $null; OperatingSystemVersion = $null + CollectionError = 'Foreign computer lookup failed' + } + InModuleScope Maester { + Test-MtAdDcOperatingSystemCount | Should -BeTrue + Test-MtAdForestFunctionalLevel | Should -BeTrue + } + $script:batchDetail | Should -Match '\| Other-domain DCs excluded \| 1 \|' + $script:batchState.DomainControllers[1].ServerReference = 'CN=foreign,CN=Domain Controllers,DC=example,DC=com' + InModuleScope Maester { + { Test-MtAdDcOperatingSystemCount } | Should -Throw '*foreign*' + { Test-MtAdForestFunctionalLevel } | Should -Throw '*foreign*' + } + } + + It 'decodes the live RID Manager pool without casting a signed hexadecimal mask' { + $script:batchState.Domain | Add-Member -NotePropertyName RIDAvailablePool -NotePropertyValue '4611686014132428208' + InModuleScope Maester { Test-MtAdRidsRemaining } + $script:batchDetail | Should -Match '\| RID Manager pool upper bound \| 1073741823 \|' + $script:batchDetail | Should -Match '\| Next allocation boundary \| 7600 \|' + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + } + + It 'renders quota values as separate metric rows without changing the baseline' { + $script:batchState.Domain | Add-Member -NotePropertyName MsDsMachineAccountQuota -NotePropertyValue 0 + InModuleScope Maester { Test-MtAdMachineAccountQuota | Should -BeTrue } + $script:batchDetail | Should -Match '\| Matches documented default \| False \|' + $script:batchState.Domain.MsDsMachineAccountQuota = 10 + InModuleScope Maester { Test-MtAdMachineAccountQuota | Should -BeFalse } + $script:batchDetail | Should -Match '\| Observed ms-DS-MachineAccountQuota \| 10 \|' + } + + It 'inventories GC status by default and evaluates minimum-forest policy only when requested' { + $script:batchState.DomainControllers[0].IsGlobalCatalog = $false + InModuleScope Maester { Test-MtAdDcNonGlobalCatalogCount | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + InModuleScope Maester { Test-MtAdDcNonGlobalCatalogCount -AssessmentMode MinimumForestCatalog | Should -BeFalse } + $script:batchDetail | Should -Match '\| Non-Global Catalog DCs \| 1 \|' + $script:batchState.DomainControllers[0].IsGlobalCatalog = $true + InModuleScope Maester { Test-MtAdDcNonGlobalCatalogCount -AssessmentMode MinimumForestCatalog | Should -BeTrue } + $script:batchState.DomainControllers[0].IsGlobalCatalog = $null + InModuleScope Maester { + Test-MtAdDcNonGlobalCatalogCount | Should -BeTrue + { Test-MtAdDcNonGlobalCatalogCount -AssessmentMode MinimumForestCatalog } | Should -Throw '*Incomplete GC status*' + } + } + + It 'requires every inventoried DC to be a GC only in all-GC policy mode' { + InModuleScope Maester { Test-MtAdDcNonGlobalCatalogCount -AssessmentMode AllGlobalCatalogs | Should -BeTrue } + $script:batchState.DomainControllers += [pscustomobject]@{ DnsHostName = 'non-gc.child.example.com'; IsGlobalCatalog = $false } + InModuleScope Maester { Test-MtAdDcNonGlobalCatalogCount -AssessmentMode AllGlobalCatalogs | Should -BeFalse } + $script:batchState.DomainControllers[1].IsGlobalCatalog = $null + InModuleScope Maester { { Test-MtAdDcNonGlobalCatalogCount -AssessmentMode AllGlobalCatalogs } | Should -Throw '*Incomplete GC status*' } + } + + It 'shows both LDAP and LDAPS unknown ports without claiming live listener evidence' { + $script:batchState.DomainControllers[0] | Add-Member -NotePropertyName LdapPort -NotePropertyValue $null + $script:batchState.DomainControllers[0] | Add-Member -NotePropertyName SslPort -NotePropertyValue $null + $script:batchState.DomainControllers[0] | Add-Member -NotePropertyName PortEvidence -NotePropertyValue 'Not measured' + InModuleScope Maester { Test-MtAdDcNonStandardLdapPortCount } + $script:batchDetail | Should -Match '\| LDAP \| 389 \| 0 \| 1 \| 0 \|' + $script:batchDetail | Should -Match '\| LDAPS \| 636 \| 0 \| 1 \| 0 \|' + $script:batchDetail | Should -Match '\| root.example.com \| Unknown \| Unknown \| Not measured \|' + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + } + + It 'reports forest partition DNS and NetBIOS syntax findings in survivor check tables' { + $script:batchState.Forest | Add-Member -NotePropertyName DomainPartitions -NotePropertyValue @( + [pscustomobject]@{ DistinguishedName = 'DC=example,DC=com'; DnsRoot = 'example.com'; NetBIOSName = 'EXAMPLE' }, + [pscustomobject]@{ DistinguishedName = 'DC=bad,DC=example,DC=com'; DnsRoot = 'bad..example.com'; NetBIOSName = 'BAD/NAME' } + ) + InModuleScope Maester { Test-MtAdDomainNameStandardCompliance | Should -BeFalse } + $script:batchDetail | Should -Match '\| bad\.\.example\.com \| Invalid \|' + InModuleScope Maester { Test-MtAdNetbiosNameStandardCompliance | Should -BeFalse } + $script:batchDetail | Should -Match '\| BAD/NAME \| Invalid \|' + } + + It 'lists every FSMO owner as a DN and counts distinct holders in DC-05' { + $root = 'DC=example,DC=com' + $owner = "CN=NTDS Settings,CN=ROOT,CN=Servers,CN=Site,CN=Sites,CN=Configuration,$root" + $script:batchState.Forest | Add-Member -NotePropertyName RootDomain -NotePropertyValue 'example.com' + $script:batchState.Forest | Add-Member -NotePropertyName RootDomainDistinguishedName -NotePropertyValue $root + $script:batchState.Forest | Add-Member -NotePropertyName SchemaOwnerDistinguishedName -NotePropertyValue $owner + $script:batchState.Forest | Add-Member -NotePropertyName DomainNamingOwnerDistinguishedName -NotePropertyValue $owner + $script:batchState.Domain | Add-Member -NotePropertyName PdcOwnerDistinguishedName -NotePropertyValue $owner + $script:batchState.Domain | Add-Member -NotePropertyName RidOwnerDistinguishedName -NotePropertyValue $owner + $script:batchState.Domain | Add-Member -NotePropertyName InfrastructureOwnerDistinguishedName -NotePropertyValue $owner + $script:batchState.DomainControllers[0] | Add-Member -NotePropertyName DistinguishedName -NotePropertyValue $owner + $script:batchState.DomainControllers[0] | Add-Member -NotePropertyName IsReadOnly -NotePropertyValue $false + InModuleScope Maester { Test-MtAdDcAllFsmoRolesCount | Should -BeTrue } + $script:batchDetail | Should -Match '\| Distinct owner DNs \| 1 \|' + $script:batchDetail | Should -Match '\| Schema \| CN=NTDS Settings' + $script:batchDetail | Should -Match '\| Infrastructure \| CN=NTDS Settings' + $otherOwner = "CN=NTDS Settings,CN=OTHER,CN=Servers,CN=Site,CN=Sites,CN=Configuration,$root" + $script:batchState.DomainControllers += [pscustomobject]@{ + DistinguishedName = $otherOwner + ServerReference = "CN=OTHER,OU=Domain Controllers,$root" + IsReadOnly = $false + IsGlobalCatalog = $true + } + $script:batchState.Domain.RidOwnerDistinguishedName = $otherOwner + InModuleScope Maester { Test-MtAdDcAllFsmoRolesCount | Should -BeFalse } + $script:batchDetail | Should -Match '(?m)^- RID Master is not on the connected domain PDC\.' + } +} + +Describe 'AD domain and forest assessments' { + It 'supports functional level 10 only with all Server 2025 DCs' { + $controllers = @( + [pscustomobject]@{ Name = 'new'; OperatingSystem = 'Windows Server 2025'; OperatingSystemVersion = '10.0 (26100)'; SupportedLevelValue = 10 }, + [pscustomobject]@{ Name = 'old'; OperatingSystem = 'Windows Server 2022'; OperatingSystemVersion = '10.0 (20348)'; SupportedLevelValue = 7 } + ) + $state = [pscustomobject]@{ Forest = [pscustomobject]@{ ForestLevelValue = 7 }; DomainControllers = $controllers } + (Get-MtAdFunctionalLevelAssessment -State $state -Scope Forest).Target | Should -Be 7 + $state.DomainControllers = @($controllers[0]) + (Get-MtAdFunctionalLevelAssessment -State $state -Scope Forest).Target | Should -Be 10 + } + + It 'errors on a foreign DC with unknown OS metadata rather than passing' { + $state = [pscustomobject]@{ Forest = [pscustomobject]@{ ForestLevelValue = 7 }; DomainControllers = @([pscustomobject]@{ Name = 'foreign'; CollectionError = 'Computer lookup failed'; OperatingSystem = $null }) } + { Get-MtAdFunctionalLevelAssessment -State $state -Scope Forest } | Should -Throw '*foreign*' + } + + It 'scopes domain controller count to the connected domain, not forest DNS suffixes' { + $state = [pscustomobject]@{ + Domain = [pscustomobject]@{ DistinguishedName = 'DC=example,DC=com'; DnsRoot = 'example.com' } + DomainControllers = @( + [pscustomobject]@{ Name = 'connected'; ServerReference = 'CN=dc,CN=Domain Controllers,DC=example,DC=com' }, + [pscustomobject]@{ Name = 'foreign'; ServerReference = 'CN=dc,CN=Domain Controllers,DC=child,DC=example,DC=com' } + ) + } + @(Get-MtAdDomainControllersInScope -State $state).Name | Should -Be 'connected' + } + + It 'treats absent forest domain partition metadata as an error' { + { Get-MtAdDomainNameFindings -Forest ([pscustomobject]@{ Domains = @('example.com') }) -Kind Dns } | Should -Throw '*partition*' + } + + It 'validates Unicode DNS labels through IDNA and checks NetBIOS names separately' { + $forest = [pscustomobject]@{ Domains = @('xn--bcher-kva.example'); DomainPartitions = @([pscustomobject]@{ DistinguishedName = 'DC=x,DC=example'; DnsRoot = 'bücher.example'; NetBIOSName = 'BÜCHER' }) } + @(Get-MtAdDomainNameFindings -Forest $forest -Kind Dns).Count | Should -Be 0 + @(Get-MtAdDomainNameFindings -Forest $forest -Kind Netbios).Count | Should -Be 0 + } + + It 'compares FSMO owners as NTDS DNs, not resolved hostnames' { + $root = 'DC=example,DC=com' + $owner = "CN=NTDS Settings,CN=DC1,CN=Servers,CN=Site,CN=Sites,CN=Configuration,$root" + $dc = [pscustomobject]@{ DistinguishedName = $owner; ServerReference = 'CN=DC1,OU=DCs,DC=example,DC=com'; Name = 'DC1'; IsReadOnly = $false; IsGlobalCatalog = $true } + $state = [pscustomobject]@{ + Forest = [pscustomobject]@{ RootDomain = 'example.com'; RootDomainDistinguishedName = $root; Domains = @('example.com'); SchemaOwnerDistinguishedName = $owner; DomainNamingOwnerDistinguishedName = $owner } + Domain = [pscustomobject]@{ DistinguishedName = $root; PdcOwnerDistinguishedName = $owner; RidOwnerDistinguishedName = $owner; InfrastructureOwnerDistinguishedName = $owner } + DomainControllers = @($dc) + } + (Get-MtAdFsmoPlacement -State $state).Issues.Count | Should -Be 0 + $state.Domain.RidOwnerDistinguishedName = 'DC1.example.com' + { Get-MtAdFsmoPlacement -State $state } | Should -Throw '*NTDS Settings DN*' + } + + It 'requires non-GC Infrastructure Master only for the multi-domain, non-all-GC, Recycle Bin disabled case' { + $root = 'DC=example,DC=com' + $owner = "CN=NTDS Settings,CN=DC1,CN=Servers,CN=Site,CN=Sites,CN=Configuration,$root" + $other = "CN=NTDS Settings,CN=DC2,CN=Servers,CN=Site,CN=Sites,CN=Configuration,$root" + $dc1 = [pscustomobject]@{ DistinguishedName = $owner; ServerReference = 'CN=DC1,OU=DCs,DC=example,DC=com'; IsReadOnly = $false; IsGlobalCatalog = $true } + $dc2 = [pscustomobject]@{ DistinguishedName = $other; ServerReference = 'CN=DC2,OU=DCs,DC=example,DC=com'; IsReadOnly = $false; IsGlobalCatalog = $false } + $state = [pscustomobject]@{ + Forest = [pscustomobject]@{ RootDomain = 'example.com'; RootDomainDistinguishedName = $root; Domains = @('example.com', 'child.example.com'); SchemaOwnerDistinguishedName = $owner; DomainNamingOwnerDistinguishedName = $owner } + Domain = [pscustomobject]@{ DistinguishedName = $root; PdcOwnerDistinguishedName = $owner; RidOwnerDistinguishedName = $owner; InfrastructureOwnerDistinguishedName = $owner } + DomainControllers = @($dc1, $dc2) + OptionalFeatures = @([pscustomobject]@{ Name = 'Recycle Bin Feature'; IsEnabled = $false }) + } + (Get-MtAdFsmoPlacement -State $state).Issues -join ' ' | Should -Match 'Infrastructure Master is a GC' + $state.OptionalFeatures[0].IsEnabled = $true + @( (Get-MtAdFsmoPlacement -State $state).Issues ).Count | Should -Be 0 + $state.OptionalFeatures[0].IsEnabled = $false + $dc2.IsGlobalCatalog = $true + @( (Get-MtAdFsmoPlacement -State $state).Issues ).Count | Should -Be 0 + } + It 'classifies Server 2012 R2 as known legacy and preserves its supported level' { + $dc = [pscustomobject]@{ Name = 'legacy'; OperatingSystem = 'Windows Server 2012 R2'; OperatingSystemVersion = '6.3 (9600)'; SupportedLevelValue = 6 } + (Get-MtAdDomainControllerRelease -Controller $dc) | Should -Be 2012 + $state = [pscustomobject]@{ Forest = [pscustomobject]@{ ForestLevelValue = 6 }; DomainControllers = @($dc) } + (Get-MtAdFunctionalLevelAssessment -State $state -Scope Forest).Target | Should -Be 6 + } +} diff --git a/powershell/tests/functions/ADGpoInventory.Tests.ps1 b/powershell/tests/functions/ADGpoInventory.Tests.ps1 new file mode 100644 index 0000000000..834269e455 --- /dev/null +++ b/powershell/tests/functions/ADGpoInventory.Tests.ps1 @@ -0,0 +1,73 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'AD GPO modification age and link inventories' { + BeforeEach { + $script:now = [datetime]'2026-11-08T12:00:00' + $script:state = [pscustomobject]@{ + GPOs = @([pscustomobject]@{ + Id = '{11111111-1111-1111-1111-111111111111}' + DisplayName = 'Policy | pilot' + CreationTime = [datetime]'2000-01-01' + ModificationTime = [datetime]'2026-01-01' + }) + GPOLinks = @([pscustomobject]@{ GpoGuid = '11111111-1111-1111-1111-111111111111' }) + LinkContainers = @( + [pscustomobject]@{ ObjectClass = @('domainDNS'); DistinguishedName = 'DC=example,DC=com'; GpLink = '' } + [pscustomobject]@{ ObjectClass = @('organizationalUnit'); DistinguishedName = 'OU=Pilot|test,DC=example,DC=com'; GpLink = '' } + ) + SiteContainers = @() + } + Mock -ModuleName Maester Get-MtADGpoState { $script:state } + Mock -ModuleName Maester Get-Date { $script:now } + Mock -ModuleName Maester Add-MtTestResultDetail { } + } + + It 'does not fail an old creation date when modification is recent' { + InModuleScope Maester { Test-MtAdGpoStale | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { + $Result -match '2000-01-01' -and $Result -match '2026-01-01' -and $Result -match '|' + } + } + + It 'fails stale modifications using five years by default' { + $script:state.GPOs[0].ModificationTime = [datetime]'2021-11-08T11:59:59' + InModuleScope Maester { Test-MtAdGpoStale | Should -BeFalse } + } + + It 'accepts a modification exactly at the cutoff' { + $script:state.GPOs[0].ModificationTime = $script:now.AddYears(-5) + InModuleScope Maester { Test-MtAdGpoStale | Should -BeTrue } + } + + It 'honors a configurable age limit' { + $script:state.GPOs[0].ModificationTime = [datetime]'2022-01-01' + InModuleScope Maester { Test-MtAdGpoStale -MaximumAgeYears 3 | Should -BeFalse } + } + + It 'errors on missing modification dates' { + $script:state.GPOs[0].ModificationTime = $null + InModuleScope Maester { { Test-MtAdGpoStale } | Should -Throw '*no modification date*' } + } + + It 'recognizes normalized links despite braces around the inventory identifier' { + InModuleScope Maester { Test-MtAdGpoUnlinkedCount | Should -BeTrue } + } + + It 'lists unlinked policies with both dates' { + $script:state.GPOLinks = @() + InModuleScope Maester { Test-MtAdGpoUnlinkedCount | Should -BeFalse } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Result -match '2000-01-01' -and $Result -match '2026-01-01' } + } + + It 'errors rather than treating failed link collection as no links' { + $script:state.GPOLinks = $null + InModuleScope Maester { { Test-MtAdGpoUnlinkedCount } | Should -Throw '*cannot be assessed*' } + } + + It 'investigates a target without direct links without claiming missing effective policy' { + InModuleScope Maester { Test-MtAdGpoUnlinkedTargetCount | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate -and $Result -match 'OU=Pilot|test' } + } +} diff --git a/powershell/tests/functions/ADGpoReports.Tests.ps1 b/powershell/tests/functions/ADGpoReports.Tests.ps1 new file mode 100644 index 0000000000..eddf9853df --- /dev/null +++ b/powershell/tests/functions/ADGpoReports.Tests.ps1 @@ -0,0 +1,125 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name Test-MtAdGpoCpasswordFoundCount, Test-MtAdGpoVersionMismatchCount, Test-MtCheckADGPOREP12, Test-MtAdGpoNoApplyGroupPolicyAceCount, Test-MtAdGpoNoPermissionsCount, Test-MtAdGpoNoAuthenticatedUsersCount +} + +Describe 'Merged AD GPO report checks' { + BeforeEach { + $script:detail = $null + $script:report = [PSCustomObject]@{ + Name = 'Example GPO' + CpasswordFound = $false + DefaultPasswordFound = $false + HasVersionMismatch = $false + DirectoryVersion = 65538 + SysvolVersion = 65538 + Errors = @() + HasApplyGroupPolicyAce = $true + PermissionsPresent = $true + HasAuthenticatedUsers = $true + } + $script:state = [PSCustomObject]@{ + GPOs = @([PSCustomObject]@{ Id = '00000000-0000-0000-0000-000000000001'; DisplayName = 'Example GPO' }) + GPOReports = @($script:report) + GPOLinks = @() + } + Mock Get-MtADGpoState -ModuleName Maester { $script:state } + Mock Add-MtTestResultDetail -ModuleName Maester { $script:detail = $Result } + } + + It 'passes only after both secret scan flags are evaluated' { + Test-MtAdGpoCpasswordFoundCount | Should -BeTrue + $script:detail | Should -Match 'Well done' + } + + It 'fails when a GPO has no permissions and lists its name' { + $script:report.PermissionsPresent = $false + Test-MtAdGpoNoPermissionsCount | Should -BeFalse + $script:detail | Should -Match 'Example GPO' + } + + It 'marks unreadable permissions for investigation' { + $script:report.PermissionsPresent = $null + Test-MtAdGpoNoPermissionsCount | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Exactly 1 -ParameterFilter { $Investigate } + } + + It 'investigates alternative security filtering rather than failing Authenticated Users absence' { + $script:report.HasAuthenticatedUsers = $false + Test-MtAdGpoNoAuthenticatedUsersCount | Should -BeTrue + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -Exactly 1 -ParameterFilter { $Investigate } + $script:detail | Should -Match 'Example GPO' + } + + It 'passes when application rights are present' { + Test-MtAdGpoNoApplyGroupPolicyAceCount | Should -BeTrue + Should -Not -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + } + + It 'fails when application rights are absent' { + $script:report.HasApplyGroupPolicyAce = $false + Test-MtAdGpoNoApplyGroupPolicyAceCount | Should -BeFalse + $script:detail | Should -Match 'Example GPO' + } + + It 'errors rather than passing when application rights are unreadable' { + $script:report.HasApplyGroupPolicyAce = $null + { Test-MtAdGpoNoApplyGroupPolicyAceCount } | Should -Throw '*could not be evaluated*' + } + + It 'fails on cpassword alone without rendering the secret value' { + $script:report.CpasswordFound = $true + $script:report | Add-Member -NotePropertyName Password -NotePropertyValue 'SECRET-MUST-NOT-PRINT' + Test-MtAdGpoCpasswordFoundCount | Should -BeFalse + $script:detail | Should -Match 'Example GPO' + $script:detail | Should -Not -Match 'SECRET-MUST-NOT-PRINT' + } + + It 'fails on a default password alone' { + $script:report.DefaultPasswordFound = $true + Test-MtAdGpoCpasswordFoundCount | Should -BeFalse + $script:detail | Should -Match 'default passwords' + } + + It 'errors on null or missing scan flags and on SYSVOL collection errors' -ForEach @( + @{ Case = 'missing cpassword flag' } + @{ Case = 'missing default password flag' } + @{ Case = 'SYSVOL error' } + ) { + switch ($Case) { + 'missing cpassword flag' { $script:report.CpasswordFound = $null } + 'missing default password flag' { $script:report.DefaultPasswordFound = $null } + 'SYSVOL error' { $script:report.Errors = @([PSCustomObject]@{ Transport = 'SYSVOL'; Message = 'failed' }) } + } + { Test-MtAdGpoCpasswordFoundCount } | Should -Throw '*incomplete*' + } + + It 'errors if report collection silently drops a GPO' { + $script:state.GPOs += [PSCustomObject]@{ Id = '00000000-0000-0000-0000-000000000002'; DisplayName = 'Other GPO' } + { Test-MtAdGpoCpasswordFoundCount } | Should -Throw '*inventory*' + } + + It 'shows both versions for mismatched policies' { + $script:report.HasVersionMismatch = $true + $script:report.SysvolVersion = 65539 + Test-MtAdGpoVersionMismatchCount | Should -BeFalse + $script:detail | Should -Match '65538 \| 65539' + } + + It 'does not pass when SYSVOL version is missing' { + $script:report.SysvolVersion = $null + { Test-MtAdGpoVersionMismatchCount } | Should -Throw '*incomplete*' + } + + It 'inventories disabled links and lists their linked container' { + $script:state.GPOLinks = @([PSCustomObject]@{ + GpoGuid = '00000000-0000-0000-0000-000000000001' + DistinguishedName = 'OU=Clients,DC=example,DC=com' + IsDisabled = $true + }) + Test-MtCheckADGPOREP12 | Should -BeTrue + $script:detail | Should -Match '1 disabled links' + $script:detail | Should -Match 'OU=Clients' + } +} diff --git a/powershell/tests/functions/ADGroupSpnChecks.Tests.ps1 b/powershell/tests/functions/ADGroupSpnChecks.Tests.ps1 new file mode 100644 index 0000000000..1a6c29326a --- /dev/null +++ b/powershell/tests/functions/ADGroupSpnChecks.Tests.ps1 @@ -0,0 +1,186 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name Test-MtAdGroupMemberDistinctGroupCount, Test-MtAdGroupMemberAccountTypeCount, + Test-MtAdGroupMemberTrustCount, Test-MtAdUserSpnTotalCount, Test-MtAdUserSpnServiceClassCount, + Test-MtAdUserSpnDomainAdminCount, Test-MtAdGroupStaleCount + Use-MtModuleFunction -Name Test-MtAdGroupMemberForeignSidCount, Test-MtAdGroupEmptyNonPrivilegedCount, Test-MtAdGroupPrivilegedWithMembersCount +} + +Describe 'AD group and SPN checks on a collected snapshot' { + It 'errors rather than treating missing group modification timestamps as recent' { + InModuleScope Maester { + { Test-MtAdGroupStaleCount } | Should -Throw '*modification timestamps are missing*' + } + } + BeforeEach { + InModuleScope Maester { + $script:adSpnDomainSid = 'S-1-5-21-111-222-333' + $script:adSpnAdminDn = 'CN=Domain Admins,DC=example,DC=com' + $script:adSpnState = [PSCustomObject]@{ + Domain = [PSCustomObject]@{ DomainSID = [PSCustomObject]@{ Value = $script:adSpnDomainSid } } + Groups = @([PSCustomObject]@{ DistinguishedName = $script:adSpnAdminDn; SID = [PSCustomObject]@{ Value = "$script:adSpnDomainSid-512" }; Name = 'Domain Admins' }) + Users = @([PSCustomObject]@{ DistinguishedName = 'CN=Ordinary,DC=example,DC=com'; SID = "$script:adSpnDomainSid-1100"; SamAccountName = 'ordinary'; PrimaryGroupId = 513; ServicePrincipalName = @() }) + ProtocolEvidence = [PSCustomObject]@{} + } + $script:adSpnMembers = @{ $script:adSpnAdminDn = @() } + $script:adSpnResult = '' + $script:adConnectionDisposed = $false + } + + Mock Get-MtADDomainState -ModuleName Maester { InModuleScope Maester { $script:adSpnState } } + Mock New-MtAdProtocolConnection -ModuleName Maester { + [PSCustomObject]@{} | Add-Member -MemberType ScriptMethod -Name Dispose -Value { + InModuleScope Maester { $script:adConnectionDisposed = $true } + } -PassThru + } + Mock Get-MtLdapGroupMember -ModuleName Maester -RemoveParameterType Connection { + InModuleScope Maester -Parameters @{ GroupDn = $GroupDistinguishedName } { + @($script:adSpnMembers[$GroupDn]) | Where-Object { $null -ne $_ } + } + } + Mock Add-MtTestResultDetail -ModuleName Maester { + InModuleScope Maester -Parameters @{ Detail = $Result } { $script:adSpnResult = $Detail } + } + } + + It 'counts members in group 51 instead of silently truncating at 50' { + InModuleScope Maester { + $script:adSpnState.Groups = @(1..51 | ForEach-Object { + [PSCustomObject]@{ DistinguishedName = "CN=G$_,DC=example,DC=com"; Name = "G$_"; SID = "$script:adSpnDomainSid-$_" } + }) + $script:adSpnMembers['CN=G51,DC=example,DC=com'] = @( + [PSCustomObject]@{ SID = "$script:adSpnDomainSid-1200"; DistinguishedName = 'CN=Member,DC=example,DC=com'; Name = 'Member'; ObjectClass = 'user' } + ) + Test-MtAdGroupMemberDistinctGroupCount | Should -BeTrue + $script:adSpnResult | Should -Match '1 out of 51 groups' + Test-MtAdGroupMemberAccountTypeCount | Should -BeTrue + $script:adSpnResult | Should -Match '1 distinct account types across 1 unique members' + } + } + + It 'disposes the LDAP connection when a complete group scan errors' -ForEach @( + @{ Command = 'Test-MtAdGroupMemberDistinctGroupCount' } + @{ Command = 'Test-MtAdGroupMemberAccountTypeCount' } + @{ Command = 'Test-MtAdGroupMemberForeignSidCount' } + @{ Command = 'Test-MtAdGroupMemberTrustCount' } + @{ Command = 'Test-MtAdGroupPrivilegedWithMembersCount' } + @{ Command = 'Test-MtAdGroupEmptyNonPrivilegedCount' } + ) { + Mock Get-MtLdapGroupMember -ModuleName Maester -RemoveParameterType Connection { throw 'Membership read failed' } + InModuleScope Maester -Parameters @{ Name = $Command } { + $script:adSpnState.Groups[0] | Add-Member -NotePropertyName adminCount -NotePropertyValue 1 -Force + { & $Name } | Should -Throw '*Membership read failed*' + $script:adConnectionDisposed | Should -BeTrue + } + } + + It 'classifies foreign domain-account SIDs without treating well-known or current-domain SIDs as foreign' { + InModuleScope Maester { + $script:adSpnMembers[$script:adSpnAdminDn] = @( + [pscustomobject]@{ SID = 'S-1-5-18'; Name = 'SYSTEM' } + [pscustomobject]@{ SID = "$script:adSpnDomainSid-1200"; Name = 'Local' } + [pscustomobject]@{ SID = 'S-1-5-21-444-555-666-1200'; Name = 'Foreign string' } + [pscustomobject]@{ SID = [pscustomobject]@{ Value = 'S-1-5-21-111-222-3334-1200' }; Name = 'Different domain sharing text prefix' } + ) + Test-MtAdGroupMemberForeignSidCount | Should -BeTrue + $script:adSpnResult | Should -Match 'Foreign SID Principals \| 2' + $script:adSpnResult | Should -Not -Match '\| SYSTEM \|' + $script:adConnectionDisposed | Should -BeTrue + } + } + + It 'accepts a string domain SID for foreign-member classification' { + InModuleScope Maester { + $script:adSpnState.Domain.DomainSID = $script:adSpnDomainSid + $script:adSpnMembers[$script:adSpnAdminDn] = @([pscustomobject]@{ SID = 'S-1-5-21-444-555-666-1200'; Name = 'Foreign' }) + Test-MtAdGroupMemberForeignSidCount | Should -BeTrue + $script:adSpnResult | Should -Match 'Foreign SID Principals \| 1' + } + } + + It 'counts trust principals from group 51 without classifying NT AUTHORITY SIDs as foreign domains' { + InModuleScope Maester { + $script:adSpnState.Groups = @(1..51 | ForEach-Object { + [PSCustomObject]@{ DistinguishedName = "CN=G$_,DC=example,DC=com"; Name = "G$_"; SID = "$script:adSpnDomainSid-$_" } + }) + $script:adSpnMembers['CN=G51,DC=example,DC=com'] = @( + [PSCustomObject]@{ SID = 'S-1-5-18'; DistinguishedName = 'CN=System,DC=example,DC=com'; Name = 'SYSTEM'; ObjectClass = 'user' }, + [PSCustomObject]@{ SID = 'S-1-5-21-444-555-666-1200'; DistinguishedName = 'CN=Foreign,DC=example,DC=com'; Name = 'Foreign'; ObjectClass = 'foreignSecurityPrincipal' } + ) + Test-MtAdGroupMemberTrustCount | Should -BeTrue + $script:adSpnResult | Should -Match 'Found 1 trust members' + $script:adSpnResult | Should -Match 'Groups Analyzed \| 51' + } + } + + It 'distinguishes two users with SPNs from seven raw SPNs' { + InModuleScope Maester { + $script:adSpnState.Users = @( + [PSCustomObject]@{ SamAccountName = 'one'; ServicePrincipalName = @('HTTP/a', 'HTTP/b', 'custom:value') }, + [PSCustomObject]@{ SamAccountName = 'two'; ServicePrincipalName = @('HTTP/c', 'HTTP/d', 'HTTP/e', 'HTTP/f') }, + [PSCustomObject]@{ SamAccountName = 'none'; ServicePrincipalName = @() } + ) + Test-MtAdUserSpnTotalCount | Should -BeTrue + $script:adSpnResult | Should -Match '7 SPNs across 2 user accounts' + Test-MtAdUserSpnServiceClassCount | Should -BeTrue + $script:adSpnResult | Should -Match 'Total User SPNs \| 7' + $script:adSpnResult | Should -Match 'Users with SPNs \| 2' + } + } + + It 'counts direct, nested and primary-group Domain Admins, including unparsed SPNs' { + InModuleScope Maester { + $nestedDn = 'CN=Nested,DC=example,DC=com' + $script:adSpnState.Groups += [PSCustomObject]@{ DistinguishedName = $nestedDn; SID = "$script:adSpnDomainSid-1400"; Name = 'Nested' } + $script:adSpnState.Users = @( + [PSCustomObject]@{ DistinguishedName = 'CN=Direct,DC=example,DC=com'; SID = [PSCustomObject]@{ Value = "$script:adSpnDomainSid-1101" }; SamAccountName = 'direct'; PrimaryGroupId = 513; ServicePrincipalName = @('HTTP/host', 'not-standard') }, + [PSCustomObject]@{ DistinguishedName = 'CN=Indirect,DC=example,DC=com'; SID = "$script:adSpnDomainSid-1102"; SamAccountName = 'indirect'; PrimaryGroupId = 513; ServicePrincipalName = @('HTTP/nested') }, + [PSCustomObject]@{ DistinguishedName = 'CN=Primary,DC=example,DC=com'; SID = "$script:adSpnDomainSid-1103"; SamAccountName = 'primary'; PrimaryGroupId = 512; ServicePrincipalName = @('opaque-spn') }, + [PSCustomObject]@{ DistinguishedName = 'CN=OtherDomain,DC=example,DC=com'; SID = 'S-1-5-21-444-555-666-1104'; SamAccountName = 'other'; PrimaryGroupId = 512; ServicePrincipalName = @('HTTP/foreign') } + ) + $script:adSpnMembers[$script:adSpnAdminDn] = @( + [PSCustomObject]@{ DistinguishedName = 'CN=Direct,DC=example,DC=com'; SID = "$script:adSpnDomainSid-1101" }, + [PSCustomObject]@{ DistinguishedName = $nestedDn; SID = "$script:adSpnDomainSid-1400" } + ) + $script:adSpnMembers[$nestedDn] = @( + [PSCustomObject]@{ DistinguishedName = 'CN=Indirect,DC=example,DC=com'; SID = "$script:adSpnDomainSid-1102" } + ) + Test-MtAdUserSpnDomainAdminCount | Should -BeFalse + $script:adSpnResult | Should -Match 'Domain Admin Accounts \| 3' + $script:adSpnResult | Should -Match 'Domain Admins with SPNs \| 3' + $script:adSpnResult | Should -Match 'Total SPNs on Domain Admins \| 4' + } + } + + It 'terminates on cyclic nested groups and deduplicates the same user' { + InModuleScope Maester { + $nestedDn = 'CN=Nested,DC=example,DC=com' + $script:adSpnState.Groups += [PSCustomObject]@{ DistinguishedName = $nestedDn; SID = "$script:adSpnDomainSid-1400"; Name = 'Nested' } + $script:adSpnState.Users = @([PSCustomObject]@{ + DistinguishedName = 'CN=Direct,DC=example,DC=com'; SID = "$script:adSpnDomainSid-1101" + SamAccountName = 'direct'; PrimaryGroupId = 512; ServicePrincipalName = @() + }) + $script:adSpnMembers[$script:adSpnAdminDn] = @( + [PSCustomObject]@{ DistinguishedName = $nestedDn; SID = "$script:adSpnDomainSid-1400" }, + [PSCustomObject]@{ DistinguishedName = 'CN=Direct,DC=example,DC=com'; SID = "$script:adSpnDomainSid-1101" } + ) + $script:adSpnMembers[$nestedDn] = @( + [PSCustomObject]@{ DistinguishedName = $script:adSpnAdminDn; SID = "$script:adSpnDomainSid-512" }, + [PSCustomObject]@{ DistinguishedName = 'CN=Direct,DC=example,DC=com'; SID = "$script:adSpnDomainSid-1101" } + ) + Test-MtAdUserSpnDomainAdminCount | Should -BeTrue + $script:adSpnResult | Should -Match 'Domain Admin Accounts \| 1' + } + } + + It 'errors instead of reporting a clean Domain Admins result when membership is unresolved' { + InModuleScope Maester { + $script:adSpnMembers[$script:adSpnAdminDn] = @( + [PSCustomObject]@{ DistinguishedName = 'CN=Missing,DC=example,DC=com'; SID = "$script:adSpnDomainSid-1999" } + ) + { Test-MtAdUserSpnDomainAdminCount } | Should -Throw '*Unresolved Domain Admins member*' + $script:adSpnResult | Should -BeNullOrEmpty + } + } +} diff --git a/powershell/tests/functions/ADGuideContent.Tests.ps1 b/powershell/tests/functions/ADGuideContent.Tests.ps1 new file mode 100644 index 0000000000..aa52603995 --- /dev/null +++ b/powershell/tests/functions/ADGuideContent.Tests.ps1 @@ -0,0 +1,51 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + $script:adTestsById = @{} + foreach ($test in Get-MtTest -Product ad) { $script:adTestsById[$test.Id] = $test } + $script:adGuideRoot = (Resolve-Path "$PSScriptRoot/../../../tests/ad").Path +} + +Describe 'AD guide references preserve full current test identities' { + It 'includes the test ID, exact title and cmdlet in each related-test bullet' { + $problems = @() + foreach ($file in Get-ChildItem $script:adGuideRoot -Recurse -Filter 'Test.*.md') { + $text = Get-Content $file.FullName -Raw + $sections = [regex]::Matches($text, '(?ms)^#### Related [Tt]ests\s*\r?\n(.*?)(?=^#### |^|\z)') + foreach ($section in $sections) { + foreach ($line in $section.Groups[1].Value -split '\r?\n') { + if ($line -notmatch '^\s*[-*]' -or $line -notmatch '(AD-[A-Z]+-\d+|Test-Mt)') { continue } + $idMatch = [regex]::Match($line, 'AD-[A-Z]+-\d+') + $reference = if ($idMatch.Success) { $script:adTestsById[$idMatch.Value] } else { $null } + if ($idMatch.Success -and $file.BaseName -eq "Test.$($idMatch.Value)") { + $problems += "$($file.Name): self-reference: $line" + } + if ($null -eq $reference -or -not $line.Contains($reference.Title) -or -not $line.Contains($reference.FunctionName)) { + $problems += "$($file.Name): $line" + } + } + } + } + $problems | Should -BeNullOrEmpty + } + + It 'keeps the description and exactly one result footer in every AD guide' { + foreach ($file in Get-ChildItem $script:adGuideRoot -Recurse -Filter 'Test.*.md') { + $text = Get-Content $file.FullName -Raw + [regex]::Matches($text, '').Count | Should -Be 1 -Because $file.Name + $text | Should -Match '(?s)\S.+\s*%TestResult%\s*$' -Because $file.Name + } + } + It 'does not pair DHCP authorization with unrelated SPN mapping checks' { + $guide = Get-Content (Join-Path $script:adGuideRoot 'config/Test.AD-CFG-11.md') -Raw + $guide | Should -Match 'DHCP' + $guide | Should -Not -Match 'AD-SPN-0[17]|configured mappings' + } + + It 'retains native invocation examples and a help link in every AD check' { + foreach ($file in Get-ChildItem $script:adGuideRoot -Recurse -Filter 'Test.*.ps1') { + $text = Get-Content $file.FullName -Raw + $text | Should -Match '(?im)^\s*\.EXAMPLE\s*$' -Because $file.Name + $text | Should -Match '(?im)^\s*\.LINK\s*$' -Because $file.Name + } + } +} diff --git a/powershell/tests/functions/ADPasswordPolicyBatch.Tests.ps1 b/powershell/tests/functions/ADPasswordPolicyBatch.Tests.ps1 new file mode 100644 index 0000000000..fb6ff64c0b --- /dev/null +++ b/powershell/tests/functions/ADPasswordPolicyBatch.Tests.ps1 @@ -0,0 +1,200 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + . "$PSScriptRoot/../../internal/checks/ad/ad/Test-MtAdPasswordPolicyConfiguration.ps1" + . "$PSScriptRoot/../../internal/checks/ad/ad/Get-MtAdPasswordPolicyUsage.ps1" + + function Get-MockPasswordPolicy { + param([int] $Length = 15, [int] $Age = 0) + [pscustomobject]@{ + DistinguishedName = 'CN=Policy,CN=Password Settings Container,DC=example,DC=org' + Name = 'Policy'; MsDsPasswordSettingsPrecedence = 1; MsDsPsoAppliesTo = @('CN=Group,DC=example,DC=org') + MinPwdLength = $Length; PwdHistoryLength = 24; MaxPwdAge = [timespan]::FromDays($Age) + MinPwdAge = [timespan]::Zero; ComplexityEnabled = $false; ReversibleEncryptionEnabled = $false + LockoutThreshold = 10; LockoutDuration = [timespan]::FromMinutes(15) + LockoutObservationWindow = [timespan]::FromMinutes(15); PwdProperties = 16 + } + } +} + +Describe 'Native AD password policy outcomes' { + BeforeEach { + InModuleScope Maester { + $script:settingsInstance = [pscustomobject]@{ Data = [pscustomobject]@{ Kind = 'Settings' } } + $script:usageInstance = [pscustomobject]@{ Data = [pscustomobject]@{ Kind = 'Usage' } } + } + $script:policy = Get-MockPasswordPolicy + $script:state = [pscustomobject]@{ + Domain = $script:policy + FineGrainedPasswordPolicies = @($script:policy) + Users = @([pscustomobject]@{ + Name = 'Alex'; Enabled = $true; PasswordNeverExpires = $false + ResultantPasswordPolicyDN = $script:policy.DistinguishedName + }) + } + Mock -ModuleName Maester Get-MtADDomainState { $script:state } + Mock -ModuleName Maester Add-MtTestResultDetail { } + } + + It 'defines exactly two stable family instances with independent severities' { + $instances = @(InModuleScope Maester { Get-MtAdFineGrainedPolicyAssessmentInstance }) + $instances.Count | Should -Be 2 + $instances[0].Id | Should -Be 'settings' + $instances[0].Severity | Should -Be 'High' + $instances[0].Data.Kind | Should -Be 'Settings' + $instances[1].Id | Should -Be 'usage' + $instances[1].Severity | Should -Be 'Low' + $instances[1].Data.Kind | Should -Be 'Usage' + (Get-MtTest -Id 'AD-FGPP-01').InstanceSource | Should -Be 'Get-MtAdFineGrainedPolicyAssessmentInstance' + } + + It 'passes a confirmed settings row and fails weak settings only on the High row' { + InModuleScope Maester { Test-MtAdFineGrainedPasswordPolicySecurity -Instance $script:settingsInstance -PolicyInventoryReadAccessConfirmed $true | Should -BeTrue } + Should -Invoke Get-MtADDomainState -ModuleName Maester -ParameterFilter { $Categories -notcontains 'Users' } + $script:policy.MinPwdLength = 8 + InModuleScope Maester { Test-MtAdFineGrainedPasswordPolicySecurity -Instance $script:settingsInstance -PolicyInventoryReadAccessConfirmed $true | Should -BeFalse } + InModuleScope Maester { Test-MtAdFineGrainedPasswordPolicySecurity -Instance $script:usageInstance -PolicyInventoryReadAccessConfirmed $true | Should -BeTrue } + } + + It 'investigates unconfirmed usage but fails confirmed zero use only on the Low row' { + $script:state.Users[0].ResultantPasswordPolicyDN = $null + InModuleScope Maester { Test-MtAdFineGrainedPasswordPolicySecurity -Instance $script:usageInstance | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + InModuleScope Maester { Test-MtAdFineGrainedPasswordPolicySecurity -Instance $script:usageInstance -PolicyInventoryReadAccessConfirmed $true | Should -BeFalse } + InModuleScope Maester { Test-MtAdFineGrainedPasswordPolicySecurity -Instance $script:settingsInstance -PolicyInventoryReadAccessConfirmed $true | Should -BeTrue } + } + + It 'errors on unknown resultant policy only in usage, without turning it into a settings failure' { + $script:state.Users[0].ResultantPasswordPolicyDN = 'CN=Unknown,DC=example,DC=org' + InModuleScope Maester { { Test-MtAdFineGrainedPasswordPolicySecurity -Instance $script:usageInstance -PolicyInventoryReadAccessConfirmed $true } | Should -Throw '*absent*' } + InModuleScope Maester { Test-MtAdFineGrainedPasswordPolicySecurity -Instance $script:settingsInstance -PolicyInventoryReadAccessConfirmed $true | Should -BeTrue } + } + + It 'investigates zero visible PSOs and fails confirmed absence only on the Low row' { + $script:state.FineGrainedPasswordPolicies = @() + InModuleScope Maester { Test-MtAdFineGrainedPasswordPolicySecurity -Instance $script:settingsInstance | Should -BeTrue } + InModuleScope Maester { Test-MtAdFineGrainedPasswordPolicySecurity -Instance $script:usageInstance | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + InModuleScope Maester { Test-MtAdFineGrainedPasswordPolicySecurity -Instance $script:usageInstance -PolicyInventoryReadAccessConfirmed $true | Should -BeFalse } + InModuleScope Maester { Test-MtAdFineGrainedPasswordPolicySecurity -Instance $script:settingsInstance -PolicyInventoryReadAccessConfirmed $true | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $SkippedBecause -eq 'NotApplicable' } + } + + It 'does not treat an empty enabled-user inventory as proof that a PSO is unused' { + $script:state.Users = @() + InModuleScope Maester { Test-MtAdFineGrainedPasswordPolicySecurity -Instance $script:usageInstance -PolicyInventoryReadAccessConfirmed $true | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + InModuleScope Maester { Test-MtAdUserEffectivePasswordExpiration -PolicyInventoryReadAccessConfirmed $true | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } -Times 2 + } + + It 'evaluates the complete default-domain profile and overrides the minimum length' { + InModuleScope Maester { Test-MtAdDefaultPasswordPolicySecurity | Should -BeTrue } + InModuleScope Maester { Test-MtAdDefaultPasswordPolicySecurity -MinimumLength 20 | Should -BeFalse } + } + + It 'checks effective user expiration and distinguishes current from legacy rotation' { + InModuleScope Maester { Test-MtAdUserEffectivePasswordExpiration -PolicyInventoryReadAccessConfirmed $true | Should -BeTrue } + InModuleScope Maester { Test-MtAdUserEffectivePasswordExpiration -Profile LegacyRotation -PolicyInventoryReadAccessConfirmed $true | Should -BeFalse } + $script:policy.MaxPwdAge = [timespan]::FromDays(90) + InModuleScope Maester { Test-MtAdUserEffectivePasswordExpiration -Profile LegacyRotation -PolicyInventoryReadAccessConfirmed $true | Should -BeTrue } + } + + It 'uses the renamed profile parameter and preserves the direct-call alias without changing the automatic variable' { + $script:policy.MaxPwdAge = [timespan]::FromDays(90) + $script:policy.ComplexityEnabled = $true + InModuleScope Maester { + $originalProfile = $PROFILE + foreach ($command in 'Test-MtAdFineGrainedPasswordPolicySecurity', 'Test-MtAdDefaultPasswordPolicySecurity', 'Test-MtAdUserEffectivePasswordExpiration') { + $parameters = @{ ConfigurationProfile = 'LegacyRotation' } + if ($command -ne 'Test-MtAdDefaultPasswordPolicySecurity') { $parameters.PolicyInventoryReadAccessConfirmed = $true } + & $command @parameters | Should -BeTrue + $parameters.Remove('ConfigurationProfile') + $parameters.Profile = 'LegacyRotation' + & $command @parameters | Should -BeTrue + } + $PROFILE | Should -Be $originalProfile + } + } + + It 'discovers the canonical profile parameter with unchanged default and allowed values' { + foreach ($id in 'AD-FGPP-01', 'AD-PWDPOL-01', 'AD-USER-03') { + $test = Get-MtTest -Id $id + $parameter = @($test.Parameters | Where-Object Name -EQ 'ConfigurationProfile') + $parameter.Count | Should -Be 1 -Because $id + $parameter[0].Default | Should -Be 'CurrentNist' + $parameter[0].AllowedValues | Should -Be @('CurrentNist', 'LegacyRotation') + InModuleScope Maester -Parameters @{ Metadata = $test } { + param($Metadata) + $binding = ConvertTo-MtTestParameter -Test $Metadata -ConfigValue @{ ConfigurationProfile = 'LegacyRotation' } + $binding.Error | Should -BeNullOrEmpty + $binding.Bound.ConfigurationProfile | Should -Be 'LegacyRotation' + } + } + } + + It 'does not assume an unconfirmed empty resultant DN means default domain' { + $script:state.Users[0].ResultantPasswordPolicyDN = $null + InModuleScope Maester { Test-MtAdUserEffectivePasswordExpiration | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + } + It 'does not use a per-account never-expire override to satisfy CurrentNist' { + $script:policy.MaxPwdAge = [timespan]::FromDays(90) + $script:state.Users[0].PasswordNeverExpires = $true + InModuleScope Maester { Test-MtAdUserEffectivePasswordExpiration -PolicyInventoryReadAccessConfirmed $true | Should -BeFalse } + } + It 'reports current-profile account overrides for investigation when the effective policy is valid' { + $script:state.Users[0].PasswordNeverExpires = $true + InModuleScope Maester { Test-MtAdUserEffectivePasswordExpiration -PolicyInventoryReadAccessConfirmed $true | Should -BeTrue } + Should -Invoke Add-MtTestResultDetail -ModuleName Maester -ParameterFilter { $Investigate } + } + It 'retains known policy failures when another user has unconfirmed default-policy visibility' { + $script:policy.MaxPwdAge = [timespan]::FromDays(90) + $script:state.Users += [pscustomobject]@{ Name = 'Unknown default'; Enabled = $true; PasswordNeverExpires = $false; ResultantPasswordPolicyDN = $null } + InModuleScope Maester { Test-MtAdUserEffectivePasswordExpiration | Should -BeFalse } + } + + It 'observes enabled complexity under CurrentNist instead of failing it' { + $script:policy.ComplexityEnabled = $true + InModuleScope Maester { Test-MtAdDefaultPasswordPolicySecurity | Should -BeTrue } + InModuleScope Maester { Test-MtAdFineGrainedPasswordPolicySecurity -Instance $script:settingsInstance -PolicyInventoryReadAccessConfirmed $true | Should -BeTrue } + (Test-MtAdPasswordPolicyConfiguration -Policy $script:policy).Rows -join ' ' | Should -Match 'ComplexityEnabled.*Observe' + } +} + +Describe 'Normalized AD password-policy batch' { + It 'assesses current profile without decoding FGPP PwdProperties or requiring composition rules' { + $result = Test-MtAdPasswordPolicyConfiguration -Policy (Get-MockPasswordPolicy) + $result.Passed | Should -BeTrue + ($result.Rows -join ' ') | Should -Match 'Observe' + } + + It 'assesses explicit legacy defaults independently from current NIST' { + $result = Test-MtAdPasswordPolicyConfiguration -Policy (Get-MockPasswordPolicy -Length 14 -Age 90) -Profile LegacyRotation + $result.Passed | Should -BeFalse + (Test-MtAdPasswordPolicyConfiguration -Policy (Get-MockPasswordPolicy -Length 14 -Age 90) -Profile LegacyRotation -Fields @('MinPwdLength', 'MaxPwdAge')).Passed | Should -BeTrue + } + + It 'accepts zero lockout duration as manual administrator unlock' { + $policy = Get-MockPasswordPolicy + $policy.LockoutDuration = [timespan]::Zero + (Test-MtAdPasswordPolicyConfiguration -Policy $policy).Passed | Should -BeTrue + } + + It 'does not turn a missing field into a false or zero' { + $policy = Get-MockPasswordPolicy + $policy.ComplexityEnabled = $null + { Test-MtAdPasswordPolicyConfiguration -Policy $policy } | Should -Throw '*ComplexityEnabled*' + } + + It 'uses actual computed resultant policy rather than direct targets' { + $policy = Get-MockPasswordPolicy + $users = @([pscustomobject]@{ Name = 'Alex'; Enabled = $true; ResultantPasswordPolicyDN = $policy.DistinguishedName }) + (Get-MtAdPasswordPolicyUsage -Users $users -Policies @($policy)).Counts[$policy.DistinguishedName] | Should -Be 1 + } + + It 'rejects missing and unknown resultant policy attributes' { + $policy = Get-MockPasswordPolicy + { Get-MtAdPasswordPolicyUsage -Users @([pscustomobject]@{ Name = 'Alex'; Enabled = $true }) -Policies @($policy) } | Should -Throw '*ResultantPasswordPolicyDN*' + { Get-MtAdPasswordPolicyUsage -Users @([pscustomobject]@{ Name = 'Alex'; Enabled = $true; ResultantPasswordPolicyDN = 'CN=unknown' }) -Policies @($policy) } | Should -Throw '*absent*' + } +} diff --git a/powershell/tests/functions/ADResultPresentation.Tests.ps1 b/powershell/tests/functions/ADResultPresentation.Tests.ps1 new file mode 100644 index 0000000000..336f664e8c --- /dev/null +++ b/powershell/tests/functions/ADResultPresentation.Tests.ps1 @@ -0,0 +1,20 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force +} + +Describe 'AD assessment summary tables' { + It 'preserves field order, zero and false values, and escapes table cells' { + InModuleScope Maester { + $table = Format-MtAdSummaryTable -Values ([ordered]@{ + 'First | metric' = 0 + 'Enabled' = $false + 'Label' = "