-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSetup-BitLockerMonitorGmsa.ps1
More file actions
443 lines (392 loc) · 20.5 KB
/
Copy pathSetup-BitLockerMonitorGmsa.ps1
File metadata and controls
443 lines (392 loc) · 20.5 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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
<#
.SYNOPSIS
Creates a gMSA account for BitLockerKeyMonitor and configures all required permissions.
.DESCRIPTION
This script must be run on a domain-joined machine with the ActiveDirectory PowerShell
module and Domain Admin privileges. It performs the following:
1. Ensures a KDS Root Key exists (required for gMSA)
2. Creates the gMSA account (svc-BlkMon$)
3. Grants the gMSA read permissions on msFVE-RecoveryInformation objects
AND the ExtendedRight on the confidential msFVE-RecoveryPassword attribute
(without ExtendedRight, AD silently omits the password from LDAP results)
3b. Registers HTTP SPNs on the gMSA (needed for Kerberos auth on the Web)
4. Installs the gMSA on the target server
5. Creates a SQL Server login with db_owner on the application database
6. Grants the gMSA "Log on as a service" right
7. Grants the gMSA read access to certificate private keys (Entra auth + Kestrel HTTPS)
8. Configures the Worker and Web services to run as the gMSA
NOTE: Uses AD PowerShell ACL cmdlets instead of dsacls (which is only available on DCs).
.PARAMETER TargetServer
The server where BitLockerKeyMonitor services are installed. Default: SRVBLKMON01
.PARAMETER GmsaName
Name for the gMSA account (without trailing $). Default: svc-BlkMon
.PARAMETER DomainDnsName
Domain DNS name. Default: MSLABS.LOCAL
.PARAMETER SearchBaseOUs
One or more OUs where BitLocker recovery keys should be readable.
Default: "OU=Clients,OU=Computers,OU=LAB,DC=MSLABS,DC=LOCAL"
.PARAMETER SqlInstance
SQL Server instance for the application database. Default: ".\SQLEXPRESS"
.PARAMETER DatabaseName
Application database name. Default: "BitLockerKeyMonitor"
.PARAMETER CertificateThumbprints
Thumbprints of certificates whose private keys the gMSA needs to read
(e.g. Entra client certificate, Kestrel HTTPS certificate).
.PARAMETER DomainController
DC to target for AD operations. If omitted, auto-discovers.
.PARAMETER LabMode
Creates the KDS Root Key with -EffectiveTime in the past (no 10-hour wait).
Use only in lab/test environments.
.EXAMPLE
.\Setup-BitLockerMonitorGmsa.ps1
# Uses all defaults for MSLABS environment
.EXAMPLE
.\Setup-BitLockerMonitorGmsa.ps1 -TargetServer "SRV01" -GmsaName "svc-BLK" `
-SearchBaseOUs @("OU=Workstations,DC=contoso,DC=com") `
-CertificateThumbprints @("ae803d83...", "855cdf61...")
#>
[CmdletBinding()]
param(
[string]$TargetServer = "SRVBLKMON01",
[string]$GmsaName = "svc-BlkMon",
[string]$DomainDnsName = "MSLABS.LOCAL",
[string[]]$SearchBaseOUs = @("OU=Clients,OU=Computers,OU=LAB,DC=MSLABS,DC=LOCAL"),
[string]$SqlInstance = ".\SQLEXPRESS",
[string]$DatabaseName = "BitLockerKeyMonitor",
[string[]]$CertificateThumbprints = @(),
[string]$DomainController,
[switch]$LabMode
)
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
Import-Module ActiveDirectory
$gmsaSamAccountName = "$GmsaName`$"
$domainNetBios = $DomainDnsName.Split('.')[0]
$gmsaLogonIdentity = "$domainNetBios\$gmsaSamAccountName"
$dcParam = @{}
if ($DomainController) { $dcParam.Server = $DomainController }
Write-Host ""
Write-Host "=== BitLockerKeyMonitor gMSA Setup ===" -ForegroundColor Cyan
Write-Host " gMSA Name : $gmsaSamAccountName"
Write-Host " Target Server : $TargetServer"
Write-Host " Domain : $DomainDnsName"
Write-Host " Search OUs : $($SearchBaseOUs -join ', ')"
Write-Host " SQL Instance : $SqlInstance"
Write-Host " Database : $DatabaseName"
Write-Host ""
# --------------------------------------------------------------------------
# Step 1: Ensure KDS Root Key
# --------------------------------------------------------------------------
Write-Host "[1/8] Checking KDS Root Key..." -ForegroundColor Yellow
$kdsKeys = Get-KdsRootKey @dcParam -ErrorAction SilentlyContinue
if (-not $kdsKeys -or $kdsKeys.Count -eq 0) {
Write-Host " No KDS Root Key found. Creating one..." -ForegroundColor Yellow
if ($LabMode) {
# Effective immediately (no 10-hour replication wait)
Add-KdsRootKey -EffectiveTime ((Get-Date).AddHours(-10)) @dcParam | Out-Null
Write-Host " KDS Root Key created (lab mode)" -ForegroundColor Green
} else {
Add-KdsRootKey -EffectiveImmediately @dcParam | Out-Null
Write-Host " KDS Root Key created (allow up to 10 hours for replication)" -ForegroundColor Green
}
} else {
Write-Host " KDS Root Key exists [OK]" -ForegroundColor Green
}
# --------------------------------------------------------------------------
# Step 2: Create gMSA
# --------------------------------------------------------------------------
Write-Host "[2/8] Creating gMSA '$gmsaSamAccountName'..." -ForegroundColor Yellow
$existingGmsa = Get-ADServiceAccount -Filter "Name -eq '$GmsaName'" @dcParam -ErrorAction SilentlyContinue
if ($existingGmsa) {
Write-Host " gMSA already exists [OK]" -ForegroundColor Green
} else {
$computer = Get-ADComputer $TargetServer @dcParam
New-ADServiceAccount `
-Name $GmsaName `
-DNSHostName "$GmsaName.$DomainDnsName" `
-PrincipalsAllowedToRetrieveManagedPassword $computer `
-Description "Service account for BitLockerKeyMonitor Worker and Web services" `
-Enabled $true `
@dcParam
Write-Host " gMSA created [OK]" -ForegroundColor Green
}
# Ensure the target server can retrieve the managed password
$gmsa = Get-ADServiceAccount $GmsaName -Properties PrincipalsAllowedToRetrieveManagedPassword @dcParam
$computer = Get-ADComputer $TargetServer @dcParam
$currentPrincipals = @($gmsa.PrincipalsAllowedToRetrieveManagedPassword)
if ($computer.DistinguishedName -notin $currentPrincipals) {
Set-ADServiceAccount $GmsaName `
-PrincipalsAllowedToRetrieveManagedPassword @($currentPrincipals + $computer.DistinguishedName) `
@dcParam
Write-Host " Added $TargetServer to PrincipalsAllowedToRetrieveManagedPassword [OK]" -ForegroundColor Green
} else {
Write-Host " $TargetServer already in PrincipalsAllowedToRetrieveManagedPassword [OK]" -ForegroundColor Green
}
# --------------------------------------------------------------------------
# Step 3: Grant AD permissions on msFVE-RecoveryInformation via AD ACLs
# Uses the ActiveDirectory PowerShell module (works on any domain member).
# --------------------------------------------------------------------------
Write-Host "[3/8] Granting AD permissions on msFVE-RecoveryInformation..." -ForegroundColor Yellow
$gmsaAccount = Get-ADServiceAccount $GmsaName -Properties SID @dcParam
$gmsaSid = New-Object System.Security.Principal.SecurityIdentifier($gmsaAccount.SID)
# Look up schema GUIDs for the msFVE classes/attributes
$rootDse = [ADSI]"LDAP://RootDSE"
$schemaPath = "LDAP://$($rootDse.schemaNamingContext)"
$searcher = New-Object DirectoryServices.DirectorySearcher([ADSI]$schemaPath)
$searcher.Filter = "(&(objectClass=classSchema)(lDAPDisplayName=msFVE-RecoveryInformation))"
$searcher.PropertiesToLoad.Add("schemaIDGUID") | Out-Null
$classResult = $searcher.FindOne()
$classGuid = New-Object Guid(,$classResult.Properties["schemaidguid"][0])
$searcher.Filter = "(&(objectClass=attributeSchema)(lDAPDisplayName=msFVE-RecoveryPassword))"
$attrResult = $searcher.FindOne()
$attrGuid = New-Object Guid(,$attrResult.Properties["schemaidguid"][0])
Write-Host " msFVE-RecoveryInformation GUID: $classGuid"
Write-Host " msFVE-RecoveryPassword GUID: $attrGuid"
foreach ($ou in $SearchBaseOUs) {
Write-Host " Delegating on: $ou"
$adPath = "AD:\$ou"
$acl = Get-Acl $adPath
# GenericRead on msFVE-RecoveryInformation descendant objects
$ace1 = New-Object System.DirectoryServices.ActiveDirectoryAccessRule(
$gmsaSid,
[System.DirectoryServices.ActiveDirectoryRights]::GenericRead,
[System.Security.AccessControl.AccessControlType]::Allow,
[DirectoryServices.ActiveDirectorySecurityInheritance]::Descendents,
$classGuid
)
$acl.AddAccessRule($ace1)
Write-Host " GenericRead on msFVE-RecoveryInformation [OK]" -ForegroundColor Green
# ReadProperty on msFVE-RecoveryPassword attribute, scoped to msFVE-RecoveryInformation objects
$ace2 = New-Object System.DirectoryServices.ActiveDirectoryAccessRule(
$gmsaSid,
[System.DirectoryServices.ActiveDirectoryRights]::ReadProperty,
[System.Security.AccessControl.AccessControlType]::Allow,
$attrGuid,
[DirectoryServices.ActiveDirectorySecurityInheritance]::Descendents,
$classGuid
)
$acl.AddAccessRule($ace2)
Write-Host " ReadProperty on msFVE-RecoveryPassword [OK]" -ForegroundColor Green
# CRITICAL: msFVE-RecoveryPassword is a CONFIDENTIAL attribute (searchFlags 0x80).
# Confidential attributes are NOT returned by AD unless the caller has the
# ExtendedRight (Control Access) permission, EVEN IF ReadProperty is granted.
# Without this ACE, LDAP queries silently omit the attribute and the
# consistency check reports "Value comparison NOT performed".
$ace3 = New-Object System.DirectoryServices.ActiveDirectoryAccessRule(
$gmsaSid,
[System.DirectoryServices.ActiveDirectoryRights]::ExtendedRight,
[System.Security.AccessControl.AccessControlType]::Allow,
$attrGuid,
[DirectoryServices.ActiveDirectorySecurityInheritance]::Descendents,
$classGuid
)
$acl.AddAccessRule($ace3)
Write-Host " ExtendedRight on msFVE-RecoveryPassword (confidential attr) [OK]" -ForegroundColor Green
Set-Acl $adPath $acl
Write-Host " ACL applied [OK]" -ForegroundColor Green
}
# --------------------------------------------------------------------------
# Step 3b: Register HTTP SPNs on the gMSA
# Required for Negotiate/Kerberos authentication on the Web portal when it
# runs as the gMSA (otherwise browsers fall back to a broken state).
# --------------------------------------------------------------------------
Write-Host "[3b/8] Registering HTTP SPNs on the gMSA..." -ForegroundColor Yellow
$spns = @(
"HTTP/$TargetServer",
"HTTP/$TargetServer.$DomainDnsName"
)
$gmsaCurrent = Get-ADServiceAccount $GmsaName -Properties servicePrincipalName @dcParam
$currentSpns = @($gmsaCurrent.servicePrincipalName)
foreach ($spn in $spns) {
if ($currentSpns -contains $spn) {
Write-Host " SPN already present: $spn [OK]" -ForegroundColor Green
} else {
Set-ADServiceAccount $GmsaName -ServicePrincipalNames @{Add=$spn} @dcParam
Write-Host " Added SPN: $spn [OK]" -ForegroundColor Green
}
}
# --------------------------------------------------------------------------
# Step 4: Install gMSA on target server
# --------------------------------------------------------------------------
Write-Host "[4/8] Installing gMSA on $TargetServer..." -ForegroundColor Yellow
try {
$testResult = Invoke-Command -ComputerName $TargetServer -ScriptBlock {
param($name)
Import-Module ActiveDirectory
Install-ADServiceAccount -Identity $name
Test-ADServiceAccount -Identity $name
} -ArgumentList $GmsaName -ErrorAction Stop
if ($testResult) {
Write-Host " gMSA installed and verified [OK]" -ForegroundColor Green
} else {
Write-Host " gMSA installed but Test-ADServiceAccount returned false" -ForegroundColor Yellow
}
} catch {
Write-Host " Remote install failed: $($_.Exception.Message)" -ForegroundColor Yellow
Write-Host " Run manually on ${TargetServer}:" -ForegroundColor Yellow
Write-Host " Install-ADServiceAccount -Identity $GmsaName" -ForegroundColor White
Write-Host " Test-ADServiceAccount -Identity $GmsaName" -ForegroundColor White
}
# --------------------------------------------------------------------------
# Step 5: Create SQL Server login and database user
# --------------------------------------------------------------------------
Write-Host "[5/8] Configuring SQL Server permissions..." -ForegroundColor Yellow
try {
Invoke-Command -ComputerName $TargetServer -ScriptBlock {
param($instance, $dbName, $loginName)
$sql = @"
IF NOT EXISTS (SELECT 1 FROM sys.server_principals WHERE name = '$loginName')
CREATE LOGIN [$loginName] FROM WINDOWS;
USE [$dbName];
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE name = '$loginName')
CREATE USER [$loginName] FOR LOGIN [$loginName];
ALTER ROLE db_owner ADD MEMBER [$loginName];
"@
$r = sqlcmd -S $instance -E -C -Q $sql 2>&1
Write-Output $r
} -ArgumentList $SqlInstance, $DatabaseName, $gmsaLogonIdentity -ErrorAction Stop |
ForEach-Object { Write-Host " $_" }
Write-Host " SQL login $gmsaLogonIdentity -> db_owner on $DatabaseName [OK]" -ForegroundColor Green
} catch {
Write-Host " SQL configuration failed: $($_.Exception.Message)" -ForegroundColor Yellow
Write-Host " Run manually on ${TargetServer}:" -ForegroundColor Yellow
Write-Host " CREATE LOGIN [$gmsaLogonIdentity] FROM WINDOWS" -ForegroundColor White
Write-Host " USE [$DatabaseName]; CREATE USER [$gmsaLogonIdentity]; ALTER ROLE db_owner ADD MEMBER [$gmsaLogonIdentity]" -ForegroundColor White
}
# --------------------------------------------------------------------------
# Step 6: Grant "Log on as a service" right
# --------------------------------------------------------------------------
Write-Host "[6/8] Granting 'Log on as a service' right..." -ForegroundColor Yellow
try {
Invoke-Command -ComputerName $TargetServer -ScriptBlock {
param($identity)
$sid = (New-Object System.Security.Principal.NTAccount($identity)).Translate(
[System.Security.Principal.SecurityIdentifier]).Value
secedit /export /cfg C:\Temp\secpol.cfg /quiet
$cfg = Get-Content C:\Temp\secpol.cfg
$line = $cfg | Where-Object { $_ -match "SeServiceLogonRight" }
if ($line -match $sid) {
Write-Output " Already has SeServiceLogonRight"
} else {
$newLine = "$line,*$sid"
$cfg = $cfg -replace [regex]::Escape($line), $newLine
$cfg | Set-Content C:\Temp\secpol.cfg -Encoding Unicode
secedit /configure /db C:\Temp\secpol.sdb /cfg C:\Temp\secpol.cfg /areas USER_RIGHTS /quiet
Write-Output " Granted SeServiceLogonRight"
}
Remove-Item C:\Temp\secpol.cfg, C:\Temp\secpol.sdb -ErrorAction SilentlyContinue
} -ArgumentList $gmsaLogonIdentity -ErrorAction Stop |
ForEach-Object { Write-Host $_ -ForegroundColor Green }
} catch {
Write-Host " Failed to grant Log on as a service: $($_.Exception.Message)" -ForegroundColor Yellow
}
# --------------------------------------------------------------------------
# Step 7: Grant gMSA read access to certificate private keys
# --------------------------------------------------------------------------
Write-Host "[7/8] Granting certificate private key access..." -ForegroundColor Yellow
if ($CertificateThumbprints.Count -eq 0) {
Write-Host " No certificate thumbprints specified -- skipping" -ForegroundColor Gray
Write-Host " (Pass -CertificateThumbprints to grant access to Entra/Kestrel certs)" -ForegroundColor Gray
} else {
try {
Invoke-Command -ComputerName $TargetServer -ScriptBlock {
param($thumbprints, $identity)
foreach ($tp in $thumbprints) {
$cert = Get-ChildItem "Cert:\LocalMachine\My\$tp" -ErrorAction SilentlyContinue
if (-not $cert) {
Write-Output " Cert $tp not found -- skipped"
continue
}
$key = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($cert)
$keyName = $key.Key.UniqueName
$keyPath = "C:\ProgramData\Microsoft\Crypto\Keys\$keyName"
if (-not (Test-Path $keyPath)) {
$keyPath = "C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys\$keyName"
}
if (Test-Path $keyPath) {
$acl = Get-Acl $keyPath
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule(
$identity, "Read", "Allow")
$acl.AddAccessRule($rule)
Set-Acl $keyPath $acl
Write-Output " Granted Read on $($cert.Subject) ($($tp.Substring(0,8))...) [OK]"
} else {
Write-Output " Private key file not found for $tp"
}
}
} -ArgumentList @(,$CertificateThumbprints), $gmsaLogonIdentity -ErrorAction Stop |
ForEach-Object { Write-Host $_ -ForegroundColor Green }
} catch {
Write-Host " Failed: $($_.Exception.Message)" -ForegroundColor Yellow
}
}
# --------------------------------------------------------------------------
# Step 8: Configure services to run as gMSA
# --------------------------------------------------------------------------
Write-Host "[8/8] Configuring services on $TargetServer..." -ForegroundColor Yellow
try {
Invoke-Command -ComputerName $TargetServer -ScriptBlock {
param($identity)
$services = @("BitLockerKeyMonitor.Worker", "BitLockerKeyMonitor.Web")
foreach ($svcName in $services) {
$svc = Get-Service -Name $svcName -ErrorAction SilentlyContinue
if (-not $svc) { Write-Output " $svcName not found -- skip"; continue }
if ($svc.Status -eq 'Running') { Stop-Service $svcName -Force }
# sc.exe requires specific formatting: obj= "DOMAIN\account$" password= ""
$r = cmd.exe /c "sc.exe config `"$svcName`" obj= `"$identity`" password= `"`""
Write-Output " $svcName -> $identity ($r)"
}
# File system permissions
$installDir = "C:\Program Files\BitLockerKeyMonitor"
if (Test-Path $installDir) {
$acl = Get-Acl $installDir
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule(
$identity, "ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)
Set-Acl $installDir $acl
Write-Output " Granted ReadAndExecute on $installDir"
}
$dataDir = "C:\ProgramData\BitLockerKeyMonitor"
if (Test-Path $dataDir) {
$acl = Get-Acl $dataDir
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule(
$identity, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)
Set-Acl $dataDir $acl
Write-Output " Granted FullControl on $dataDir"
}
# Start services
Start-Service BitLockerKeyMonitor.Worker -ErrorAction SilentlyContinue
Start-Sleep -Seconds 5
Start-Service BitLockerKeyMonitor.Web -ErrorAction SilentlyContinue
Start-Sleep -Seconds 3
foreach ($svcName in $services) {
$svc = Get-Service -Name $svcName
Write-Output " $svcName status: $($svc.Status)"
}
} -ArgumentList $gmsaLogonIdentity -ErrorAction Stop |
ForEach-Object { Write-Host $_ -ForegroundColor Green }
} catch {
Write-Host " Remote configuration failed: $($_.Exception.Message)" -ForegroundColor Yellow
Write-Host " Run these on ${TargetServer} manually:" -ForegroundColor Yellow
Write-Host " cmd /c 'sc.exe config ""BitLockerKeyMonitor.Worker"" obj= ""$gmsaLogonIdentity"" password= """"'" -ForegroundColor White
Write-Host " cmd /c 'sc.exe config ""BitLockerKeyMonitor.Web"" obj= ""$gmsaLogonIdentity"" password= """"'" -ForegroundColor White
Write-Host " Restart-Service BitLockerKeyMonitor.Worker, BitLockerKeyMonitor.Web" -ForegroundColor White
}
# --------------------------------------------------------------------------
# Summary
# --------------------------------------------------------------------------
Write-Host ""
Write-Host "=== Setup Complete ===" -ForegroundColor Cyan
Write-Host " gMSA Account : $gmsaLogonIdentity"
Write-Host " Target Server : $TargetServer"
Write-Host " AD Permissions : GenericRead(msFVE-RecoveryInformation) + ReadProperty + ExtendedRight(msFVE-RecoveryPassword)"
Write-Host " HTTP SPNs : HTTP/$TargetServer, HTTP/$TargetServer.$DomainDnsName"
Write-Host " SQL Access : db_owner on $DatabaseName"
Write-Host ""
Write-Host " IMPORTANT: Set AdAuthMode to 'WindowsIntegrated' in Worker appsettings.json" -ForegroundColor Yellow
Write-Host " (the gMSA Kerberos ticket is used automatically for LDAP auth)." -ForegroundColor Yellow
Write-Host ""
Write-Host " Verify:" -ForegroundColor Yellow
Write-Host " Get-Service BitLockerKeyMonitor.Worker, BitLockerKeyMonitor.Web" -ForegroundColor White
Write-Host ""