-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenable-os-bitlocker.ps1
More file actions
409 lines (352 loc) · 16.7 KB
/
Copy pathenable-os-bitlocker.ps1
File metadata and controls
409 lines (352 loc) · 16.7 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
$ErrorActionPreference = "Stop"; $scriptArgs = $args
function ArgValue($name, $defaultValue = "") {
for ($i = 0; $i -lt $scriptArgs.Count; $i++) {
if ($scriptArgs[$i] -in @("-$name", "--$name")) { return $scriptArgs[$i + 1] }
}
return $defaultValue
}
function Flag($name) {
for ($i = 0; $i -lt $scriptArgs.Count; $i++) {
if ($scriptArgs[$i] -in @("-$name", "--$name")) { return $true }
}
return $false
}
function FullPath($path) {
$path = [Environment]::ExpandEnvironmentVariables([string]$path)
if ($path -match '^~[\\/](.*)$') { return (Join-Path $HOME $Matches[1]) }
if ([IO.Path]::IsPathRooted($path)) { return $path }
return (Join-Path $PSScriptRoot $path)
}
function Default($cfg, $name, $value) {
if ($null -eq $cfg.$name) { $cfg | Add-Member -Force NoteProperty $name $value }
}
function Log($scope, $message) {
Write-Host ("[{0}] {1}" -f $scope, $message)
}
function AssertAdministrator {
$principal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
throw "Run this script from PowerShell as Administrator. VM security settings and DVD media changes require an elevated token."
}
}
function SecureText($text) {
$secure = [Security.SecureString]::new()
foreach ($ch in ([string]$text).ToCharArray()) { $secure.AppendChar($ch) }
$secure.MakeReadOnly()
return $secure
}
function PlainTextFromSecureString($secure) {
$bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
try {
[Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr)
} finally {
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
}
}
function StartupPinValue {
$pinFile = ArgValue "startup-pin-file"
if (-not [string]::IsNullOrWhiteSpace($pinFile)) {
return (Get-Content -Raw -LiteralPath (FullPath $pinFile)).Trim()
}
$pin = Read-Host "BitLocker startup PIN for the VM OS disk" -AsSecureString
PlainTextFromSecureString $pin
}
function GuestCredential($cfg) {
$path = Join-Path (FullPath $cfg.baseDir) "credentials.txt"
if (-not (Test-Path -LiteralPath $path)) { throw "Credentials file '$path' was not found." }
$content = Get-Content -LiteralPath $path
$userLine = $content | Where-Object { $_ -match '^User:\s*(.+)$' } | Select-Object -First 1
$passwordLine = $content | Where-Object { $_ -match '^Password:\s*(.+)$' } | Select-Object -First 1
if (-not $userLine -or -not $passwordLine) { throw "Credentials file '$path' does not contain User and Password lines." }
$user = [regex]::Match($userLine, '^User:\s*(.+)$').Groups[1].Value
$password = [regex]::Match($passwordLine, '^Password:\s*(.+)$').Groups[1].Value
[pscredential]::new($user, (SecureText $password))
}
function WaitForVmState($vmName, $state, $timeoutSeconds) {
$deadline = (Get-Date).AddSeconds($timeoutSeconds)
do {
$vm = Get-VM -Name $vmName -ErrorAction Stop
if ($vm.State -eq $state) { return $vm }
Start-Sleep -Seconds 3
} while ((Get-Date) -lt $deadline)
throw "VM '$vmName' did not reach state '$state' within $timeoutSeconds seconds."
}
function WaitForPowerShellDirect($cfg, $credential, $timeoutSeconds) {
$deadline = (Get-Date).AddSeconds($timeoutSeconds)
$lastLog = [datetime]::MinValue
$lastError = ""
do {
$vm = Get-VM -Name $cfg.vmName -ErrorAction Stop
try {
if ($vm.State -ne "Running") {
$lastError = "VM state is '$($vm.State)', not Running"
} else {
Invoke-Command -VMName $cfg.vmName -Credential $credential -ScriptBlock { "ready" } -ErrorAction Stop | Out-Null
Log "vm" "PowerShell Direct is ready"
return
}
} catch {
$lastError = $_.Exception.Message
}
if (((Get-Date) - $lastLog).TotalSeconds -ge 30) {
Log "vm" "Waiting for PowerShell Direct: state=$($vm.State), heartbeat=$($vm.Heartbeat), uptime=$($vm.Uptime), last error=$lastError"
$lastLog = Get-Date
}
Start-Sleep -Seconds 5
} while ((Get-Date) -lt $deadline)
$vm = Get-VM -Name $cfg.vmName -ErrorAction Stop
throw "PowerShell Direct did not become ready for VM '$($cfg.vmName)' within $timeoutSeconds seconds. VM state=$($vm.State), heartbeat=$($vm.Heartbeat), uptime=$($vm.Uptime), last error=$lastError. If the VM is waiting at a BitLocker pre-boot prompt, open Hyper-V Connect and enter the PIN or recovery key."
}
function EnsureVmRunning($cfg, $timeoutSeconds) {
$vm = Get-VM -Name $cfg.vmName -ErrorAction Stop
if ($vm.State -eq "Running") {
Log "vm" "VM '$($cfg.vmName)' is already running"
return
}
if ($vm.State -eq "Paused") {
Log "vm" "Resuming VM '$($cfg.vmName)'"
Resume-VM -Name $cfg.vmName | Out-Null
WaitForVmState $cfg.vmName "Running" $timeoutSeconds | Out-Null
return
}
if ($vm.State -eq "Off" -or $vm.State -eq "Saved") {
Log "vm" "Starting VM '$($cfg.vmName)' from state '$($vm.State)'"
Start-VM -Name $cfg.vmName | Out-Null
WaitForVmState $cfg.vmName "Running" $timeoutSeconds | Out-Null
return
}
throw "VM '$($cfg.vmName)' must be Running, Off, Saved or Paused before OS BitLocker can be configured. Current state is '$($vm.State)'."
}
function StopVmGracefully($cfg, $credential) {
$vm = Get-VM -Name $cfg.vmName -ErrorAction Stop
if ($vm.State -eq "Off") { return $false }
Log "vm" "Shutting down VM '$($cfg.vmName)'"
try {
Invoke-Command -VMName $cfg.vmName -Credential $credential -ScriptBlock { Stop-Computer -Force } -ErrorAction Stop | Out-Null
} catch {
Stop-VM -Name $cfg.vmName -Shutdown -ErrorAction SilentlyContinue | Out-Null
}
WaitForVmState $cfg.vmName "Off" 300 | Out-Null
return $true
}
function EnsureVmTpm($cfg, $credential) {
$vm = Get-VM -Name $cfg.vmName -ErrorAction Stop
if ($vm.Generation -ne 2) { throw "VM '$($cfg.vmName)' must be Generation 2 for vTPM-backed OS BitLocker." }
$security = Get-VMSecurity -VMName $cfg.vmName -ErrorAction Stop
if ($security.TpmEnabled) {
Log "host" "vTPM is already enabled"
return
}
$wasRunning = StopVmGracefully $cfg $credential
Log "host" "Enabling local VM key protector"
Set-VMKeyProtector -VMName $cfg.vmName -NewLocalKeyProtector
Log "host" "Enabling vTPM"
Enable-VMTPM -VMName $cfg.vmName
if ($wasRunning) {
Log "vm" "Starting VM '$($cfg.vmName)'"
Start-VM -Name $cfg.vmName | Out-Null
WaitForVmState $cfg.vmName "Running" 120 | Out-Null
WaitForPowerShellDirect $cfg $credential 600
}
}
function EnsureNoBootableDvd($vmName) {
$drives = @(Get-VMDvdDrive -VMName $vmName -ErrorAction SilentlyContinue | Where-Object { -not [string]::IsNullOrWhiteSpace($_.Path) })
foreach ($drive in $drives) {
Log "host" "Ejecting VM DVD media from controller $($drive.ControllerNumber), location $($drive.ControllerLocation)"
Set-VMDvdDrive -VMName $vmName -ControllerNumber $drive.ControllerNumber -ControllerLocation $drive.ControllerLocation -Path $null
}
}
function RecoveryFile($path, $vmName) {
$resolved = FullPath $path
$isDirectory = $false
if (Test-Path -LiteralPath $resolved -PathType Container) {
$isDirectory = $true
} elseif ([string]::IsNullOrWhiteSpace([IO.Path]::GetExtension($resolved))) {
$isDirectory = $true
}
if ($isDirectory) {
New-Item -ItemType Directory -Force -Path $resolved | Out-Null
return (Join-Path $resolved "$vmName-os-bitlocker-recovery-key.txt")
}
$parent = Split-Path -Parent $resolved
if (-not [string]::IsNullOrWhiteSpace($parent)) {
New-Item -ItemType Directory -Force -Path $parent | Out-Null
}
return $resolved
}
function SecureFileForCurrentUser($path) {
$user = [Security.Principal.WindowsIdentity]::GetCurrent().Name
& icacls.exe $path /inheritance:r /grant:r "${user}:F" | Out-Null
}
function EnableGuestOsBitLocker($cfg, $credential, $requireStartupPin, $startupPin) {
Invoke-Command -VMName $cfg.vmName -Credential $credential -ArgumentList $requireStartupPin, $startupPin -ScriptBlock {
param($requireStartupPin, $startupPin)
$mountPoint = "C:"
function RefreshVolume {
Get-BitLockerVolume -MountPoint $mountPoint -ErrorAction Stop
}
function ProtectorsOfType($volume, $type) {
@($volume.KeyProtector | Where-Object { $_.KeyProtectorType -eq $type })
}
function TpmPinProtectors($volume) {
@($volume.KeyProtector | Where-Object { [string]$_.KeyProtectorType -match '^Tpm.*Pin$|^TpmPin$|^TpmAndPin$' })
}
function RemoveProtectors($protectors) {
foreach ($protector in @($protectors)) {
$protectorId = [string]$protector.KeyProtectorId
if ([string]::IsNullOrWhiteSpace($protectorId)) { continue }
Remove-BitLockerKeyProtector -MountPoint $mountPoint -KeyProtectorId $protectorId | Out-Null
}
}
function ConfigureStartupPolicy($requirePin) {
$path = "HKLM:\SOFTWARE\Policies\Microsoft\FVE"
New-Item -Path $path -Force | Out-Null
function SetDword($name, $value) {
New-ItemProperty -Path $path -Name $name -PropertyType DWord -Value $value -Force | Out-Null
}
SetDword UseAdvancedStartup 1
SetDword EnableBDEWithNoTPM 0
SetDword UseTPM 2
SetDword UseTPMKey 2
SetDword UseTPMKeyPIN 2
SetDword MinimumPIN 6
if ($requirePin) {
SetDword UseTPMPIN 1
} else {
SetDword UseTPMPIN 2
}
}
$tpm = Get-Tpm -ErrorAction Stop
if (-not $tpm.TpmPresent) { throw "Guest TPM is not present." }
if (-not $tpm.TpmReady) { throw "Guest TPM is present but not ready." }
if ($requireStartupPin -and $startupPin -notmatch '^\d{6,20}$') {
throw "Startup PIN must be 6 to 20 digits."
}
ConfigureStartupPolicy $requireStartupPin
$volume = RefreshVolume
$recoveryPassword = ""
$recoveryProtectorId = ""
$createdRecoveryProtector = $false
if ($volume.VolumeStatus -eq "FullyDecrypted") {
if ($requireStartupPin) {
Enable-BitLocker -MountPoint $mountPoint -UsedSpaceOnly -TpmAndPinProtector -Pin (ConvertTo-SecureString $startupPin -AsPlainText -Force) -SkipHardwareTest -WarningAction SilentlyContinue | Out-Null
} else {
Enable-BitLocker -MountPoint $mountPoint -UsedSpaceOnly -TpmProtector -SkipHardwareTest -WarningAction SilentlyContinue | Out-Null
}
$volume = RefreshVolume
}
if ((ProtectorsOfType $volume "RecoveryPassword").Count -eq 0) {
Add-BitLockerKeyProtector -MountPoint $mountPoint -RecoveryPasswordProtector -WarningAction SilentlyContinue | Out-Null
$volume = RefreshVolume
$createdRecoveryProtector = $true
}
if ($requireStartupPin) {
RemoveProtectors (TpmPinProtectors $volume)
Add-BitLockerKeyProtector -MountPoint $mountPoint -TpmAndPinProtector -Pin (ConvertTo-SecureString $startupPin -AsPlainText -Force) -WarningAction SilentlyContinue | Out-Null
$volume = RefreshVolume
RemoveProtectors (ProtectorsOfType $volume "Tpm")
$volume = RefreshVolume
} else {
if ((ProtectorsOfType $volume "Tpm").Count -eq 0) {
Add-BitLockerKeyProtector -MountPoint $mountPoint -TpmProtector -WarningAction SilentlyContinue | Out-Null
$volume = RefreshVolume
}
RemoveProtectors (TpmPinProtectors $volume)
$volume = RefreshVolume
}
$recovery = ProtectorsOfType $volume "RecoveryPassword" | Select-Object -Last 1
if ($recovery) {
$recoveryPassword = [string]$recovery.RecoveryPassword
$recoveryProtectorId = [string]$recovery.KeyProtectorId
}
if ([string]::IsNullOrWhiteSpace($recoveryPassword)) {
throw "OS BitLocker recovery password could not be read. Refusing to continue without exporting it."
}
if ($volume.ProtectionStatus -ne "On") {
Resume-BitLocker -MountPoint $mountPoint -ErrorAction SilentlyContinue | Out-Null
& manage-bde.exe -protectors -enable $mountPoint | Out-Null
if ($LASTEXITCODE -ne 0) { throw "manage-bde failed to enable protectors for $mountPoint." }
$volume = RefreshVolume
}
[pscustomobject]@{
MountPoint = $volume.MountPoint
ProtectionStatus = [string]$volume.ProtectionStatus
VolumeStatus = [string]$volume.VolumeStatus
EncryptionPercentage = [int]$volume.EncryptionPercentage
LockStatus = [string]$volume.LockStatus
RecoveryPassword = $recoveryPassword
RecoveryProtectorId = $recoveryProtectorId
CreatedRecoveryProtector = $createdRecoveryProtector
TpmProtectorCount = (ProtectorsOfType $volume "Tpm").Count
TpmPinProtectorCount = (TpmPinProtectors $volume).Count
RecoveryProtectorCount = (ProtectorsOfType $volume "RecoveryPassword").Count
StartupPinRequired = [bool]$requireStartupPin
}
}
}
function WaitForGuestOsBitLocker($cfg, $credential, $timeoutSeconds) {
$lastText = ""
$deadline = (Get-Date).AddSeconds($timeoutSeconds)
do {
$state = Invoke-Command -VMName $cfg.vmName -Credential $credential -ScriptBlock {
$volume = Get-BitLockerVolume -MountPoint "C:" -ErrorAction Stop
[pscustomobject]@{
ProtectionStatus = [string]$volume.ProtectionStatus
VolumeStatus = [string]$volume.VolumeStatus
EncryptionPercentage = [int]$volume.EncryptionPercentage
}
}
$text = "C: protection=$($state.ProtectionStatus) status=$($state.VolumeStatus) encrypted=$($state.EncryptionPercentage)%"
if ($text -ne $lastText) {
Log "guest" $text
$lastText = $text
}
if ($state.ProtectionStatus -eq "On" -and $state.VolumeStatus -eq "FullyEncrypted") { return $state }
Start-Sleep -Seconds 15
} while ((Get-Date) -lt $deadline)
throw "OS BitLocker did not reach Protection=On and FullyEncrypted within $timeoutSeconds seconds."
}
$configPath = ArgValue "config" "config\windows.json"
$recoveryKeyPath = ArgValue "recovery-key-path"
$waitTimeoutSeconds = [int](ArgValue "wait-timeout-seconds" "14400")
$requireStartupPin = Flag "require-startup-pin"
$startupPin = if ($requireStartupPin) { StartupPinValue } else { "" }
if ([string]::IsNullOrWhiteSpace($recoveryKeyPath)) {
throw "Usage: .\enable-os-bitlocker.ps1 --config config\windows.json --recovery-key-path <secure-host-directory-or-file>"
}
$cfg = Get-Content -Raw (FullPath $configPath) | ConvertFrom-Json
@{
vmName = "WorkstationW11"
user = "work"
baseDir = "~/VMs/WorkstationWindows11"
}.GetEnumerator() | ForEach-Object { Default $cfg $_.Key $_.Value }
AssertAdministrator
$credential = GuestCredential $cfg
$recoveryFile = RecoveryFile $recoveryKeyPath $cfg.vmName
Log "host" "Preparing OS BitLocker for VM '$($cfg.vmName)'"
EnsureNoBootableDvd $cfg.vmName
EnsureVmTpm $cfg $credential
EnsureVmRunning $cfg 120
WaitForPowerShellDirect $cfg $credential 600
$state = EnableGuestOsBitLocker $cfg $credential $requireStartupPin $startupPin
$createdText = if ($state.CreatedRecoveryProtector) { "created" } else { "existing" }
$recoveryText = @(
"VM: $($cfg.vmName)",
"Volume: $($state.MountPoint)",
"CreatedUtc: $((Get-Date).ToUniversalTime().ToString('s'))Z",
"RecoveryProtector: $($state.RecoveryProtectorId)",
"RecoveryPassword: $($state.RecoveryPassword)"
)
Set-Content -LiteralPath $recoveryFile -Value $recoveryText -Encoding ascii
SecureFileForCurrentUser $recoveryFile
Log "host" "Recovery key exported to $recoveryFile ($createdText protector)"
if ($state.StartupPinRequired) {
Log "guest" "Startup PIN mode is enabled. The VM will require the PIN at BitLocker pre-boot after restart."
} else {
Log "guest" "TPM-only mode is enabled. The OS disk auto-unlocks during normal VM boot."
}
$final = WaitForGuestOsBitLocker $cfg $credential $waitTimeoutSeconds
if ($final.ProtectionStatus -ne "On") { throw "OS BitLocker protection is not on." }
if ($final.VolumeStatus -ne "FullyEncrypted") { throw "OS BitLocker is not fully encrypted." }
Write-Host ""
Write-Host "READY: OS BitLocker is enabled for VM '$($cfg.vmName)'."