├── PSAmsi
├── Obfuscators
│ ├── PowerShell
│ │ ├── Invoke-Obfuscation
│ │ │ ├── Out-ObfuscatedStringCommand.ps1
│ │ │ ├── Out-ObfuscatedTokenCommand.ps1
│ │ │ └── LICENSE
│ │ └── PowerShellObfuscator.ps1
│ └── ObfuscatorTemplate.ps1
├── PSAmsi.psd1
├── Start-PSAmsiClient.ps1
├── Invoke-PSAmsiScan.ps1
├── Start-PSAmsiServer.ps1
├── AmsiFunctions.ps1
├── PSAmsiScanner.ps1
├── PSReflect.ps1
└── Find-AmsiSignatures.ps1
├── README.md
└── LICENSE
/PSAmsi/Obfuscators/PowerShell/Invoke-Obfuscation/Out-ObfuscatedStringCommand.ps1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cobbr/PSAmsi/HEAD/PSAmsi/Obfuscators/PowerShell/Invoke-Obfuscation/Out-ObfuscatedStringCommand.ps1
--------------------------------------------------------------------------------
/PSAmsi/Obfuscators/PowerShell/Invoke-Obfuscation/Out-ObfuscatedTokenCommand.ps1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cobbr/PSAmsi/HEAD/PSAmsi/Obfuscators/PowerShell/Invoke-Obfuscation/Out-ObfuscatedTokenCommand.ps1
--------------------------------------------------------------------------------
/PSAmsi/Obfuscators/ObfuscatorTemplate.ps1:
--------------------------------------------------------------------------------
1 | class Obfuscator {
2 | <#
3 |
4 | .SYNOPSIS
5 |
6 | Exists purely as a template class for implementing Obfuscators.
7 |
8 | Author: Ryan Cobb (@cobbr_io)
9 | License: GNU GPLv3
10 | Required Dependecies: none
11 | Optional Dependencies: none
12 |
13 | .DESCRIPTION
14 |
15 | Obfuscator is a template class for obfuscators. Would function as an
16 | interface, but PowerShell v5 does not implement true interfaces.
17 |
18 | .EXAMPLE
19 |
20 | class SomeLanguageObfuscator {
21 | SomeLanguageObfuscator() { }
22 | [String] OutMinimallyObfuscated($ScriptString) { return $ScriptString }
23 | }
24 |
25 | .NOTES
26 |
27 | Obfuscator is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
28 |
29 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
30 |
31 | #>
32 |
33 | Obfuscator() {}
34 |
35 | [String] OutMinimallyObfuscated([String] $ScriptString) { return $ScriptString }
36 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PSAmsi
2 |
3 | PSAmsi is a tool for auditing and defeating AMSI signatures.
4 |
5 | It's best utilized in a test environment to quickly create payloads you know will not be detected by a particular AntiMalware Provider, although it can be useful in certain situations outside of a test environment.
6 |
7 | When using outside of a test environment, be sure to understand how PSAmsi works, as it can generate AMSI alerts.
8 |
9 | # Getting Started
10 |
11 | [Installation instructions](https://github.com/cobbr/PSAmsi/wiki/Installation-and-Setup) and an [introduction to using PSAmsi](https://github.com/cobbr/PSAmsi/wiki/Introduction-To-PSAmsi) are available in the Wiki.
12 |
13 | # Disclaimer
14 |
15 | You are only authorized to use PSAmsi (and payloads created with PSAmsi) on systems that you have permission to use it on. It was created for research purposes only.
16 |
17 | # Acknowledgements
18 |
19 | A huge thanks to the following people whose code is used by PSAmsi:
20 | * Daniel Bohannon ([@danielhbohannon](https://twitter.com/danielhbohannon)) - PSAmsi currently uses [Invoke-Obfuscation](https://github.com/danielbohannon/Invoke-Obfuscation) for *all* of it's obfuscation. Thanks Daniel!
21 | * Matt Graeber ([@mattifestation](https://twitter.com/mattifestation)) - PSAmsi uses [PSReflect](https://github.com/mattifestation/PSReflect) to call the AMSI functions exported from the AMSI dll, while staying in memory. Thanks Matt!
22 |
--------------------------------------------------------------------------------
/PSAmsi/PSAmsi.psd1:
--------------------------------------------------------------------------------
1 | # Module manifest for module 'PSAmsi'
2 |
3 | @{
4 |
5 | # Version number of this module.
6 | ModuleVersion = '1.1'
7 |
8 | # ID used to uniquely identify this module
9 | GUID = 'e53f158d-8aa2-8c53-da89-ab75d32c8c01'
10 |
11 | # Author of this module
12 | Author = 'Ryan Cobb (@cobbr_io)'
13 |
14 | # Description of the functionality provided by this module
15 | Description = 'PSAmsi is a tool for auditing and defeating AMSI signatures.'
16 |
17 | # Minimum version of the Windows PowerShell engine required by this module
18 | PowerShellVersion = '5.0'
19 |
20 | # Script files (.ps1) that are run in the caller's environment prior to importing this module
21 | ScriptsToProcess = @('PSReflect.ps1','AmsiFunctions.ps1','PSAmsiScanner.ps1',
22 | 'Find-AmsiSignatures.ps1'
23 | 'Invoke-PSAmsiScan.ps1','Start-PSAmsiServer.ps1','Start-PSAmsiClient.ps1',
24 | 'Obfuscators\PowerShell\PowerShellObfuscator.ps1', 'Obfuscators\PowerShell\Invoke-Obfuscation\Out-ObfuscatedAst.ps1',
25 | 'Obfuscators\PowerShell\Invoke-Obfuscation\Out-ObfuscatedTokenCommand.ps1', 'Obfuscators\PowerShell\Invoke-Obfuscation\Out-ObfuscatedStringCommand.ps1')
26 |
27 | # Functions to export from this module
28 | FunctionsToExport = @('Start-PSAmsiServer', 'Start-PSAmsiClient', 'Invoke-PSAmsiScan',
29 | 'New-PSAmsiScanner', 'Get-PSAmsiScanResult', 'Reset-PSAmsiScanCache', 'Invoke-PSAmsiScan',
30 | 'Find-AmsiSignatures', 'Find-AmsiAstSignatures', 'Get-AmsiPSTokenSignatures',
31 | 'Test-ContainsAmsiSignatures', 'Test-ContainsAmsiAstSignatures', 'Test-ContainsAmsiPSTokenSignatures',
32 | 'Get-Ast', 'Get-PSTokens'
33 | 'Out-MinimallyObfuscated', 'Get-ContainingTokens',
34 | 'AmsiInitialize', 'AmsiOpenSession', 'AmsiScanString', 'AmsiScanBuffer', 'AmsiCloseSession', 'AmsiUninitialize')
35 |
36 | }
--------------------------------------------------------------------------------
/PSAmsi/Start-PSAmsiClient.ps1:
--------------------------------------------------------------------------------
1 | function Start-PSAmsiClient {
2 | <#
3 |
4 | .SYNOPSIS
5 |
6 | Conducts a series of PSAmsiScans retrieved from a PSAmsiServer.
7 |
8 | Author: Ryan Cobb (@cobbr_io)
9 | License: GNU GPLv3
10 | Required Dependecies: New-PSAmsiScanner, Invoke-PSAmsiScan
11 | Optional Dependencies: none
12 |
13 | .DESCRIPTION
14 |
15 | Start-PSAmsiClient retrieves PSAmsiScan requests from a PSAmsiServer and
16 | checks them against the client's AMSI AntiMalware Provider using Invoke-PSAmsiScan.
17 |
18 | .PARAMETER ServerUri
19 |
20 | Specifies the URI of the PSAmsiServer to retreive requests from.
21 |
22 | .PARAMETER AlertLimit
23 |
24 | Specifies the maximum amount of AMSI alerts this client is allowed to generate.
25 |
26 | .PARAMETER Delay
27 |
28 | Specifies the amount of time (in seconds) to wait between AMSI alerts.
29 |
30 | .PARAMETER PSAmsiScanner
31 |
32 | Specifies the PSAmsiScanner to use for AMSI scans.
33 |
34 | .PARAMETER FindAmsiSignatures
35 |
36 | Specifies that the PSAmsiScan should find and return the AMSI signatures found in the script
37 | in addition to the result of the scan.
38 |
39 | .PARAMETER GetMinimallyObfuscated
40 |
41 | Specifies that the PSAmsiScan should minimally obfuscate the script until it is no longer flagged by AMSI.
42 |
43 | .EXAMPLE
44 |
45 | Start-PSAmsiClient -ServerUri http://10.100.100.10
46 |
47 | .EXAMPLE
48 |
49 | Start-PSAmsiClient -ServerUri http://example.com -AlertLimit 10 -Delay 3600 -FindAmsiSignatures
50 |
51 | .EXAMPLE
52 |
53 | Start-PSAmsiClient -ServerUri http://example.com -Delay 60 -GetMinimallyObfuscated
54 |
55 | .NOTES
56 |
57 | Start-PSAmsiClient is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
58 |
59 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
60 |
61 | #>
62 |
63 | Param(
64 | [Parameter(Position = 0, Mandatory)]
65 | [ValidateScript({$_.Scheme -match 'http|https'})]
66 | [Uri] $ServerUri,
67 |
68 | [Parameter(Position = 1)]
69 | [ValidateRange(0, [Int]::MaxValue)]
70 | [Int] $AlertLimit = 0,
71 |
72 | [Parameter(Position = 2)]
73 | [ValidateRange(0, [Int]::MaxValue)]
74 | [Int] $Delay = 0,
75 |
76 | [Parameter(Position = 3)]
77 | [ValidateScript({$_.GetType().Name -eq 'PSAmsiScanner'})]
78 | [System.Object] $PSAmsiScanner,
79 |
80 | [Switch] $FindAmsiSignatures,
81 |
82 | [Switch] $GetMinimallyObfuscated
83 | )
84 |
85 | $CreatedPSAmsiScanner = $False
86 | # Create the PSAmsiScanner to be used by the PSAmsiClient, if not provided one.
87 | If (-not $PSAmsiScanner) {
88 | $CreatedPSAmsiScanner = $True
89 | $PSAmsiScanner = New-PSAmsiScanner -AlertLimit $AlertLimit -Delay $Delay
90 | } Else {
91 | $PSAmsiScanner.AlertLimit = $AlertLimit
92 | $PSAmsiScanner.Delay = $Delay
93 | }
94 |
95 | # Use the system web proxy, if one exists
96 | (New-Object System.Net.WebClient).Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
97 |
98 | # Retrieve the PSAmsiScanRequests from the PSAmsiScanServer
99 | $PSAmsiScanRequestObj = Invoke-RestMethod -Uri $ServerUri -TimeoutSec 0
100 |
101 | # Read CachedAmsiScanResults, PSAmsiServer will provide cached results from other PSAmsiScanClients, if any.
102 | $CachedAmsiScanResults = @{}
103 | $Result = $PSAmsiScanRequestObj.CachedAmsiScanResults | Get-Member -MemberType Properties | % {
104 | $CachedAmsiScanResults.Add($_.Name, $PSAmsiScanRequestObj.CachedAmsiScanResults.($_.Name))
105 | }
106 | Write-Verbose "[Start-PSAmsiClient] Received $($CachedAmsiScanResults.Count) cached scan results from PSAmsiServer"
107 | Write-Verbose "[Start-PSAmsiClient] Received $($PSAmsiScanRequestObj.PSAmsiScanRequests.Count) PSAmsiScanRequests from PSAmsiServer"
108 | # Have the PSAmsiScanner use any cached scan results provided from the server
109 | $PSAmsiScanner.ScanCache = $CachedAmsiScanResults
110 |
111 | # Iterate through PSAmsiScanRequests, calling Invoke-PSAmsiScan for each one
112 | $PSAmsiScanRequests = $PSAmsiScanRequestObj.PSAmsiScanRequests
113 | If ($FindAmsiSignatures -and $GetMinimallyObfuscated) {
114 | $PSAmsiScanResults = $PSAmsiScanRequests | % { Invoke-PSAmsiScan -ScriptName $_.ScriptName -ScriptString $_.ScriptString -PSAmsiScanner $PSAmsiScanner -FindAmsiSignatures -GetMinimallyObfuscated -IncludeStatus }
115 | } ElseIf ($FindAmsiSignatures) {
116 | $PSAmsiScanResults = $PSAmsiScanRequests | % { Invoke-PSAmsiScan -ScriptName $_.ScriptName -ScriptString $_.ScriptString -PSAmsiScanner $PSAmsiScanner -FindAmsiSignatures -IncludeStatus }
117 | } ElseIf ($GetMinimallyObfuscated) {
118 | $PSAmsiScanResults = $PSAmsiScanRequests | % { Invoke-PSAmsiScan -ScriptName $_.ScriptName -ScriptString $_.ScriptString -PSAmsiScanner $PSAmsiScanner -GetMinimallyObfuscated -IncludeStatus }
119 | } Else {
120 | $PSAmsiScanResults = $PSAmsiScanRequests | % { Invoke-PSAmsiScan -ScriptName $_.ScriptName -ScriptString $_.ScriptString -PSAmsiScanner $PSAmsiScanner -IncludeStatus }
121 | }
122 |
123 | # If any PSAmsiScanRequests are not complete due to AlertLimit, then provide CachedAmsiScanResults to PSAmsiScanServer
124 | # Otherwise, we will just give an empty object to reduce network traffic
125 | $UnfinishedPSAmsiScanRequests = @()
126 | $UnfinishedPSAmsiScanRequests += $PSAmsiScanResults | ? { -not $_.RequestCompleted }
127 |
128 | If ($UnfinishedPSAmsiScanRequests.Count -gt 0) {
129 | Write-Verbose "[Start-PSAmsiClient] $($UnfinishedPSAmsiScanRequests.Count) PSAmsiScanRequest(s) were not completed. Sending $($PSAmsiScanner.ScanCache.Count) cached scan results back to PSAmsiServer."
130 | $PSAmsiScanResultObj = [PSCustomObject] @{ PSAmsiScanResults = $PSAmsiScanResults; CachedAmsiScanResults = $PSAmsiScanner.ScanCache }
131 | }
132 | Else {
133 | $PSAmsiScanResultObj = [PSCustomObject] @{ PSAmsiScanResults = $PSAmsiScanResults; CachedAmsiScanResults = @{} }
134 | }
135 |
136 | # We can now dispose the PSAmsiScanner object, if we created it
137 | If ($CreatedPSAmsiScanner) {
138 | $PSAmsiScanner.Dispose()
139 | }
140 |
141 | # Convert the results to JSON and POST them back to the PSAmsiServer
142 | $JsonString = $PSAmsiScanResultObj | ConvertTo-Json -Depth 4 -Compress
143 | $Response = Invoke-RestMethod -Method Post -Uri $ServerUri -Body $JsonString -TimeoutSec 0
144 | }
--------------------------------------------------------------------------------
/PSAmsi/Invoke-PSAmsiScan.ps1:
--------------------------------------------------------------------------------
1 | function Invoke-PSAmsiScan {
2 | <#
3 |
4 | .SYNOPSIS
5 |
6 | Conducts a PSAmsiScan on a given script.
7 |
8 | Author: Ryan Cobb (@cobbr_io)
9 | License: GNU GPLv3
10 | Required Dependecies: New-PSAmsiScanner, Find-AmsiSignatures, Out-MinimallyObfuscated
11 | Optional Dependencies: none
12 |
13 | .DESCRIPTION
14 |
15 | Invoke-PSAmsiScan conducts a PSAmsiScan on a given script, and optionally provides the AMSI signatures
16 | within the script and/or a minimally obfuscated copy of the script that is no longer flagged by AMSI.
17 |
18 | .PARAMETER ScriptString
19 |
20 | The string containing the script to be scanned.
21 |
22 | .PARAMETER ScriptBlock
23 |
24 | The ScriptBlock containing the script to be scanned.
25 |
26 | .PARAMETER ScriptPath
27 |
28 | The Path to the script to be scanned.
29 |
30 | .PARAMETER ScriptUri
31 |
32 | The URI of the script to be scanned.
33 |
34 | .PARAMETER ScriptName
35 |
36 | The name of the script to be scanned.
37 |
38 | .PARAMETER AlertLimit
39 |
40 | Specifies the maximum amount of AMSI alerts this scan is allowed to generate.
41 |
42 | .PARAMETER Delay
43 |
44 | Specifies the amount of time (in seconds) to wait between AMSI alerts.
45 |
46 | .PARAMETER PSAmsiScanner
47 |
48 | Specifies the PSAmsiScanner to use for AMSI scans.
49 |
50 | .PARAMETER FindAmsiSignatures
51 |
52 | Specifies that the PSAmsiScan should find and return the AMSI signatures found in the script
53 | in addition to the result of the scan.
54 |
55 | .PARAMETER GetMinimallyObfuscated
56 |
57 | Specifies that the PSAmsiScan should minimally obfuscate the script until it is
58 | no longer flagged by AMSI.
59 |
60 | .OUTPUTS
61 |
62 | PSCustomObject
63 |
64 | .EXAMPLE
65 |
66 | Invoke-PSAmsiScan -ScriptString "Write-Host test"
67 |
68 | .EXAMPLE
69 |
70 | Invoke-PSAmsiScan -ScriptString "Write-Host test" -FindAmsiSignatures -AlertLimit 15 -Delay 3
71 |
72 | .EXAMPLE
73 |
74 | Invoke-PSAmsiScan -ScriptString "Write-Host test" -GetMinimallyObfuscated
75 |
76 | .NOTES
77 |
78 | Invoke-PSAmsiScan is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
79 |
80 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
81 |
82 | #>
83 | [CmdletBinding(DefaultParameterSetName = "ByString")] Param(
84 | [Parameter(ParameterSetName = "ByString", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
85 | [ValidateNotNullOrEmpty()]
86 | [String] $ScriptString,
87 |
88 | [Parameter(ParameterSetName = "ByScriptBlock", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
89 | [ValidateNotNullOrEmpty()]
90 | [ScriptBlock] $ScriptBlock,
91 |
92 | [Parameter(ParameterSetName = "ByPath", Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
93 | [ValidateScript({Test-Path $_ -PathType leaf})]
94 | [Alias('PSPath')]
95 | [String] $ScriptPath,
96 |
97 | [Parameter(ParameterSetName = "ByUri", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
98 | [ValidateScript({$_.Scheme -match 'http|https'})]
99 | [Uri] $ScriptUri,
100 |
101 | [Parameter(Position = 1, ValueFromPipelineByPropertyName)]
102 | [ValidateNotNullOrEmpty()]
103 | [String] $ScriptName,
104 |
105 | [Parameter(Position = 2)]
106 | [ValidateRange(0,[Int]::MaxValue)]
107 | [Int] $AlertLimit = 0,
108 |
109 | [Parameter(Position = 3)]
110 | [ValidateRange(0,[Int]::MaxValue)]
111 | [Int] $Delay = 0,
112 |
113 | [Parameter(Position = 4)]
114 | [ValidateScript({$_.GetType().Name -eq 'PSAmsiScanner'})]
115 | [System.Object] $PSAmsiScanner,
116 |
117 | [Switch] $FindAmsiSignatures,
118 |
119 | [Switch] $GetMinimallyObfuscated,
120 |
121 | [Switch] $IncludeStatus
122 | )
123 | Begin {
124 | $CreatedPSAmsiScanner = $False
125 | If (-not $PSAmsiScanner) {
126 | # Create a PSAmsiScanner
127 | $PSAmsiScanner = New-PSAmsiScanner -AlertLimit $AlertLimit -Delay $Delay
128 | $CreatedPSAmsiScanner = $True
129 | }
130 | Else {
131 | If ($AlertLimit -gt 0) {
132 | $PSAmsiScanner.AlertLimit = $AlertLimit
133 | $PSAmsiScanner.AlertLimitEnabled = $True
134 | }
135 | $PSAmsiScanner.Delay = $Delay
136 | }
137 | }
138 |
139 | Process {
140 | If ($ScriptBlock) { $ScriptString = $ScriptBlock -as [String] }
141 | ElseIf ($ScriptPath) { $ScriptString = Get-Content -Path $ScriptPath -Raw }
142 | ElseIf ($ScriptUri) { $ScriptString = [Net.Webclient]::new().DownloadString($ScriptUri) }
143 |
144 | # Scan the given ScriptString
145 | $ScriptIsFlagged = Test-ContainsAmsiSignatures -ScriptString $ScriptString -PSAmsiScanner $PSAmsiScanner
146 | $PSAmsiScanResult = [PSCustomObject] @{ ScriptIsFlagged = $ScriptIsFlagged }
147 | If ($FindAmsiSignatures) {
148 | $AmsiSignatures = @()
149 | If ($ScriptIsFlagged) {
150 | Write-Verbose "[Invoke-PSAmsiScan] Finding Amsi Signatures in the Script."
151 | $AmsiSignatures = Find-AmsiSignatures -ScriptString $ScriptString -PSAmsiScanner $PSAmsiScanner
152 | # Use Find-AmsiSignatures to retreive the exact strings flagged by AMSI
153 | Write-Verbose "[Invoke-PSAmsiScan] Found $($AmsiSignatures.Count) Amsi Signatures in the Script."
154 | }
155 | $PSAmsiScanResult | Add-Member -Name 'AmsiSignatures' -Value $AmsiSignatures -MemberType NoteProperty
156 | }
157 | If ($GetMinimallyObfuscated) {
158 | Write-Verbose "[Invoke-PSAmsiScan] Getting MinimallyObfuscated copy of Script"
159 | # Use Get-MinimallyObfuscated to retrieve a minimally obfuscated copy of the ScriptString
160 | # that is not flagged by AMSI
161 | $MinimallyObfuscated = $ScriptString
162 | If ($ScanResult -and (-not $PSAmsiScanner.AlertLimitReached)) {
163 | If ($AmsiSignatures) {
164 | $MinimallyObfuscated = Get-MinimallyObfuscated -ScriptString $ScriptString -AmsiSignatures $AmsiSignatures -PSAmsiScanner $PSAmsiScanner
165 | } Else {
166 | $MinimallyObfuscated = Get-MinimallyObfuscated -ScriptString $ScriptString -PSAmsiScanner $PSAmsiScanner
167 | }
168 | }
169 | $PSAmsiScanResult | Add-Member -Name 'MinimallyObfuscated' -Value $MinimallyObfuscated -MemberType NoteProperty
170 | }
171 |
172 | If ($IncludeStatus -or $PSAmsiScanner.AlertLimitEnabled) {
173 | If ($PSAmsiScanner.AlertLimitReached) {
174 | Write-Verbose "[Invoke-PSAmsiScan] AlertLimit reached during execution. Reporting scan as not completed."
175 | }
176 | $PSAmsiScanResult | Add-Member -Name 'RequestCompleted' -Value (-not $PSAmsiScanner.AlertLimitReached) -MemberType NoteProperty
177 | }
178 | If ($ScriptName) {
179 | $PSAmsiScanResult | Add-Member -Name 'ScriptName' -Value $ScriptName -MemberType NoteProperty
180 | }
181 | $PSAmsiScanResult
182 | }
183 |
184 | End {
185 | # Dispose the PSAmsiScanner when done, if it was created within this function
186 | If ($CreatedPSAmsiScanner) {
187 | $PSAmsiScanner.Dispose()
188 | }
189 | }
190 | }
--------------------------------------------------------------------------------
/PSAmsi/Start-PSAmsiServer.ps1:
--------------------------------------------------------------------------------
1 | function Start-PSAmsiServer {
2 | <#
3 |
4 | .SYNOPSIS
5 |
6 | Starts a PSAmsiServer that sends PSAmsiScanRequests to connecting PSAmsiClients.
7 |
8 | Author: Ryan Cobb (@cobbr_io)
9 | License: GNU GPLv3
10 | Required Dependecies: none
11 | Optional Dependencies: none
12 |
13 | .DESCRIPTION
14 |
15 | Start-PSAmsiServer starts a PSAmsiServer HTTP Listener and sends PSAmsiScanRequests
16 | to connecting PSAmsiClients and receives the results of the scans.
17 |
18 | .PARAMETER Port
19 |
20 | Specifies the port to start the PSAmsiServer HTTP Listener on.
21 |
22 | .PARAMETER ScriptString
23 |
24 | Specifies the string containing the script to be sent as PSAmsiScanRequests
25 | to PSAmsiClients.
26 |
27 | .PARAMETER ScriptBlock
28 |
29 | Specifies the ScriptBlock containing the script to be sent as PSAmsiScanRequests
30 | to PSAmsiClients.
31 |
32 | .PARAMETER ScriptPath
33 |
34 | Specifies the Path to the script to be sent as PSAmsiScanRequests to PSAMsiClients.
35 |
36 | .PARAMETER ScriptUri
37 |
38 | Specifies the URI of the script to be sent as PSAmsiScanRequests to PSAMsiClients.
39 |
40 | .OUTPUTS
41 |
42 | PSCustomObject
43 |
44 | .EXAMPLE
45 |
46 | Start-PSAmsiServer -Port 443 -ScriptPath Invoke-Example.ps1
47 |
48 | .EXAMPLE
49 |
50 | Get-ChildItem /path/to/scripts -Recurse -Include *.ps1 | Start-PSAmsiServer -Port 80
51 |
52 | .NOTES
53 |
54 | Start-PSAmsiServer is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
55 |
56 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
57 |
58 | #>
59 | [CmdletBinding(DefaultParameterSetName = "ByPath")] Param(
60 | [Parameter(Position = 0, Mandatory)]
61 | [ValidateRange(1, 65535)]
62 | [Int] $Port,
63 |
64 | [Parameter(ParameterSetName = "ByString", Position = 1, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
65 | [ValidateNotNull()]
66 | [String] $ScriptString,
67 |
68 | [Parameter(ParameterSetName = "ByScriptBlock", Position = 1, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
69 | [ValidateNotNullOrEmpty()]
70 | [ScriptBlock] $ScriptBlock,
71 |
72 | [Parameter(ParameterSetName = "ByPath", Position = 1, ValueFromPipelineByPropertyName, Mandatory)]
73 | [ValidateScript({Test-Path $_ -PathType leaf})]
74 | [Alias('PSPath')]
75 | [String] $ScriptPath,
76 |
77 | [Parameter(ParameterSetName = "ByUri", Position = 1, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
78 | [ValidateScript({$_.Scheme -match 'http|https'})]
79 | [Uri] $ScriptUri
80 | )
81 | Begin{
82 | $ErrorActionPreference = "Stop"
83 | $HTTPServer = New-Object System.Net.HTTPListener
84 | Write-Verbose "[Start-PSAmsiServer] HTTP Listener starting on port $($Port)"
85 | $HTTPServer.Prefixes.Add("http://+:" + $Port + "/")
86 | $HTTPServer.Start()
87 |
88 | $PSAmsiScanRequests = @()
89 | $ScriptForName = @{}
90 | }
91 |
92 | Process{
93 | If ($ScriptBlock) {
94 | $ScriptString = $ScriptBlock -as [String]
95 | $ScriptName = $ScriptBlock.Id
96 | }
97 | ElseIf ($ScriptPath) {
98 | $ScriptString = Get-Content -Path $ScriptPath -Raw;
99 | $ScriptName = Split-Path -Path $ScriptPath -Leaf -Resolve
100 | }
101 | ElseIf ($ScriptUri) {
102 | $ScriptString = [Net.Webclient]::new().DownloadString($ScriptUri)
103 | $ScriptName = Split-Path -Path $ScriptUri.OriginalString -Leaf
104 | }
105 | Else {
106 | $ScriptName = ""
107 | $null = [System.Security.Cryptography.HashAlgorithm]::Create('SHA256').ComputeHash([Text.Encoding]::UTF8.GetBytes($ScriptString)) | % {
108 | $ScriptName += $_.ToString("x2")
109 | }
110 | }
111 |
112 | $ScriptForName[$ScriptName] = $ScriptString
113 | $PSAmsiScanRequests += [PSCustomObject] @{ ScriptName = $ScriptName; ScriptString = $ScriptString; }
114 | }
115 |
116 | End {
117 | Write-Verbose "[Start-PSAmsiServer] Prepared $($PSAmsiScanRequests.Count) PSAmsiScanRequest(s)."
118 | $CachedAmsiScanResults = @{}
119 | $PSAmsiScanResults = @()
120 | $PendingGetRequestResponsesQueue = New-Object System.Collections.Queue
121 |
122 | $AwaitingGetRequest = $True
123 |
124 | $Finished = $False
125 |
126 | While (-not $Finished) {
127 | If ($AwaitingGetRequest -and $PendingGetRequestResponsesQueue.Count -gt 0) {
128 | Write-Verbose "[Start-PSAmsiServer] Servicing GET request from queue."
129 | $HTTPServerResponse = $PendingGetRequestResponsesQueue.Dequeue()
130 |
131 | $PSAmsiScanRequestObj = [PSCustomObject] @{ PSAmsiScanRequests = $PSAmsiScanRequests; CachedAmsiScanResults = $CachedAmsiScanResults }
132 | $JsonString = $PSAmsiScanRequestObj | ConvertTo-Json -Depth 4 -Compress
133 |
134 | $ResponseWriter = New-Object System.IO.StreamWriter($HTTPServerResponse.OutputStream)
135 | $ResponseWriter.Write($JsonString)
136 | $ResponseWriter.Close()
137 | $AwaitingGetRequest = $False
138 | }
139 | Write-Verbose "[Start-PSAmsiServer] Waiting for request from a client..."
140 | $HTTPServerContext = $HTTPServer.GetContext()
141 | $HTTPClientRequest = $HTTPServerContext.Request
142 | $HTTPServerResponse = $HTTPServerContext.Response
143 | If ($HTTPClientRequest.HttpMethod -eq 'GET') {
144 | If ((Split-Path -Path ($HTTPClientRequest.Url) -Leaf).ToLower().EndsWith('psamsiclient.ps1')) {
145 | Write-Verbose "[Start-PSAmsiServer] Received GET request from client for PSAmsiClient.ps1"
146 | $ResponseWriter = New-Object System.IO.StreamWriter($HTTPServerResponse.OutputStream)
147 | $PSAmsiClientPath = (Split-Path -Parent $PSCommandPath) + "/../PSAmsiClient.ps1"
148 | If (Test-Path $PSAmsiClientPath) {
149 | Write-Verbose "[Start-PSAmsiServer] Serving PSAmsiClient.ps1 to client"
150 | $ClientCode = Get-Content $PSAmsiClientPath -Raw
151 | $ResponseWriter.Write($ClientCode)
152 | $ResponseWriter.Close()
153 | }
154 | Else {
155 | Write-Error "[Start-PSAmsiServer] PSAmsiClient.ps1 file could not be found. Sending empty response."
156 | $ResponseWriter.Write('')
157 | $ResponseWriter.Close()
158 | }
159 | }
160 | Else {
161 | Write-Verbose "[Start-PSAmsiServer] Received GET request from client. Adding it to the queue."
162 | $PendingGetRequestResponsesQueue.Enqueue($HTTPServerResponse)
163 | }
164 | }
165 | ElseIf ($HTTPClientRequest.HttpMethod -eq 'POST') {
166 | Write-Verbose "[Start-PSAmsiServer] Received POST request from client. Processing data returned."
167 | $RequestReader = New-Object System.IO.StreamReader($HTTPClientRequest.InputStream, $HTTPClientRequest.ContentEncoding)
168 | $PSAmsiScanResultObj = $RequestReader.ReadToEnd() | ConvertFrom-Json
169 | $HTTPServerResponse.ContentLength64 = 0
170 | $HTTPServerResponse.OutputStream.Close()
171 | $PSAmsiScanResults += $PSAmsiScanResultObj.PSAmsiScanResults | ? { $_.RequestCompleted }
172 | $UnfinishedPSAmsiScanResults = $PSAmsiScanResultObj.PSAmsiScanResults | ? { -not $_.RequestCompleted }
173 | If ($UnfinishedPSAmsiScanResults) {
174 | Write-Verbose "[Start-PSAmsiServer] $($UnfinishedPSAmsiScanResults.Count) PSAmsiScanRequest(s) were not completed."
175 | # Not finished with at least one scan request
176 | $CachedAmsiScanResults = @{}
177 | $Result = $PSAmsiScanResultObj.CachedAmsiScanResults | Get-Member -MemberType Properties | % {
178 | $CachedAmsiScanResults.Add($_.Name, $PSAmsiScanResultObj.CachedAmsiScanResults.($_.Name))
179 | }
180 | $PSAmsiScanRequests = @()
181 | ForEach ($UnfinishedPSAmsiScanResult in $UnfinishedPSAmsiScanResults) {
182 | If ($UnfinishedPSAmsiScanResult.MinimallyObfuscated) {
183 | $ScriptString = $UnfinishedPSAmsiScanResult.MinimallyObfuscated
184 | }
185 | Else {
186 | $ScriptString = $ScriptForName[$UnfinishedPSAmsiScanResult.ScriptName]
187 | }
188 | $PSAmsiScanRequests += [PSCustomObject] @{ ScriptName = $UnfinishedPSAmsiScanResult.ScriptName; ScriptString = $ScriptString; }
189 | }
190 | $AwaitingGetRequest = $True
191 | }
192 | Else {
193 | $Finished = $True
194 | }
195 | }
196 | Else {
197 | Write-Error "[Start-PSAmsiServer] Client $($Client.RemoteEndpoint) attempted unknown HttpMethod $($HTTPClientRequest.HttpMethod)"
198 | }
199 | }
200 | Write-Verbose "[Start-PSAmsiServer] All scans completed. Stopping Server."
201 | $HTTPServer.Stop()
202 | $Properties = @('ScriptName', 'ScriptIsFlagged', 'RequestCompleted')
203 | If ($PSAmsiScanResults | ? { $_.AmsiSignatures }) { $Properties += 'AmsiSignatures' }
204 | If ($PSAmsiScanResults | ? { $_.MinimallyObfuscated }) { $Properties += 'MinimallyObfuscated' }
205 | $PSAmsiScanResults | Select-Object -Property $Properties -ExcludeProperty RequestCompleted | Sort-Object ScriptIsFlagged -Descending
206 | }
207 | }
--------------------------------------------------------------------------------
/PSAmsi/Obfuscators/PowerShell/Invoke-Obfuscation/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2017 Daniel Bohannon
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/PSAmsi/AmsiFunctions.ps1:
--------------------------------------------------------------------------------
1 | If ((gci env: | ? { $_.Name -eq 'OS' }).Value -eq 'Windows_NT' -AND
2 | (Get-CimInstance Win32_OperatingSystem).Version.StartsWith('10')) {
3 | # Create an InMemoryModule, amsi, and AMSI_RESULT enum. (Uses PSReflect written by Matt Graeber (@mattifestation))
4 | $Module = New-InMemoryModule -ModuleName AMSI
5 |
6 | $FunctionDefinitions = @(
7 | (func amsi AmsiInitialize ([UInt32]) @(
8 | [String], # _In_ LPCWSTR appName,
9 | [Int64].MakeByRefType() # _Out_ HAMSICONTEXT *amsiContext
10 | ) -EntryPoint AmsiInitialize -SetLastError),
11 |
12 | (func amsi AmsiUninitialize ([Void]) @(
13 | [IntPtr] # _In_ HAMSICONTEXT amsiContext
14 | ) -EntryPoint AmsiUninitialize -SetLastError),
15 |
16 | (func amsi AmsiOpenSession ([UInt32]) @(
17 | [IntPtr], # _In_ HAMSICONTEXT amsiContext
18 | [Int].MakeByRefType() # _Out_ HAMSISESSION *session
19 | ) -EntryPoint AmsiOpenSession -SetLastError),
20 |
21 | (func amsi AmsiCloseSession ([Void]) @(
22 | [IntPtr], # _In_ HAMSICONTEXT amsiContext
23 | [IntPtr] # _In_ HAMSISESSION session
24 | ) -EntryPoint AmsiCloseSession -SetLastError),
25 |
26 | (func amsi AmsiScanBuffer ([UInt32]) @(
27 | [IntPtr], # _In_ HAMSICONTEXT amsiContext
28 | [IntPtr], # _In_ PVOID buffer
29 | [UInt32], # _In_ ULONG length
30 | [String], # _In_ LPCWSTR contentName
31 | [IntPtr], # _In_opt_ HAMSISESSION session
32 | [Int].MakeByRefType() # _Out_ AMSI_RESULT *result
33 | ) -EntryPoint AmsiScanBuffer -SetLastError),
34 |
35 | (func amsi AmsiScanString ([UInt32]) @(
36 | [IntPtr], # _In_ HAMSICONTEXT amsiContext
37 | [String], # _In_ LPCWSTR string
38 | [String], # _In_ LPCWSTR contentName
39 | [IntPtr], # _In_opt_ HAMSISESSION session
40 | [Int].MakeByRefType() # _Out_ AMSI_RESULT *result
41 | ) -EntryPoint AmsiScanString -SetLastError)
42 | )
43 |
44 | $AMSI_RESULT = psenum $Module AMSI.AMSI_RESULT UInt32 @{
45 | AMSI_RESULT_CLEAN = 0
46 | AMSI_RESULT_NOT_DETECTED = 1
47 | AMSI_RESULT_BLOCKED_BY_ADMIN_START = 16384
48 | AMSI_RESULT_BLOCKED_BY_ADMIN_END = 20479
49 | AMSI_RESULT_DETECTED = 32768
50 | }
51 |
52 | $Types = $FunctionDefinitions | Add-Win32Type -Module $Module -Namespace 'AMSI.NativeMethods'
53 | $amsi = $Types['amsi']
54 | }
55 |
56 | function AmsiInitialize {
57 | <#
58 |
59 | .SYNOPSIS
60 |
61 | Initializes an AmsiContext to conduct AMSI scans.
62 |
63 | Author: Ryan Cobb (@cobbr_io)
64 | License: GNU GPLv3
65 | Required Dependecies: PSReflect, amsi
66 | Optional Dependencies: none
67 |
68 | .DESCRIPTION
69 |
70 | AmsiInitialize initializes an AmsiContext to conduct AMSI scans by calling the function
71 | described here: https://msdn.microsoft.com/en-us/library/windows/desktop/dn889862(v=vs.85).aspx
72 |
73 | .PARAMETER appName
74 |
75 | The name of the App that will be submitting AMSI scan requests.
76 |
77 | .PARAMETER amsiContext
78 |
79 | A reference to the amsiContext that will be set by this function.
80 |
81 | .OUTPUTS
82 |
83 | Int
84 |
85 | .EXAMPLE
86 |
87 | $AmsiContext = [IntPtr]::Zero
88 | AmsiInitialize -appName "PSAmsi" -amsiContext ([ref]$AmsiContext)
89 |
90 | .NOTES
91 |
92 | AmsiInitialize is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
93 |
94 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
95 |
96 | #>
97 | Param (
98 | [Parameter(Position = 0, Mandatory)]
99 | [ValidateNotNullOrEmpty()]
100 | [String] $appName,
101 |
102 | [Parameter(Position = 1, Mandatory)]
103 | [ref] $amsiContext
104 | )
105 |
106 | $HResult = $amsi::AmsiInitialize($appName, $amsiContext)
107 |
108 | If ($HResult -ne 0) {
109 | throw "AmsiInitialize Error: $($HResult). AMSI may not be enabled on your system."
110 | }
111 |
112 | $HResult
113 | }
114 |
115 | function AmsiOpenSession {
116 | <#
117 |
118 | .SYNOPSIS
119 |
120 | Opens an AmsiSession associated with an AmsiContext to conduct AMSI scans.
121 |
122 | Author: Ryan Cobb (@cobbr_io)
123 | License: GNU GPLv3
124 | Required Dependecies: PSReflect, amsi
125 | Optional Dependencies: none
126 |
127 | .DESCRIPTION
128 |
129 | AmsiOpenSession opens an AmsiSession assocaited with an AmsiContext by calling the function
130 | described here: https://msdn.microsoft.com/en-us/library/windows/desktop/dn889863(v=vs.85).aspx
131 |
132 | .PARAMETER amsiContext
133 |
134 | A pointer to the AmsiContext for which this AmsiSession will be associated.
135 |
136 | .PARAMETER session
137 |
138 | A reference to the AmsiSession that will be set by this function.
139 |
140 | .OUTPUTS
141 |
142 | Int
143 |
144 | .EXAMPLE
145 |
146 | $AmsiSession = [IntPtr]::Zero
147 | AmsiInitialize -amsiContext $AmsiContext -session ([ref]$AmsiSession)
148 |
149 | .NOTES
150 |
151 | AmsiOpenSession is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
152 |
153 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
154 |
155 | #>
156 | Param (
157 | [Parameter(Position = 0, Mandatory)]
158 | [ValidateNotNullOrEmpty()]
159 | [IntPtr] $amsiContext,
160 |
161 | [Parameter(Position = 1, Mandatory)]
162 | [ref] $session
163 | )
164 |
165 | $HResult = $amsi::AmsiOpenSession($amsiContext, $session)
166 |
167 | If ($HResult -ne 0) {
168 | throw "AmsiOpenSession Error: $($HResult)"
169 | }
170 |
171 | $HResult
172 | }
173 |
174 | function AmsiScanString {
175 | <#
176 |
177 | .SYNOPSIS
178 |
179 | Submits a string to the AMSI to be scanned by the AntiMalware Provider.
180 |
181 | Author: Ryan Cobb (@cobbr_io)
182 | License: GNU GPLv3
183 | Required Dependecies: PSReflect, amsi
184 | Optional Dependencies: none
185 |
186 | .DESCRIPTION
187 |
188 | AmsiScanString submits a string to to the AMSI to be scanned by the AntiMalware provider by calling
189 | the function described here: https://msdn.microsoft.com/en-us/library/windows/desktop/dn889866(v=vs.85).aspx
190 |
191 | .PARAMETER amsiContext
192 |
193 | A pointer to the AmsiContext this scan is associated with.
194 |
195 | .PARAMETER string
196 |
197 | The string to be scanned for malware.
198 |
199 | .PARAMETER contentName
200 |
201 | The name of the content to be scanned.
202 |
203 | .PARAMETER session
204 |
205 | A pointer to the AmsiSession this scan is a part of.
206 |
207 | .PARAMETER result
208 |
209 | A reference to the result of the scan that will be set by this function.
210 |
211 | .OUTPUTS
212 |
213 | Int
214 |
215 | .EXAMPLE
216 |
217 | $AmsiResult = $AMSI_RESULT::AMSI_RESULT_NOT_DETECTED
218 | AmsiScanString $AmsiContext $ScriptString $ContentName $AmsiSession -result ([ref]$AmsiResult)
219 |
220 | .NOTES
221 |
222 | AmsiScanString is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
223 |
224 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
225 |
226 | #>
227 | Param (
228 | [Parameter(Position = 0, Mandatory)]
229 | [ValidateNotNullOrEmpty()]
230 | [IntPtr] $amsiContext,
231 |
232 | [Parameter(Position = 1, Mandatory)]
233 | [ValidateNotNullOrEmpty()]
234 | [String] $string,
235 |
236 | [Parameter(Position = 2, Mandatory)]
237 | [ValidateNotNullOrEmpty()]
238 | [String] $contentName,
239 |
240 | [Parameter(Position = 3, Mandatory)]
241 | [ValidateNotNullOrEmpty()]
242 | [IntPtr] $session,
243 |
244 | [Parameter(Position = 4, Mandatory)]
245 | [ref] $result
246 | )
247 |
248 | $HResult = $amsi::AmsiScanString($amsiContext, $string, $contentName, $session, $result)
249 |
250 | If ($HResult -ne 0) {
251 | $ErrorMessage = "AmsiScanString Error: $($HResult)"
252 | If ($HResult -eq 2147942421) {
253 | $ErrorMessage += ". If the AmsiInitialize and AmsiOpenSession functions succeeded and AmsiScanString fails with error code $($HResult), it is likely that your AMSI AntiMalware Provider is being somewhat deceptive when they say they have implemented AMSI support."
254 | }
255 | throw $ErrorMessage
256 | }
257 |
258 | $HResult
259 | }
260 |
261 | function AmsiScanBuffer {
262 | <#
263 |
264 | .SYNOPSIS
265 |
266 | Submits a buffer to the AMSI to be scanned by the AntiMalware Provider.
267 |
268 | Author: Ryan Cobb (@cobbr_io)
269 | License: GNU GPLv3
270 | Required Dependecies: PSReflect, amsi
271 | Optional Dependencies: none
272 |
273 | .DESCRIPTION
274 |
275 | AmsiScanBuffer submits a buffer to the AMSI to be scanned by the AntiMalware provider by calling the
276 | function described here: https://msdn.microsoft.com/en-us/library/windows/desktop/dn889865(v=vs.85).aspx
277 |
278 | .PARAMETER amsiContext
279 |
280 | A pointer to the AmsiContext this scan is associated with.
281 |
282 | .PARAMETER buffer
283 |
284 | A pointer to the buffer to be scanned for malware.
285 |
286 | .PARAMETER length
287 |
288 | The length of the buffer to be scanned for malware.
289 |
290 | .PARAMETER contentName
291 |
292 | The name of the content to be scanned.
293 |
294 | .PARAMETER session
295 |
296 | A pointer to the AmsiSession this scan is a part of.
297 |
298 | .PARAMETER result
299 |
300 | A reference to the result of the scan that will be set by this function.
301 |
302 | .OUTPUTS
303 |
304 | Int
305 |
306 | .EXAMPLE
307 |
308 | $AmsiResult = $AMSI_RESULT::AMSI_RESULT_NOT_DETECTED
309 | AmsiScanBuffer $AmsiContext $Buffer $Length $ContentName $AmsiSession -result ([ref]$AmsiResult)
310 |
311 | .NOTES
312 |
313 | AmsiScanBuffer is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
314 |
315 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
316 |
317 | #>
318 | Param (
319 | [Parameter(Position = 0, Mandatory)]
320 | [ValidateNotNullOrEmpty()]
321 | [IntPtr] $amsiContext,
322 |
323 | [Parameter(Position = 1, Mandatory)]
324 | [ValidateNotNullOrEmpty()]
325 | [IntPtr] $buffer,
326 |
327 | [Parameter(Position = 2, Mandatory)]
328 | [ValidateNotNullOrEmpty()]
329 | [Int] $length,
330 |
331 | [Parameter(Position = 3, Mandatory)]
332 | [ValidateNotNullOrEmpty()]
333 | [String] $contentName,
334 |
335 | [Parameter(Position = 4, Mandatory)]
336 | [ValidateNotNullOrEmpty()]
337 | [IntPtr] $session,
338 |
339 | [Parameter(Position = 5, Mandatory)]
340 | [ref] $result
341 | )
342 |
343 | $HResult = $amsi::AmsiScanBuffer($amsiContext, $buffer, $length, $contentName, $session, $result)
344 |
345 | If ($HResult -ne 0) {
346 | $ErrorMessage = "AmsiScanBuffer Error: $($HResult)"
347 | If ($HResult -eq 2147942421) {
348 | $ErrorMessage += ". If the AmsiInitialize and AmsiOpenSession functions succeeded and AmsiScanBuffer fails with error code $($HResult), it is likely that your AMSI AntiMalware Provider is being somewhat deceptive when they say they have implemented AMSI support."
349 | }
350 | throw $ErrorMessage
351 | }
352 |
353 | $HResult
354 | }
355 |
356 | function AmsiResultIsMalware {
357 | <#
358 |
359 | .SYNOPSIS
360 |
361 | Determines if a previous AmsiScan detected malware, based on it's AmsiResult.
362 |
363 | Author: Ryan Cobb (@cobbr_io)
364 | License: GNU GPLv3
365 | Required Dependecies: PSReflect, AMSI_RESULT
366 | Optional Dependencies: none
367 |
368 | .DESCRIPTION
369 |
370 | AmsiResultIsMalware takes the result from an AmsiScanString or AmsiScanBuffer scan and
371 | uses the AMSI_RESULT enum to determine if the scan detected malware.
372 |
373 | .PARAMETER AMSIRESULT
374 |
375 | The result from a AmsiScanString or AmsiScanBuffer call.
376 |
377 | .OUTPUTS
378 |
379 | Bool
380 |
381 | .EXAMPLE
382 |
383 | $AmsiResult = $AMSI_RESULT::AMSI_RESULT_NOT_DETECTED
384 | AmsiScanString $Context $Content $ContentName $Session -result ([ref]$AmsiResult)
385 | AmsiResultIsMalware -AMSIRESULT $AmsiResult
386 |
387 | .NOTES
388 |
389 | AmsiResultIsMalware is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
390 |
391 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
392 |
393 | #>
394 | Param (
395 | [Parameter(Position = 0, Mandatory)]
396 | [ValidateScript({($_ -in @(0,1)) -OR (($_ -ge 16384) -AND ($_ -le 20479)) -OR ($_ -ge 32768)})]
397 | [UInt32] $AMSIRESULT
398 | )
399 |
400 | If(($AMSIRESULT -ne $AMSI_RESULT::AMSI_RESULT_CLEAN) -and
401 | ($AMSIRESULT -ne $AMSI_RESULT::AMSI_RESULT_NOT_DETECTED)) {
402 | $True
403 | }
404 | Else { $False }
405 | }
406 |
407 | function AmsiCloseSession {
408 | <#
409 |
410 | .SYNOPSIS
411 |
412 | Closes an AmsiSession opened with AmsiOpenSession.
413 |
414 | Author: Ryan Cobb (@cobbr_io)
415 | License: GNU GPLv3
416 | Required Dependecies: PSReflect, amsi
417 | Optional Dependencies: none
418 |
419 | .DESCRIPTION
420 |
421 | AmsiCloseSession closes an AmsiSession opened with AmsiOpenSession by calling the function
422 | described here: https://msdn.microsoft.com/en-us/library/windows/desktop/dn889861(v=vs.85).aspx
423 |
424 | .PARAMETER amsiContext
425 |
426 | A pointer to the AmsiContext for which this AmsiSession is associated.
427 |
428 | .PARAMETER session
429 |
430 | A pointer to the AmsiSession to be closed.
431 |
432 | .OUTPUTS
433 |
434 | None
435 |
436 | .EXAMPLE
437 |
438 | $AmsiSession = [IntPtr]::Zero
439 | AmsiOpenSession -amsiContext $AmsiContext -session ([ref]$AmsiSession)
440 | AmsiCloseSession -amsiConext $AmsiContext -session $AmsiSession
441 |
442 | .NOTES
443 |
444 | AmsiCloseSession is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
445 |
446 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
447 |
448 | #>
449 | Param (
450 | [Parameter(Position = 0, Mandatory)]
451 | [ValidateNotNullOrEmpty()]
452 | [IntPtr] $amsiContext,
453 |
454 | [Parameter(Position = 1, Mandatory)]
455 | [ValidateNotNullOrEmpty()]
456 | [IntPtr] $session
457 | )
458 |
459 | $HResult = $amsi::AmsiCloseSession($amsiContext, $session)
460 | }
461 |
462 | function AmsiUninitialize {
463 | <#
464 |
465 | .SYNOPSIS
466 |
467 | Uninitializes an AmsiContext initialized with AmsiInitialize.
468 |
469 | Author: Ryan Cobb (@cobbr_io)
470 | License: GNU GPLv3
471 | Required Dependecies: PSReflect, amsi
472 | Optional Dependencies: none
473 |
474 | .DESCRIPTION
475 |
476 | AmsiUninitialize uninitializes an AmsiContext initialized with AmsiInitialize by calling the function
477 | described here: https://msdn.microsoft.com/en-us/library/windows/desktop/dn889867(v=vs.85).aspx
478 |
479 | .PARAMETER amsiContext
480 |
481 | A pointer to the AmsiContext to be uninitialized.
482 |
483 | .OUTPUTS
484 |
485 | None
486 |
487 | .EXAMPLE
488 |
489 | $AmsiContext = [IntPtr]::Zero
490 | AmsiInitialize -appName "PSAmsi" -amsiContext ([ref]$AmsiContext)
491 | AmsiUninitialize -amsiConext $AmsiContext
492 |
493 | .NOTES
494 |
495 | AmsiUninitialize is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
496 |
497 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
498 |
499 | #>
500 | Param (
501 | [Parameter(Position = 0, Mandatory)]
502 | [IntPtr] $amsiContext
503 | )
504 |
505 | $HResult = $amsi::AmsiUninitialize($amsiContext)
506 | }
507 |
--------------------------------------------------------------------------------
/PSAmsi/PSAmsiScanner.ps1:
--------------------------------------------------------------------------------
1 | class PSAmsiScanner : System.IDisposable {
2 | [ValidateNotNull()]
3 | [String] $PSAmsiScannerAppName = "PSAmsi"
4 |
5 | [ValidateNotNull()]
6 | [Bool] $CacheEnabled = $True
7 | [ValidateNotNull()]
8 | [HashTable] $ScanCache = @{}
9 |
10 | [ValidateNotNull()]
11 | [String[]] $ScanBlacklist = @()
12 | [ValidateNotNull()]
13 | [String[]] $ScanWhitelist = @()
14 | [Bool] $OnlyUseBlacklist = $False
15 |
16 | [ValidateNotNull()]
17 | [Bool] $AlertLimitEnabled = $False
18 | [ValidateNotNull()]
19 | [Bool] $AlertLimitReached = $False
20 | [ValidateRange(0,[Int]::MaxValue)]
21 | [Int] $AlertLimit = 0
22 | [ValidateRange(0, [Int]::MaxValue)]
23 | [Int] $AlertCount = 0
24 | [ValidateRange(0, [Int]::MaxValue)]
25 | [Int] $Delay = 0
26 |
27 | hidden [Long] $AmsiContext
28 | hidden [Long] $AmsiSession
29 |
30 | # InitAmsi initializes items shared by all Constructors
31 | hidden InitAmsi() {
32 | $TempContext = [IntPtr]::Zero
33 | $TempSession = [IntPtr]::Zero
34 | $Result = AmsiInitialize -appName $this.PSAmsiScannerAppName -amsiContext ([ref] $TempContext)
35 | $Result = AmsiOpenSession -amsiContext $TempContext -session ([ref] $TempSession)
36 | $this.AmsiContext = $TempContext
37 | $this.AmsiSession = $TempSession
38 | }
39 |
40 | # Default constructor
41 | PSAmsiScanner() {
42 | $this.InitAmsi()
43 | }
44 |
45 | # Constructor - Specify AppName
46 | PSAmsiScanner([String] $PSAmsiScannerAppName) {
47 | $this.PSAmsiScannerAppName = $PSAmsiScannerAppName
48 | $this.InitAmsi()
49 | }
50 |
51 | # Constructor - Specify if Cache is enabled.
52 | PSAmsiScanner([Bool] $CacheEnabled) {
53 | $this.CacheEnabled = $CacheEnabled
54 | $this.InitAmsi()
55 | }
56 |
57 | # Constructor - Specify the ScanCache to use.
58 | PSAmsiScanner([HashTable] $ScanCache) {
59 | $this.ScanCache = $ScanCache
60 | $this.InitAmsi()
61 | }
62 |
63 | # Constructor - Specify an AlertLimit.
64 | PSAmsiScanner([Int] $AlertLimit) {
65 | If ($AlertLimit -gt 0) {
66 | $this.AlertLimitEnabled = $True
67 | $this.AlertLimit = $AlertLimit
68 | }
69 | $this.InitAmsi()
70 | }
71 |
72 | # Constructor - Specify a ScanBlacklist and a ScanWhitelist.
73 | PSAmsiScanner([String[]] $ScanBlacklist, [String[]] $ScanWhitelist) {
74 | $this.ScanBlacklist = $ScanBlacklist
75 | $this.ScanWhitelist = $ScanWhitelist
76 | $this.InitAmsi()
77 | }
78 |
79 | # Constructor - Specify a ScanBlacklist and if the scanner should only use the Blacklist, w/o doing AMSI scanning.
80 | PSAmsiScanner([String[]] $ScanBlacklist, $OnlyUseBlacklist) {
81 | $this.ScanBlacklist = $ScanBlacklist
82 | $this.OnlyUseBlacklist = $OnlyUseBlacklist
83 | $this.InitAmsi()
84 | }
85 |
86 | # Constructor - Specify an AlertLimit and a Delay.
87 | PSAmsiScanner([Int] $AlertLimit, [Int] $Delay) {
88 | $this.Delay = $Delay
89 | If ($AlertLimit -gt 0) {
90 | $this.AlertLimitEnabled = $True
91 | $this.AlertLimit = $AlertLimit
92 | }
93 | $this.InitAmsi()
94 | }
95 |
96 | # Constructor - Specify an AppName, an AlertLimit, and a Delay.
97 | PSAmsiScanner([String] $PSAmsiScannerAppName, [Int] $AlertLimit, [Int] $Delay) {
98 | $this.PSAmsiScannerAppName = $PSAmsiScannerAppName
99 | $this.Delay = $Delay
100 | If ($AlertLimit -gt 0) {
101 | $this.AlertLimitEnabled = $True
102 | $this.AlertLimit = $AlertLimit
103 | }
104 | $this.InitAmsi()
105 | }
106 |
107 | # Constructor - Specify an AppName, if the Cache is enabled, an AlertLimit, and a Delay.
108 | PSAmsiScanner([String] $PSAmsiScannerAppName, [Bool] $CacheEnabled, [Int] $AlertLimit, [Int] $Delay) {
109 | $this.PSAmsiScannerAppName = $PSAmsiScannerAppName
110 | $this.CacheEnabled = $CacheEnabled
111 | If ($AlertLimit -gt 0) {
112 | $this.AlertLimitEnabled = $True
113 | $this.AlertLimit = $AlertLimit
114 | }
115 | $this.Delay = $Delay
116 | $this.InitAmsi()
117 | }
118 |
119 | # Constructor - Specify an AppName, the ScanCache to use, an AlertLimit, and a Delay.
120 | PSAmsiScanner([String] $PSAmsiScannerAppName, [HashTable] $ScanCache, [Int] $AlertLimit, [Int] $Delay) {
121 | $this.PSAmsiScannerAppName = $PSAmsiScannerAppName
122 | $this.ScanCache = $this.ScanCache
123 | $this.CacheEnabled = $True
124 | If ($AlertLimit -gt 0) {
125 | $this.AlertLimitEnabled = $True
126 | $this.AlertLimit = $AlertLimit
127 | }
128 | $this.Delay = $Delay
129 | $this.InitAmsi()
130 | }
131 |
132 | # Constructor - Specify an AppName, the ScanCache to use, an AlertLimit, a Delay, a ScanBlacklist, and a ScanWhitelist.
133 | PSAmsiScanner([String] $PSAmsiScannerAppName, [HashTable] $ScanCache, [Int] $AlertLimit, [Int] $Delay, [String[]] $ScanBlacklist, [String[]] $ScanWhitelist) {
134 | $this.ScanBlacklist = $ScanBlacklist
135 | $this.ScanWhitelist = $ScanWhitelist
136 | $this.PSAmsiScannerAppName = $PSAmsiScannerAppName
137 | $this.ScanCache = $this.ScanCache
138 | $this.CacheEnabled = $True
139 | If ($AlertLimit -gt 0) {
140 | $this.AlertLimitEnabled = $True
141 | $this.AlertLimit = $AlertLimit
142 | }
143 | $this.Delay = $Delay
144 | $this.InitAmsi()
145 | }
146 |
147 | [Void] Dispose() {
148 | $this.Dispose($true)
149 | [System.GC]::SuppressFinalize($this)
150 | }
151 |
152 | [Void] Dispose([Bool] $Disposing) {
153 | If ($Disposing) {
154 | [IntPtr] $TempContext = $this.AmsiContext
155 | [IntPtr] $TempSession = $this.AmsiSession
156 | $Result = AmsiCloseSession -amsiContext $TempContext -session $TempSession
157 | $Result = AmsiUninitialize $TempContext
158 | }
159 | }
160 |
161 | [Bool] GetPSAmsiScanResult([String] $ScriptString, [String] $PSAmsiContentName) {
162 | If (-not $ScriptString) {
163 | return $False
164 | }
165 |
166 | $HashCode = $ScriptString.GetHashCode() -as [String]
167 | If (($ScriptString.ToLower() -in $this.ScanBlacklist) -or ($ScriptString.ToLower().GetHashCode() -in $this.ScanBlacklist)) { return $True }
168 | ElseIf ($this.OnlyUseBlacklist) { return $False }
169 | If (($ScriptString -in $this.ScanWhitelist) -or ($HashCode -in $this.ScanWhitelist)) { return $False }
170 |
171 | If ($this.CacheEnabled -and ($this.ScanCache.Contains($HashCode))) {
172 | return $this.ScanCache.Get_Item($HashCode)
173 | }
174 |
175 | # If we have reached our global alert limit, we will not conduct a scan. Instead, we return false, but this does
176 | # not guarantee the given string will not be flagged.
177 | If ($this.AlertLimitReached) {
178 | return $False
179 | }
180 | Else {
181 | # 1 is AMSI_RESULT_NOT_DETECTED
182 | $AmsiResult = 1
183 | $IsFlaggedAsMalware = $False
184 | [IntPtr] $TempContext = $this.AmsiContext
185 | [IntPtr] $TempSession = $this.AmsiSession
186 | $Result = AmsiScanString -amsiContext $TempContext -string $ScriptString -contentName $this.PSAmsiScannerAppName -session $TempSession -result ([ref]$AmsiResult)
187 | If (AmsiResultIsMalware -AMSIRESULT $AmsiResult) {
188 | $IsFlaggedAsMalware = $True
189 | }
190 |
191 | If ($this.CacheEnabled) {
192 | $this.ScanCache.Set_Item($HashCode, $IsFlaggedAsMalware)
193 | }
194 |
195 | If ($IsFlaggedAsMalware) {
196 | If ($this.Delay -gt 0) {
197 | Write-Verbose "Delaying for $($this.Delay) second(s)..."
198 | Start-Sleep -Seconds $this.Delay
199 | }
200 | $this.AlertCount++
201 | If ($this.AlertLimitEnabled -and $this.AlertCount -ge $this.AlertLimit) { $this.AlertLimitReached = $True }
202 | }
203 |
204 | return $IsFlaggedAsMalware
205 | }
206 | }
207 |
208 | [Bool] GetPSAmsiScanResult([ScriptBlock] $ScriptBlock, [String] $PSAmsiContentName) {
209 | $ScriptString = $ScriptBlock -as [String]
210 | return $this.GetPSAmsiScanResult($ScriptString, $PSAmsiContentName)
211 | }
212 |
213 | [Bool] GetPSAmsiScanResult([IO.FileInfo] $ScriptPath, [String] $PSAmsiContentName) {
214 | $ScriptString = Get-Content $ScriptPath -Raw
215 | return $this.GetPSAmsiScanResult($ScriptString, $PSAmsiContentName)
216 | }
217 |
218 | [Bool] GetPSAmsiScanResult([Uri] $ScriptUri, [String] $PSAmsiContentName) {
219 | $ScriptString = [Net.Webclient]::new().DownloadString($ScriptUri)
220 | return $this.GetPSAmsiScanResult($ScriptString, $PSAmsiContentName)
221 | }
222 |
223 | [Bool] GetPSAmsiScanResult([String] $ScriptString) {
224 | return $this.GetPSAmsiScanResult($ScriptString, $this.PSAmsiScannerAppName)
225 | }
226 |
227 | [Bool] GetPSAmsiScanResult([ScriptBlock] $ScriptBlock) {
228 | return $this.GetPSAmsiScanResult($ScriptBlock, $this.PSAmsiScannerAppName)
229 | }
230 |
231 | [Bool] GetPSAmsiScanResult([IO.FileInfo] $ScriptPath) {
232 | return $this.GetPSAmsiScanResult($ScriptPath, $this.PSAmsiScannerAppName)
233 | }
234 |
235 | [Bool] GetPSAmsiScanResult([Uri] $ScriptUri) {
236 | return $this.GetPSAmsiScanResult($ScriptUri, $this.PSAmsiScannerAppName)
237 | }
238 |
239 | [Bool] TestEicarDetection() {
240 | $Test = ("Y6P`"Q&ABQ\5]Q[Y65)Q_*8DD*8~%FJDBS.TUBOEBSE.BOUJWJSVT.UFTU.GJMF`"%I,I+".ToCharArray() | % { (($_ -as [Int]) - 1) -as [Char]}) -join ""
241 | return $this.GetPSAmsiScanResult($Test)
242 | }
243 |
244 | [Void] ResetPSAmsiScanCache() {
245 | $this.ScanCache = @{}
246 | }
247 | }
248 |
249 | function New-PSAmsiScanner {
250 | <#
251 | .SYNOPSIS
252 |
253 | Creates a new PSAmsiScanner object for conducting PSAmsi scans.
254 | Author: Ryan Cobb (@cobbr_io)
255 | License: GNU GPLv3
256 | Required Dependecies: PSAmsiScanner
257 | Optional Dependencies: none
258 |
259 | .DESCRIPTION
260 |
261 | New-PSAmsiScanner creates a new PSAmsiScanner object for conducting PSAmsi scans.
262 |
263 | .PARAMETER AppName
264 |
265 | The name of the Application that will be submitting PSAmsi scans through the PSAmsiScanner.
266 |
267 | .PARAMETER AlertLimit
268 |
269 | Specifies the maximum amount of AMSI alerts this PSAmsiScanner is allowed to generate.
270 |
271 | .PARAMETER Delay
272 |
273 | Specifies the amount of time (in seconds) this PSAmsiScanner will wait between generated AMSI alerts.
274 |
275 | .PARAMETER ScanCache
276 |
277 | Specify a pre-computed hashtable of cached PSAmsiScanResults that this PSAmsiScanner will use.
278 |
279 | .PARAMETER DisableCache
280 |
281 | Disabled the caching and use of cached PSAmsiScanResults for this PSAmsiScanner. Every request will guaranteed
282 | to be submitted to the AMSI AntiMawlare provider if caching is disabled. Default is cache enabled.
283 |
284 | .OUTPUTS
285 |
286 | PSAmsiScanner
287 |
288 | .EXAMPLE
289 |
290 | New-PSAmsiScanner
291 |
292 | .EXAMPLE
293 |
294 | New-PSAmsiScanner -AppName "PSAmsi" -AlertLimit 100 -Delay 1
295 |
296 | .NOTES
297 |
298 | New-PSAmsiScanner is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
299 |
300 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
301 |
302 | #>
303 | Param (
304 | [Parameter(Position = 0)]
305 | [ValidateNotNullOrEmpty()]
306 | [String] $AppName = "PSAmsi",
307 |
308 | [Parameter(Position = 1)]
309 | [ValidateRange(0, [Int]::MaxValue)]
310 | [Int] $AlertLimit = 0,
311 |
312 | [Parameter(Position = 2)]
313 | [ValidateRange(0,[Int]::MaxValue)]
314 | [Int] $Delay = 0,
315 |
316 | [Parameter(Position = 3)]
317 | [ValidateNotNull()]
318 | [HashTable] $ScanCache = @{},
319 |
320 | [Parameter(Position = 4)]
321 | [ValidateNotNullOrEmpty()]
322 | [String[]] $ScanBlacklist = @(),
323 |
324 | [Parameter(Position = 5)]
325 | [ValidateNotNullOrEmpty()]
326 | [String[]] $ScanWhitelist = @(),
327 |
328 | [Switch] $DisableCache,
329 |
330 | [Switch] $OnlyUseBlacklist
331 | )
332 | If ($DisableCache) {
333 | $PSAmsiScanner = [PSAmsiScanner]::new($AppName, $False, $AlertLimit, $Delay, $ScanBlacklist, $ScanWhitelist)
334 | }
335 | Else {
336 | $PSAmsiScanner = [PSAmsiScanner]::new($AppName, $ScanCache, $AlertLimit, $Delay, $ScanBlacklist, $ScanWhitelist)
337 | }
338 | If ($OnlyUseBlacklist) { $PSAmsiScanner.OnlyUseBlacklist = $True }
339 |
340 | $PSAmsiScanner
341 | }
342 |
343 | function Get-PSAmsiScanResult {
344 | <#
345 | .SYNOPSIS
346 |
347 | Gets the result of a PSAmsiScan on a given string using a given PSAmsiScanner.
348 |
349 | Author: Ryan Cobb (@cobbr_io)
350 | License: GNU GPLv3
351 | Required Dependecies: PSAmsiScanner
352 | Optional Dependencies: none
353 |
354 | .DESCRIPTION
355 |
356 | Get-PSAmsiScanResult gets the result of a PSAmsiScan on a given string using a given PSAmsiScanner
357 | to determine if the current AMSI AntiMalware Provider detects the string as malicious.
358 |
359 | .PARAMETER ScriptString
360 |
361 | The string containing the script to be scanned.
362 |
363 | .PARAMETER ScriptBlock
364 |
365 | The ScriptBlock containing the script to be scanned.
366 |
367 | .PARAMETER ScriptPath
368 |
369 | The Path to the script to be scanned.
370 |
371 | .PARAMETER ScriptUri
372 |
373 | The URI of the script to be scanned.
374 |
375 | .OUTPUTS
376 |
377 | PSCustomObject
378 |
379 | .EXAMPLE
380 |
381 | Get-PSAmsiScanResult -ScriptString "Write-Host example"
382 |
383 | .EXAMPLE
384 |
385 | Get-PSAmsiScanResult -ScriptBlock { Write-Host test }
386 |
387 | .EXAMPLE
388 |
389 | Get-PSAmsiScanResult -ScriptPath ./Example.ps1
390 |
391 | .EXAMPLE
392 |
393 | Get-PSAmsiScanResult -ScriptUri 'http://example.com/Example.ps1'
394 |
395 | .NOTES
396 |
397 | Get-PSAmsiScanResult is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
398 |
399 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
400 |
401 | #>
402 |
403 | [CmdletBinding(DefaultParameterSetName = "ByString")] Param (
404 | [Parameter(ParameterSetName = "ByString", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
405 | [ValidateNotNullOrEmpty()]
406 | [String] $ScriptString,
407 |
408 | [Parameter(ParameterSetName = "ByScriptBlock", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
409 | [ValidateNotNullOrEmpty()]
410 | [ScriptBlock] $ScriptBlock,
411 |
412 | [Parameter(ParameterSetName = "ByPath", Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
413 | [ValidateScript({Test-Path $_ -PathType leaf})]
414 | [Alias('PSPath')]
415 | [String] $ScriptPath,
416 |
417 | [Parameter(ParameterSetName = "ByUri", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
418 | [ValidateScript({$_.Scheme -match 'http|https'})]
419 | [Uri] $ScriptUri,
420 |
421 | [Parameter(Position = 1)]
422 | [ValidateScript({$_.GetType().Name -eq 'PSAmsiScanner'})]
423 | [System.Object] $PSAmsiScanner,
424 |
425 | [Parameter(Position = 2)]
426 | [ValidateNotNullOrEmpty()]
427 | [String] $ContentName
428 | )
429 | Begin {
430 | $CreatedPSAmsiScanner = $False
431 | If (-not $PSAmsiScanner) {
432 | $PSAmsiScanner = New-PSAmsiScanner
433 | $CreatedPSAmsiScanner = $True
434 | }
435 | }
436 | Process {
437 | If ($ScriptString) {
438 | If ($ContentName) { $PSAmsiScanner.GetPSAmsiScanResult($ScriptString, $ContentName) }
439 | Else { $PSAmsiScanner.GetPSAmsiScanResult($ScriptString) }
440 | }
441 | ElseIf ($ScriptBlock) {
442 | If ($ContentName) { $PSAmsiScanner.GetPSAmsiScanResult($ScriptBlock, $ContentName) }
443 | Else { $PSAmsiScanner.GetPSAmsiScanResult($ScriptBlock) }
444 | }
445 | ElseIf ($ScriptPath) {
446 | If ($ContentName) { $PSAmsiScanner.GetPSAmsiScanResult((Get-ChildItem $ScriptPath), $ContentName) }
447 | Else { $PSAmsiScanner.GetPSAmsiScanResult((Get-ChildItem $ScriptPath)) }
448 | }
449 | ElseIf ($ScriptUri) {
450 | If ($ContentName) { $PSAmsiScanner.GetPSAmsiScanResult($ScriptUri) }
451 | Else { $PSAmsiScanner.GetPSAmsiScanResult($ScriptUri) }
452 | }
453 | }
454 | End {
455 | If ($CreatedPSAmsiScanner) {
456 | $PSAmsiScanner.Dispose()
457 | }
458 | }
459 | }
460 |
461 | function Reset-PSAmsiScanCache {
462 | <#
463 | .SYNOPSIS
464 |
465 | Resets the ScanCache of a given PSAmsiScanner.
466 |
467 | Author: Ryan Cobb (@cobbr_io)
468 | License: GNU GPLv3
469 | Required Dependecies: PSAmsiScanner
470 | Optional Dependencies: none
471 |
472 | .DESCRIPTION
473 |
474 | Reset-PSAmsiScanCache resets the ScanCache of a given PSAmsiScanner so all
475 | new requests will return fresh responses from the AMSI AntiMalware Provider.
476 |
477 | .EXAMPLE
478 |
479 | Reset-PSAmsiScanCache
480 |
481 | .NOTES
482 |
483 | Reset-PSAmsiScanCache is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
484 |
485 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
486 |
487 | #>
488 |
489 | Param (
490 | [Parameter(Position = 0, Mandatory)] [ValidateNotNull()]
491 | [ValidateScript({$_.GetType().Name -eq 'PSAmsiScanner'})]
492 | [System.Object] $PSAmsiScanner
493 | )
494 | $PSAmsiScanner.ResetPSAmsiScanCache()
495 | }
496 |
497 | function Test-EicarDetection {
498 | <#
499 | .SYNOPSIS
500 |
501 | Tests if the current AMSI AntiMalware Provider detects a standard test EICAR payload.
502 |
503 | Author: Ryan Cobb (@cobbr_io)
504 | License: GNU GPLv3
505 | Required Dependecies: PSAmsiScanner
506 | Optional Dependencies: none
507 |
508 | .DESCRIPTION
509 |
510 | Test-EicarDetection tests if the current AMSI AntiMalware Provider detects a standard test EICAR payload. If your AMSI AntiMalware
511 | Provider does not detect an EICAR payload it is likely that your AMSI AntiMalware Provider is being somewhat deceptive when they say
512 | they have implemented AMSI support.
513 |
514 | .EXAMPLE
515 |
516 | Test-EicarDetection
517 |
518 | .EXAMPLE
519 |
520 | Test-EicarDetection -PSAmsiScanner $Scanner
521 |
522 | .NOTES
523 |
524 | Test-EicarDetection is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
525 |
526 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
527 |
528 | #>
529 |
530 | Param (
531 | [Parameter(Position = 0)] [ValidateNotNull()]
532 | [ValidateScript({$_.GetType().Name -eq 'PSAmsiScanner'})]
533 | [System.Object] $PSAmsiScanner
534 | )
535 | $CreatedPSAmsiScanner = $False
536 | If (-not $PSAmsiScanner) {
537 | $PSAmsiScanner = New-PSAmsiScanner
538 | $CreatedPSAmsiScanner = $True
539 | }
540 |
541 | $PSAmsiScanner.TestEicarDetection()
542 |
543 | If ($CreatedPSAmsiScanner) {
544 | $PSAmsiScanner.Dispose()
545 | }
546 | }
--------------------------------------------------------------------------------
/PSAmsi/PSReflect.ps1:
--------------------------------------------------------------------------------
1 | #Requires -Version 2
2 |
3 | ########################################################
4 | #
5 | # PSReflect code for Windows API access
6 | # Author: @mattifestation
7 | # https://raw.githubusercontent.com/mattifestation/PSReflect/master/PSReflect.psm1
8 | #
9 | ########################################################
10 |
11 | function New-InMemoryModule
12 | {
13 | <#
14 | .SYNOPSIS
15 | Creates an in-memory assembly and module
16 | Author: Matthew Graeber (@mattifestation)
17 | License: BSD 3-Clause
18 | Required Dependencies: None
19 | Optional Dependencies: None
20 |
21 | .DESCRIPTION
22 | When defining custom enums, structs, and unmanaged functions, it is
23 | necessary to associate to an assembly module. This helper function
24 | creates an in-memory module that can be passed to the 'enum',
25 | 'struct', and Add-Win32Type functions.
26 | .PARAMETER ModuleName
27 | Specifies the desired name for the in-memory assembly and module. If
28 | ModuleName is not provided, it will default to a GUID.
29 | .EXAMPLE
30 | $Module = New-InMemoryModule -ModuleName Win32
31 | #>
32 |
33 | Param
34 | (
35 | [Parameter(Position = 0)]
36 | [ValidateNotNullOrEmpty()]
37 | [String]
38 | $ModuleName = [Guid]::NewGuid().ToString()
39 | )
40 |
41 | $AppDomain = [Reflection.Assembly].Assembly.GetType('System.AppDomain').GetProperty('CurrentDomain').GetValue($null, @())
42 | $LoadedAssemblies = $AppDomain.GetAssemblies()
43 |
44 | foreach ($Assembly in $LoadedAssemblies) {
45 | if ($Assembly.FullName -and ($Assembly.FullName.Split(',')[0] -eq $ModuleName)) {
46 | return $Assembly
47 | }
48 | }
49 |
50 | $DynAssembly = New-Object Reflection.AssemblyName($ModuleName)
51 | $Domain = $AppDomain
52 | $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, 'Run')
53 | $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule($ModuleName, $False)
54 |
55 | return $ModuleBuilder
56 | }
57 |
58 |
59 | # A helper function used to reduce typing while defining function
60 | # prototypes for Add-Win32Type.
61 | function func
62 | {
63 | Param
64 | (
65 | [Parameter(Position = 0, Mandatory = $True)]
66 | [String]
67 | $DllName,
68 |
69 | [Parameter(Position = 1, Mandatory = $True)]
70 | [string]
71 | $FunctionName,
72 |
73 | [Parameter(Position = 2, Mandatory = $True)]
74 | [Type]
75 | $ReturnType,
76 |
77 | [Parameter(Position = 3)]
78 | [Type[]]
79 | $ParameterTypes,
80 |
81 | [Parameter(Position = 4)]
82 | [Runtime.InteropServices.CallingConvention]
83 | $NativeCallingConvention,
84 |
85 | [Parameter(Position = 5)]
86 | [Runtime.InteropServices.CharSet]
87 | $Charset,
88 |
89 | [String]
90 | $EntryPoint,
91 |
92 | [Switch]
93 | $SetLastError
94 | )
95 |
96 | $Properties = @{
97 | DllName = $DllName
98 | FunctionName = $FunctionName
99 | ReturnType = $ReturnType
100 | }
101 |
102 | if ($ParameterTypes) { $Properties['ParameterTypes'] = $ParameterTypes }
103 | if ($NativeCallingConvention) { $Properties['NativeCallingConvention'] = $NativeCallingConvention }
104 | if ($Charset) { $Properties['Charset'] = $Charset }
105 | if ($SetLastError) { $Properties['SetLastError'] = $SetLastError }
106 | if ($EntryPoint) { $Properties['EntryPoint'] = $EntryPoint }
107 |
108 | New-Object PSObject -Property $Properties
109 | }
110 |
111 |
112 | function Add-Win32Type
113 | {
114 | <#
115 | .SYNOPSIS
116 | Creates a .NET type for an unmanaged Win32 function.
117 | Author: Matthew Graeber (@mattifestation)
118 | License: BSD 3-Clause
119 | Required Dependencies: None
120 | Optional Dependencies: func
121 |
122 | .DESCRIPTION
123 | Add-Win32Type enables you to easily interact with unmanaged (i.e.
124 | Win32 unmanaged) functions in PowerShell. After providing
125 | Add-Win32Type with a function signature, a .NET type is created
126 | using reflection (i.e. csc.exe is never called like with Add-Type).
127 | The 'func' helper function can be used to reduce typing when defining
128 | multiple function definitions.
129 | .PARAMETER DllName
130 | The name of the DLL.
131 | .PARAMETER FunctionName
132 | The name of the target function.
133 | .PARAMETER EntryPoint
134 | The DLL export function name. This argument should be specified if the
135 | specified function name is different than the name of the exported
136 | function.
137 | .PARAMETER ReturnType
138 | The return type of the function.
139 | .PARAMETER ParameterTypes
140 | The function parameters.
141 | .PARAMETER NativeCallingConvention
142 | Specifies the native calling convention of the function. Defaults to
143 | stdcall.
144 | .PARAMETER Charset
145 | If you need to explicitly call an 'A' or 'W' Win32 function, you can
146 | specify the character set.
147 | .PARAMETER SetLastError
148 | Indicates whether the callee calls the SetLastError Win32 API
149 | function before returning from the attributed method.
150 | .PARAMETER Module
151 | The in-memory module that will host the functions. Use
152 | New-InMemoryModule to define an in-memory module.
153 | .PARAMETER Namespace
154 | An optional namespace to prepend to the type. Add-Win32Type defaults
155 | to a namespace consisting only of the name of the DLL.
156 | .EXAMPLE
157 | $Mod = New-InMemoryModule -ModuleName Win32
158 | $FunctionDefinitions = @(
159 | (func kernel32 GetProcAddress ([IntPtr]) @([IntPtr], [String]) -Charset Ansi -SetLastError),
160 | (func kernel32 GetModuleHandle ([Intptr]) @([String]) -SetLastError),
161 | (func ntdll RtlGetCurrentPeb ([IntPtr]) @())
162 | )
163 | $Types = $FunctionDefinitions | Add-Win32Type -Module $Mod -Namespace 'Win32'
164 | $Kernel32 = $Types['kernel32']
165 | $Ntdll = $Types['ntdll']
166 | $Ntdll::RtlGetCurrentPeb()
167 | $ntdllbase = $Kernel32::GetModuleHandle('ntdll')
168 | $Kernel32::GetProcAddress($ntdllbase, 'RtlGetCurrentPeb')
169 | .NOTES
170 | Inspired by Lee Holmes' Invoke-WindowsApi http://poshcode.org/2189
171 | When defining multiple function prototypes, it is ideal to provide
172 | Add-Win32Type with an array of function signatures. That way, they
173 | are all incorporated into the same in-memory module.
174 | #>
175 |
176 | [OutputType([Hashtable])]
177 | Param(
178 | [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]
179 | [String]
180 | [ValidateNotNullOrEmpty()]
181 | $DllName,
182 |
183 | [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]
184 | [String]
185 | [ValidateNotNullOrEmpty()]
186 | $FunctionName,
187 |
188 | [Parameter(ValueFromPipelineByPropertyName = $True)]
189 | [String]
190 | [ValidateNotNullOrEmpty()]
191 | $EntryPoint,
192 |
193 | [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]
194 | [Type]
195 | $ReturnType,
196 |
197 | [Parameter(ValueFromPipelineByPropertyName = $True)]
198 | [Type[]]
199 | $ParameterTypes,
200 |
201 | [Parameter(ValueFromPipelineByPropertyName = $True)]
202 | [Runtime.InteropServices.CallingConvention]
203 | $NativeCallingConvention = [Runtime.InteropServices.CallingConvention]::StdCall,
204 |
205 | [Parameter(ValueFromPipelineByPropertyName = $True)]
206 | [Runtime.InteropServices.CharSet]
207 | $Charset = [Runtime.InteropServices.CharSet]::Auto,
208 |
209 | [Parameter(ValueFromPipelineByPropertyName = $True)]
210 | [Switch]
211 | $SetLastError,
212 |
213 | [Parameter(Mandatory = $True)]
214 | [ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]
215 | $Module,
216 |
217 | [ValidateNotNull()]
218 | [String]
219 | $Namespace = ''
220 | )
221 |
222 | BEGIN
223 | {
224 | $TypeHash = @{}
225 | }
226 |
227 | PROCESS
228 | {
229 | if ($Module -is [Reflection.Assembly])
230 | {
231 | if ($Namespace)
232 | {
233 | $TypeHash[$DllName] = $Module.GetType("$Namespace.$DllName")
234 | }
235 | else
236 | {
237 | $TypeHash[$DllName] = $Module.GetType($DllName)
238 | }
239 | }
240 | else
241 | {
242 | # Define one type for each DLL
243 | if (!$TypeHash.ContainsKey($DllName))
244 | {
245 | if ($Namespace)
246 | {
247 | $TypeHash[$DllName] = $Module.DefineType("$Namespace.$DllName", 'Public,BeforeFieldInit')
248 | }
249 | else
250 | {
251 | $TypeHash[$DllName] = $Module.DefineType($DllName, 'Public,BeforeFieldInit')
252 | }
253 | }
254 |
255 | $Method = $TypeHash[$DllName].DefineMethod(
256 | $FunctionName,
257 | 'Public,Static,PinvokeImpl',
258 | $ReturnType,
259 | $ParameterTypes)
260 |
261 | # Make each ByRef parameter an Out parameter
262 | $i = 1
263 | foreach($Parameter in $ParameterTypes)
264 | {
265 | if ($Parameter.IsByRef)
266 | {
267 | [void] $Method.DefineParameter($i, 'Out', $null)
268 | }
269 |
270 | $i++
271 | }
272 |
273 | $DllImport = [Runtime.InteropServices.DllImportAttribute]
274 | $SetLastErrorField = $DllImport.GetField('SetLastError')
275 | $CallingConventionField = $DllImport.GetField('CallingConvention')
276 | $CharsetField = $DllImport.GetField('CharSet')
277 | $EntryPointField = $DllImport.GetField('EntryPoint')
278 | if ($SetLastError) { $SLEValue = $True } else { $SLEValue = $False }
279 |
280 | if ($EntryPoint) { $ExportedFuncName = $EntryPoint } else { $ExportedFuncName = $FunctionName }
281 |
282 | # Equivalent to C# version of [DllImport(DllName)]
283 | $Constructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor([String])
284 | $DllImportAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($Constructor,
285 | $DllName,
286 | [Reflection.PropertyInfo[]] @(),
287 | [Object[]] @(),
288 | [Reflection.FieldInfo[]] @($SetLastErrorField,
289 | $CallingConventionField,
290 | $CharsetField,
291 | $EntryPointField),
292 | [Object[]] @($SLEValue,
293 | ([Runtime.InteropServices.CallingConvention] $NativeCallingConvention),
294 | ([Runtime.InteropServices.CharSet] $Charset),
295 | $ExportedFuncName))
296 |
297 | $Method.SetCustomAttribute($DllImportAttribute)
298 | }
299 | }
300 |
301 | END
302 | {
303 | if ($Module -is [Reflection.Assembly])
304 | {
305 | return $TypeHash
306 | }
307 |
308 | $ReturnTypes = @{}
309 |
310 | foreach ($Key in $TypeHash.Keys)
311 | {
312 | $Type = $TypeHash[$Key].CreateType()
313 |
314 | $ReturnTypes[$Key] = $Type
315 | }
316 |
317 | return $ReturnTypes
318 | }
319 | }
320 |
321 |
322 | function psenum
323 | {
324 | <#
325 | .SYNOPSIS
326 | Creates an in-memory enumeration for use in your PowerShell session.
327 | Author: Matthew Graeber (@mattifestation)
328 | License: BSD 3-Clause
329 | Required Dependencies: None
330 | Optional Dependencies: None
331 |
332 | .DESCRIPTION
333 | The 'psenum' function facilitates the creation of enums entirely in
334 | memory using as close to a "C style" as PowerShell will allow.
335 | .PARAMETER Module
336 | The in-memory module that will host the enum. Use
337 | New-InMemoryModule to define an in-memory module.
338 | .PARAMETER FullName
339 | The fully-qualified name of the enum.
340 | .PARAMETER Type
341 | The type of each enum element.
342 | .PARAMETER EnumElements
343 | A hashtable of enum elements.
344 | .PARAMETER Bitfield
345 | Specifies that the enum should be treated as a bitfield.
346 | .EXAMPLE
347 | $Mod = New-InMemoryModule -ModuleName Win32
348 | $ImageSubsystem = psenum $Mod PE.IMAGE_SUBSYSTEM UInt16 @{
349 | UNKNOWN = 0
350 | NATIVE = 1 # Image doesn't require a subsystem.
351 | WINDOWS_GUI = 2 # Image runs in the Windows GUI subsystem.
352 | WINDOWS_CUI = 3 # Image runs in the Windows character subsystem.
353 | OS2_CUI = 5 # Image runs in the OS/2 character subsystem.
354 | POSIX_CUI = 7 # Image runs in the Posix character subsystem.
355 | NATIVE_WINDOWS = 8 # Image is a native Win9x driver.
356 | WINDOWS_CE_GUI = 9 # Image runs in the Windows CE subsystem.
357 | EFI_APPLICATION = 10
358 | EFI_BOOT_SERVICE_DRIVER = 11
359 | EFI_RUNTIME_DRIVER = 12
360 | EFI_ROM = 13
361 | XBOX = 14
362 | WINDOWS_BOOT_APPLICATION = 16
363 | }
364 | .NOTES
365 | PowerShell purists may disagree with the naming of this function but
366 | again, this was developed in such a way so as to emulate a "C style"
367 | definition as closely as possible. Sorry, I'm not going to name it
368 | New-Enum. :P
369 | #>
370 |
371 | [OutputType([Type])]
372 | Param
373 | (
374 | [Parameter(Position = 0, Mandatory = $True)]
375 | [ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]
376 | $Module,
377 |
378 | [Parameter(Position = 1, Mandatory = $True)]
379 | [ValidateNotNullOrEmpty()]
380 | [String]
381 | $FullName,
382 |
383 | [Parameter(Position = 2, Mandatory = $True)]
384 | [Type]
385 | $Type,
386 |
387 | [Parameter(Position = 3, Mandatory = $True)]
388 | [ValidateNotNullOrEmpty()]
389 | [Hashtable]
390 | $EnumElements,
391 |
392 | [Switch]
393 | $Bitfield
394 | )
395 |
396 | if ($Module -is [Reflection.Assembly])
397 | {
398 | return ($Module.GetType($FullName))
399 | }
400 |
401 | $EnumType = $Type -as [Type]
402 |
403 | $EnumBuilder = $Module.DefineEnum($FullName, 'Public', $EnumType)
404 |
405 | if ($Bitfield)
406 | {
407 | $FlagsConstructor = [FlagsAttribute].GetConstructor(@())
408 | $FlagsCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($FlagsConstructor, @())
409 | $EnumBuilder.SetCustomAttribute($FlagsCustomAttribute)
410 | }
411 |
412 | foreach ($Key in $EnumElements.Keys)
413 | {
414 | # Apply the specified enum type to each element
415 | $null = $EnumBuilder.DefineLiteral($Key, $EnumElements[$Key] -as $EnumType)
416 | }
417 |
418 | $EnumBuilder.CreateType()
419 | }
420 |
421 |
422 | # A helper function used to reduce typing while defining struct
423 | # fields.
424 | function field
425 | {
426 | Param
427 | (
428 | [Parameter(Position = 0, Mandatory = $True)]
429 | [UInt16]
430 | $Position,
431 |
432 | [Parameter(Position = 1, Mandatory = $True)]
433 | [Type]
434 | $Type,
435 |
436 | [Parameter(Position = 2)]
437 | [UInt16]
438 | $Offset,
439 |
440 | [Object[]]
441 | $MarshalAs
442 | )
443 |
444 | @{
445 | Position = $Position
446 | Type = $Type -as [Type]
447 | Offset = $Offset
448 | MarshalAs = $MarshalAs
449 | }
450 | }
451 |
452 |
453 | function struct
454 | {
455 | <#
456 | .SYNOPSIS
457 | Creates an in-memory struct for use in your PowerShell session.
458 | Author: Matthew Graeber (@mattifestation)
459 | License: BSD 3-Clause
460 | Required Dependencies: None
461 | Optional Dependencies: field
462 |
463 | .DESCRIPTION
464 | The 'struct' function facilitates the creation of structs entirely in
465 | memory using as close to a "C style" as PowerShell will allow. Struct
466 | fields are specified using a hashtable where each field of the struct
467 | is comprosed of the order in which it should be defined, its .NET
468 | type, and optionally, its offset and special marshaling attributes.
469 | One of the features of 'struct' is that after your struct is defined,
470 | it will come with a built-in GetSize method as well as an explicit
471 | converter so that you can easily cast an IntPtr to the struct without
472 | relying upon calling SizeOf and/or PtrToStructure in the Marshal
473 | class.
474 | .PARAMETER Module
475 | The in-memory module that will host the struct. Use
476 | New-InMemoryModule to define an in-memory module.
477 | .PARAMETER FullName
478 | The fully-qualified name of the struct.
479 | .PARAMETER StructFields
480 | A hashtable of fields. Use the 'field' helper function to ease
481 | defining each field.
482 | .PARAMETER PackingSize
483 | Specifies the memory alignment of fields.
484 | .PARAMETER ExplicitLayout
485 | Indicates that an explicit offset for each field will be specified.
486 | .PARAMETER CharSet
487 | Dictates which character set marshaled strings should use.
488 | .EXAMPLE
489 | $Mod = New-InMemoryModule -ModuleName Win32
490 | $ImageDosSignature = psenum $Mod PE.IMAGE_DOS_SIGNATURE UInt16 @{
491 | DOS_SIGNATURE = 0x5A4D
492 | OS2_SIGNATURE = 0x454E
493 | OS2_SIGNATURE_LE = 0x454C
494 | VXD_SIGNATURE = 0x454C
495 | }
496 | $ImageDosHeader = struct $Mod PE.IMAGE_DOS_HEADER @{
497 | e_magic = field 0 $ImageDosSignature
498 | e_cblp = field 1 UInt16
499 | e_cp = field 2 UInt16
500 | e_crlc = field 3 UInt16
501 | e_cparhdr = field 4 UInt16
502 | e_minalloc = field 5 UInt16
503 | e_maxalloc = field 6 UInt16
504 | e_ss = field 7 UInt16
505 | e_sp = field 8 UInt16
506 | e_csum = field 9 UInt16
507 | e_ip = field 10 UInt16
508 | e_cs = field 11 UInt16
509 | e_lfarlc = field 12 UInt16
510 | e_ovno = field 13 UInt16
511 | e_res = field 14 UInt16[] -MarshalAs @('ByValArray', 4)
512 | e_oemid = field 15 UInt16
513 | e_oeminfo = field 16 UInt16
514 | e_res2 = field 17 UInt16[] -MarshalAs @('ByValArray', 10)
515 | e_lfanew = field 18 Int32
516 | }
517 | # Example of using an explicit layout in order to create a union.
518 | $TestUnion = struct $Mod TestUnion @{
519 | field1 = field 0 UInt32 0
520 | field2 = field 1 IntPtr 0
521 | } -ExplicitLayout
522 | .NOTES
523 | PowerShell purists may disagree with the naming of this function but
524 | again, this was developed in such a way so as to emulate a "C style"
525 | definition as closely as possible. Sorry, I'm not going to name it
526 | New-Struct. :P
527 | #>
528 |
529 | [OutputType([Type])]
530 | Param
531 | (
532 | [Parameter(Position = 1, Mandatory = $True)]
533 | [ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})]
534 | $Module,
535 |
536 | [Parameter(Position = 2, Mandatory = $True)]
537 | [ValidateNotNullOrEmpty()]
538 | [String]
539 | $FullName,
540 |
541 | [Parameter(Position = 3, Mandatory = $True)]
542 | [ValidateNotNullOrEmpty()]
543 | [Hashtable]
544 | $StructFields,
545 |
546 | [Reflection.Emit.PackingSize]
547 | $PackingSize = [Reflection.Emit.PackingSize]::Unspecified,
548 |
549 | [Switch]
550 | $ExplicitLayout,
551 |
552 | [System.Runtime.InteropServices.CharSet]
553 | $CharSet = [System.Runtime.InteropServices.CharSet]::Ansi
554 | )
555 |
556 | if ($Module -is [Reflection.Assembly])
557 | {
558 | return ($Module.GetType($FullName))
559 | }
560 |
561 | [Reflection.TypeAttributes] $StructAttributes = 'Class,
562 | Public,
563 | Sealed,
564 | BeforeFieldInit'
565 |
566 | if ($ExplicitLayout)
567 | {
568 | $StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::ExplicitLayout
569 | }
570 | else
571 | {
572 | $StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::SequentialLayout
573 | }
574 |
575 | switch($CharSet)
576 | {
577 | Ansi
578 | {
579 | $StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::AnsiClass
580 | }
581 | Auto
582 | {
583 | $StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::AutoClass
584 | }
585 | Unicode
586 | {
587 | $StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::UnicodeClass
588 | s}
589 | }
590 |
591 | $StructBuilder = $Module.DefineType($FullName, $StructAttributes, [ValueType], $PackingSize)
592 | $ConstructorInfo = [Runtime.InteropServices.MarshalAsAttribute].GetConstructors()[0]
593 | $SizeConst = @([Runtime.InteropServices.MarshalAsAttribute].GetField('SizeConst'))
594 |
595 | $Fields = New-Object Hashtable[]($StructFields.Count)
596 |
597 | # Sort each field according to the orders specified
598 | # Unfortunately, PSv2 doesn't have the luxury of the
599 | # hashtable [Ordered] accelerator.
600 | foreach ($Field in $StructFields.Keys)
601 | {
602 | $Index = $StructFields[$Field]['Position']
603 | $Fields[$Index] = @{FieldName = $Field; Properties = $StructFields[$Field]}
604 | }
605 |
606 | foreach ($Field in $Fields)
607 | {
608 | $FieldName = $Field['FieldName']
609 | $FieldProp = $Field['Properties']
610 |
611 | $Offset = $FieldProp['Offset']
612 | $Type = $FieldProp['Type']
613 | $MarshalAs = $FieldProp['MarshalAs']
614 |
615 | $NewField = $StructBuilder.DefineField($FieldName, $Type, 'Public')
616 |
617 | if ($MarshalAs)
618 | {
619 | $UnmanagedType = $MarshalAs[0] -as ([Runtime.InteropServices.UnmanagedType])
620 | if ($MarshalAs[1])
621 | {
622 | $Size = $MarshalAs[1]
623 | $AttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($ConstructorInfo,
624 | $UnmanagedType, $SizeConst, @($Size))
625 | }
626 | else
627 | {
628 | $AttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, [Object[]] @($UnmanagedType))
629 | }
630 |
631 | $NewField.SetCustomAttribute($AttribBuilder)
632 | }
633 |
634 | if ($ExplicitLayout) { $NewField.SetOffset($Offset) }
635 | }
636 |
637 | # Make the struct aware of its own size.
638 | # No more having to call [Runtime.InteropServices.Marshal]::SizeOf!
639 | $SizeMethod = $StructBuilder.DefineMethod('GetSize',
640 | 'Public, Static',
641 | [Int],
642 | [Type[]] @())
643 | $ILGenerator = $SizeMethod.GetILGenerator()
644 | # Thanks for the help, Jason Shirk!
645 | $ILGenerator.Emit([Reflection.Emit.OpCodes]::Ldtoken, $StructBuilder)
646 | $ILGenerator.Emit([Reflection.Emit.OpCodes]::Call,
647 | [Type].GetMethod('GetTypeFromHandle'))
648 | $ILGenerator.Emit([Reflection.Emit.OpCodes]::Call,
649 | [Runtime.InteropServices.Marshal].GetMethod('SizeOf', [Type[]] @([Type])))
650 | $ILGenerator.Emit([Reflection.Emit.OpCodes]::Ret)
651 |
652 | # Allow for explicit casting from an IntPtr
653 | # No more having to call [Runtime.InteropServices.Marshal]::PtrToStructure!
654 | $ImplicitConverter = $StructBuilder.DefineMethod('op_Implicit',
655 | 'PrivateScope, Public, Static, HideBySig, SpecialName',
656 | $StructBuilder,
657 | [Type[]] @([IntPtr]))
658 | $ILGenerator2 = $ImplicitConverter.GetILGenerator()
659 | $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Nop)
660 | $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ldarg_0)
661 | $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ldtoken, $StructBuilder)
662 | $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Call,
663 | [Type].GetMethod('GetTypeFromHandle'))
664 | $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Call,
665 | [Runtime.InteropServices.Marshal].GetMethod('PtrToStructure', [Type[]] @([IntPtr], [Type])))
666 | $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Unbox_Any, $StructBuilder)
667 | $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ret)
668 |
669 | $StructBuilder.CreateType()
670 | }
--------------------------------------------------------------------------------
/PSAmsi/Obfuscators/PowerShell/PowerShellObfuscator.ps1:
--------------------------------------------------------------------------------
1 | class PowerShellObfuscator {
2 |
3 | $ObfuscationCache = @{}
4 |
5 | PowerShellObfuscator() {}
6 |
7 | PowerShellObfuscator([HashTable] $ObfuscationCache) {
8 | $this.ObfuscationCache = $ObfuscationCache
9 | }
10 |
11 | [String] GetMinimallyObfuscated([String] $ScriptString, [Object] $PSAmsiScanner, [Object[]] $AmsiSignatures) {
12 | $CreatedPSAmsiScanner = $False
13 | If (-not $PSAmsiScanner) {
14 | $CreatedPSAmsiScanner = $True
15 | $PSAmsiScanner = New-PSAmsiScanner
16 | } ElseIf (-not $PSAmsiScanner.GetType().Name -eq 'PSAmsiScanner') {
17 | throw "PSAmsiScanner must be of type [PSAmsiScanner]"
18 | }
19 |
20 | If ($this.ObfuscationCache.Contains($ScriptString)) { return $this.ObfuscationCache[$ScriptString] }
21 |
22 | $PSTokens = Get-PSTokens -ScriptString $ScriptString
23 | $OriginalScript = $ScriptString
24 |
25 | # Get all the AmsiFlaggedStrings that we must obfuscate, if they were not provided
26 | If (-not $AmsiSignatures) {
27 | # No need to get the AbstractSyntaxTree unless we must search for AmsiFlaggedStrings
28 | $AbstractSyntaxTree = Get-Ast -ScriptString $ScriptString
29 | $AmsiSignatures = Find-AmsiSignatures -Ast $AbstractSyntaxTree -PSTokens $PSTokens -PSAmsiScanner $PSAmsiScanner | Sort-Object -Descending { $_.StartOffset}
30 | }
31 |
32 | $AmsiAstSignatures = @()
33 | If ($AmsiSignatures.Count -gt 0) {
34 | $AmsiAstSignatures = $AmsiSignatures | ? { $_.SignatureType.Contains('Ast') }
35 | }
36 | ForEach ($AmsiAstSignature in $AmsiAstSignatures) {
37 | If ($this.ObfuscationCache.Contains($AmsiAstSignature.SignatureContent)) { continue }
38 |
39 | $ObfuscatedAstExtent = Out-ObfuscatedAst -ScriptString $AmsiAstSignature.SignatureContent
40 | If (-not (Get-PSAmsiScanResult -ScriptString $ObfuscatedAstExtent -PSAmsiScanner $PSAmsiScanner)) {
41 | Write-Verbose "[Get-MinimallyObfuscated] Out-ObfuscatedAst obfuscation successful!"
42 | $this.ObfuscationCache[$AmsiAstSignature.SignatureContent] = $ObfuscatedAstExtent
43 | } Else { Write-Verbose "[Get-MinimallyObfuscated] Out-ObfuscatedAst obfuscation unsuccessful." }
44 | }
45 |
46 | ForEach($AmsiSignature in $AmsiSignatures) {
47 | If ($this.ObfuscationCache.Contains($AmsiSignature.SignatureContent)) { continue }
48 |
49 | # Reset the ScriptString for each Signature obfuscation iteration, so token indices are correct
50 | # We will actually replace w/ all obfuscated values at the end
51 | $ScriptString = $OriginalScript
52 | $ObfuscationSuccessful = $False
53 | $ObfuscationLevel = 0
54 | # Iterate obuscation levels until obfuscation succeeds
55 | While ((-not $ObfuscationSuccessful) -and ($ObfuscationLevel -lt 4)) {
56 |
57 | $ObfuscationLevel++
58 |
59 | $MatchingTokenArrays = (Get-MatchingPSTokens -SearchString $OriginalScript -SignatureString $AmsiSignature.SignatureContent -PSTokens $PSTokens) -as [array]
60 | ForEach ($MatchingTokenArray in $MatchingTokenArrays) {
61 | # If obfuscation already found for this string, skip it
62 | If ($this.ObfuscationCache.Contains($MatchingTokenArray.MatchingString)) { continue }
63 |
64 | $MatchingTokens = $MatchingTokenArray.MatchingTokens
65 | $DoneObfuscating = $False
66 | $TokenIndex = 0
67 | # Obfuscate the tokens until the string is no longer flagged
68 | While (-not $DoneObfuscating) {
69 | $MatchingToken = $MatchingTokens[$TokenIndex]
70 |
71 | If ($MatchingToken.Type -eq 'Comment') {
72 | $this.ObfuscationCache[$MatchingTokenArray.MatchingString] = ""
73 | $DoneObfuscating = $True
74 | $ObfuscationSuccessful = $True
75 | }
76 | # Only obfuscate the following token types
77 | ElseIf ($MatchingToken.Type -in @('String', 'Member', 'CommandArgument', 'Command', 'Variable')) {
78 | $ScriptString = Out-ObfuscatedPSToken -ScriptString $ScriptString -PSTokens $MatchingTokens -Index $TokenIndex -ObfuscationLevel $ObfuscationLevel
79 | # Calculate the replacement string for the current AmsiFlaggedString, based on current obfuscation
80 | $ReplacementString = $ScriptString.Substring($MatchingTokenArray.StartIndex, $MatchingTokenArray.Length + ($ScriptString.Length - $OriginalScript.Length))
81 | # Check if this current replacement string is still flagged
82 | If (-not (Get-PSAmsiScanResult -ScriptString $ReplacementString -PSAmsiScanner $PSAmsiScanner)) {
83 | # Done obfuscating if the resulting string is no longer flagged
84 | $DoneObfuscating = $True
85 | $ObfuscationSuccessful = $True
86 | $this.ObfuscationCache[$MatchingTokenArray.MatchingString] = $ReplacementString
87 | }
88 | }
89 | # If we've run through all the strings and the string is still flagged, obfuscation fails
90 | If (($TokenIndex -ge ($MatchingTokens.Count-1))) { $DoneObfuscating = $True }
91 |
92 | Else { $TokenIndex++ }
93 | }
94 | }
95 | }
96 | }
97 |
98 | $this.ObfuscationCache.Keys | % {
99 | # Replace all the strings at the end
100 | $ScriptString = $ScriptString.Replace($_, $this.ObfuscationCache[$_])
101 | }
102 |
103 | $this.ObfuscationCache[$OriginalScript] = $ScriptString
104 |
105 | If ($CreatedPSAmsiScanner) {
106 | $PSAmsiScanner.Dispose()
107 | }
108 |
109 | return $ScriptString
110 | }
111 |
112 | [String] GetMinimallyObfuscated([String] $ScriptString, [Object] $PSAmsiScanner) {
113 | $CreatedPSAmsiScanner = $False
114 | If (-not $PSAmsiScanner) {
115 | $CreatedPSAmsiScanner = $True
116 | $PSAmsiScanner = New-PSAmsiScanner
117 | } ElseIf (-not $PSAmsiScanner.GetType().Name -eq 'PSAmsiScanner') {
118 | throw "PSAmsiScanner must be of type [PSAmsiScanner]"
119 | }
120 |
121 | $Detected = $True
122 | $MinimallyObfuscated = $ScriptString
123 | Do {
124 | $MinimallyObfuscated = $this.GetMinimallyObfuscated($MinimallyObfuscated, $PSAmsiScanner, $null)
125 | $Detected = Get-PSAmsiScanResult -ScriptString $MinimallyObfuscated -PSAmsiScanner $PSAmsiScanner
126 | } While($Detected)
127 |
128 | If ($CreatedPSAmsiScanner) {
129 | $PSAmsiScanner.Dispose()
130 | }
131 |
132 | return $MinimallyObfuscated
133 | }
134 |
135 | [String] GetMinimallyObfuscated([String] $ScriptString) {
136 | return $this.GetMinimallyObfuscated($ScriptString, $null)
137 | }
138 |
139 | [String] GetMinimallyObfuscated([ScriptBlock] $ScriptBlock, [Object] $PSAmsiScanner, [Object[]] $AmsiSignatures) {
140 | $ScriptString = $ScriptBlock -as [String]
141 | return $this.GetMinimallyObfuscated($ScriptString, $PSAmsiScanner, $AmsiSignatures)
142 | }
143 |
144 | [String] GetMinimallyObfuscated([ScriptBlock] $ScriptBlock, [Object] $PSAmsiScanner) {
145 | return $this.GetMinimallyObfuscated($ScriptBlock, $PSAmsiScanner)
146 | }
147 |
148 | [String] GetMinimallyObfuscated([ScriptBlock] $ScriptBlock) {
149 | return $this.GetMinimallyObfuscated($ScriptBlock, $null)
150 | }
151 |
152 | [String] GetMinimallyObfuscated([IO.FileInfo] $ScriptPath, [Object] $PSAmsiScanner, [Object[]] $AmsiSignatures) {
153 | $ScriptString = Get-Content $ScriptPath -Raw
154 | return $this.GetMinimallyObfuscated($ScriptString, $PSAmsiScanner, $AmsiSignatures)
155 | }
156 |
157 | [String] GetMinimallyObfuscated([IO.FileInfo] $ScriptPath, [Object] $PSAmsiScanner) {
158 | return $this.GetMinimallyObfuscated($ScriptPath, $PSAmsiScanner)
159 | }
160 |
161 | [String] GetMinimallyObfuscated([IO.FileInfo] $ScriptPath) {
162 | return $this.GetMinimallyObfuscated($ScriptPath, $null)
163 | }
164 |
165 | [String] GetMinimallyObfuscated([Uri] $ScriptUri, [Object] $PSAmsiScanner, [Object[]] $AmsiSignatures) {
166 | $ScriptString = [Net.Webclient]::new().DownloadString($ScriptUri)
167 | return $this.GetMinimallyObfuscated($ScriptString, $PSAmsiScanner, $AmsiSignatures)
168 | }
169 |
170 | [String] GetMinimallyObfuscated([Uri] $ScriptUri, [Object] $PSAmsiScanner) {
171 | return $this.GetMinimallyObfuscated($ScriptUri, $PSAmsiScanner)
172 | }
173 |
174 | [String] GetMinimallyObfuscated([Uri] $ScriptUri) {
175 | $ScriptString = [Net.Webclient]::new().DownloadString($ScriptUri)
176 | return $this.GetMinimallyObfuscated($ScriptString, $null)
177 | }
178 | }
179 |
180 | function Get-MatchingPSTokens {
181 | <#
182 |
183 | .SYNOPSIS
184 |
185 | Gets the PSTokens from a script that contains a portion of an AMSI signature.
186 |
187 | Author: Ryan Cobb (@cobbr_io)
188 | License: GNU GPLv3
189 | Required Dependecies: none
190 | Optional Dependencies: none
191 |
192 | .DESCRIPTION
193 |
194 | Get-MatchingPSTokens gets the tokens from a script that contains a portion of an AMSI signature.
195 |
196 | .PARAMETER SearchString
197 |
198 | The string containing the script to search for the AMSI signature.
199 |
200 | .PARAMETER SignatureString
201 |
202 | The string containing the AMSI signature to search for in the SearchString.
203 |
204 | .PARAMETER PSTokens
205 |
206 | The PSTokens that make up the SearchString script.
207 |
208 | .OUTPUTS
209 |
210 | PSCustomObject
211 |
212 | .EXAMPLE
213 |
214 | $AmsiSignatures = Find-AmsiSignatures -ScriptString $ScriptString
215 | Get-MatchingPSTokens -SearchString $ScriptString -SignatureString $AmsiSignatures[0] -PSTokens (Get-PSTokens -ScriptString $ScriptString)
216 |
217 | .NOTES
218 |
219 | Get-MatchingPSTokens is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
220 |
221 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
222 |
223 | #>
224 | [CmdletBinding()] Param (
225 | [String] $SearchString,
226 | [String] $SignatureString,
227 | [System.Management.Automation.PSToken[]] $PSTokens
228 | )
229 | $MinIndex = $SearchString.IndexOf($SignatureString)
230 |
231 | While ($MinIndex -ne -1) {
232 | $MaxIndex = $MinIndex + $SignatureString.Length
233 | $MatchingTokens = $PSTokens | ? {
234 | $StartIndex = $_.Start
235 | $EndIndex = $_.Start + $_.Length
236 | If ($StartIndex -ge $MinIndex -AND $EndIndex -le $MaxIndex) { $True }
237 | ElseIf ($EndIndex -ge $MinIndex -AND $EndIndex -le $MaxIndex) { $True }
238 | ElseIf ($StartIndex -ge $MinIndex -AND $StartIndex -le $MaxIndex) { $True }
239 | ElseIf ($StartIndex -le $MinIndex -AND $EndIndex -ge $MaxIndex) { $True }
240 | }
241 | If ($MatchingTokens.Count -gt 1) {
242 | $Start = $MatchingTokens[0].Start
243 | $Length = $MatchingTokens[$MatchingTokens.Count-1].Start + $MatchingTokens[$MatchingTokens.Count-1].Length - $Start
244 | $MatchingString = $SearchString.Substring($Start, $Length)
245 | [PSCustomObject] @{ MatchingTokens = ($MatchingTokens | Sort-Object -Descending { $_.Start }); MatchingString = $MatchingString; StartIndex = $Start; Length = $Length}
246 | } ElseIf ($MatchingTokens.Count -eq 1) {
247 | [PSCustomObject] @{ MatchingTokens = $MatchingTokens; MatchingString = $SearchString.Substring($MatchingTokens.Start, $MatchingTokens.Length); StartIndex = $MatchingTokens.Start; Length = $MatchingTokens.Length }
248 | }
249 | $MinIndex = $SearchString.IndexOf($SignatureString, $MinIndex+1)
250 | }
251 | }
252 |
253 | function Out-ObfuscatedPSToken {
254 | <#
255 | .SYNOPSIS
256 |
257 | Obfuscates a single PSToken within a script.
258 |
259 | Author: Daniel Bohannon (@danielhbohannon)
260 | Modified By: Ryan Cobb (@cobbr_io)
261 | License: Apache License, Version 2.0
262 | Required Dependencies: none
263 | Optional Dependencies: Out-ObfuscatedStringTokenLevel1, Out-RandomCaseToken, Out-ObfuscatedWithTicks,
264 | Out-ObfuscatedMemberTokenLevel3, Out-ObfuscatedCommandArgumentTokenLevel3,
265 | Out-ObfuscatedCommandTokenLevel2, Out-ObfuscatedVariableTokenLevel1, Out-ObfuscatedTypeToken,
266 | Out-RemoveComments
267 |
268 | .DESCRIPTION
269 |
270 | Out-ObfuscatedPSToken obfuscates a specified token within a script and returns
271 | the resulting script.
272 |
273 | .PARAMETER ScriptString
274 |
275 | The ScriptString that contains the token to be obfuscated.
276 |
277 | .PARAMETER PSTokens
278 |
279 | The set of PSTokens that represents the given ScriptString.
280 |
281 | .PARAMETER Index
282 |
283 | The index of the specified token to be obfuscated within the PSTokens array.
284 |
285 | .OUTPUTS
286 |
287 | String
288 |
289 | .EXAMPLE
290 |
291 | Out-ObfuscatedPSToken -ScriptString "Write-Host example" -PSTokens $(Get-PSTokens "Write-Host example") -Index 2
292 |
293 | .NOTES
294 |
295 | Out-ObfuscatedPSToken is a modified version of the original Out-ObfuscatedTokenCommand function included in
296 | Invoke-Obfuscation. The original description of Out-ObfuscatedTokenCommand is as follows:
297 | Out-ObfuscatedTokenCommand orchestrates the tokenization and application of all token-based obfuscation functions to provided PowerShell script and places obfuscated tokens back into the provided PowerShell script to evade detection by simple IOCs and process execution monitoring relying solely on command-line arguments. If no $TokenTypeToObfuscate is defined then Out-ObfuscatedTokenCommand will automatically perform ALL token obfuscation functions in random order at the highest obfuscation level.
298 | This is a personal project developed by Daniel Bohannon while an employee at MANDIANT, A FireEye Company.
299 |
300 | .LINK
301 |
302 | http://www.danielbohannon.com
303 |
304 | #>
305 | param(
306 | [Parameter(Position = 0, Mandatory)]
307 | [ValidateNotNullOrEmpty()]
308 | [String] $ScriptString,
309 |
310 | [Parameter(Position = 1, Mandatory)]
311 | [ValidateNotNullOrEmpty()]
312 | [System.Management.Automation.PSToken[]] $PSTokens,
313 |
314 | [Parameter(Position = 2, Mandatory)]
315 | [ValidateRange(0, [Int]::MaxValue)]
316 | [Int] $Index,
317 |
318 | [Parameter(Position = 3)]
319 | [ValidateRange(1, 4)]
320 | [Int] $ObfuscationLevel = 1
321 |
322 | )
323 | $PSToken = $PSTokens[$Index]
324 | If (($PSToken.Type -eq 'String')) {
325 | # If String $Token immediately follows a period (and does not begin $ScriptString) then do not obfuscate as a String.
326 | # In this scenario $Token is originally a Member token that has quotes added to it.
327 | # E.g. both InvokeCommand and InvokeScript in $ExecutionContext.InvokeCommand.InvokeScript
328 | If (($PSToken.Start -gt 0) -AND ($ScriptString.SubString($PSToken.Start-1,1) -eq '.')) {
329 | Continue
330 | }
331 |
332 | # Set valid obfuscation levels for current token type.
333 | $ValidObfuscationLevels = @(1,2)
334 |
335 | # If invalid obfuscation level is passed to this function then default to highest obfuscation level available for current token type.
336 | If($ValidObfuscationLevels -NotContains $ObfuscationLevel) {$ObfuscationLevel = $ValidObfuscationLevels | Sort-Object -Descending | Select-Object -First 1}
337 |
338 | # The below Parameter Binding Validation Attributes cannot have their string values formatted with the -f format operator unless treated as a scriptblock.
339 | # When we find strings following these Parameter Binding Validation Attributes then if we are using a -f format operator we will treat the result as a scriptblock.
340 | # Source: https://technet.microsoft.com/en-us/library/hh847743.aspx
341 | $ParameterValidationAttributesToTreatStringAsScriptblock = @()
342 | $ParameterValidationAttributesToTreatStringAsScriptblock += 'alias'
343 | $ParameterValidationAttributesToTreatStringAsScriptblock += 'allownull'
344 | $ParameterValidationAttributesToTreatStringAsScriptblock += 'allowemptystring'
345 | $ParameterValidationAttributesToTreatStringAsScriptblock += 'allowemptycollection'
346 | $ParameterValidationAttributesToTreatStringAsScriptblock += 'validatecount'
347 | $ParameterValidationAttributesToTreatStringAsScriptblock += 'validatelength'
348 | $ParameterValidationAttributesToTreatStringAsScriptblock += 'validatepattern'
349 | $ParameterValidationAttributesToTreatStringAsScriptblock += 'validaterange'
350 | $ParameterValidationAttributesToTreatStringAsScriptblock += 'validatescript'
351 | $ParameterValidationAttributesToTreatStringAsScriptblock += 'validateset'
352 | $ParameterValidationAttributesToTreatStringAsScriptblock += 'validatenotnull'
353 | $ParameterValidationAttributesToTreatStringAsScriptblock += 'validatenotnullorempty'
354 |
355 | $ParameterValidationAttributesToTreatStringAsScriptblock += 'helpmessage'
356 | $ParameterValidationAttributesToTreatStringAsScriptblock += 'confirmimpact'
357 | $ParameterValidationAttributesToTreatStringAsScriptblock += 'outputtype'
358 |
359 | Switch ($ObfuscationLevel) {
360 | 1 {$ScriptString = Out-ObfuscatedStringTokenLevel1 $ScriptString $PSToken 1}
361 | 2 {$ScriptString = Out-ObfuscatedStringTokenLevel1 $ScriptString $PSToken 2}
362 | }
363 |
364 | }
365 | ElseIf ($PSToken.Type -eq 'Member') {
366 | # Set valid obfuscation levels for current token type.
367 | $ValidObfuscationLevels = @(1,2,3,4)
368 |
369 | # If invalid obfuscation level is passed to this function then default to highest obfuscation level available for current token type.
370 | If($ValidObfuscationLevels -NotContains $ObfuscationLevel) {$ObfuscationLevel = $ValidObfuscationLevels | Sort-Object -Descending | Select-Object -First 1}
371 |
372 | # The below Parameter Attributes cannot be obfuscated like other Member Tokens, so we will only randomize the case of these tokens.
373 | # Source 1: https://technet.microsoft.com/en-us/library/hh847743.aspx
374 | $MemberTokensToOnlyRandomCase = @()
375 | $MemberTokensToOnlyRandomCase += 'mandatory'
376 | $MemberTokensToOnlyRandomCase += 'position'
377 | $MemberTokensToOnlyRandomCase += 'parametersetname'
378 | $MemberTokensToOnlyRandomCase += 'valuefrompipeline'
379 | $MemberTokensToOnlyRandomCase += 'valuefrompipelinebypropertyname'
380 | $MemberTokensToOnlyRandomCase += 'valuefromremainingarguments'
381 | $MemberTokensToOnlyRandomCase += 'helpmessage'
382 | $MemberTokensToOnlyRandomCase += 'alias'
383 | # Source 2: https://technet.microsoft.com/en-us/library/hh847872.aspx
384 | $MemberTokensToOnlyRandomCase += 'confirmimpact'
385 | $MemberTokensToOnlyRandomCase += 'defaultparametersetname'
386 | $MemberTokensToOnlyRandomCase += 'helpuri'
387 | $MemberTokensToOnlyRandomCase += 'supportspaging'
388 | $MemberTokensToOnlyRandomCase += 'supportsshouldprocess'
389 | $MemberTokensToOnlyRandomCase += 'positionalbinding'
390 |
391 | $MemberTokensToOnlyRandomCase += 'ignorecase'
392 |
393 | Switch ($ObfuscationLevel) {
394 | 1 {$ScriptString = Out-RandomCaseToken $ScriptString $PSToken}
395 | 2 {$ScriptString = Out-ObfuscatedWithTicks $ScriptString $PSToken}
396 | 3 {$ScriptString = Out-ObfuscatedMemberTokenLevel3 $ScriptString $PSTokens $Index 1}
397 | 4 {$ScriptString = Out-ObfuscatedMemberTokenLevel3 $ScriptString $PSTokens $Index 2}
398 | }
399 | }
400 | ElseIf ($PSToken.Type -eq 'CommandArgument') {
401 | # Set valid obfuscation levels for current token type.
402 | $ValidObfuscationLevels = @(1,2,3,4)
403 |
404 | # If invalid obfuscation level is passed to this function then default to highest obfuscation level available for current token type.
405 | If($ValidObfuscationLevels -NotContains $ObfuscationLevel) {$ObfuscationLevel = $ValidObfuscationLevels | Sort-Object -Descending | Select-Object -First 1}
406 |
407 | Switch($ObfuscationLevel)
408 | {
409 | 1 {$ScriptString = Out-RandomCaseToken $ScriptString $PSToken}
410 | 2 {$ScriptString = Out-ObfuscatedWithTicks $ScriptString $PSToken}
411 | 3 {$ScriptString = Out-ObfuscatedCommandArgumentTokenLevel3 $ScriptString $PSToken 1}
412 | 4 {$ScriptString = Out-ObfuscatedCommandArgumentTokenLevel3 $ScriptString $PSToken 2}
413 | }
414 | }
415 | ElseIf ($PSToken.Type -eq 'Command') {
416 | # Set valid obfuscation levels for current token type.
417 | $ValidObfuscationLevels = @(1,2,3)
418 |
419 | # If invalid obfuscation level is passed to this function then default to highest obfuscation level available for current token type.
420 | If($ValidObfuscationLevels -NotContains $ObfuscationLevel) {$ObfuscationLevel = $ValidObfuscationLevels | Sort-Object -Descending | Select-Object -First 1}
421 |
422 | # If a variable is encapsulated in curly braces (e.g. ${ExecutionContext}) then the string inside is treated as a Command token.
423 | # So we will force tick obfuscation (option 1) instead of splatting (option 2) as that would cause errors.
424 | If(($PSToken.Start -gt 1) -AND ($ScriptString.SubString($PSToken.Start-1,1) -eq '{') -AND ($ScriptString.SubString($PSToken.Start+$PSToken.Length,1) -eq '}')) {
425 | $ObfuscationLevel = 1
426 | }
427 |
428 | Switch($ObfuscationLevel) {
429 | 1 {$ScriptString = Out-ObfuscatedWithTicks $ScriptString $PSToken}
430 | 2 {$ScriptString = Out-ObfuscatedCommandTokenLevel2 $ScriptString $PSToken 1}
431 | 3 {$ScriptString = Out-ObfuscatedCommandTokenLevel2 $ScriptString $PSToken 2}
432 | }
433 | }
434 | ElseIf ($PSToken.Type -eq 'Variable') {
435 | $ScriptString = Out-ObfuscatedVariableTokenLevel1 $ScriptString $PSToken
436 | }
437 | ElseIf ($PSToken.Type -eq 'Type') {
438 | # Set valid obfuscation levels for current token type.
439 | $ValidObfuscationLevels = @(1,2)
440 |
441 | # If invalid obfuscation level is passed to this function then default to lowest obfuscation level available for current token type.
442 | If($ValidObfuscationLevels -NotContains $ObfuscationLevel) {$ObfuscationLevel = $ValidObfuscationLevels | Select-Object -First 1}
443 |
444 | # The below Type value substrings are part of Types that cannot be direct Type casted, so we will not perform direct Type casting on Types containing these values.
445 | $TypesThatCannotByDirectTypeCasted = @()
446 | $TypesThatCannotByDirectTypeCasted += 'directoryservices.accountmanagement.'
447 | $TypesThatCannotByDirectTypeCasted += 'windows.clipboard'
448 |
449 | Switch ($ObfuscationLevel) {
450 | 1 {$ScriptString = Out-ObfuscatedTypeToken $ScriptString $PSToken 1}
451 | 2 {$ScriptString = Out-ObfuscatedTypeToken $ScriptString $PSToken 2}
452 | }
453 | }
454 | ElseIf ($PSToken.Type -eq 'Comment') {
455 | $ScriptString = Out-RemoveComments $ScriptString $PSTokens[$Index]
456 | }
457 |
458 | $ScriptString
459 | }
460 |
461 | function New-PowerShellObfuscator {
462 | <#
463 |
464 | .SYNOPSIS
465 |
466 | Creates a [PowerShellObfuscator] object for obfuscating PowerShell scripts to pass AMSI scans.
467 |
468 | Author: Ryan Cobb (@cobbr_io)
469 | License: GNU GPLv3
470 | Required Dependecies: PowerShellObfuscator
471 | Optional Dependencies: none
472 |
473 | .DESCRIPTION
474 |
475 | New-PowerShellObfuscator creates a [PowerShellObfuscator] object for obfuscating PowerShell scripts to pass AMSI scans.
476 |
477 | .PARAMETER ObfuscationCache
478 |
479 | Specify an ObfuscationCache that is a Hastable correlating AMSI signatures to known successful obfuscated version that pass AMSI scans.
480 |
481 | .OUTPUTS
482 |
483 | PowerShellObfuscator
484 |
485 | .EXAMPLE
486 |
487 | $Obfuscator = New-PowerShellObfuscator
488 |
489 | .NOTES
490 |
491 | New-PowerShellObfuscator is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
492 |
493 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
494 |
495 | #>
496 | Param (
497 | [Parameter(Position = 0)]
498 | [ValidateNotNull()]
499 | [HashTable] $ObfuscationCache = @{}
500 | )
501 | [PowerShellObfuscator]::new($ObfuscationCache)
502 | }
503 |
504 | function Get-MinimallyObfuscated {
505 | <#
506 | .SYNOPSIS
507 |
508 | Gets a minimally obfuscated copy of a script that passes AMSI scans.
509 |
510 | Author: Ryan Cobb (@cobbr_io)
511 | License: GNU GPLv3
512 | Required Dependecies: PowerShellObfuscator, New-PowerShellObfuscator
513 | Optional Dependencies: none
514 |
515 | .DESCRIPTION
516 |
517 | Get-MinimallyObfuscated gets a minimally obfuscated copy of a script that passes AMSI scans.
518 |
519 | .PARAMETER ScriptString
520 |
521 | Specifies the string containing the original script to be minimally obfuscated.
522 |
523 | .PARAMETER ScriptBlock
524 |
525 | Specifies the ScriptBlock containing the original script to be minimally obfuscated.
526 |
527 | .PARAMETER ScriptPath
528 |
529 | Specifies the Path to the original script to be minimally obfuscated.
530 |
531 | .PARAMETER ScriptUri
532 |
533 | The URI of the original script to be minimally obfuscated.
534 |
535 | .PARAMETER AmsiSignatures
536 |
537 | Specify the AMSI signatures that need to be obfuscated. These
538 | strings will be found manually, if not provided.
539 |
540 | .PARAMETER PSAmsiScanner
541 |
542 | Specifies the PSAmsiScanner to use for AMSI scans.
543 |
544 | .PARAMETER Obfuscator
545 |
546 | Specifies the PowerShellObfuscator to use for obfuscation.
547 |
548 | .OUTPUTS
549 |
550 | String
551 |
552 | .EXAMPLE
553 |
554 | Get-MinimallyObfuscated -ScriptString "Write-Host example"
555 |
556 | .EXAMPLE
557 |
558 | Get-MinamallyObfuscated -ScriptBlock { Write-Host "example" }
559 |
560 | .EXAMPLE
561 |
562 | Get-MinimallyObfuscated -ScriptPath ./Write-Example.ps1
563 |
564 | .NOTES
565 |
566 | New-PowerShellObfuscator is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
567 |
568 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
569 |
570 | #>
571 | [CmdletBinding(DefaultParameterSetName = "ByString")] Param(
572 | [Parameter(ParameterSetName = "ByString", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
573 | [ValidateNotNullOrEmpty()]
574 | [String] $ScriptString,
575 |
576 | [Parameter(ParameterSetName = "ByScriptBlock", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
577 | [ValidateNotNullOrEmpty()]
578 | [ScriptBlock] $ScriptBlock,
579 |
580 | [Parameter(ParameterSetName = "ByPath", Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
581 | [ValidateScript({Test-Path $_ -PathType leaf})]
582 | [Alias('PSPath')]
583 | [String] $ScriptPath,
584 |
585 | [Parameter(ParameterSetName = "ByUri", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
586 | [ValidateScript({$_.Scheme -match 'http|https'})]
587 | [Uri] $ScriptUri,
588 |
589 | [Parameter(Position = 1)]
590 | [String[]] $AmsiSignatures,
591 |
592 | [Parameter(Position = 2)]
593 | [ValidateScript({$_.GetType().Name -eq 'PSAmsiScanner'})]
594 | [Object] $PSAmsiScanner,
595 |
596 | [Parameter(Position = 3)]
597 | [ValidateScript({$_.GetType().Name -eq 'PowerShellObfuscator'})]
598 | [Object] $Obfuscator
599 | )
600 | Begin {
601 | If (-not $Obfuscator) { $Obfuscator = New-PowerShellObfuscator }
602 | }
603 | Process {
604 | If ($AmsiSignatures) {
605 | If ($ScriptString) { $Obfuscator.GetMinimallyObfuscated($ScriptString, $PSAmsiScanner, $AmsiSignatures) }
606 | ElseIf ($ScriptBlock) { $Obfuscator.GetMinimallyObfuscated($ScriptBlock, $PSAmsiScanner, $AmsiSignatures) }
607 | ElseIf ($ScriptPath) { $Obfuscator.GetMinimallyObfuscated($ScriptPath, $PSAmsiScanner, $AmsiSignatures) }
608 | ElseIf ($ScriptUri) { $Obfuscator.GetMinimallyObfuscated($ScriptUri, $PSAmsiScanner, $AmsiSignatures) }
609 | }
610 | Else {
611 | If ($ScriptString) { $Obfuscator.GetMinimallyObfuscated($ScriptString, $PSAmsiScanner) }
612 | ElseIf ($ScriptBlock) { $Obfuscator.GetMinimallyObfuscated($ScriptBlock, $PSAmsiScanner) }
613 | ElseIf ($ScriptPath) { $Obfuscator.GetMinimallyObfuscated($ScriptPath, $PSAmsiScanner) }
614 | ElseIf ($ScriptUri) { $Obfuscator.GetMinimallyObfuscated($ScriptUri, $PSAmsiScanner) }
615 | }
616 | }
617 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/PSAmsi/Find-AmsiSignatures.ps1:
--------------------------------------------------------------------------------
1 | function Find-AmsiSignatures {
2 | <#
3 |
4 | .SYNOPSIS
5 |
6 | Finds the AMSI signatures within a script that are flagged as malware by AMSI.
7 |
8 | Author: Ryan Cobb (@cobbr_io)
9 | License: GNU GPLv3
10 | Required Dependecies: none
11 | Optional Dependencies: New-PSAmsiScanner, Find-AmsiAstSignatures, Find-AmsiPSTokenSignatures
12 |
13 | .DESCRIPTION
14 |
15 | Find-AmsiSignatures finds the AMSI signatures within a script that are flagged as malware
16 | by the current AMSI AntiMalware Provider.
17 |
18 | .PARAMETER AbstractSyntaxTree
19 |
20 | Specifies the root Ast of an AbstractSyntaxTree that represents the script to get AMSI
21 | signatures from.
22 |
23 | .PARAMETER PSTokens
24 |
25 | Specifies the PSTokens that represents the script to get AMSI signatures from.
26 |
27 | .PARAMETER ScriptString
28 |
29 | Specifies the string containing the script to get AMSI signatures from.
30 |
31 | .PARAMETER ScriptBlock
32 |
33 | Specifies the ScriptBlock containing the script to get AMSI signatures from.
34 |
35 | .PARAMETER ScriptPath
36 |
37 | Specifies the Path to the script to get AMSI signatures from.
38 |
39 | .PARAMETER ScriptUri
40 |
41 | Specifies the URI of the script to get AMSI signatures from.
42 |
43 | .PARAMETER PSAmsiScanner
44 |
45 | Specifies the PSAmsiScanner to use to scan for finding AMSI signatures.
46 |
47 | .OUTPUTS
48 |
49 | String[]
50 |
51 | .EXAMPLE
52 |
53 | Find-AmsiSignatures "Write-Host example"
54 |
55 | Find-AmsiSignatures $AST $PSTokens
56 |
57 | @('Write-Host example1', 'Write-Host example2', 'Write-Host example3') | Find-AmsiSignatures
58 |
59 | .NOTES
60 |
61 | Find-AmsiSignatures is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
62 |
63 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
64 |
65 | #>
66 | [CmdletBinding(DefaultParameterSetName = "ByString")] Param(
67 | [Parameter(ParameterSetName = "ByComponents", Position = 0, Mandatory)]
68 | [Alias('Ast')]
69 | [System.Management.Automation.Language.Ast] $AbstractSyntaxTree,
70 |
71 | [Parameter(ParameterSetName = "ByComponents", Position = 1, Mandatory)]
72 | [System.Management.Automation.PSToken[]] $PSTokens,
73 |
74 | [Parameter(ParameterSetName = "ByString", Position = 0, ValueFromPipeline, Mandatory)]
75 | [ValidateNotNullOrEmpty()]
76 | [String] $ScriptString,
77 |
78 | [Parameter(ParameterSetName = "ByScriptBlock", Position = 0, ValueFromPipeline, Mandatory)]
79 | [ValidateNotNullOrEmpty()]
80 | [ScriptBlock] $ScriptBlock,
81 |
82 | [Parameter(ParameterSetName = "ByPath", Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
83 | [ValidateScript({Test-Path $_ -PathType leaf})]
84 | [Alias('PSPath')]
85 | [String] $ScriptPath,
86 |
87 | [Parameter(ParameterSetName = "ByUri", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
88 | [ValidateScript({$_.Scheme -match 'http|https'})]
89 | [Uri] $ScriptUri,
90 |
91 | [ValidateScript({$_.GetType().Name -eq 'PSAmsiScanner'})]
92 | [System.Object] $PSAmsiScanner,
93 |
94 | [Switch] $Unique
95 | )
96 | Begin {
97 | $CreatedPSAmsiScanner = $False
98 | If (-not $PSAmsiScanner) {
99 | $PSAmsiScanner = New-PSAmsiScanner
100 | $CreatedPSAmsiScanner = $True
101 | }
102 | }
103 | Process {
104 | If ($ScriptString) {
105 | $AmsiAstSignatures = Find-AmsiAstSignatures -ScriptString $ScriptString -PSAmsiScanner $PSAmsiScanner
106 | $AmsiPSTokenSignatures = Find-AmsiPSTokenSignatures -ScriptString $ScriptString -PSAmsiScanner $PSAmsiScanner -FilterPSTokenTypes 'Comment'
107 | } ElseIf ($ScriptBlock) {
108 | $AmsiAstSignatures = Find-AmsiAstSignatures -ScriptBlock $ScriptBlock -PSAmsiScanner $PSAmsiScanner
109 | $AmsiPSTokenSignatures = Find-AmsiPSTokenSignatures -ScriptBlock $ScriptBlock -PSAmsiScanner $PSAmsiScanner -FilterPSTokenTypes 'Comment'
110 | } ElseIf ($ScriptPath) {
111 | $AmsiAstSignatures = Find-AmsiAstSignatures -ScriptPath $ScriptPath -PSAmsiScanner $PSAmsiScanner
112 | $AmsiPSTokenSignatures = Find-AmsiPSTokenSignatures -ScriptPath $ScriptPath -PSAmsiScanner $PSAmsiScanner -FilterPSTokenTypes 'Comment'
113 | } ElseIf ($ScriptUri) {
114 | $AmsiAstSignatures = Find-AmsiAstSignatures -ScriptUri $ScriptUri -PSAmsiScanner $PSAmsiScanner
115 | $AmsiPSTokenSignatures = Find-AmsiPSTokenSignatures -ScriptUri $ScriptUri -PSAmsiScanner $PSAmsiScanner -FilterPSTokenTypes 'Comment'
116 | } ElseIf ($AbstractSyntaxTree -and $PSTokens) {
117 | $AmsiAstSignatures = Find-AmsiAstSignatures -AbstractSyntaxTree $AbstractSyntaxTree -PSAmsiScanner $PSAmsiScanner
118 | $AmsiPSTokenSignatures = Find-AmsiPSTokenSignatures -PSTokens $PSTokens -PSAmsiScanner $PSAmsiScanner -FilterPSTokenTypes 'Comment'
119 | }
120 | # Create AmsiSignature objects
121 | $AmsiAstSignatures = ($AmsiAstSignatures | % { [PSCustomObject] @{ StartOffset = $_.Extent.StartOffset; SignatureType = $_.GetType().Name; SignatureContent = $_.Extent.Text } }) -as [array]
122 | $AmsiPSTokenSignatures = ($AmsiPSTokenSignatures | % { [PSCustomObject] @{ StartOffset = $_.Start; SignatureType = $_.GetType().Name; SignatureContent = $_.Content; } }) -as [array]
123 | $AmsiSignatures = $AmsiAstSignatures + $AmsiPSTokenSignatures
124 |
125 | If ($Unique) { $AmsiSignatures | Sort-Object -Unique { $_.SignatureContent } }
126 | Else { $AmsiSignatures }
127 | }
128 | End {
129 | If ($CreatedPSAmsiScanner) { $PSAmsiScanner.Dispose() }
130 | }
131 | }
132 |
133 | function Test-ContainsAmsiSignatures {
134 | <#
135 |
136 | .SYNOPSIS
137 |
138 | Tests if any AMSI signatures are contained in a given script.
139 |
140 | Author: Ryan Cobb (@cobbr_io)
141 | License: GNU GPLv3
142 | Required Dependecies: Test-ContainsAmsiAstSignatures, Test-ContainsAmsiPSTokenSignatures
143 | Optional Dependencies: New-PSAmsiScanner
144 |
145 | .DESCRIPTION
146 |
147 | Test-ContainsAmsiSignatures tests if any AMSI signatures are contained in a given script. This function
148 | is much quicker than a full Find-AmsiSignatures search.
149 |
150 | .PARAMETER AbstractSyntaxTree
151 |
152 | Specifies the root Ast of an AbstractSyntaxTree that represents the script to get AMSI
153 | signatures from.
154 |
155 | .PARAMETER PSTokens
156 |
157 | Specifies the PSTokens that represents the script to get AMSI signatures from.
158 |
159 | .PARAMETER ScriptString
160 |
161 | Specifies the string containing the script to get AMSI signatures from.
162 |
163 | .PARAMETER ScriptBlock
164 |
165 | Specifies the ScriptBlock containing the script to get AMSI signatures from.
166 |
167 | .PARAMETER ScriptPath
168 |
169 | Specifies the Path to the script to get AMSI signatures from.
170 |
171 | .PARAMETER ScriptUri
172 |
173 | Specifies the URI of the script to get AMSI signatures from.
174 |
175 | .PARAMETER PSAmsiScanner
176 |
177 | Specifies the PSAmsiScanner to use to scan for finding AMSI signatures.
178 |
179 | .OUTPUTS
180 |
181 | String[]
182 |
183 | .EXAMPLE
184 |
185 | Test-ContainsAmsiSignatures "Write-Host example"
186 |
187 | Test-ContainsAmsiSignatures $AST $PSTokens
188 |
189 | @('Write-Host example1', 'Write-Host example2', 'Write-Host example3') | Test-ContainsAmsiSignatures
190 |
191 | .NOTES
192 |
193 | Test-ContainsAmsiSignatures is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
194 |
195 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
196 |
197 | #>
198 | [CmdletBinding(DefaultParameterSetName = "ByString")] Param(
199 | [Parameter(ParameterSetName = "ByComponents", Position = 0, Mandatory)]
200 | [Alias('Ast')]
201 | [System.Management.Automation.Language.Ast] $AbstractSyntaxTree,
202 |
203 | [Parameter(ParameterSetName = "ByComponents", Position = 1, Mandatory)]
204 | [System.Management.Automation.PSToken[]] $PSTokens,
205 |
206 | [Parameter(ParameterSetName = "ByString", Position = 0, ValueFromPipeline, Mandatory)]
207 | [ValidateNotNullOrEmpty()]
208 | [String] $ScriptString,
209 |
210 | [Parameter(ParameterSetName = "ByScriptBlock", Position = 0, ValueFromPipeline, Mandatory)]
211 | [ValidateNotNullOrEmpty()]
212 | [ScriptBlock] $ScriptBlock,
213 |
214 | [Parameter(ParameterSetName = "ByPath", Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
215 | [ValidateScript({Test-Path $_ -PathType leaf})]
216 | [Alias('PSPath')]
217 | [String] $ScriptPath,
218 |
219 | [Parameter(ParameterSetName = "ByUri", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
220 | [ValidateScript({$_.Scheme -match 'http|https'})]
221 | [Uri] $ScriptUri,
222 |
223 | [ValidateScript({$_.GetType().Name -eq 'PSAmsiScanner'})]
224 | [System.Object] $PSAmsiScanner
225 | )
226 | Begin {
227 | $CreatedPSAmsiScanner = $False
228 | If (-not $PSAmsiScanner) {
229 | $PSAmsiScanner = New-PSAmsiScanner
230 | $CreatedPSAmsiScanner = $True
231 | }
232 | }
233 | Process {
234 | If ($ScriptBlock) { $ScriptString = $ScriptBlock -as [String] }
235 | ElseIf ($ScriptPath) { $ScriptString = Get-Content -Path $ScriptPath -Raw }
236 | ElseIf ($ScriptUri) { $ScriptString = [Net.Webclient]::new().DownloadString($ScriptUri) }
237 |
238 | $ContainsAstSignatures = Test-ContainsAmsiAstSignatures -ScriptString $ScriptString -PSAmsiScanner $PSAmsiScanner
239 | If ($ContainsAstSignatures) { $True }
240 | Else {
241 | $ContainsPSTokenSignatures = Test-ContainsAmsiPSTokenSignatures -ScriptString $ScriptString -PSAmsiScanner $PSAmsiScanner -FilterPSTokenTypes 'Comment'
242 | If ($ContainsPSTokenSignatures) { $True }
243 | Else { $False }
244 | }
245 | }
246 | End {
247 | If ($CreatedPSAmsiScanner) {
248 | $PSAmsiScanner.Dispose()
249 | }
250 | }
251 | }
252 |
253 | function Find-AmsiAstSignatures {
254 | <#
255 |
256 | .SYNOPSIS
257 |
258 | Finds the Asts that contain AMSI signatures within an AbstractSyntaxTree.
259 |
260 | Author: Ryan Cobb (@cobbr_io)
261 | License: GNU GPLv3
262 | Required Dependecies: none
263 | Optional Dependencies: New-PSAmsiScanner, Get-Ast
264 |
265 | .DESCRIPTION
266 |
267 | Find-AmsiAstSignatures finds the Asts that contain AMSI signatures within an AbstactSyntaxTree.
268 |
269 | .PARAMETER AbstractSyntaxTree
270 |
271 | Specifies the root Ast that represents the script to find Asts that contain AMSI signatures.
272 |
273 | .PARAMETER ScriptString
274 |
275 | Specifies the string containing the script to find Asts that contain AMSI signatures.
276 |
277 | .PARAMETER ScriptBlock
278 |
279 | Specifies the ScriptBlock containing the script to find Asts that contain AMSI signatures.
280 |
281 | .PARAMETER ScriptPath
282 |
283 | Specifies the Path containing the script to find Asts that contain AMSI signatures.
284 |
285 | .PARAMETER ScriptUri
286 |
287 | Specifies the Uri of the script to find Asts that contain AMSI signatures.
288 |
289 | .PARAMETER PSAmsiScanner
290 |
291 | Specifies the PSAmsiScanner to use to scan to find Asts that contain AMSI signatures.
292 |
293 | .OUTPUTS
294 |
295 | System.Management.Automation.Language.Ast[]
296 |
297 | .EXAMPLE
298 |
299 | Find-AmsiAstSignatures -Ast $AbstractSyntaxTree
300 |
301 | .EXAMPLE
302 |
303 | Find-AmsiAstSignatures "Write-Host example"
304 |
305 | .EXAMPLE
306 |
307 | Find-AmsiAstSignatures { Write-Host example }
308 |
309 | .EXAMPLE
310 |
311 | Find-AmsiAstSignatures -ScriptPath $ScriptPath
312 |
313 | .EXAMPLE
314 |
315 | @($Ast1, $Ast2, $Ast3) | Find-AmsiAstSignatures
316 |
317 | .EXAMPLE
318 |
319 | Get-ChildItem /path/to/scripts -Recurse -Include *.ps1 | Find-AmsiAstSignatures
320 |
321 | .EXAMPLE
322 |
323 | @('Write-Host example1', 'Write-Host example2', 'Write-Host example3') | Find-AmsiAstSignatures
324 |
325 | .EXAMPLE
326 |
327 | @({ Write-Host example1 }, { Write-Host example2 }, { Write-Host example3 }) | Find-AmsiAstSignatures
328 |
329 | .NOTES
330 |
331 | Find-AmsiAstSignatures is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
332 |
333 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
334 |
335 | #>
336 | [CmdletBinding(DefaultParameterSetName="ByString")] Param(
337 | [Parameter(ParameterSetName="ByAst", Position = 0, ValueFromPipeline, Mandatory)]
338 | [ValidateNotNullOrEmpty()]
339 | [Alias('Ast')]
340 | [System.Management.Automation.Language.Ast] $AbstractSyntaxTree,
341 |
342 | [Parameter(ParameterSetName = "ByString", Position = 0, ValueFromPipeline, Mandatory)]
343 | [ValidateNotNullOrEmpty()]
344 | [String] $ScriptString,
345 |
346 | [Parameter(ParameterSetName = "ByScriptBlock", Position = 0, ValueFromPipeline, Mandatory)]
347 | [ValidateNotNullOrEmpty()]
348 | [ScriptBlock] $ScriptBlock,
349 |
350 | [Parameter(ParameterSetName = "ByPath", Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
351 | [ValidateScript({Test-Path $_ -PathType leaf})]
352 | [Alias('PSPath')]
353 | [String] $ScriptPath,
354 |
355 | [Parameter(ParameterSetName = "ByUri", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
356 | [ValidateScript({$_.Scheme -match 'http|https'})]
357 | [Uri] $ScriptUri,
358 |
359 | [Parameter(Position = 1)]
360 | [ValidateScript({$_.GetType().Name -eq 'PSAmsiScanner'})]
361 | [System.Object] $PSAmsiScanner
362 | )
363 | Begin {
364 | $CreatedPSAmsiScanner = $False
365 | If (-not $PSAmsiScanner) {
366 | $PSAmsiScanner = New-PSAmsiScanner
367 | $CreatedPSAmsiScanner = $True
368 | }
369 | }
370 |
371 | Process {
372 | # Get the Ast object, if given a different ParameterSetName
373 | If ($ScriptString) { $AbstractSyntaxTree = Get-Ast -ScriptString $ScriptString }
374 | ElseIf ($ScriptBlock) { $AbstractSyntaxTree = Get-Ast -ScriptBlock $ScriptBlock }
375 | ElseIf ($ScriptPath) { $AbstractSyntaxTree = Get-Ast -ScriptPath $ScriptPath }
376 | ElseIf ($ScriptUri) { $AbstractSyntaxTree = Get-Ast -ScriptUri $ScriptUri }
377 |
378 | $AmsiAstSignatures = $AbstractSyntaxTree.FindAll(
379 | {
380 | param($ast) (
381 | # This Ast has text
382 | ($ast.Extent.Text) -and
383 | # And it is flagged by AMSI
384 | ($PSAmsiScanner.GetPSAmsiScanResult($ast.Extent.Text))
385 | )
386 | }, $True) | Sort-Object { $_.Extent.Text.Length }
387 | # Need to find 'leaves' of detected tree to get the real signatures
388 | $NonDuplicates = @()
389 | ForEach ($AmsiAstSignature in $AmsiAstSignatures) {
390 | $Duplicate = $False
391 | ForEach ($NonDuplicate in $NonDuplicates) {
392 | If ($AmsiAstSignature.Extent.Text.Contains($NonDuplicate.Extent.Text)) {
393 | If (-not ($AmsiAstSignature.Extent.Text.Length -eq $NonDuplicate.Extent.Text.Length -AND $AmsiAstSignature.Extent.StartOffset -ne $NonDuplicate.Extent.StartOffset)) {
394 | $Duplicate = $True
395 | }
396 | break
397 | }
398 | }
399 | If (-not $Duplicate) {
400 | $NonDuplicates += $AmsiAstSignature
401 | }
402 | }
403 | $NonDuplicates -as [array]
404 | }
405 | End {
406 | If ($CreatedPSAmsiScanner) { $PSAmsiScanner.Dispose() }
407 | }
408 | }
409 |
410 | function Test-ContainsAmsiAstSignatures {
411 | <#
412 |
413 | .SYNOPSIS
414 |
415 | Tests if any Ast AMSI signatures are contained within an AbstractSyntaxTree.
416 |
417 | Author: Ryan Cobb (@cobbr_io)
418 | License: GNU GPLv3
419 | Required Dependecies: none
420 | Optional Dependencies: New-PSAmsiScanner, Get-Ast
421 |
422 | .DESCRIPTION
423 |
424 | Test-ContainsAmsiAstSignatures tests if any Ast AMSI signatures are contained within an AbstractSyntaxTree.
425 | This function is much quicker than a full Find-AmsiAstSignatures search.
426 |
427 | .PARAMETER AbstractSyntaxTree
428 |
429 | Specifies the root Ast that represents the script to find Asts that contain AMSI signatures.
430 |
431 | .PARAMETER ScriptString
432 |
433 | Specifies the string containing the script to find Asts that contain AMSI signatures.
434 |
435 | .PARAMETER ScriptBlock
436 |
437 | Specifies the ScriptBlock containing the script to find Asts that contain AMSI signatures.
438 |
439 | .PARAMETER ScriptPath
440 |
441 | Specifies the Path containing the script to find Asts that contain AMSI signatures.
442 |
443 | .PARAMETER ScriptUri
444 |
445 | Specifies the Uri of the script to find Asts that contain AMSI signatures.
446 |
447 | .PARAMETER PSAmsiScanner
448 |
449 | Specifies the PSAmsiScanner to use to scan to find Asts that contain AMSI signatures.
450 |
451 | .OUTPUTS
452 |
453 | System.Management.Automation.Language.Ast[]
454 |
455 | .EXAMPLE
456 |
457 | Test-ContainsAmsiAstSignatures -Ast $AbstractSyntaxTree
458 |
459 | .EXAMPLE
460 |
461 | Test-ContainsAmsiAstSignatures "Write-Host example"
462 |
463 | .EXAMPLE
464 |
465 | Test-ContainsAmsiAstSignatures { Write-Host example }
466 |
467 | .EXAMPLE
468 |
469 | Test-ContainsAmsiAstSignatures -ScriptPath $ScriptPath
470 |
471 | .EXAMPLE
472 |
473 | @($Ast1, $Ast2, $Ast3) | Test-ContainsAmsiAstSignatures
474 |
475 | .EXAMPLE
476 |
477 | Get-ChildItem /path/to/scripts -Recurse -Include *.ps1 | Test-ContainsAmsiAstSignatures
478 |
479 | .EXAMPLE
480 |
481 | @('Write-Host example1', 'Write-Host example2', 'Write-Host example3') | Test-ContainsAmsiAstSignatures
482 |
483 | .EXAMPLE
484 |
485 | @({ Write-Host example1 }, { Write-Host example2 }, { Write-Host example3 }) | Test-ContainsAmsiAstSignatures
486 |
487 | .NOTES
488 |
489 | Test-ContainsAmsiAstSignatures is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
490 |
491 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
492 |
493 | #>
494 | [CmdletBinding(DefaultParameterSetName="ByString")] Param(
495 | [Parameter(ParameterSetName="ByAst", Position = 0, ValueFromPipeline, Mandatory)]
496 | [ValidateNotNullOrEmpty()]
497 | [Alias('Ast')]
498 | [System.Management.Automation.Language.Ast] $AbstractSyntaxTree,
499 |
500 | [Parameter(ParameterSetName = "ByString", Position = 0, ValueFromPipeline, Mandatory)]
501 | [ValidateNotNullOrEmpty()]
502 | [String] $ScriptString,
503 |
504 | [Parameter(ParameterSetName = "ByScriptBlock", Position = 0, ValueFromPipeline, Mandatory)]
505 | [ValidateNotNullOrEmpty()]
506 | [ScriptBlock] $ScriptBlock,
507 |
508 | [Parameter(ParameterSetName = "ByPath", Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
509 | [ValidateScript({Test-Path $_ -PathType leaf})]
510 | [Alias('PSPath')]
511 | [String] $ScriptPath,
512 |
513 | [Parameter(ParameterSetName = "ByUri", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
514 | [ValidateScript({$_.Scheme -match 'http|https'})]
515 | [Uri] $ScriptUri,
516 |
517 | [ValidateScript({$_.GetType().Name -eq 'PSAmsiScanner'})]
518 | [System.Object] $PSAmsiScanner
519 | )
520 | Begin {
521 | $CreatedPSAmsiScanner = $False
522 | If (-not $PSAmsiScanner) {
523 | $PSAmsiScanner = New-PSAmsiScanner
524 | $CreatedPSAmsiScanner = $True
525 | }
526 | }
527 |
528 | Process {
529 | # Get the Ast object, if given a different ParameterSetName
530 | If ($ScriptString) { $AbstractSyntaxTree = Get-Ast -ScriptString $ScriptString }
531 | ElseIf ($ScriptBlock) { $AbstractSyntaxTree = Get-Ast -ScriptBlock $ScriptBlock }
532 | ElseIf ($ScriptPath) { $AbstractSyntaxTree = Get-Ast -ScriptPath $ScriptPath }
533 | ElseIf ($ScriptUri) { $AbstractSyntaxTree = Get-Ast -ScriptUri $ScriptUri }
534 |
535 | # Use the Find function to find first matching ScriptBlockAst flagged by AMSI
536 | $FirstFlagged = $AbstractSyntaxTree.Find(
537 | {
538 | param($ast) (
539 | $ast -is [System.Management.Automation.Language.ScriptBlockAst] -AND
540 | # This Ast has text
541 | ($ast.Extent.Text) -AND
542 | # And it is flagged by AMSI
543 | ($PSAmsiScanner.GetPSAmsiScanResult($ast.Extent.Text))
544 | )
545 | }, $True)
546 | If ($FirstFlagged) { $True }
547 | Else { $False }
548 | }
549 | End {
550 | If ($CreatedPSAmsiScanner) { $PSAmsiScanner.Dispose() }
551 | }
552 | }
553 |
554 | function Find-AmsiPSTokenSignatures {
555 | <#
556 | .SYNOPSIS
557 |
558 | Finds the PSTokens within a script that contain AMSI signatures that are flagged by AMSI.
559 |
560 | Author: Ryan Cobb (@cobbr_io)
561 | License: GNU GPLv3
562 | Required Dependecies: none
563 | Optional Dependencies: New-PSAmsiScanner, Get-PSTokens
564 |
565 | .DESCRIPTION
566 |
567 | Find-AmsiPSTokenSignatures finds the PSTokens within a script that contain AMSI signatures.
568 |
569 | .PARAMETER PSTokens
570 |
571 | Specifies the list of PSTokens that represent the script to find PSTokens from that contain AMSI signatures.
572 |
573 | .PARAMETER ScriptString
574 |
575 | Specifies the string containing the script to find PSTokens from that contain AMSI signatures.
576 |
577 | .PARAMETER ScriptBlock
578 |
579 | Specifies the ScriptBlock containing the script to find PSTokens from that contain AMSI signatures.
580 |
581 | .PARAMETER ScriptPath
582 |
583 | Specifies the Path containing the script to find PSTokens from that contain AMSI signatures.
584 |
585 | .PARAMETER ScriptUri
586 |
587 | Specifies the URI of the script to find PSTokens from that contain AMSI signatures.
588 |
589 | .PARAMETER PSAmsiScanner
590 |
591 | Specifies the PSAmsiScanner to use to find PSTokens that contain AMSI signatures.
592 |
593 | .PARAMETER FilterPSTokenTypes
594 |
595 | Specifies to only get PSTokens that have a PSTokenType in the provided list.
596 |
597 | .OUTPUTS
598 |
599 | System.Management.Automation.PSToken[]
600 |
601 | .EXAMPLE
602 |
603 | Find-AmsiPSTokenSignatures -PSTokens $PSTokens -FilterTokenTypes @('Comment', 'String')
604 |
605 | .EXAMPLE
606 |
607 | Find-AmsiPSTokenSignatures "Write-Host example"
608 |
609 | .EXAMPLE
610 |
611 | Find-AmsiPSTokenSignatures { Write-Host example }
612 |
613 | .EXAMPLE
614 |
615 | Find-AmsiPSTokenSignatures -ScriptPath $ScriptPath -FilterPSTokenTypes Comment
616 |
617 | .EXAMPLE
618 |
619 | @($PSTokens1, $PSTokens2, $PSTokens3) | Find-AmsiPSTokenSignatures
620 |
621 | .EXAMPLE
622 |
623 | Get-ChildItem /path/to/scripts -Recurse -Include *.ps1 | Find-AmsiPSTokenSignatures
624 |
625 | .EXAMPLE
626 |
627 | @('Write-Host example1', 'Write-Host example2', 'Write-Host example3') | Find-AmsiPSTokenSignatures
628 |
629 | .EXAMPLE
630 |
631 | @({ Write-Host example1 }, { Write-Host example2 }, { Write-Host example3 }) | Find-AmsiPSTokenSignatures
632 |
633 | .NOTES
634 |
635 | Find-AmsiPSTokenSignatures is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
636 |
637 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
638 |
639 | #>
640 |
641 | [CmdletBinding(DefaultParameterSetName="ByString")] Param(
642 | [Parameter(ParameterSetName = "ByPSTokens", Position = 0, ValueFromPipeline, Mandatory)]
643 | [ValidateNotNullOrEmpty()]
644 | [System.Management.Automation.PSToken[]] $PSTokens,
645 |
646 | [Parameter(ParameterSetName = "ByString", Position = 0, ValueFromPipeline, Mandatory)]
647 | [ValidateNotNullOrEmpty()]
648 | [String] $ScriptString,
649 |
650 | [Parameter(ParameterSetName = "ByScriptBlock", Position = 0, ValueFromPipeline, Mandatory)]
651 | [ValidateNotNullOrEmpty()]
652 | [ScriptBlock] $ScriptBlock,
653 |
654 | [Parameter(ParameterSetName = "ByPath", Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
655 | [ValidateScript({Test-Path $_ -PathType leaf})]
656 | [Alias('PSPath')]
657 | [String] $ScriptPath,
658 |
659 | [Parameter(ParameterSetName = "ByUri", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
660 | [ValidateScript({$_.Scheme -match 'http|https'})]
661 | [Uri] $ScriptUri,
662 |
663 | [ValidateScript({$_.GetType().Name -eq 'PSAmsiScanner'})]
664 | [System.Object] $PSAmsiScanner,
665 |
666 | [ValidateNotNullOrEmpty()]
667 | [System.Management.Automation.PSTokenType[]] $FilterPSTokenTypes = @('String', 'Member', 'CommandArgument', 'Command', 'Variable', 'Type', 'Comment')
668 | )
669 | Begin {
670 | $CreatedPSAmsiScanner = $False
671 | If (-not $PSAmsiScanner) {
672 | $PSAmsiScanner = New-PSAmsiScanner
673 | $CreatedPSAmsiScanner = $True
674 | }
675 | }
676 | Process {
677 | # Get the PSTokens that represent the script, if not provided
678 | If ($ScriptString) { $PSTokens = Get-PSTokens -ScriptString $ScriptString }
679 | ElseIf ($ScriptBlock) { $PSTokens = Get-PSTokens -ScriptBlock $ScriptBlock }
680 | ElseIf ($ScriptPath) { $PSTokens = Get-PSTokens -ScriptPath $ScriptPath }
681 | ElseIf ($ScriptUri) { $PSTokens = Get-PSTokens -ScriptUri $ScriptUri }
682 |
683 | # Filter given tokens by type, and check if PSToken content is flagged by AMSI
684 | $AmsiPSTokenSignatures = $PSTokens | ? { $_.Type -in $FilterPSTokenTypes } | ? { $PSAmsiScanner.GetPSAmsiScanResult($_.Content) }
685 | $AmsiPSTokenSignatures -as [array]
686 | }
687 | End {
688 | If ($CreatedPSAmsiScanner) { $PSAmsiScanner.Dispose() }
689 | }
690 | }
691 |
692 | function Test-ContainsAmsiPSTokenSignatures {
693 | <#
694 | .SYNOPSIS
695 |
696 | Tests if any PSTokens within a script contain AMSI signatures that are flagged by AMSI.
697 |
698 | Author: Ryan Cobb (@cobbr_io)
699 | License: GNU GPLv3
700 | Required Dependecies: none
701 | Optional Dependencies: New-PSAmsiScanner, Get-PSTokens
702 |
703 | .DESCRIPTION
704 |
705 | Test-ContainsAmsiPSTokenSignatures tests if any PSTokens within a script contain AMSI signatures that are flagged by AMSI.
706 | This function is much quicker than a full Find-AmsiPSTokenSignatures search.
707 |
708 | .PARAMETER PSTokens
709 |
710 | Specifies the list of PSTokens that represent the script to find PSTokens from that contain AMSI signatures.
711 |
712 | .PARAMETER ScriptString
713 |
714 | Specifies the string containing the script to find PSTokens from that contain AMSI signatures.
715 |
716 | .PARAMETER ScriptBlock
717 |
718 | Specifies the ScriptBlock containing the script to find PSTokens from that contain AMSI signatures.
719 |
720 | .PARAMETER ScriptPath
721 |
722 | Specifies the Path containing the script to find PSTokens from that contain AMSI signatures.
723 |
724 | .PARAMETER ScriptUri
725 |
726 | Specifies the URI of the script to find PSTokens from that contain AMSI signatures.
727 |
728 | .PARAMETER PSAmsiScanner
729 |
730 | Specifies the PSAmsiScanner to use to find PSTokens that contain AMSI signatures.
731 |
732 | .PARAMETER FilterPSTokenTypes
733 |
734 | Specifies to only get PSTokens that have a PSTokenType in the provided list.
735 |
736 | .OUTPUTS
737 |
738 | System.Management.Automation.PSToken[]
739 |
740 | .EXAMPLE
741 |
742 | Test-ContainsAmsiPSTokenSignatures -PSTokens $PSTokens -FilterTokenTypes @('Comment', 'String')
743 |
744 | .EXAMPLE
745 |
746 | Test-ContainsAmsiPSTokenSignatures "Write-Host example"
747 |
748 | .EXAMPLE
749 |
750 | Test-ContainsAmsiPSTokenSignatures { Write-Host example }
751 |
752 | .EXAMPLE
753 |
754 | Test-ContainsAmsiPSTokenSignatures -ScriptPath $ScriptPath -FilterPSTokenTypes Comment
755 |
756 | .EXAMPLE
757 |
758 | @($PSTokens1, $PSTokens2, $PSTokens3) | Test-ContainsAmsiPSTokenSignatures
759 |
760 | .EXAMPLE
761 |
762 | Get-ChildItem /path/to/scripts -Recurse -Include *.ps1 | Test-ContainsAmsiPSTokenSignatures
763 |
764 | .EXAMPLE
765 |
766 | @('Write-Host example1', 'Write-Host example2', 'Write-Host example3') | Test-ContainsAmsiPSTokenSignatures
767 |
768 | .EXAMPLE
769 |
770 | @({ Write-Host example1 }, { Write-Host example2 }, { Write-Host example3 }) | Test-ContainsAmsiPSTokenSignatures
771 |
772 | .NOTES
773 |
774 | Test-ContainsAmsiPSTokenSignatures is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
775 |
776 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
777 |
778 | #>
779 |
780 | [CmdletBinding(DefaultParameterSetName="ByString")] Param(
781 | [Parameter(ParameterSetName = "ByPSTokens", Position = 0, ValueFromPipeline, Mandatory)]
782 | [ValidateNotNullOrEmpty()]
783 | [System.Management.Automation.PSToken[]] $PSTokens,
784 |
785 | [Parameter(ParameterSetName = "ByString", Position = 0, ValueFromPipeline, Mandatory)]
786 | [ValidateNotNullOrEmpty()]
787 | [String] $ScriptString,
788 |
789 | [Parameter(ParameterSetName = "ByScriptBlock", Position = 0, ValueFromPipeline, Mandatory)]
790 | [ValidateNotNullOrEmpty()]
791 | [ScriptBlock] $ScriptBlock,
792 |
793 | [Parameter(ParameterSetName = "ByPath", Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
794 | [ValidateScript({Test-Path $_ -PathType leaf})]
795 | [Alias('PSPath')]
796 | [String] $ScriptPath,
797 |
798 | [Parameter(ParameterSetName = "ByUri", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
799 | [ValidateScript({$_.Scheme -match 'http|https'})]
800 | [Uri] $ScriptUri,
801 |
802 | [ValidateScript({$_.GetType().Name -eq 'PSAmsiScanner'})]
803 | [System.Object] $PSAmsiScanner,
804 |
805 | [ValidateNotNullOrEmpty()]
806 | [System.Management.Automation.PSTokenType[]] $FilterPSTokenTypes = @('String', 'Member', 'CommandArgument', 'Command', 'Variable', 'Type', 'Comment')
807 | )
808 | Begin {
809 | $CreatedPSAmsiScanner = $False
810 | If (-not $PSAmsiScanner) {
811 | $PSAmsiScanner = New-PSAmsiScanner
812 | $CreatedPSAmsiScanner = $True
813 | }
814 | }
815 | Process {
816 | # Get the PSTokens that represent the script, if not provided
817 | If ($ScriptString) { $PSTokens = Get-PSTokens -ScriptString $ScriptString }
818 | ElseIf ($ScriptBlock) { $PSTokens = Get-PSTokens -ScriptBlock $ScriptBlock }
819 | ElseIf ($ScriptPath) { $PSTokens = Get-PSTokens -ScriptPath $ScriptPath }
820 | ElseIf ($ScriptUri) { $PSTokens = Get-PSTokens -ScriptUri $ScriptUri }
821 |
822 | # Filter given tokens by type, and check if Token content is flagged by AMSI
823 | $PSTokens | ? { $_.Type -in $FilterPSTokenTypes } | % {
824 | $Result = $PSAmsiScanner.GetPSAmsiScanResult($_.Content)
825 | If ($Result) { $True; break }
826 | }
827 | }
828 | End {
829 | If ($CreatedPSAmsiScanner) { $PSAmsiScanner.Dispose() }
830 | }
831 | }
832 |
833 | function Get-Ast {
834 | <#
835 |
836 | .SYNOPSIS
837 |
838 | Gets the root Ast for a given script.
839 |
840 | Author: Ryan Cobb (@cobbr_io)
841 | License: GNU GPLv3
842 | Required Dependecies: none
843 | Optional Dependencies: none
844 |
845 | .DESCRIPTION
846 |
847 | Get-Ast gets the AbstractSyntaxTree that represents a given script.
848 |
849 | .PARAMETER ScriptString
850 |
851 | Specifies the String containing a script to get the AbstractSyntaxTree of.
852 |
853 | .PARAMETER ScriptBlock
854 |
855 | Specifies the ScriptBlock containing a script to get the AbstractSyntaxTree of.
856 |
857 | .PARAMETER ScriptPath
858 |
859 | Specifies the Path to a file containing the script to get the AbstractSyntaxTree of.
860 |
861 | .PARAMETER ScriptUri
862 |
863 | Specifies the URI of the script to get the AbstractSyntaxTree of.
864 |
865 | .OUTPUTS
866 |
867 | System.Management.Automation.Language.Ast
868 |
869 | .EXAMPLE
870 |
871 | Get-Ast "Write-Host example"
872 |
873 | .EXAMPLE
874 |
875 | Get-Ast {Write-Host example}
876 |
877 | .EXAMPLE
878 |
879 | Get-Ast -ScriptPath Write-Example.ps1
880 |
881 | .EXAMPLE
882 |
883 | Get-ChildItem /path/to/scripts -Recurse -Include *.ps1 | Get-Ast
884 |
885 | .EXAMPLE
886 |
887 | @('Write-Host example1', 'Write-Host example2', 'Write-Host example3') | Get-Ast
888 |
889 | .EXAMPLE
890 |
891 | @({ Write-Host example1 }, { Write-Host example2 }, { Write-Host example3 }) | Get-Ast
892 |
893 | .NOTES
894 |
895 | Get-Ast is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
896 |
897 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
898 |
899 | #>
900 | [CmdletBinding(DefaultParameterSetName = "ByString")] Param(
901 | [Parameter(ParameterSetName = "ByString", Position = 0, ValueFromPipeline, Mandatory)]
902 | [ValidateNotNullOrEmpty()]
903 | [String] $ScriptString,
904 |
905 | [Parameter(ParameterSetName = "ByScriptBlock", Position = 0, ValueFromPipeline, Mandatory)]
906 | [ValidateNotNullOrEmpty()]
907 | [ScriptBlock] $ScriptBlock,
908 |
909 | [Parameter(ParameterSetName = "ByPath", Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
910 | [ValidateScript({Test-Path $_ -PathType leaf})]
911 | [Alias('PSPath')]
912 | [String] $ScriptPath,
913 |
914 | [Parameter(ParameterSetName = "ByUri", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
915 | [ValidateScript({$_.Scheme -match 'http|https'})]
916 | [Uri] $ScriptUri
917 | )
918 | Process {
919 | If ($ScriptBlock) { $ScriptString = $ScriptBlock -as [String] }
920 | ElseIf ($ScriptPath) { $ScriptString = Get-Content -Path $ScriptPath -Raw }
921 | ElseIf ($ScriptUri) { $ScriptString = [Net.Webclient]::new().DownloadString($ScriptUri) }
922 |
923 | # Parse script and return root Ast
924 | [Management.Automation.Language.ParseError[]] $ParseErrors = @()
925 | $Ast = [Management.Automation.Language.Parser]::ParseInput($ScriptString, $null, [ref] $null, [ref] $ParseErrors)
926 | $Ast
927 | }
928 | }
929 |
930 | function Get-PSTokens {
931 | <#
932 |
933 | .SYNOPSIS
934 |
935 | Gets the PSTokens for a given script.
936 |
937 | Author: Ryan Cobb (@cobbr_io)
938 | License: GNU GPLv3
939 | Required Dependecies: none
940 | Optional Dependencies: none
941 |
942 | .DESCRIPTION
943 |
944 | Get-PSTokens gets the PSTokens that represent a given script.
945 |
946 | .PARAMETER ScriptString
947 |
948 | Specifies the String containing a script to get the PSTokens from.
949 |
950 | .PARAMETER ScriptBlock
951 |
952 | Specifies the ScriptBlock containing a script to get the PSTokens from.
953 |
954 | .PARAMETER ScriptPath
955 |
956 | Specifies the Path to a file containing the script to get the PSTokens from.
957 |
958 | .PARAMETER ScriptUri
959 |
960 | Specifies the URI of the script to get the PSTokens from.
961 |
962 | .OUTPUTS
963 |
964 | System.Management.Automation.PSToken[]
965 |
966 | .EXAMPLE
967 |
968 | Get-PSTokens "Write-Host example"
969 |
970 | .EXAMPLE
971 |
972 | Get-PSTokens {Write-Host example}
973 |
974 | .EXAMPLE
975 |
976 | Get-PSTokens -ScriptPath Write-Example.ps1
977 |
978 | .EXAMPLE
979 |
980 | Get-ChildItem /path/to/scripts -Recurse -Include *.ps1 | Get-PSTokens
981 |
982 | .EXAMPLE
983 |
984 | @('Write-Host example1', 'Write-Host example2', 'Write-Host example3') | Get-PSTokens
985 |
986 | .EXAMPLE
987 |
988 | @({ Write-Host example1 }, { Write-Host example2 }, { Write-Host example3 }) | Get-PSTokens
989 |
990 | .NOTES
991 |
992 | Get-PSTokens is a part of PSAmsi, a tool for auditing and defeating AMSI signatures.
993 |
994 | PSAmsi is located at https://github.com/cobbr/PSAmsi. Additional information can be found at https://cobbr.io.
995 |
996 | #>
997 | [CmdletBinding(DefaultParameterSetName = "ByString")] Param(
998 | [Parameter(ParameterSetName = "ByString", Position = 0, ValueFromPipeline, Mandatory)]
999 | [ValidateNotNullOrEmpty()]
1000 | [String] $ScriptString,
1001 |
1002 | [Parameter(ParameterSetName = "ByScriptBlock", Position = 0, ValueFromPipeline, Mandatory)]
1003 | [ValidateNotNullOrEmpty()]
1004 | [ScriptBlock] $ScriptBlock,
1005 |
1006 | [Parameter(ParameterSetName = "ByPath", Position = 0, ValueFromPipelineByPropertyName, Mandatory)]
1007 | [ValidateScript({Test-Path $_ -PathType leaf})]
1008 | [Alias('PSPath')]
1009 | [String] $ScriptPath,
1010 |
1011 | [Parameter(ParameterSetName = "ByUri", Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
1012 | [ValidateScript({$_.Scheme -match 'http|https'})]
1013 | [Uri] $ScriptUri
1014 | )
1015 | Process {
1016 | If ($ScriptBlock) { $ScriptString = $ScriptBlock -as [String] }
1017 | ElseIf ($ScriptPath) { $ScriptString = Get-Content -Path $ScriptPath -Raw }
1018 | ElseIf ($ScriptUri) { $ScriptString = [Net.Webclient]::new().DownloadString($ScriptUri) }
1019 |
1020 | # Tokenize script and return PSTokens
1021 | [Management.Automation.PSParseError[]] $PSParseErrors = @()
1022 | $PSTokens = [Management.Automation.PSParser]::Tokenize($ScriptString, [ref]$PSParseErrors)
1023 | $PSTokens
1024 | }
1025 | }
--------------------------------------------------------------------------------