This repository has been archived by the owner on Jan 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
AutomationHelpers.ps1
483 lines (435 loc) · 12.8 KB
/
AutomationHelpers.ps1
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
function CopyPSModules
{
try
{
Expand-Archive -LiteralPath ".\bosh-psmodules.zip" -DestinationPath "C:\Program Files\WindowsPowerShell\Modules\" -Force
Write-Log "Succesfully migrated Bosh Powershell modules to destination dir"
}
catch [Exception]
{
Write-Log $_.Exception.Message
Write-Log "Failed to copy Bosh Powershell Modules into destination dir. See 'c:\provision\log.log' for more info."
throw $_.Exception
}
}
function InstallCFFeatures
{
try
{
Install-CFFeatures2016
Write-Log "Successfully installed CF features"
}
catch [Exception]
{
Write-Log $_.Exception.Message
Write-Log "Failed to install the CF features. See 'c:\provision\log.log' for more info."
throw $_.Exception
}
}
function Enable-HyperV
{
try
{
$osVersion2019Regex = "10\.0\.17763\..+"
$osVersion = Get-OSVersionString
if ($osVersion -match $osVersion2019Regex) {
Enable-Hyper-V
Write-Log "Successfully enabled HyperV"
}
else {
Write-Log "Did not enable HyperV because OS Version is not 2019"
}
}
catch [Exception]
{
Write-Log $_.Exception.Message
Write-Log "Failed to enable HyperV. See 'c:\provision\log.log' for more info."
throw $_.Exception
}
}
function InstallCFCell
{
try
{
Protect-CFCell
Write-Log "Succesfully ran Protect-CFCell"
}
catch [Exception]
{
Write-Log $_.Exception.Message
Write-Log "Failed to execute Protect-CFCell powershell cmdlet. See 'c:\provision\log.log' for more info."
throw $_.Exception
}
}
function InstallBoshAgent
{
try
{
Install-Agent -Iaas "vsphere" -agentZipPath ".\agent.zip"
Write-Log "Bosh agent successfully installed"
}
catch [Exception]
{
Write-Log $_.Exception.Message
Write-Log "Failed to execute Install-Agent powershell cmdlet. See 'c:\provision\log.log' for more info."
throw $_.Exception
}
}
function InstallOpenSSH
{
try
{
Install-SSHD -SSHZipFile ".\OpenSSH-Win64.zip"
Write-Log "OpenSSH successfully installed"
}
catch [Exception]
{
Write-Log $_.Exception.Message
Write-Log "Failed to execute Install-SSHD powershell cmdlet. See 'c:\provision\log.log' for more info."
throw $_.Exception
}
}
#This function contains all our registry changes related to fixing the zombieload and meltdown bugs
function Set-RegKeys
{
$PathExists = Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\QualityCompat'
try
{
if ($PathExists -eq $False)
{
New-Item -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\QualityCompat'
}
New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\QualityCompat' -Value 0 -Name 'cadca5fe-87d3-4b96-b7fb-a231484277cc' -force
New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization' -Value 1.0 -Name 'MinVmVersionForCpuBasedMitigations' -force
New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management' -Value 3 -Name 'FeatureSettingsOverrideMask' -force
New-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management' -Value 72 -Name 'FeatureSettingsOverride' -force
Write-Log "Meltdown/zombieload registry keys successfully added"
}
catch [Exception]
{
Write-Log $_.Exception.Message
Write-Log "Failed to set meltdown/zombieload registry keys. See 'c:\provision\log.log' for more info."
throw $_.Exception
}
}
function CleanUpVM
{
try
{
Optimize-Disk
Compress-Disk
Write-Log "Successfully cleaned up the VM's disk"
}
catch [Exception]
{
Write-Log $_.Exception.Message
Write-Log "Failed to clean up the VM's disk. See 'c:\provision\log.log' for more info."
throw $_.Exception
}
}
function Is-Special()
{
param ([parameter(Mandatory = $true)] [string]$c)
return $c -cmatch '[!-/:-@[-`{-~]'
}
function Valid-Password()
{
param ([parameter(Mandatory = $true)] [string]$Password)
$digits = 0
$special = 0
$alphaLow = 0
$alphaHigh = 0
if ($Password.Length -lt 8)
{
return $false
}
$tmp = $Password.ToCharArray()
foreach ($c in $Password.ToCharArray())
{
if ($c -cmatch '\d')
{
$digits = 1
}
elseif ($c -cmatch '[a-z]')
{
$alphaLow = 1
}
elseif ($c -cmatch '[A-Z]')
{
$alphaHigh = 1
}
elseif (Is-Special $c)
{
$special = 1
}
else
{
#Invalid char
return $false
}
}
return ($digits + $special + $alphaLow + $alphaHigh) -ge 3
}
function GenerateRandomPassword
{
$CharList = "!`"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_``abcdefghijklmnopqrstuvwxyz{|}~".ToCharArray()
$limit = 200
$count = 0
while ($limit-- -gt 0)
{
$passwd = (Get-Random -InputObject $CharList -Count 24) -join ''
if (Valid-Password -Password $passwd)
{
Write-Log "Successfully generated password"
return $passwd
}
}
Write-Log "Failed to generate password after 200 attempts"
throw "Unable to generate a valid password after 200 attempts"
}
function SysprepVM
{
param (
[string]$Organization = "",
[string]$Owner = "",
[bool]$SkipRandomPassword = $false
)
try
{
if ($SkipRandomPassword) {
Invoke-Sysprep -IaaS "vsphere" -Organization $Organization -Owner $Owner
}else {
$randomPassword = GenerateRandomPassword
Invoke-Sysprep -IaaS "vsphere" -NewPassword $randomPassword -Organization $Organization -Owner $Owner
}
}
catch [Exception]
{
Write-Log $_.Exception.Message
Write-Log "Failed to Sysprep the VM's. See 'c:\provision\log.log' for more info."
throw $_.Exception
}
}
function Check-Dependencies
{
try
{
$depsObj = (Get-Content -Path "$PSScriptRoot/deps.json") -join '' | ConvertFrom-Json
if ($depsObj.psobject.properties.Count -eq 0 -or $depsObj.psobject.properties.Count -eq $null)
{
throw "Dependency file is empty"
}
$corruptedOrMissingFile = $false
$depsObj.psobject.properties | ForEach {
$fileName = $_.Name
$expectedFileHash = $_.Value.sha
if (Test-Path -Path "$PSScriptRoot/$fileName")
{
$fileHash = Get-FileHash -Path "$PSScriptRoot/$fileName"
if ($fileHash.Hash -notmatch $expectedFileHash)
{
Write-Log "$PSScriptRoot/$fileName does not have the correct hash"
$corruptedOrMissingFile = $true
}
}
else
{
Write-Log "$PSScriptRoot/$fileName is required but was not found"
$corruptedOrMissingFile = $true
}
}
if ($corruptedOrMissingFile)
{
throw "One or more files are corrupted or missing."
}
}
catch [Exception]
{
Write-Log $_.Exception.Message
Write-Log "Failed to validate required dependencies. See 'c:\provision\log.log' for more info."
throw $_.Exception
}
Write-Log "Found all dependencies"
}
function Get-OSVersionString
{
return [System.Environment]::OSVersion.Version.ToString()
}
function Validate-OSVersion
{
try
{
$osVersion = Get-OSVersionString
if ($osVersion -match "10\.0\.17763\..+")
{
Write-Log "Found correct OS version: Windows Server 2019"
}
else {
throw "OS Version Mismatch: Please use Windows Server 2019"
}
}
catch [Exception]
{
Write-Log $_.Exception.Message
Write-Log "Failed to validate the OS version. See 'c:\provision\log.log' for more info."
throw $_.Exception
}
}
function DeleteScheduledTask {
try {
if ((Get-ScheduledTask | ForEach { $_.TaskName }) -ccontains "BoshCompleteVMPrep") {
Unregister-ScheduledTask -TaskName BoshCompleteVMPrep -Confirm:$false
Write-Log "Successfully deleted the 'BoshCompleteVMPrep' scheduled task"
}
else {
Write-Log "BoshCompleteVMPrep schedule task was not registered"
}
}
catch [Exception] {
Write-Log $_.Exception.Message
Write-Log "Failed to unregister the BoshCompleteVMPrep scheduled task. See 'c:\provision\log.log' for more info."
throw $_.Exception
}
}
function Create-VMPrepTaskAction {
param(
[string]$Organization="",
[string]$Owner="",
[switch]$SkipRandomPassword
)
$arguments = "-NoExit -File ""$PSScriptRoot\Complete-VMPrep.ps1"""
if ($Organization -ne "") {
$arguments += " -Organization ""$Organization"""
}
if ($Owner -ne "") {
$arguments += " -Owner ""$Owner"""
}
if ($SkipRandomPassword) {
$arguments += " -SkipRandomPassword"
}
New-ScheduledTaskAction -Execute "powershell.exe" -Argument $arguments
}
function Remove-SSHKeys
{
$SSHDir = "C:\Program Files\OpenSSH"
Push-Location $SSHDir
New-Item -ItemType Directory -Path "$env:ProgramData\ssh" -ErrorAction Ignore
"Removing any existing host keys"
Remove-Item -Path "$env:ProgramData\ssh\ssh_host_*" -ErrorAction Ignore
Pop-Location
}
function Run-LGPO
{
param (
[string]$LGPOPath = $( Throw "Provide LGPO path" ),
[string]$InfFilePath = $( Throw "Provide Inf file path" )
)
& $LGPOPath /s $InfFilePath
}
function Enable-SSHD
{
if ((Get-NetFirewallRule | where { $_.DisplayName -ieq 'SSH' }) -eq $null)
{
"Creating firewall rule for SSH"
New-NetFirewallRule -Protocol TCP -LocalPort 22 -Direction Inbound -Action Allow -DisplayName SSH
}
else
{
"Firewall rule for SSH already exists"
}
$InfFilePath = "$env:WINDIR\Temp\enable-ssh.inf"
$InfFileContents = @'
[Unicode]
Unicode=yes
[Version]
signature=$CHICAGO$
Revision=1:w
[Registry Values]
[System Access]
[Privilege Rights]
SeDenyNetworkLogonRight=*S-1-5-32-546
SeAssignPrimaryTokenPrivilege=*S-1-5-19,*S-1-5-20,*S-1-5-80-3847866527-469524349-687026318-516638107-1125189541
'@
$LGPOPath = "$env:WINDIR\LGPO.exe"
if (Test-Path $LGPOPath)
{
Out-File -FilePath $InfFilePath -Encoding unicode -InputObject $InfFileContents -Force
try
{
Run-LGPO -LGPOPath $LGPOPath -InfFilePath $InfFilePath
}
catch
{
throw "LGPO.exe failed with: $_.Exception.Message"
}
}
else
{
"Did not find $LGPOPath. Assuming existing security policies are sufficient to support ssh."
}
Set-Service -Name sshd -StartupType Automatic
# ssh-agent is not the same as ssh-agent in *nix openssh
Set-Service -Name ssh-agent -StartupType Automatic
Remove-SSHKeys
}
function Install-SecurityPoliciesAndRegistries
{
try
{
$osVersion2019Regex = "10\.0\.17763\..+"
$osVersion = Get-OSVersionString
Write-Log "osVersion: $osVersion"
if ($osVersion -match $osVersion2019Regex) {
Set-InternetExplorerRegistries
Write-Log "Succesfully ran Set-InternetExplorerRegistries"
} else {
Write-Log "Did not run Set-InternetExplorerRegistries because OS version was not 2019"
}
}
catch [Exception]
{
Write-Log $_.Exception.Message
Write-Log "Failed to execute Set-InternetExplorerRegistries powershell cmdlet. See 'c:\provision\log.log' for more info."
throw $_.Exception
}
}
function Extract-LGPO
{
process
{
$LGPOPath="./LGPO.zip"
Expand-Archive -LiteralPath $LGPOPath -DestinationPath "$env:WINDIR\"
Write-Log "Successfully migrated LGPO to destination dir"
}
}
function Install-WUCerts
{
try
{
Get-WUCerts
Write-Log "Successfully retrieved Windows Update certs"
}
catch [Exception]
{
Write-Log $_.Exception.Message
Write-Log "Failed to retrieve updated root certificates from the public Windows Update Server."
throw $_.Exception
}
}
function Create-VersionFile
{
param(
[string]$Version
)
try
{
New-VersionFile -Version $Version
Write-Log "Successfully created stemcell version file"
}
catch [Exception]
{
Write-Log $_.Exception.Message
Write-Log "Failed to execute Create-VersionFile command"
throw $_.Exception
}
}