-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRootDC-GPO-Cleaner.ps1
More file actions
334 lines (282 loc) · 10.9 KB
/
RootDC-GPO-Cleaner.ps1
File metadata and controls
334 lines (282 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
<#
.SYNOPSIS
RootDC-GPO-Cleaner — audit and optional remediation for GPO hygiene at scale.
.REQUIREMENTS
- Windows PowerShell 5.1+ or PowerShell 7 with WindowsCompatibility
- RSAT: ActiveDirectory, GroupPolicy modules
- Domain auth with read access to Sysvol/AD and GPO ACLs
.USAGE
# Audit only
.\RootDC-GPO-Cleaner.ps1 -ExportPath C:\Reports -CountryFilter FRA,POL,ESP
# Audit + generate remediation script (no changes now)
.\RootDC-GPO-Cleaner.ps1 -ExportPath C:\Reports -CountryFilter FRA -GenerateRemediation
.NOTES
Conventions enforced (from RootDC.io):
- Only process GPOs whose DisplayName starts with a country trigram: ^([A-Z]{3})_
- Allowed baseline trustees (delegation):
Authenticated Users (Read only is tolerated)
Domain Admins
Enterprise Admins
Enterprise Domain Controllers
SYSTEM
XXX_GS_T1_* # country-scoped Tier1 groups
GG_GPO_XXX_* # central GPO admin groups per country
GRP_GL_Admin_<CountryFull> # optional naming
- Column “Country” is populated with the trigram. No “UNK”.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string] $ExportPath,
# Process only these country trigrams. If empty, process all matching ^[A-Z]{3}_.
[string[]] $CountryFilter = @(),
# If set, write a remediation script that can fix delegations and disable stale GPOs.
[switch] $GenerateRemediation
)
# -------------------- Guardrails --------------------
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
function Test-Module {
param([string]$Name)
if (-not (Get-Module -ListAvailable -Name $Name)) {
throw "Module '$Name' not found. Install RSAT component containing $Name."
}
}
Test-Module -Name ActiveDirectory
Test-Module -Name GroupPolicy
Import-Module ActiveDirectory -ErrorAction Stop
Import-Module GroupPolicy -ErrorAction Stop
# Ensure export path
$null = New-Item -ItemType Directory -Path $ExportPath -Force
# -------------------- Helpers --------------------
function Get-CountryFromName {
param([string]$DisplayName)
$m = [regex]::Match($DisplayName, '^(?<cc>[A-Z]{3})_')
if ($m.Success) { return $m.Groups['cc'].Value } else { return $null }
}
# Allowed patterns. Country placeholder ‘XXX’ replaced with actual trigram.
$BaselineAllowed = @(
'^SYSTEM$',
'^Domain Admins$',
'^Enterprise Admins$',
'^Enterprise Domain Controllers$',
'^Authenticated Users$' # Read-only tolerated
)
# Patterns that include the country trigram
$CountryAllowed = @(
'^XXX_GS_T1_.*$',
'^GG_GPO_XXX_.*$',
'^GRP_GL_Admin_.*$' # free-form country full name group
)
# Map effective permission names that imply more than Read
# Get-GPPermissions returns: GpoRead, GpoApply, GpoEdit, GpoEditDeleteModifySecurity
$WriteLike = @('GpoEdit','GpoEditDeleteModifySecurity')
# -------------------- Data shells --------------------
$Audit = New-Object System.Collections.Generic.List[object]
$DelegFindings = New-Object System.Collections.Generic.List[object]
$LinkIssues = New-Object System.Collections.Generic.List[object]
# Collect all GPOs quickly
$allGpos = Get-GPO -All
# Optionally narrow by country prefix
if ($CountryFilter.Count -gt 0) {
$allGpos = $allGpos | Where-Object {
$cc = Get-CountryFromName $_.DisplayName
$cc -and ($CountryFilter -contains $cc)
}
} else {
$allGpos = $allGpos | Where-Object { Get-CountryFromName $_.DisplayName }
}
# Preload WMI filters to resolve object names fast
$wmiFiltersById = @{}
try {
foreach ($wf in Get-GPWmiFilter) { $wmiFiltersById[$wf.Id] = $wf }
} catch { } # not fatal
# -------------------- Main loop --------------------
Write-Verbose "Evaluating $($allGpos.Count) GPOs..."
foreach ($g in $allGpos) {
$cc = Get-CountryFromName $g.DisplayName
if (-not $cc) { continue } # enforced rule
# Grab XML once and reuse
$xmlPath = Join-Path $env:TEMP ("gpo_{0}.xml" -f $g.Id)
Get-GPOReport -Guid $g.Id -ReportType Xml -Path $xmlPath
[xml]$gx = Get-Content -LiteralPath $xmlPath -Encoding UTF8
# Determine emptiness by checking for any settings extensions
$hasUserExt = $gx.GPO.User.ExtensionData.Extension -ne $null
$hasCompExt = $gx.GPO.Computer.ExtensionData.Extension -ne $null
$isEmpty = -not ($hasUserExt -or $hasCompExt)
# Links
$links = @()
if ($gx.GPO.LinksTo) {
$links = @($gx.GPO.LinksTo | ForEach-Object {
[pscustomobject]@{
Target = $_.SOMPath
Enabled = [bool]$_.Enabled
NoOverride = [bool]$_.NoOverride
Order = [int]$_.Order
}
})
}
$isUnlinked = ($links.Count -eq 0)
# WMI filter
$wmi = $null
if ($gx.GPO.FilterName -and $gx.GPO.FilterId) {
$wmi = [pscustomobject]@{
Id = $gx.GPO.FilterId
Name = $gx.GPO.FilterName
}
}
# Delegation and security filtering
$perms = Get-GPPermissions -Guid $g.Id -All
# Build set of Security Filtering subjects (Apply Group Policy permission)
$securityFiltering = $perms | Where-Object { $_.Permission -eq 'GpoApply' } | Select-Object -ExpandProperty Trustee | Sort-Object -Unique
# Evaluate unexpected trustees
$unexpected = New-Object System.Collections.Generic.List[string]
# Build allowed regexes for this country
$allowed = @()
$allowed += $BaselineAllowed
foreach ($p in $CountryAllowed) {
$allowed += ($p -replace 'XXX', [regex]::Escape($cc))
}
foreach ($p in $perms) {
$name = $p.Trustee
$perm = $p.Permission
# Unresolved SIDs are exposed as raw SID strings sometimes
$isSid = $false
try { $null = New-Object System.Security.Principal.SecurityIdentifier($name); $isSid = $true } catch { $isSid = $false }
$isAllowedByPattern = $false
foreach ($rx in $allowed) {
if ($name -match $rx) { $isAllowedByPattern = $true; break }
}
$isReadOnly = ($perm -eq 'GpoRead' -or $perm -eq 'GpoApply')
$isWriteLike = $WriteLike -contains $perm
# Rule: read-only entries are tolerated ONLY if they are part of Security Filtering or baseline patterns.
$readIsOk =
($perm -eq 'GpoRead' -and ($name -eq 'Authenticated Users' -or $isAllowedByPattern)) -or
($perm -eq 'GpoApply' -and ($securityFiltering -contains $name))
$violation = $false
if (-not $isAllowedByPattern) {
if ($isWriteLike) { $violation = $true }
elseif (-not $readIsOk) { $violation = $true }
}
if ($violation) {
$unexpected.Add($name)
$DelegFindings.Add([pscustomobject]@{
GpoName = $g.DisplayName
Country = $cc
GpoId = $g.Id
Trustee = $name
Permission = $perm
InSecurityFilter = ($securityFiltering -contains $name)
Note = $(if ($isSid) { 'Unresolved SID or external principal' } else { 'Non-standard principal' })
})
}
}
# Disabled halves
$disabledState = switch ($g.GpoStatus) {
'AllSettingsEnabled' { 'Enabled' }
'UserSettingsDisabled' { 'UserDisabled' }
'ComputerSettingsDisabled' { 'ComputerDisabled' }
'AllSettingsDisabled' { 'Disabled' }
default { $g.GpoStatus }
}
# Build audit row
$Audit.Add([pscustomobject]@{
Country = $cc
GpoName = $g.DisplayName
GpoId = $g.Id
Owner = $gx.GPO.SecurityDescriptor.Owner.Name
Created = [datetime]$g.CreationTime
Modified = [datetime]$g.ModificationTime
Status = $disabledState
HasUserSettings = [bool]$hasUserExt
HasComputerSettings= [bool]$hasCompExt
IsEmpty = [bool]$isEmpty
IsUnlinked = [bool]$isUnlinked
WmiFilter = $(if ($wmi) { $wmi.Name } else { '' })
LinkCount = $links.Count
UnexpectedObjects = ($unexpected -join '; ')
})
# Link issues table for quick triage
if ($isUnlinked -or $isEmpty) {
$LinkIssues.Add([pscustomobject]@{
Country = $cc
GpoName = $g.DisplayName
GpoId = $g.Id
Reason = @(
$(if ($isUnlinked) { 'Unlinked' }),
$(if ($isEmpty) { 'Empty' })
) -join '+'
Status = $disabledState
})
}
}
# -------------------- Exports --------------------
$ts = Get-Date -Format 'yyyyMMdd_HHmmss'
$pathAudit = Join-Path $ExportPath "GPO_Audit_$ts.csv"
$pathDeleg = Join-Path $ExportPath "GPO_DelegationFindings_$ts.csv"
$pathLink = Join-Path $ExportPath "GPO_LinkIssues_$ts.csv"
$pathRemed = Join-Path $ExportPath "GPO_Remediation_$ts.ps1"
$Audit | Sort-Object Country,GpoName | Export-Csv -NoTypeInformation -Encoding UTF8 -Path $pathAudit
$DelegFindings| Sort-Object Country,GpoName,Trustee| Export-Csv -NoTypeInformation -Encoding UTF8 -Path $pathDeleg
$LinkIssues | Sort-Object Country,GpoName | Export-Csv -NoTypeInformation -Encoding UTF8 -Path $pathLink
Write-Host "Reports:" -ForegroundColor Cyan
Write-Host " - $pathAudit"
Write-Host " - $pathDeleg"
Write-Host " - $pathLink"
# -------------------- Optional remediation generator --------------------
if ($GenerateRemediation) {
@"
<# Autogenerated remediation — review before execution.
- Removes all UnexpectedObjects from each GPO ACL.
- Disables GPOs that are Empty+Unlinked.
- Safe by default: -WhatIf on every change. Remove -WhatIf after review.
#>
param([switch]`$Execute) # when used, removes -WhatIf from calls
Import-Module GroupPolicy
`$audit = Import-Csv '$pathAudit'
`$deleg = Import-Csv '$pathDeleg'
# 1) Fix delegations
`$groupsByGpo = `$deleg | Group-Object GpoId
foreach (`$g in `$groupsByGpo) {
`$gid = `$g.Name
`$toRemove = `$g.Group | Select-Object -ExpandProperty Trustee -Unique
foreach (`$t in `$toRemove) {
try {
if (`$Execute) {
Set-GPPermissions -Guid `$gid -TargetName `$t -TargetType Group -Permission None
} else {
Set-GPPermissions -Guid `$gid -TargetName `$t -TargetType Group -Permission None -WhatIf
}
} catch {
# Try as user in case trustee is a user
try {
if (`$Execute) {
Set-GPPermissions -Guid `$gid -TargetName `$t -TargetType User -Permission None
} else {
Set-GPPermissions -Guid `$gid -TargetName `$t -TargetType User -Permission None -WhatIf
}
} catch {
Write-Warning "Could not remove trustee [`$t] from GPO [`$gid]: `$($_.Exception.Message)"
}
}
}
}
# 2) Disable empty and unlinked
`$toDisable = `$audit | Where-Object { `$_.IsEmpty -eq 'True' -and `$_.IsUnlinked -eq 'True' -and `$_.Status -ne 'Disabled' }
foreach (`$row in `$toDisable) {
try {
if (`$Execute) {
Set-GPO -Guid `$row.GpoId -Status AllSettingsDisabled
} else {
Set-GPO -Guid `$row.GpoId -Status AllSettingsDisabled -WhatIf
}
} catch {
Write-Warning "Could not disable GPO [`$($row.GpoName)]: `$($_.Exception.Message)"
}
}
Write-Host "Remediation plan complete." -ForegroundColor Green
"@ | Set-Content -Path $pathRemed -Encoding UTF8
Write-Host "Remediation script: $pathRemed"
}
Write-Host "Done." -ForegroundColor Green