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..0d079f3575 --- /dev/null +++ b/powershell/internal/checks/ad/ad/Get-MtAdCertificateInventory.ps1 @@ -0,0 +1,61 @@ +function Get-MtAdCertificateInventory { + [CmdletBinding()] + [OutputType([object[]])] + param( + [Parameter(Mandatory)] $Configuration, + + [switch] $IncludeRawData + ) + + $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 ($raw -is [array] -and $raw.Count -gt 0 -and @($raw | Where-Object { $_ -isnot [byte] }).Count -eq 0) { + # A single LDAP binary attribute can be projected as an object array of bytes. + $values.Add([byte[]]$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 [array] -and $value.Count -gt 0 -and @($value | Where-Object { $_ -isnot [byte] }).Count -eq 0) { + # Each value of a multi-valued LDAP binary attribute can also be projected as an object array of bytes. + [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) + $row = [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' } + } + if ($IncludeRawData) { $row | Add-Member -NotePropertyName RawData -NotePropertyValue $cert.RawData } + $rows += $row + } 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/Get-MtAdNtAuthCertificatePath.ps1 b/powershell/internal/services/ad/Get-MtAdNtAuthCertificatePath.ps1 new file mode 100644 index 0000000000..f89c2c73c6 --- /dev/null +++ b/powershell/internal/services/ad/Get-MtAdNtAuthCertificatePath.ps1 @@ -0,0 +1,122 @@ +function Get-MtAdNtAuthCertificatePath { + <# + .SYNOPSIS + Builds offline NTAuth CA certificate paths using the published AD CA inventory. + #> + [CmdletBinding()] + [OutputType([PSCustomObject])] + param( + [Parameter(Mandatory)] [AllowNull()] [PSCustomObject] $Configuration + ) + + $config = Get-MtAdConfigurationInventory -State ([pscustomobject]@{ Configuration = $Configuration }) -Required NtAuthCertificates + $hasCertificate = $false + foreach ($entry in @($config.NtAuthCertificates)) { + if ($null -eq $entry -or $null -eq $entry.PSObject.Properties['cACertificate']) { + throw 'NTAuth certificate attributes were not collected.' + } + if ($entry.cACertificate -is [byte[]] -or $entry.cACertificate -is [string] -or + ($null -ne $entry.cACertificate -and @($entry.cACertificate).Count -gt 0)) { $hasCertificate = $true } + } + if (-not $hasCertificate) { return } + + $roles = @('EnterpriseCAs', 'TrustedRootCAs', 'IntermediateCAs', 'NtAuthCertificates') + $config = Get-MtAdConfigurationInventory -State ([pscustomobject]@{ Configuration = $config }) -Required $roles + foreach ($role in $roles) { + foreach ($entry in @($config.$role)) { + if ($null -eq $entry -or $null -eq $entry.PSObject.Properties['cACertificate']) { + throw "Published $role certificate attributes were not collected." + } + } + } + + # Reuse the parser and binary-value handling of AD-CFG-15/21, retaining only public DER data. + $records = @(Get-MtAdCertificateInventory -Configuration $config -IncludeRawData) + $certificates = @{} + $roots = @{} + $targets = @{} + try { + foreach ($record in $records) { + $cert = [Security.Cryptography.X509Certificates.X509Certificate2]::new([byte[]]$record.RawData) + $id = $cert.GetCertHashString([Security.Cryptography.HashAlgorithmName]::SHA256) + if ($certificates.ContainsKey($id)) { $cert.Dispose() } + else { $certificates[$id] = $cert } + if ($record.Role -eq 'Trusted root') { $roots[$id] = $true } + if ($record.Role -eq 'NTAuth') { $targets[$id] = $record } + } + + foreach ($id in @($targets.Keys | Sort-Object)) { + $cert = $certificates[$id] + $chain = [Security.Cryptography.X509Certificates.X509Chain]::new() + try { + $policy = $chain.ChainPolicy + $policy.TrustMode = [Security.Cryptography.X509Certificates.X509ChainTrustMode]::CustomRootTrust + $policy.DisableCertificateDownloads = $true + $policy.RevocationMode = [Security.Cryptography.X509Certificates.X509RevocationMode]::NoCheck + $policy.VerificationFlags = [Security.Cryptography.X509Certificates.X509VerificationFlags]::NoFlag + foreach ($rootId in $roots.Keys) { [void]$policy.CustomTrustStore.Add($certificates[$rootId]) } + foreach ($known in $certificates.Values) { [void]$policy.ExtraStore.Add($known) } + + $built = $chain.Build($cert) + $issues = [Collections.Generic.List[string]]::new() + foreach ($status in $chain.ChainStatus) { $issues.Add($status.Status.ToString()) } + $path = @($chain.ChainElements | ForEach-Object { + [pscustomobject]@{ + Subject = $_.Certificate.Subject + Thumbprint = $_.Certificate.Thumbprint + CertificateId = $_.Certificate.GetCertHashString([Security.Cryptography.HashAlgorithmName]::SHA256) + } + }) + + # Custom roots prevent ambient root trust; this also rejects intermediates supplied by OS caches. + $unpublished = @($path | Where-Object { -not $certificates.ContainsKey($_.CertificateId) }) + if ($unpublished.Count -gt 0) { $issues.Add('PathUsesCertificateOutsidePublishedInventory') } + $root = if ($path.Count -gt 0 -and $roots.ContainsKey($path[-1].CertificateId)) { $path[-1] } else { $null } + if ($null -eq $root) { $issues.Add('NoPublishedTrustAnchor') } + + # Build treats its input as an end certificate, so explicitly require an NTAuth CA certificate. + $basic = $cert.Extensions | Where-Object { $_.Oid.Value -eq '2.5.29.19' } | Select-Object -First 1 + $isCa = $null -ne $basic -and ([Security.Cryptography.X509Certificates.X509BasicConstraintsExtension]::new($basic, $basic.Critical)).CertificateAuthority + if (-not $isCa) { $issues.Add('NtAuthCertificateIsNotCa') } + $usage = $cert.Extensions | Where-Object { $_.Oid.Value -eq '2.5.29.15' } | Select-Object -First 1 + if ($null -ne $usage) { + $keyUsage = ([Security.Cryptography.X509Certificates.X509KeyUsageExtension]::new($usage, $usage.Critical)).KeyUsages + if (($keyUsage -band [Security.Cryptography.X509Certificates.X509KeyUsageFlags]::KeyCertSign) -eq 0) { $issues.Add('NtAuthCertificateCannotSignCertificates') } + } + + # The chain engine treats the target as an end entity. Include a non-self-issued CA + # target when checking the number of subordinate CAs allowed by issuer constraints. + $subordinateCas = 0 + foreach ($element in $chain.ChainElements) { + $constraints = $element.Certificate.Extensions | Where-Object { $_.Oid.Value -eq '2.5.29.19' } | Select-Object -First 1 + if ($null -ne $constraints) { + $decoded = [Security.Cryptography.X509Certificates.X509BasicConstraintsExtension]::new($constraints, $constraints.Critical) + if ($decoded.HasPathLengthConstraint -and $subordinateCas -gt $decoded.PathLengthConstraint) { + $issues.Add('CaPathLengthConstraintExceeded') + } + if ($decoded.CertificateAuthority -and $element.Certificate.Subject -ne $element.Certificate.Issuer) { $subordinateCas++ } + } + } + + $verified = $built -and $issues.Count -eq 0 + [pscustomobject]@{ + Subject = $cert.Subject + Thumbprint = $cert.Thumbprint + CertificateId = $id + Verified = $verified + Status = if ($verified) { 'Verified' } else { 'NotVerified' } + Issues = @($issues.ToArray() | Sort-Object -Unique) + RootSubject = if ($root) { $root.Subject } else { $null } + RootThumbprint = if ($root) { $root.Thumbprint } else { $null } + Path = $path + RevocationChecked = $false + CertificateDownloadsEnabled = $false + } + } finally { + $chain.Dispose() + } + } + } finally { + foreach ($cert in $certificates.Values) { $cert.Dispose() } + } +} 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 ' inventory' -ForEach @( + @{ Property = 'EnterpriseCAs'; Role = 'Enterprise CA' } + @{ Property = 'TrustedRootCAs'; Role = 'Trusted root' } + @{ Property = 'IntermediateCAs'; Role = 'Intermediate' } + @{ Property = 'NtAuthCertificates'; Role = 'NTAuth' } + ) { + BeforeEach { + $script:projectionConfiguration = [pscustomobject]@{ + EnterpriseCAs = @(); TrustedRootCAs = @(); IntermediateCAs = @(); NtAuthCertificates = @() + } + } + + It 'accepts a single DER value projected as an object array of bytes' { + $script:projectionConfiguration.$Property = @([pscustomobject]@{ Name = 'Projected CA'; cACertificate = [object[]]$script:certBytes }) + $rows = @(Get-MtAdCertificateInventory -Configuration $script:projectionConfiguration) + $rows.Count | Should -Be 1 + $rows[0].Role | Should -Be $Role + $rows[0].Thumbprint | Should -Not -BeNullOrEmpty + $rows[0].PSObject.Properties.Name | Should -Not -Contain RawData + } + + It 'retains multiple projected DER values on one directory object' { + $values = [Collections.Generic.List[object]]::new() + $values.Add([object[]]$script:certBytes) + $values.Add([object[]]$script:certBytes) + $script:projectionConfiguration.$Property = @([pscustomobject]@{ Name = 'Two certificates'; cACertificate = $values.ToArray() }) + $rows = @(Get-MtAdCertificateInventory -Configuration $script:projectionConfiguration) + $rows.Count | Should -Be 2 + @($rows | Where-Object Role -EQ $Role).Count | Should -Be 2 + } + + It 'rejects non-byte content alongside a valid projected certificate' { + $values = [Collections.Generic.List[object]]::new() + $values.Add([object[]]$script:certBytes) + $values.Add(@([byte]1, 'unexpected value')) + $script:projectionConfiguration.$Property = @([pscustomobject]@{ Name = 'Mixed input'; cACertificate = $values.ToArray() }) + { Get-MtAdCertificateInventory -Configuration $script:projectionConfiguration } | Should -Throw '*Unsupported certificate value*' + } + + It 'rejects malformed DER alongside a valid projected certificate' { + $values = [Collections.Generic.List[object]]::new() + $values.Add([object[]]$script:certBytes) + $values.Add([object[]][byte[]](1, 2, 3)) + $script:projectionConfiguration.$Property = @([pscustomobject]@{ Name = 'Malformed input'; cACertificate = $values.ToArray() }) + { Get-MtAdCertificateInventory -Configuration $script:projectionConfiguration } | Should -Throw '*Unable to parse public certificate*' + } + } + + It 'distinguishes missing data from a retrieved empty collection' { + $state = [pscustomobject]@{ Configuration = [pscustomobject]@{ SiteLinks = @() } } + @(Get-MtAdConfigurationInventory -State $state -Required SiteLinks).Count | Should -Be 1 + { Get-MtAdConfigurationInventory -State $state -Required CertificateTemplates } | Should -Throw '*unavailable*' + } + + It 'classifies transport by parent DN and retains zero cost' { + $config = [pscustomobject]@{ SiteLinks = @( + [pscustomobject]@{ Name = 'A'; DistinguishedName = 'CN=A,CN=SMTP,CN=Inter-Site Transports,CN=Sites,DC=test'; cost = 0; ReplicationFrequencyInMinutes = 15; siteList = @('CN=Site1') }, + [pscustomobject]@{ Name = 'B'; DistinguishedName = 'CN=B,CN=IP,CN=Inter-Site Transports,CN=Sites,DC=test'; cost = 10; ReplicationFrequencyInMinutes = $null; siteList = @() } + ) } + $links = @(Get-MtAdConfigurationInventorySiteLinkTransport -Configuration $config) + $links[0].Transport | Should -Be 'SMTP' + $links[0].Cost | Should -Be 0 + $links[1].Transport | Should -Be 'IP' + } + + It 'escapes Markdown table markup and HTML in directory values' { + (ConvertTo-MtAdConfigurationInventoryCell "bad|