importbase64importsysimportreimportgzipimportStringIOimporthexdumpashfromcapstoneimport*deffind_base64(str_data):# most base64 regex patterns are too strict. This patter returns non-base64 patternspattern=re.compile(r'(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?')found=re.findall(pattern,str_data)#iffound:# assumes the largest based64 is valid.returnmax(found,key=len)else:return""defdecode_base64(test_data):"""decode base64 data"""try:temp=base64.b64decode(test_data)return(True,temp)except:return(False,"")defdecompress_gzip(data):"""decompress gzip data"""try:temp=StringIO.StringIO(data)decompressedFile=gzip.GzipFile(fileobj=temp)return(True,decompressedFile.read())except:return(False,None)defdisassemble(code):"""prints assembly using capstone engine"""print"\nPosible Shellcode 32-bit"md=Cs(CS_ARCH_X86,CS_MODE_32)foriinmd.disasm(code,0x1000):print("0x%x:\t%s\t%s"%(i.address,i.mnemonic,i.op_str))print"\nPosible Shellcode 64-bit"md=Cs(CS_ARCH_X86,CS_MODE_64)foriinmd.disasm(code,0x1000):print("0x%x:\t%s\t%s"%(i.address,i.mnemonic,i.op_str))defwrite_file(data,name):"""write file"""withopen(name,"wb")asout:out.write(data)defrun():f=open(sys.argv[1],"rb")_input=f.read()# carveout base64 from powershellfound_base64=find_base64(_input)# decode base64status,decoded_base64=decode_base64(found_base64)ifstatus:print"\nBase64 Data:"printfound_base64# decompress Gzipstatus,decompressed=decompress_gzip(decoded_base64)ifstatus:print"\nDecompressed PowerShell Script:"printdecompressed# write decompressed powershell scriptwrite_file(decompressed,f.name+".ps.txt")found_base64=find_base64(decompressed)status,decoded_base64=decode_base64(found_base64)ifstatus:# decoded_base64 is the shellcodewrite_file(decoded_base64,f.name+".bin")print"\nHex dump of decoded base64 Shellcode"h.hexdump(decoded_base64)disassemble(decoded_base64)run()
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.