-
Notifications
You must be signed in to change notification settings - Fork 443
/
Copy pathBuild.ps1
458 lines (378 loc) · 16.6 KB
/
Build.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
function Invoke-Build {
[CmdletBinding()]
param(
[string] $Name,
[switch] $NoRandomNames
)
begin {
$BuildProfileCore = @(
".\src\core\Compression.ps1",
".\src\core\Multithreading.ps1",
".\src\core\Reflection.ps1",
".\src\core\WinApi.Enum.ps1",
".\src\core\WinApi.Struct.ps1",
".\src\core\WinApi.Wrappers.ps1",
".\src\core\WinApi.ps1"
)
$BuildProfilePrivescCheck = $BuildProfileCore + @(
".\src\helper\AccessControl.ps1",
".\src\helper\Environment.ps1",
".\src\helper\Msi.ps1",
".\src\helper\SystemConfiguration.ps1",
".\src\helper\SystemInformation.ps1",
".\src\helper\Utility.ps1",
".\src\check\Globals.ps1",
".\src\check\Main.ps1",
".\src\check\User.ps1",
".\src\check\Services.ps1",
".\src\check\Applications.ps1",
".\src\check\ScheduledTasks.ps1",
".\src\check\Hardening.ps1",
".\src\check\Configuration.ps1",
".\src\check\Network.ps1",
".\src\check\Updates.ps1",
".\src\check\Credentials.ps1",
".\src\check\Misc.ps1"
)
$BuildProfilePointAndPrint = $BuildProfileCore + @(
".\src\exploit\PointAndPrint.ps1"
)
$SanityCheck = $true
$BuildProfiles = @{
"PrivescCheck" = $BuildProfilePrivescCheck
"PointAndPrint" = $BuildProfilePointAndPrint
}
if ($Name -and (-not ($BuildProfiles.Keys -contains $Name))) {
Write-Message -Type Error "Build profile '$($Name)' not found."
$SanityCheck = $false
}
if (-not (Test-Path -Path "build")) {
Write-Message -Type Error "Build folder not found."
$SanityCheck = $false
}
if ($SanityCheck) {
$ScriptHeader = "#Requires -Version 2`r`n`r`n"
$RootPath = Split-Path -Path (Split-Path -Path $PSCommandPath -Parent) -Parent
if ($NoRandomNames) {
Write-Message -Type Warning "Random name disabled."
}
else {
$Wordlist = Get-Wordlist -WordLength 10
}
$LolDrivers = Get-LolDriverList
$CheckCsvBlob = Get-FileContentAsEmbeddedTextBlob -FileName "Checks.csv"
$EndpointProtectionSignatureCsvBlob = Get-FileContentAsEmbeddedTextBlob -FileName "EndpointProtectionSignatures.csv"
}
}
process {
if (-not $SanityCheck) { return }
foreach ($BuildProfileName in $BuildProfiles.Keys) {
if ($Name -and ($BuildProfileName -ne $Name)) { continue }
$BuildProfile = $BuildProfiles[$BuildProfileName]
$ScriptFilename = "$($BuildProfileName).ps1"
$ScriptPath = Join-Path -Path $RootPath -ChildPath "release\$($ScriptFilename)"
$ScriptContent = "$($ScriptHeader)"
$ErrorCount = 0
$Modules = @()
Write-Message "Building script '$($ScriptFilename)'..."
foreach ($ModuleRelativePath in $BuildProfile) {
$ModulePath = Join-Path -Path $RootPath -ChildPath $ModuleRelativePath
$ModuleItem = Get-Item -Path $ModulePath -ErrorAction SilentlyContinue
if ($null -eq $ModuleItem) {
Write-Message -Type Error "Failed to open file '$($ModulePath)'."
$ErrorCount += 1
break
}
$ModuleFilename = $ModuleItem.Name
if ($null -ne $Wordlist) {
# Pick a random name from the wordlist.
$RandomName = Get-Random -InputObject $Wordlist -Count 1
$Wordlist = $Wordlist | Where-Object { $_ -ne $RandomName }
$ModuleName = $RandomName.ToLower()
$ModuleName = ([regex] $ModuleName[0].ToString()).Replace($ModuleName, $ModuleName[0].ToString().ToUpper(), 1)
}
else {
# Otherwise use the filename as the module name.
$ModuleFilenameSplit = $ModuleFilename.Split('.')
$ModuleName = ($ModuleFilenameSplit[0..($ModuleFilenameSplit.Count-2)] -join '.') -replace '\.',''
}
[string[]] $Modules += $ModuleName
$ScriptBlock = Get-Content -Path $ModulePath | Out-String
$CompressScriptBlock = $true
if ($ModuleFilename -like "Globals*") {
if ($null -ne $LolDrivers) {
# Populate vulnerable driver list.
$LolDriversCsv = $LolDrivers | ConvertTo-Csv -Delimiter ";" | Out-String
$ScriptBlock = $ScriptBlock -replace "VULNERABLE_DRIVERS",$LolDriversCsv
Write-Message "Driver list written to '$($ModuleFilename)'."
}
else {
Write-Message -Type Warning "Known vulnerable driver CSV is null."
}
if ($null -ne $CheckCsvBlob) {
# Populate check list as an encoded blob.
$ScriptBlock = $ScriptBlock -replace "CHECK_CSV_BLOB",$CheckCsvBlob
Write-Message "Check list written to '$($ModuleFilename)'."
}
else {
Write-Message -Type Warning "Check CSV text blob is null."
}
if ($null -ne $EndpointProtectionSignatureCsvBlob) {
# Populate list of endpoint protection software signature list
$ScriptBlock = $ScriptBlock -replace "ENDPOINT_PROTECTION_SIGNATURE_CSV_BLOB",$EndpointProtectionSignatureCsvBlob
Write-Message "Endpoint protection signature list written to '$($ModuleFilename)'."
}
else {
Write-Message -Type Warning "Endpoint protection signature CSV text blob is null."
}
}
if ($ModuleFilename -like "Compression*") {
$CompressScriptBlock = $false
}
# Is the script block detected by AMSI after stripping the comments?
# Note: if the script block is caught by AMSI, an exception is triggered, so we go
# directly to the "catch" block. Otherwise, it means that the module was successfully
# loaded.
$ScriptBlock = Remove-CommentsFromScriptBlock -ScriptBlock $ScriptBlock
try {
$ScriptBlock | Invoke-Expression
}
catch {
$ErrorCount += 1
Write-Message -Type Error "$($_.Exception.Message.Trim())"
}
Write-Message "File '$($ModuleFilename)' (name: '$($ModuleName)') was loaded successfully."
if ($CompressScriptBlock) {
$ScriptEncoded = ConvertTo-Gzip -InputText $ScriptBlock
}
else {
$ScriptEncoded = [Text.Encoding]::UTF8.GetBytes($ScriptBlock)
}
$ScriptEncoded = [System.Convert]::ToBase64String($ScriptEncoded)
$ScriptContent += "`$$($ModuleName) = `"$($ScriptEncoded)`"`r`n"
}
if ($ErrorCount -eq 0) {
Write-Message -Type Success "Build successful, writing result to file '$($ScriptPath)'..."
$ScriptContent += "`r`n$(Get-ScriptLoader -Modules $Modules)"
$ScriptContent | Out-File -FilePath $ScriptPath -Encoding ascii
if ($BuildProfileName -eq "PrivescCheck") {
# If the output script is PrivescCheck.ps1, copy the result at the root of the
# project as well.
$ScriptPath = Join-Path -Path $RootPath -ChildPath "$($ScriptFilename)"
Write-Message -Type Info "Copying result to file '$($ScriptPath)'..."
$ScriptContent | Out-File -FilePath $ScriptPath -Encoding ascii
}
}
}
}
}
function Write-Message {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true)]
[String] $Message,
[ValidateSet("Success", "Info", "Warning", "Error")]
[String] $Type
)
$Symbol = "[*]"; $Color = "Blue"
switch ($Type) {
"Success" {
$Symbol = "[+]"; $Color = "Green"
}
"Warning" {
$Symbol = "[!]"; $Color = "Yellow"
}
"Error" {
$Symbol = "[-]"; $Color = "Red"
}
}
Write-Host -NoNewline -ForegroundColor "$Color" "$($Symbol) "
Write-Host "$Message"
}
function ConvertTo-EmbeddedTextBlob {
param([String] $Text)
$Compressed = ConvertTo-Gzip -InputText $Text
[System.Convert]::ToBase64String($Compressed)
}
function Get-FileContentAsEmbeddedTextBlob {
param ([String] $FileName)
$FilePath = Split-Path -Path $PSCommandPath -Parent
$FilePath = Join-Path -Path $FilePath -ChildPath $FileName
$FileContent = Get-Content -Path $FilePath -Encoding Ascii | Out-String
ConvertTo-EmbeddedTextBlob -Text $FileContent
}
function Get-AssetFileContent {
[CmdletBinding()]
param(
[OutputType([String])]
[Parameter(Mandatory=$true)]
[ValidateSet("WordList", "KnownVulnerableDriverList")]
[string] $Name
)
begin {
$ExpirationDelayInDays = 30
switch ($Name) {
"WordList" {
$Filename = "wordlist.txt"
$FileUrl = "https://raw.githubusercontent.com/CBHue/PyFuscation/master/wordList.txt"
}
"KnownVulnerableDriverList" {
$Filename = "vulnerable_drivers.csv"
$FileUrl = "https://www.loldrivers.io/api/drivers.csv"
}
}
$BuildPath = Split-Path -Path $PSCommandPath -Parent
$FilePath = Join-Path -Path $BuildPath -ChildPath "cache"
$FilePath = Join-Path -Path $FilePath -ChildPath "$($Filename)"
}
process {
$DownloadFile = $true
$CachedFile = Get-Item -Path $FilePath -ErrorAction SilentlyContinue
if ($null -ne $CachedFile) {
$TimeSpan = New-TimeSpan -Start $CachedFile.LastWriteTime -End $(Get-Date)
$TimeSpanTotalDays = [MAth]::Round($TimeSpan.TotalDays)
if ($TimeSpanTotalDays -gt $ExpirationDelayInDays) {
# Cached file expired, so delete it.
Write-Message "File '$($Filename)' expired, deleting it..." -Type Warning
Remove-Item -Path $FilePath -Force
}
else {
# Cached file has not expired yet, use it.
Write-Message "File '$($Filename)' is $($TimeSpanTotalDays) day$(if ($TimeSpanTotalDays -gt 1) { "s" }) old."
$DownloadFile = $false
}
}
if ($DownloadFile) {
try {
# Download the file.
$FileContent = (New-Object Net.WebClient).DownloadString($FileUrl)
Write-Message "File '$($Filename)' downloaded from: $($FileUrl)"
# Save the file to the local cache folder.
$FileContent | Out-File -FilePath $FilePath -Encoding ASCII
Write-Message "File '$($Filename)' saved to: $($FilePath)"
}
catch {
Write-Message -Type Error "Failed to download file '$($Filename)' from $($FileUrl)."
}
}
Get-Content -LiteralPath $FilePath | Out-String
}
}
function Get-Wordlist {
[CmdletBinding()]
param (
[UInt32] $WordLength = 8
)
$Wordlist = Get-AssetFileContent -Name "WordList"
if ($null -ne $Wordlist) {
$Wordlist = $Wordlist -split "`n" | ForEach-Object { $_.Trim() }
$Wordlist | Where-Object { (-not [string]::IsNullOrEmpty($_)) -and ($_.length -eq $WordLength) -and ($_.ToLower() -match "^[a-z]+$") }
}
}
function Get-LolDriverList {
[CmdletBinding()]
param ()
$LolDriversCsv = Get-AssetFileContent -Name "KnownVulnerableDriverList"
try { $LolDrivers = ConvertFrom-Csv -InputObject $LolDriversCsv }
catch { Write-Message -Type Warning "Failed to parse CSV file: $($_.Exception.Message.Trim())"; return }
Write-Message "Number of drivers in the list: $($LolDrivers.Count)"
$LolDriversVulnerable = $LolDrivers | Where-Object { $_.Category -like "*vulnerable*" }
Write-Message "Number of vulnerable drivers: $($LolDriversVulnerable.Count)"
$LolDriversVulnerable | ForEach-Object {
# Keep the UUID for future reference in the LOL drivers database.
$Result = New-Object -TypeName PSObject
$Result | Add-Member -MemberType "NoteProperty" -Name "Id" -Value $_.Id
# Extract all the valid hashes from the data
$HashesMd5 = [string[]] ($_.KnownVulnerableSamples_MD5 -split "," | ForEach-Object { $_.Trim() } | Where-Object { $_.Length -eq 32 })
$HashesSha1 = [string[]] ($_.KnownVulnerableSamples_SHA1 -split "," | ForEach-Object { $_.Trim() } | Where-Object { $_.Length -eq 40 })
$HashesSha256 = [string[]] ($_.KnownVulnerableSamples_SHA256 -split "," | ForEach-Object { $_.Trim() } | Where-Object { $_.Length -eq 64 })
# Find the hash list that has the most values
$HashesMax = (@($HashesMd5.Count, $HashesSha1.Count, $HashesSha256.Count) | Measure-Object -Maximum).Maximum
# Keep the hash list that has the most values, prioritize the shortest hashes
# to minimize the total space they will take in the final script.
if ($HashesMd5.Count -eq $HashesMax) {
$Result | Add-Member -MemberType "NoteProperty" -Name "HashType" -Value "Md5"
$Result | Add-Member -MemberType "NoteProperty" -Name "Hash" -Value ($HashesMd5 -join ",")
}
elseif ($HashesSha1.Count -eq $HashesMax) {
$Result | Add-Member -MemberType "NoteProperty" -Name "HashType" -Value "Sha1"
$Result | Add-Member -MemberType "NoteProperty" -Name "Hash" -Value ($HashesSha1 -join ",")
}
elseif ($HashesSha256.Count -eq $HashesMax) {
$Result | Add-Member -MemberType "NoteProperty" -Name "HashType" -Value "Sha256"
$Result | Add-Member -MemberType "NoteProperty" -Name "Hash" -Value ($HashesSha256 -join ",")
}
$Result
}
}
function Get-ScriptLoader {
[CmdletBinding()]
param(
[string[]] $Modules
)
begin {
$LoaderBlock = @"
`$Modules = @(MODULE_LIST)
`$Modules | ForEach-Object {
`$Decoded = [System.Convert]::FromBase64String(`$_)
if (`$_ -like "H4s*") {
`$Decoded = ConvertFrom-Gzip -Bytes `$Decoded
}
else {
`$Decoded = [Text.Encoding]::UTF8.GetString(`$Decoded)
}
`$ScriptBlock = `$ExecutionContext.InvokeCommand.NewScriptBlock(`$Decoded)
. `$ScriptBlock
Remove-Variable -Name "Decoded"
Remove-Variable -Name "ScriptBlock"
}
Remove-Variable -Name "Modules"
@(MODULE_STR_LIST) | ForEach-Object { Remove-Variable -Name `$_ }
"@
}
process {
$ModuleList = ($Modules | ForEach-Object { "`$$($_)" }) -join ','
$ModuleStrList = ($Modules | ForEach-Object { "`"$($_)`"" }) -join ','
($LoaderBlock -replace "MODULE_LIST",$ModuleList) -replace "MODULE_STR_LIST",$ModuleStrList
}
}
function Remove-CommentsFromScriptBlock {
[OutputType([String])]
[CmdletBinding()]
param(
[String] $ScriptBlock
)
$IsCommentBlock = $False
$Output = ""
ForEach ($Line in $ScriptBlock.Split("`n")) {
if ($Line -like "*<#*") {
$IsCommentBlock = $True
}
if ((-not $IsCommentBlock) -and ($Line -match "^\s*#.*")) {
continue
}
if (-not $IsCommentBlock) {
$Output += "$Line`n"
}
if ($Line -like "*#>*") {
$IsCommentBlock = $False
}
}
$Output
}
function ConvertTo-Gzip {
[CmdletBinding()]
param (
[string] $InputText
)
process {
[System.Text.Encoding] $Encoding = [System.Text.Encoding]::UTF8
[byte[]] $InputTextEncoded = $Encoding.GetBytes($InputText)
[System.IO.MemoryStream] $MemoryStream = New-Object System.IO.MemoryStream
$GzipStream = New-Object System.IO.Compression.GzipStream $MemoryStream, ([System.IO.Compression.CompressionMode]::Compress)
$GzipStream.Write($InputTextEncoded, 0, $InputTextEncoded.Length)
$GzipStream.Close()
$MemoryStream.Close()
$MemoryStream.ToArray()
}
}