-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathPSAmsiClient.ps1
11761 lines (8579 loc) · 442 KB
/
PSAmsiClient.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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function Start-PSAmsiClient {
<#
.SYNOPSIS
Conducts a series of PSAmsiScans retrieved from a PSAmsiServer.
Author: Ryan Cobb (@cobbr_io)
License: GNU GPLv3
Required Dependecies: New-PSAmsiScanner, Invoke-PSAmsiScan
Optional Dependencies: none
.DESCRIPTION
Start-PSAmsiClient retrieves PSAmsiScan requests from a PSAmsiServer and
checks them against the client's AMSI AntiMalware Provider using Invoke-PSAmsiScan.
.PARAMETER ServerUri
Specifies the URI of the PSAmsiServer to retreive requests from.
.PARAMETER AlertLimit
Specifies the maximum amount of AMSI alerts this client is allowed to generate.
.PARAMETER Delay
Specifies the amount of time (in seconds) to wait between AMSI alerts.
.PARAMETER PSAmsiScanner
Specifies the PSAmsiScanner to use for AMSI scans.
.PARAMETER FindAmsiSignatures
Specifies that the PSAmsiScan should find and return the AMSI signatures found in the script
in addition to the result of the scan.
.PARAMETER GetMinimallyObfuscated
Specifies that the PSAmsiScan should minimally obfuscate the script until it is no longer flagged by AMSI.
.EXAMPLE
Start-PSAmsiClient -ServerUri http://10.100.100.10
.EXAMPLE
Start-PSAmsiClient -ServerUri http://example.com -AlertLimit 10 -Delay 3600 -FindAmsiSignatures
.EXAMPLE
Start-PSAmsiClient -ServerUri http://example.com -Delay 60 -GetMinimallyObfuscated
.NOTES
Start-PSAmsiClient is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
#>
Param(
[Parameter(Position = 0, Mandatory)]
[ValidateScript({$_.Scheme -match 'http|https'})]
[Uri] $ServerUri,
[Parameter(Position = 1)]
[ValidateRange(0, [Int]::MaxValue)]
[Int] $AlertLimit = 0,
[Parameter(Position = 2)]
[ValidateRange(0, [Int]::MaxValue)]
[Int] $Delay = 0,
[Parameter(Position = 3)]
[ValidateScript({$_.GetType().Name -eq 'PSAmsiScanner'})]
[System.Object] $PSAmsiScanner,
[Switch] $FindAmsiSignatures,
[Switch] $GetMinimallyObfuscated
)
$CreatedPSAmsiScanner = $False
# Create the PSAmsiScanner to be used by the PSAmsiClient, if not provided one.
If (-not $PSAmsiScanner) {
$CreatedPSAmsiScanner = $True
$PSAmsiScanner = New-PSAmsiScanner -AlertLimit $AlertLimit -Delay $Delay
} Else {
$PSAmsiScanner.AlertLimit = $AlertLimit
$PSAmsiScanner.Delay = $Delay
}
# Use the system web proxy, if one exists
(New-Object System.Net.WebClient).Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
# Retrieve the PSAmsiScanRequests from the PSAmsiScanServer
$PSAmsiScanRequestObj = Invoke-RestMethod -Uri $ServerUri -TimeoutSec 0
# Read CachedAmsiScanResults, PSAmsiServer will provide cached results from other PSAmsiScanClients, if any.
$CachedAmsiScanResults = @{}
$Result = $PSAmsiScanRequestObj.CachedAmsiScanResults | Get-Member -MemberType Properties | % {
$CachedAmsiScanResults.Add($_.Name, $PSAmsiScanRequestObj.CachedAmsiScanResults.($_.Name))
}
Write-Verbose "[Start-PSAmsiClient] Received $($CachedAmsiScanResults.Count) cached scan results from PSAmsiServer"
Write-Verbose "[Start-PSAmsiClient] Received $($PSAmsiScanRequestObj.PSAmsiScanRequests.Count) PSAmsiScanRequests from PSAmsiServer"
# Have the PSAmsiScanner use any cached scan results provided from the server
$PSAmsiScanner.ScanCache = $CachedAmsiScanResults
# Iterate through PSAmsiScanRequests, calling Invoke-PSAmsiScan for each one
$PSAmsiScanRequests = $PSAmsiScanRequestObj.PSAmsiScanRequests
If ($FindAmsiSignatures -and $GetMinimallyObfuscated) {
$PSAmsiScanResults = $PSAmsiScanRequests | % { Invoke-PSAmsiScan -ScriptName $_.ScriptName -ScriptString $_.ScriptString -PSAmsiScanner $PSAmsiScanner -FindAmsiSignatures -GetMinimallyObfuscated -IncludeStatus }
} ElseIf ($FindAmsiSignatures) {
$PSAmsiScanResults = $PSAmsiScanRequests | % { Invoke-PSAmsiScan -ScriptName $_.ScriptName -ScriptString $_.ScriptString -PSAmsiScanner $PSAmsiScanner -FindAmsiSignatures -IncludeStatus }
} ElseIf ($GetMinimallyObfuscated) {
$PSAmsiScanResults = $PSAmsiScanRequests | % { Invoke-PSAmsiScan -ScriptName $_.ScriptName -ScriptString $_.ScriptString -PSAmsiScanner $PSAmsiScanner -GetMinimallyObfuscated -IncludeStatus }
} Else {
$PSAmsiScanResults = $PSAmsiScanRequests | % { Invoke-PSAmsiScan -ScriptName $_.ScriptName -ScriptString $_.ScriptString -PSAmsiScanner $PSAmsiScanner -IncludeStatus }
}
# If any PSAmsiScanRequests are not complete due to AlertLimit, then provide CachedAmsiScanResults to PSAmsiScanServer
# Otherwise, we will just give an empty object to reduce network traffic
$UnfinishedPSAmsiScanRequests = @()
$UnfinishedPSAmsiScanRequests += $PSAmsiScanResults | ? { -not $_.RequestCompleted }
If ($UnfinishedPSAmsiScanRequests.Count -gt 0) {
Write-Verbose "[Start-PSAmsiClient] $($UnfinishedPSAmsiScanRequests.Count) PSAmsiScanRequest(s) were not completed. Sending $($PSAmsiScanner.ScanCache.Count) cached scan results back to PSAmsiServer."
$PSAmsiScanResultObj = [PSCustomObject] @{ PSAmsiScanResults = $PSAmsiScanResults; CachedAmsiScanResults = $PSAmsiScanner.ScanCache }
}
Else {
$PSAmsiScanResultObj = [PSCustomObject] @{ PSAmsiScanResults = $PSAmsiScanResults; CachedAmsiScanResults = @{} }
}
# We can now dispose the PSAmsiScanner object, if we created it
If ($CreatedPSAmsiScanner) {
$PSAmsiScanner.Dispose()
}
# Convert the results to JSON and POST them back to the PSAmsiServer
$JsonString = $PSAmsiScanResultObj | ConvertTo-Json -Depth 4 -Compress
$Response = Invoke-RestMethod -Method Post -Uri $ServerUri -Body $JsonString -TimeoutSec 0
}
function Invoke-PSAmsiScan {
<#
.SYNOPSIS
Conducts a PSAmsiScan on a given script.
Author: Ryan Cobb (@cobbr_io)
License: GNU GPLv3
Required Dependecies: New-PSAmsiScanner, Find-AmsiSignatures, Out-MinimallyObfuscated
Optional Dependencies: none
.DESCRIPTION
Invoke-PSAmsiScan conducts a PSAmsiScan on a given script, and optionally provides the AMSI signatures
within the script and/or a minimally obfuscated copy of the script that is no longer flagged by AMSI.
.PARAMETER ScriptString
The string containing the script to be scanned.
.PARAMETER ScriptBlock
The ScriptBlock containing the script to be scanned.
.PARAMETER ScriptPath
The Path to the script to be scanned.
.PARAMETER ScriptUri
The URI of the script to be scanned.
.PARAMETER ScriptName
The name of the script to be scanned.
.PARAMETER AlertLimit
Specifies the maximum amount of AMSI alerts this scan is allowed to generate.
.PARAMETER Delay
Specifies the amount of time (in seconds) to wait between AMSI alerts.
.PARAMETER PSAmsiScanner
Specifies the PSAmsiScanner to use for AMSI scans.
.PARAMETER FindAmsiSignatures
Specifies that the PSAmsiScan should find and return the AMSI signatures found in the script
in addition to the result of the scan.
.PARAMETER GetMinimallyObfuscated
Specifies that the PSAmsiScan should minimally obfuscate the script until it is
no longer flagged by AMSI.
.OUTPUTS
PSCustomObject
.EXAMPLE
Invoke-PSAmsiScan -ScriptString "Write-Host test"
.EXAMPLE
Invoke-PSAmsiScan -ScriptString "Write-Host test" -FindAmsiSignatures -AlertLimit 15 -Delay 3
.EXAMPLE
Invoke-PSAmsiScan -ScriptString "Write-Host test" -GetMinimallyObfuscated
.NOTES
Invoke-PSAmsiScan is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
#>
[CmdletBinding(DefaultParameterSetName = "ByString")] Param(
[Parameter(ParameterSetName = "ByString", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
[ValidateNotNullOrEmpty()]
[String] $ScriptString,
[Parameter(ParameterSetName = "ByScriptBlock", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
[ValidateNotNullOrEmpty()]
[ScriptBlock] $ScriptBlock,
[Parameter(ParameterSetName = "ByPath", Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
[ValidateScript({Test-Path $_ -PathType leaf})]
[Alias('PSPath')]
[String] $ScriptPath,
[Parameter(ParameterSetName = "ByUri", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
[ValidateScript({$_.Scheme -match 'http|https'})]
[Uri] $ScriptUri,
[Parameter(Position = 1, ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[String] $ScriptName,
[Parameter(Position = 2)]
[ValidateRange(0,[Int]::MaxValue)]
[Int] $AlertLimit = 0,
[Parameter(Position = 3)]
[ValidateRange(0,[Int]::MaxValue)]
[Int] $Delay = 0,
[Parameter(Position = 4)]
[ValidateScript({$_.GetType().Name -eq 'PSAmsiScanner'})]
[System.Object] $PSAmsiScanner,
[Switch] $FindAmsiSignatures,
[Switch] $GetMinimallyObfuscated,
[Switch] $IncludeStatus
)
Begin {
$CreatedPSAmsiScanner = $False
If (-not $PSAmsiScanner) {
# Create a PSAmsiScanner
$PSAmsiScanner = New-PSAmsiScanner -AlertLimit $AlertLimit -Delay $Delay
$CreatedPSAmsiScanner = $True
}
Else {
If ($AlertLimit -gt 0) {
$PSAmsiScanner.AlertLimit = $AlertLimit
$PSAmsiScanner.AlertLimitEnabled = $True
}
$PSAmsiScanner.Delay = $Delay
}
}
Process {
If ($ScriptBlock) { $ScriptString = $ScriptBlock -as [String] }
ElseIf ($ScriptPath) { $ScriptString = Get-Content -Path $ScriptPath -Raw }
ElseIf ($ScriptUri) { $ScriptString = [Net.Webclient]::new().DownloadString($ScriptUri) }
# Scan the given ScriptString
$ScriptIsFlagged = Test-ContainsAmsiSignatures -ScriptString $ScriptString -PSAmsiScanner $PSAmsiScanner
$PSAmsiScanResult = [PSCustomObject] @{ ScriptIsFlagged = $ScriptIsFlagged }
If ($FindAmsiSignatures) {
$AmsiSignatures = @()
If ($ScriptIsFlagged) {
Write-Verbose "[Invoke-PSAmsiScan] Finding Amsi Signatures in the Script."
$AmsiSignatures = Find-AmsiSignatures -ScriptString $ScriptString -PSAmsiScanner $PSAmsiScanner
# Use Find-AmsiSignatures to retreive the exact strings flagged by AMSI
Write-Verbose "[Invoke-PSAmsiScan] Found $($AmsiSignatures.Count) Amsi Signatures in the Script."
}
$PSAmsiScanResult | Add-Member -Name 'AmsiSignatures' -Value $AmsiSignatures -MemberType NoteProperty
}
If ($GetMinimallyObfuscated) {
Write-Verbose "[Invoke-PSAmsiScan] Getting MinimallyObfuscated copy of Script"
# Use Get-MinimallyObfuscated to retrieve a minimally obfuscated copy of the ScriptString
# that is not flagged by AMSI
$MinimallyObfuscated = $ScriptString
If ($ScanResult -and (-not $PSAmsiScanner.AlertLimitReached)) {
If ($AmsiSignatures) {
$MinimallyObfuscated = Get-MinimallyObfuscated -ScriptString $ScriptString -AmsiSignatures $AmsiSignatures -PSAmsiScanner $PSAmsiScanner
} Else {
$MinimallyObfuscated = Get-MinimallyObfuscated -ScriptString $ScriptString -PSAmsiScanner $PSAmsiScanner
}
}
$PSAmsiScanResult | Add-Member -Name 'MinimallyObfuscated' -Value $MinimallyObfuscated -MemberType NoteProperty
}
If ($IncludeStatus -or $PSAmsiScanner.AlertLimitEnabled) {
If ($PSAmsiScanner.AlertLimitReached) {
Write-Verbose "[Invoke-PSAmsiScan] AlertLimit reached during execution. Reporting scan as not completed."
}
$PSAmsiScanResult | Add-Member -Name 'RequestCompleted' -Value (-not $PSAmsiScanner.AlertLimitReached) -MemberType NoteProperty
}
If ($ScriptName) {
$PSAmsiScanResult | Add-Member -Name 'ScriptName' -Value $ScriptName -MemberType NoteProperty
}
$PSAmsiScanResult
}
End {
# Dispose the PSAmsiScanner when done, if it was created within this function
If ($CreatedPSAmsiScanner) {
$PSAmsiScanner.Dispose()
}
}
}
function Find-AmsiSignatures {
<#
.SYNOPSIS
Finds the AMSI signatures within a script that are flagged as malware by AMSI.
Author: Ryan Cobb (@cobbr_io)
License: GNU GPLv3
Required Dependecies: none
Optional Dependencies: New-PSAmsiScanner, Find-AmsiAstSignatures, Find-AmsiPSTokenSignatures
.DESCRIPTION
Find-AmsiSignatures finds the AMSI signatures within a script that are flagged as malware
by the current AMSI AntiMalware Provider.
.PARAMETER AbstractSyntaxTree
Specifies the root Ast of an AbstractSyntaxTree that represents the script to get AMSI
signatures from.
.PARAMETER PSTokens
Specifies the PSTokens that represents the script to get AMSI signatures from.
.PARAMETER ScriptString
Specifies the string containing the script to get AMSI signatures from.
.PARAMETER ScriptBlock
Specifies the ScriptBlock containing the script to get AMSI signatures from.
.PARAMETER ScriptPath
Specifies the Path to the script to get AMSI signatures from.
.PARAMETER ScriptUri
Specifies the URI of the script to get AMSI signatures from.
.PARAMETER PSAmsiScanner
Specifies the PSAmsiScanner to use to scan for finding AMSI signatures.
.OUTPUTS
String[]
.EXAMPLE
Find-AmsiSignatures "Write-Host example"
Find-AmsiSignatures $AST $PSTokens
@('Write-Host example1', 'Write-Host example2', 'Write-Host example3') | Find-AmsiSignatures
.NOTES
Find-AmsiSignatures is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
#>
[CmdletBinding(DefaultParameterSetName = "ByString")] Param(
[Parameter(ParameterSetName = "ByComponents", Position = 0, Mandatory)]
[Alias('Ast')]
[System.Management.Automation.Language.Ast] $AbstractSyntaxTree,
[Parameter(ParameterSetName = "ByComponents", Position = 1, Mandatory)]
[System.Management.Automation.PSToken[]] $PSTokens,
[Parameter(ParameterSetName = "ByString", Position = 0, ValueFromPipeline, Mandatory)]
[ValidateNotNullOrEmpty()]
[String] $ScriptString,
[Parameter(ParameterSetName = "ByScriptBlock", Position = 0, ValueFromPipeline, Mandatory)]
[ValidateNotNullOrEmpty()]
[ScriptBlock] $ScriptBlock,
[Parameter(ParameterSetName = "ByPath", Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
[ValidateScript({Test-Path $_ -PathType leaf})]
[Alias('PSPath')]
[String] $ScriptPath,
[Parameter(ParameterSetName = "ByUri", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
[ValidateScript({$_.Scheme -match 'http|https'})]
[Uri] $ScriptUri,
[ValidateScript({$_.GetType().Name -eq 'PSAmsiScanner'})]
[System.Object] $PSAmsiScanner,
[Switch] $Unique
)
Begin {
$CreatedPSAmsiScanner = $False
If (-not $PSAmsiScanner) {
$PSAmsiScanner = New-PSAmsiScanner
$CreatedPSAmsiScanner = $True
}
}
Process {
If ($ScriptString) {
$AmsiAstSignatures = Find-AmsiAstSignatures -ScriptString $ScriptString -PSAmsiScanner $PSAmsiScanner
$AmsiPSTokenSignatures = Find-AmsiPSTokenSignatures -ScriptString $ScriptString -PSAmsiScanner $PSAmsiScanner -FilterPSTokenTypes 'Comment'
} ElseIf ($ScriptBlock) {
$AmsiAstSignatures = Find-AmsiAstSignatures -ScriptBlock $ScriptBlock -PSAmsiScanner $PSAmsiScanner
$AmsiPSTokenSignatures = Find-AmsiPSTokenSignatures -ScriptBlock $ScriptBlock -PSAmsiScanner $PSAmsiScanner -FilterPSTokenTypes 'Comment'
} ElseIf ($ScriptPath) {
$AmsiAstSignatures = Find-AmsiAstSignatures -ScriptPath $ScriptPath -PSAmsiScanner $PSAmsiScanner
$AmsiPSTokenSignatures = Find-AmsiPSTokenSignatures -ScriptPath $ScriptPath -PSAmsiScanner $PSAmsiScanner -FilterPSTokenTypes 'Comment'
} ElseIf ($ScriptUri) {
$AmsiAstSignatures = Find-AmsiAstSignatures -ScriptUri $ScriptUri -PSAmsiScanner $PSAmsiScanner
$AmsiPSTokenSignatures = Find-AmsiPSTokenSignatures -ScriptUri $ScriptUri -PSAmsiScanner $PSAmsiScanner -FilterPSTokenTypes 'Comment'
} ElseIf ($AbstractSyntaxTree -and $PSTokens) {
$AmsiAstSignatures = Find-AmsiAstSignatures -AbstractSyntaxTree $AbstractSyntaxTree -PSAmsiScanner $PSAmsiScanner
$AmsiPSTokenSignatures = Find-AmsiPSTokenSignatures -PSTokens $PSTokens -PSAmsiScanner $PSAmsiScanner -FilterPSTokenTypes 'Comment'
}
# Create AmsiSignature objects
$AmsiAstSignatures = ($AmsiAstSignatures | % { [PSCustomObject] @{ StartOffset = $_.Extent.StartOffset; SignatureType = $_.GetType().Name; SignatureContent = $_.Extent.Text } }) -as [array]
$AmsiPSTokenSignatures = ($AmsiPSTokenSignatures | % { [PSCustomObject] @{ StartOffset = $_.Start; SignatureType = $_.GetType().Name; SignatureContent = $_.Content; } }) -as [array]
$AmsiSignatures = $AmsiAstSignatures + $AmsiPSTokenSignatures
If ($Unique) { $AmsiSignatures | Sort-Object -Unique { $_.SignatureContent } }
Else { $AmsiSignatures }
}
End {
If ($CreatedPSAmsiScanner) { $PSAmsiScanner.Dispose() }
}
}
function Test-ContainsAmsiSignatures {
<#
.SYNOPSIS
Tests if any AMSI signatures are contained in a given script.
Author: Ryan Cobb (@cobbr_io)
License: GNU GPLv3
Required Dependecies: Test-ContainsAmsiAstSignatures, Test-ContainsAmsiPSTokenSignatures
Optional Dependencies: New-PSAmsiScanner
.DESCRIPTION
Test-ContainsAmsiSignatures tests if any AMSI signatures are contained in a given script. This function
is much quicker than a full Find-AmsiSignatures search.
.PARAMETER AbstractSyntaxTree
Specifies the root Ast of an AbstractSyntaxTree that represents the script to get AMSI
signatures from.
.PARAMETER PSTokens
Specifies the PSTokens that represents the script to get AMSI signatures from.
.PARAMETER ScriptString
Specifies the string containing the script to get AMSI signatures from.
.PARAMETER ScriptBlock
Specifies the ScriptBlock containing the script to get AMSI signatures from.
.PARAMETER ScriptPath
Specifies the Path to the script to get AMSI signatures from.
.PARAMETER ScriptUri
Specifies the URI of the script to get AMSI signatures from.
.PARAMETER PSAmsiScanner
Specifies the PSAmsiScanner to use to scan for finding AMSI signatures.
.OUTPUTS
String[]
.EXAMPLE
Test-ContainsAmsiSignatures "Write-Host example"
Test-ContainsAmsiSignatures $AST $PSTokens
@('Write-Host example1', 'Write-Host example2', 'Write-Host example3') | Test-ContainsAmsiSignatures
.NOTES
Test-ContainsAmsiSignatures is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
#>
[CmdletBinding(DefaultParameterSetName = "ByString")] Param(
[Parameter(ParameterSetName = "ByComponents", Position = 0, Mandatory)]
[Alias('Ast')]
[System.Management.Automation.Language.Ast] $AbstractSyntaxTree,
[Parameter(ParameterSetName = "ByComponents", Position = 1, Mandatory)]
[System.Management.Automation.PSToken[]] $PSTokens,
[Parameter(ParameterSetName = "ByString", Position = 0, ValueFromPipeline, Mandatory)]
[ValidateNotNullOrEmpty()]
[String] $ScriptString,
[Parameter(ParameterSetName = "ByScriptBlock", Position = 0, ValueFromPipeline, Mandatory)]
[ValidateNotNullOrEmpty()]
[ScriptBlock] $ScriptBlock,
[Parameter(ParameterSetName = "ByPath", Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
[ValidateScript({Test-Path $_ -PathType leaf})]
[Alias('PSPath')]
[String] $ScriptPath,
[Parameter(ParameterSetName = "ByUri", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
[ValidateScript({$_.Scheme -match 'http|https'})]
[Uri] $ScriptUri,
[ValidateScript({$_.GetType().Name -eq 'PSAmsiScanner'})]
[System.Object] $PSAmsiScanner
)
Begin {
$CreatedPSAmsiScanner = $False
If (-not $PSAmsiScanner) {
$PSAmsiScanner = New-PSAmsiScanner
$CreatedPSAmsiScanner = $True
}
}
Process {
If ($ScriptBlock) { $ScriptString = $ScriptBlock -as [String] }
ElseIf ($ScriptPath) { $ScriptString = Get-Content -Path $ScriptPath -Raw }
ElseIf ($ScriptUri) { $ScriptString = [Net.Webclient]::new().DownloadString($ScriptUri) }
$ContainsAstSignatures = Test-ContainsAmsiAstSignatures -ScriptString $ScriptString -PSAmsiScanner $PSAmsiScanner
If ($ContainsAstSignatures) { $True }
Else {
$ContainsPSTokenSignatures = Test-ContainsAmsiPSTokenSignatures -ScriptString $ScriptString -PSAmsiScanner $PSAmsiScanner -FilterPSTokenTypes 'Comment'
If ($ContainsPSTokenSignatures) { $True }
Else { $False }
}
}
End {
If ($CreatedPSAmsiScanner) {
$PSAmsiScanner.Dispose()
}
}
}
function Find-AmsiAstSignatures {
<#
.SYNOPSIS
Finds the Asts that contain AMSI signatures within an AbstractSyntaxTree.
Author: Ryan Cobb (@cobbr_io)
License: GNU GPLv3
Required Dependecies: none
Optional Dependencies: New-PSAmsiScanner, Get-Ast
.DESCRIPTION
Find-AmsiAstSignatures finds the Asts that contain AMSI signatures within an AbstactSyntaxTree.
.PARAMETER AbstractSyntaxTree
Specifies the root Ast that represents the script to find Asts that contain AMSI signatures.
.PARAMETER ScriptString
Specifies the string containing the script to find Asts that contain AMSI signatures.
.PARAMETER ScriptBlock
Specifies the ScriptBlock containing the script to find Asts that contain AMSI signatures.
.PARAMETER ScriptPath
Specifies the Path containing the script to find Asts that contain AMSI signatures.
.PARAMETER ScriptUri
Specifies the Uri of the script to find Asts that contain AMSI signatures.
.PARAMETER PSAmsiScanner
Specifies the PSAmsiScanner to use to scan to find Asts that contain AMSI signatures.
.OUTPUTS
System.Management.Automation.Language.Ast[]
.EXAMPLE
Find-AmsiAstSignatures -Ast $AbstractSyntaxTree
.EXAMPLE
Find-AmsiAstSignatures "Write-Host example"
.EXAMPLE
Find-AmsiAstSignatures { Write-Host example }
.EXAMPLE
Find-AmsiAstSignatures -ScriptPath $ScriptPath
.EXAMPLE
@($Ast1, $Ast2, $Ast3) | Find-AmsiAstSignatures
.EXAMPLE
Get-ChildItem /path/to/scripts -Recurse -Include *.ps1 | Find-AmsiAstSignatures
.EXAMPLE
@('Write-Host example1', 'Write-Host example2', 'Write-Host example3') | Find-AmsiAstSignatures
.EXAMPLE
@({ Write-Host example1 }, { Write-Host example2 }, { Write-Host example3 }) | Find-AmsiAstSignatures
.NOTES
Find-AmsiAstSignatures is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
#>
[CmdletBinding(DefaultParameterSetName="ByString")] Param(
[Parameter(ParameterSetName="ByAst", Position = 0, ValueFromPipeline, Mandatory)]
[ValidateNotNullOrEmpty()]
[Alias('Ast')]
[System.Management.Automation.Language.Ast] $AbstractSyntaxTree,
[Parameter(ParameterSetName = "ByString", Position = 0, ValueFromPipeline, Mandatory)]
[ValidateNotNullOrEmpty()]
[String] $ScriptString,
[Parameter(ParameterSetName = "ByScriptBlock", Position = 0, ValueFromPipeline, Mandatory)]
[ValidateNotNullOrEmpty()]
[ScriptBlock] $ScriptBlock,
[Parameter(ParameterSetName = "ByPath", Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
[ValidateScript({Test-Path $_ -PathType leaf})]
[Alias('PSPath')]
[String] $ScriptPath,
[Parameter(ParameterSetName = "ByUri", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
[ValidateScript({$_.Scheme -match 'http|https'})]
[Uri] $ScriptUri,
[Parameter(Position = 1)]
[ValidateScript({$_.GetType().Name -eq 'PSAmsiScanner'})]
[System.Object] $PSAmsiScanner
)
Begin {
$CreatedPSAmsiScanner = $False
If (-not $PSAmsiScanner) {
$PSAmsiScanner = New-PSAmsiScanner
$CreatedPSAmsiScanner = $True
}
}
Process {
# Get the Ast object, if given a different ParameterSetName
If ($ScriptString) { $AbstractSyntaxTree = Get-Ast -ScriptString $ScriptString }
ElseIf ($ScriptBlock) { $AbstractSyntaxTree = Get-Ast -ScriptBlock $ScriptBlock }
ElseIf ($ScriptPath) { $AbstractSyntaxTree = Get-Ast -ScriptPath $ScriptPath }
ElseIf ($ScriptUri) { $AbstractSyntaxTree = Get-Ast -ScriptUri $ScriptUri }
$AmsiAstSignatures = $AbstractSyntaxTree.FindAll(
{
param($ast) (
# This Ast has text
($ast.Extent.Text) -and
# And it is flagged by AMSI
($PSAmsiScanner.GetPSAmsiScanResult($ast.Extent.Text))
)
}, $True) | Sort-Object { $_.Extent.Text.Length }
# Need to find 'leaves' of detected tree to get the real signatures
$NonDuplicates = @()
ForEach ($AmsiAstSignature in $AmsiAstSignatures) {
$Duplicate = $False
ForEach ($NonDuplicate in $NonDuplicates) {
If ($AmsiAstSignature.Extent.Text.Contains($NonDuplicate.Extent.Text)) {
If (-not ($AmsiAstSignature.Extent.Text.Length -eq $NonDuplicate.Extent.Text.Length -AND $AmsiAstSignature.Extent.StartOffset -ne $NonDuplicate.Extent.StartOffset)) {
$Duplicate = $True
}
break
}
}
If (-not $Duplicate) {
$NonDuplicates += $AmsiAstSignature
}
}
$NonDuplicates -as [array]
}
End {
If ($CreatedPSAmsiScanner) { $PSAmsiScanner.Dispose() }
}
}
function Test-ContainsAmsiAstSignatures {
<#
.SYNOPSIS
Tests if any Ast AMSI signatures are contained within an AbstractSyntaxTree.
Author: Ryan Cobb (@cobbr_io)
License: GNU GPLv3
Required Dependecies: none
Optional Dependencies: New-PSAmsiScanner, Get-Ast
.DESCRIPTION
Test-ContainsAmsiAstSignatures tests if any Ast AMSI signatures are contained within an AbstractSyntaxTree.
This function is much quicker than a full Find-AmsiAstSignatures search.
.PARAMETER AbstractSyntaxTree
Specifies the root Ast that represents the script to find Asts that contain AMSI signatures.
.PARAMETER ScriptString
Specifies the string containing the script to find Asts that contain AMSI signatures.
.PARAMETER ScriptBlock
Specifies the ScriptBlock containing the script to find Asts that contain AMSI signatures.
.PARAMETER ScriptPath
Specifies the Path containing the script to find Asts that contain AMSI signatures.
.PARAMETER ScriptUri
Specifies the Uri of the script to find Asts that contain AMSI signatures.
.PARAMETER PSAmsiScanner
Specifies the PSAmsiScanner to use to scan to find Asts that contain AMSI signatures.
.OUTPUTS
System.Management.Automation.Language.Ast[]
.EXAMPLE
Test-ContainsAmsiAstSignatures -Ast $AbstractSyntaxTree
.EXAMPLE
Test-ContainsAmsiAstSignatures "Write-Host example"
.EXAMPLE
Test-ContainsAmsiAstSignatures { Write-Host example }
.EXAMPLE
Test-ContainsAmsiAstSignatures -ScriptPath $ScriptPath
.EXAMPLE
@($Ast1, $Ast2, $Ast3) | Test-ContainsAmsiAstSignatures
.EXAMPLE
Get-ChildItem /path/to/scripts -Recurse -Include *.ps1 | Test-ContainsAmsiAstSignatures
.EXAMPLE
@('Write-Host example1', 'Write-Host example2', 'Write-Host example3') | Test-ContainsAmsiAstSignatures
.EXAMPLE
@({ Write-Host example1 }, { Write-Host example2 }, { Write-Host example3 }) | Test-ContainsAmsiAstSignatures
.NOTES
Test-ContainsAmsiAstSignatures is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
#>
[CmdletBinding(DefaultParameterSetName="ByString")] Param(
[Parameter(ParameterSetName="ByAst", Position = 0, ValueFromPipeline, Mandatory)]
[ValidateNotNullOrEmpty()]
[Alias('Ast')]
[System.Management.Automation.Language.Ast] $AbstractSyntaxTree,
[Parameter(ParameterSetName = "ByString", Position = 0, ValueFromPipeline, Mandatory)]
[ValidateNotNullOrEmpty()]
[String] $ScriptString,
[Parameter(ParameterSetName = "ByScriptBlock", Position = 0, ValueFromPipeline, Mandatory)]
[ValidateNotNullOrEmpty()]
[ScriptBlock] $ScriptBlock,
[Parameter(ParameterSetName = "ByPath", Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
[ValidateScript({Test-Path $_ -PathType leaf})]
[Alias('PSPath')]
[String] $ScriptPath,
[Parameter(ParameterSetName = "ByUri", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
[ValidateScript({$_.Scheme -match 'http|https'})]
[Uri] $ScriptUri,
[ValidateScript({$_.GetType().Name -eq 'PSAmsiScanner'})]
[System.Object] $PSAmsiScanner
)
Begin {
$CreatedPSAmsiScanner = $False
If (-not $PSAmsiScanner) {
$PSAmsiScanner = New-PSAmsiScanner
$CreatedPSAmsiScanner = $True
}
}
Process {
# Get the Ast object, if given a different ParameterSetName
If ($ScriptString) { $AbstractSyntaxTree = Get-Ast -ScriptString $ScriptString }
ElseIf ($ScriptBlock) { $AbstractSyntaxTree = Get-Ast -ScriptBlock $ScriptBlock }
ElseIf ($ScriptPath) { $AbstractSyntaxTree = Get-Ast -ScriptPath $ScriptPath }
ElseIf ($ScriptUri) { $AbstractSyntaxTree = Get-Ast -ScriptUri $ScriptUri }
# Use the Find function to find first matching ScriptBlockAst flagged by AMSI
$FirstFlagged = $AbstractSyntaxTree.Find(
{
param($ast) (
$ast -is [System.Management.Automation.Language.ScriptBlockAst] -AND
# This Ast has text
($ast.Extent.Text) -AND
# And it is flagged by AMSI
($PSAmsiScanner.GetPSAmsiScanResult($ast.Extent.Text))
)
}, $True)
If ($FirstFlagged) { $True }
Else { $False }
}
End {
If ($CreatedPSAmsiScanner) { $PSAmsiScanner.Dispose() }
}
}
function Find-AmsiPSTokenSignatures {
<#
.SYNOPSIS
Finds the PSTokens within a script that contain AMSI signatures that are flagged by AMSI.
Author: Ryan Cobb (@cobbr_io)
License: GNU GPLv3
Required Dependecies: none
Optional Dependencies: New-PSAmsiScanner, Get-PSTokens
.DESCRIPTION
Find-AmsiPSTokenSignatures finds the PSTokens within a script that contain AMSI signatures.
.PARAMETER PSTokens
Specifies the list of PSTokens that represent the script to find PSTokens from that contain AMSI signatures.
.PARAMETER ScriptString
Specifies the string containing the script to find PSTokens from that contain AMSI signatures.
.PARAMETER ScriptBlock
Specifies the ScriptBlock containing the script to find PSTokens from that contain AMSI signatures.
.PARAMETER ScriptPath
Specifies the Path containing the script to find PSTokens from that contain AMSI signatures.
.PARAMETER ScriptUri
Specifies the URI of the script to find PSTokens from that contain AMSI signatures.
.PARAMETER PSAmsiScanner
Specifies the PSAmsiScanner to use to find PSTokens that contain AMSI signatures.
.PARAMETER FilterPSTokenTypes
Specifies to only get PSTokens that have a PSTokenType in the provided list.
.OUTPUTS
System.Management.Automation.PSToken[]
.EXAMPLE
Find-AmsiPSTokenSignatures -PSTokens $PSTokens -FilterTokenTypes @('Comment', 'String')
.EXAMPLE
Find-AmsiPSTokenSignatures "Write-Host example"
.EXAMPLE
Find-AmsiPSTokenSignatures { Write-Host example }
.EXAMPLE
Find-AmsiPSTokenSignatures -ScriptPath $ScriptPath -FilterPSTokenTypes Comment
.EXAMPLE
@($PSTokens1, $PSTokens2, $PSTokens3) | Find-AmsiPSTokenSignatures
.EXAMPLE
Get-ChildItem /path/to/scripts -Recurse -Include *.ps1 | Find-AmsiPSTokenSignatures
.EXAMPLE
@('Write-Host example1', 'Write-Host example2', 'Write-Host example3') | Find-AmsiPSTokenSignatures
.EXAMPLE
@({ Write-Host example1 }, { Write-Host example2 }, { Write-Host example3 }) | Find-AmsiPSTokenSignatures
.NOTES
Find-AmsiPSTokenSignatures is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
#>
[CmdletBinding(DefaultParameterSetName="ByString")] Param(
[Parameter(ParameterSetName = "ByPSTokens", Position = 0, ValueFromPipeline, Mandatory)]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PSToken[]] $PSTokens,
[Parameter(ParameterSetName = "ByString", Position = 0, ValueFromPipeline, Mandatory)]
[ValidateNotNullOrEmpty()]
[String] $ScriptString,
[Parameter(ParameterSetName = "ByScriptBlock", Position = 0, ValueFromPipeline, Mandatory)]
[ValidateNotNullOrEmpty()]
[ScriptBlock] $ScriptBlock,
[Parameter(ParameterSetName = "ByPath", Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
[ValidateScript({Test-Path $_ -PathType leaf})]
[Alias('PSPath')]
[String] $ScriptPath,
[Parameter(ParameterSetName = "ByUri", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
[ValidateScript({$_.Scheme -match 'http|https'})]
[Uri] $ScriptUri,
[ValidateScript({$_.GetType().Name -eq 'PSAmsiScanner'})]
[System.Object] $PSAmsiScanner,